diff --git a/build.gradle b/build.gradle index a0aa2e6..e10ef36 100644 --- a/build.gradle +++ b/build.gradle @@ -56,10 +56,8 @@ dependencies { // Standard Maven repository dependencies shade 'org.apache.commons:commons-math3:3.2' - shade 'org.jfree:jcommon:1.0.21' shade 'org.jfree:jfreechart:1.0.17' shade 'com.miglayout:miglayout-swing:4.2' - shade 'net.sf.opencsv:opencsv:2.3' // Necessary for deployment deployerJars "org.apache.maven.wagon:wagon-ssh:2.2" diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java deleted file mode 100644 index ebeb786..0000000 --- a/src/main/java/mapwriter/BackgroundExecutor.java +++ /dev/null @@ -1,124 +0,0 @@ -package mapwriter; - -import java.util.LinkedList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import mapwriter.tasks.Task; - - - -/* -This class handles executing and managing 'tasks'. -A single background thread runs tasks in the sequence they are added (via addTask()). -A linked list FIFO queue of every unfinished task is processed every time the processTaskQueue method is called. -processTaskQueue checks the task at the front of the queue to see if the background thread has processed it. -If it the task is complete processTaskQueue calls the onComplete() method of the task and removes it from the queue. -If it is not complete the task is added to the front of the queue again. -In this way the tasks are always processed sequentially, in the order they were added to the queue. - -Tasks are extensions of the base Task class. -There are two abstract methods which must be overwritten by the extending class. - void run() - Is executed in the background thread when the executor reaches this task. - void onComplete() - Is called by processTaskQueue() when the task is done (after the run method is complete). - This method runs in the main thread so is a good place to copy the results of the run() method. - -The run() method of a task added to the queue is guaranteed to be run before the run() method of the next task -added. Likewise the onComplete() method of the first task is guaranteed to be run before the onComplete() of the second -task. However the run() method of any class added after a Task may be executed before the onComplete() method of -the earlier Task is called. - -e.g. addTask(Task1) - addTask(Task2) - addTask(Task3) - -may run in the order: - Task1.run() - Task2.run() - Task1.onComplete() - Task3.run() - Task2.onComplete() - Task3.onComplete() -*/ - -public class BackgroundExecutor { - - private ExecutorService executor; - private LinkedList taskQueue; - public boolean closed = false; - - public BackgroundExecutor() { - this.executor = Executors.newSingleThreadExecutor(); - this.taskQueue = new LinkedList(); - } - - // add a task to the queue - public boolean addTask(Task task) { - if (!this.closed) { - Future future = this.executor.submit(task); - task.setFuture(future); - this.taskQueue.add(task); - } else { - MwUtil.log("MwExecutor.addTask: error: cannot add task to closed executor"); - } - return this.closed; - } - - // Pop a Task entry from the task queue and check if the task's thread has finished. - // If it has completed then call onComplete for the task. - // If it has not completed then push the task back on the queue. - public boolean processTaskQueue() { - boolean processed = false; - Task task = this.taskQueue.poll(); - if (task != null) { - if (task.isDone()) { - task.printException(); - task.onComplete(); - processed = true; - } else { - // put entry back on top of queue - this.taskQueue.push(task); - } - } - return !processed; - } - - public boolean processRemainingTasks(int attempts, int delay) { - while ((this.taskQueue.size() > 0) && (attempts > 0)) { - if (this.processTaskQueue()) { - try { - Thread.sleep(delay); - } catch (Exception e) { - } - attempts--; - } - } - return (attempts <= 0); - } - - public int tasksRemaining() { - return this.taskQueue.size(); - } - - public boolean close() { - boolean error = true; - try { - // stop accepting new tasks - this.executor.shutdown(); - // process remaining tasks - this.processRemainingTasks(50, 5); - // should already be terminated, but just in case... - error = !this.executor.awaitTermination(10L, TimeUnit.SECONDS); - error = false; - } catch (InterruptedException e) { - MwUtil.log("error: IO task was interrupted during shutdown"); - e.printStackTrace(); - } - this.closed = true; - return error; - } -} diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java deleted file mode 100644 index d8a4ed2..0000000 --- a/src/main/java/mapwriter/BlockColourGen.java +++ /dev/null @@ -1,176 +0,0 @@ -package mapwriter; - -import mapwriter.region.BlockColours; -import mapwriter.region.BlockColours.BlockType; -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.IIcon; -import net.minecraft.world.biome.BiomeGenBase; - -// Static class to generate BlockColours. -// This is separate from BlockColours because it needs to run in the GL rendering thread -// whereas the generated BlockColours object is used only in the background thread. -// So basically split to make it clear that BlockColourGen and the generated BlockColours -// must not have any interaction after it is generated. - -public class BlockColourGen { - - private static int getIconMapColour(IIcon icon, Texture terrainTexture) { - // flipped icons have the U and V coords reversed (minU > maxU, minV > maxV). - // thanks go to taelnia for fixing this. - int iconX = (int) Math.round(((float) terrainTexture.w) * Math.min(icon.getMinU(), icon.getMaxU())); - int iconY = (int) Math.round(((float) terrainTexture.h) * Math.min(icon.getMinV(), icon.getMaxV())); - int iconWidth = (int) Math.round(((float) terrainTexture.w) * Math.abs(icon.getMaxU() - icon.getMinU())); - int iconHeight = (int) Math.round(((float) terrainTexture.h) * Math.abs(icon.getMaxV() - icon.getMinV())); - - int[] pixels = new int[iconWidth * iconHeight]; - - //MwUtil.log("(%d, %d) %dx%d", iconX, iconY, iconWidth, iconHeight); - - terrainTexture.getRGB(iconX, iconY, iconWidth, iconHeight, pixels, 0, iconWidth); - - // need to use custom averaging routine rather than scaling down to one pixel to - // stop transparent pixel colours being included in the average. - return Render.getAverageColourOfArray(pixels); - } - - private static int adjustBlockColourFromType(BlockColours bc, int blockAndMeta, int blockColour) { - // for normal blocks multiply the block colour by the render colour. - // for other blocks the block colour will be multiplied by the biome colour. - int blockid = blockAndMeta >> 4; - Block block = (Block) Block.blockRegistry.getObjectById(blockid); - BlockType blockType = bc.getBlockType(blockAndMeta); - switch (blockType) { - - case OPAQUE: - blockColour |= 0xff000000; - case NORMAL: - // fix crash when mods don't implement getRenderColor for all - // block meta values. - try { - int renderColour = block.getRenderColor(blockAndMeta & 0xf); - if (renderColour != 0xffffff) { - blockColour = Render.multiplyColours(blockColour, 0xff000000 | renderColour); - } - } catch (RuntimeException e) { - // do nothing - } - break; - case LEAVES: - // leaves look weird on the map if they are not opaque. - // they also look too dark if the render colour is applied. - blockColour |= 0xff000000; - break; - default: - break; - } - return blockColour; - } - - private static void genBiomeColours(BlockColours bc) { - // generate array of foliage, grass, and water colour multipliers - // for each biome. - - for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { - if (BiomeGenBase.getBiomeGenArray()[i] != null) { - bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i].getWaterColorMultiplier() & 0xffffff); - bc.setBiomeGrassShading(i, BiomeGenBase.getBiomeGenArray()[i].getBiomeGrassColor(0,0,0) & 0xffffff); //FIXME 0,0,0? - bc.setBiomeFoliageShading(i, BiomeGenBase.getBiomeGenArray()[i].getBiomeFoliageColor(0,0,0) & 0xffffff); //FIXME 0,0,0? - } else { - bc.setBiomeWaterShading(i, 0xffffff); - bc.setBiomeGrassShading(i, 0xffffff); - bc.setBiomeFoliageShading(i, 0xffffff); - } - } - } - - public static void genBlockColours(BlockColours bc) { - - MwUtil.log("generating block map colours from textures"); - - // copy terrain texture to MwRender pixel bytebuffer - - // bind the terrain texture - //Minecraft.getMinecraft().func_110434_K().func_110577_a(TextureMap.field_110575_b); - // get the bound texture id - //int terrainTextureId = Render.getBoundTextureId(); - - int terrainTextureId = Minecraft.getMinecraft().renderEngine.getTexture(TextureMap.locationBlocksTexture).getGlTextureId(); - - // create texture object from the currently bound GL texture - if (terrainTextureId == 0) { - MwUtil.log("error: could get terrain texture ID"); - return; - } - Texture terrainTexture = new Texture(terrainTextureId); - - double u1Last = 0; - double u2Last = 0; - double v1Last = 0; - double v2Last = 0; - int blockColourLast = 0; - int e_count = 0; - int b_count = 0; - int s_count = 0; - - for (int blockID = 0; blockID < 4096; blockID++) { //TODO: replace hardcoded 4096 with actual registry size - for (int dv = 0; dv < 16; dv++) { - - int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); - Block block = (Block) Block.blockRegistry.getObjectById(blockID); - int blockColour = 0; - - if (block != null) { - - IIcon icon = null; - try { - icon = block.getIcon(1, dv); - } catch (Exception e) { - //MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", blockID, dv); - //e.printStackTrace(); - e_count++; - } - - if (icon != null) { - double u1 = icon.getMinU(); - double u2 = icon.getMaxU(); - double v1 = icon.getMinV(); - double v2 = icon.getMaxV(); - - if ((u1 == u1Last) && (u2 == u2Last) && (v1 == v1Last) && (v2 == v2Last)) { - blockColour = blockColourLast; - s_count++; - } else { - blockColour = getIconMapColour(icon, terrainTexture); - u1Last = u1; - u2Last = u2; - v1Last = v1; - v2Last = v2; - blockColourLast = blockColour; - b_count++; - } - //if (dv == 0) - // MwUtil.log("block %03x:%x colour = %08x", blockID, dv, blockColour); - } - - // doesn't work as some leaves blocks aren't rendered using the biome - // foliage colour - //try { - // if (block.isLeaves(null, 0, 0, 0)) { - // bc.setBlockType(blockAndMeta, BlockType.LEAVES); - // } - //} catch (NullPointerException e) { - //} - - blockColour = adjustBlockColourFromType(bc, blockAndMeta, blockColour); - } - bc.setColour(blockAndMeta, blockColour); - } - } - - MwUtil.log("processed %d block textures, %d skipped, %d exceptions", b_count, s_count, e_count); - - genBiomeColours(bc); - } -} diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java deleted file mode 100644 index 674a4b8..0000000 --- a/src/main/java/mapwriter/ChunkManager.java +++ /dev/null @@ -1,149 +0,0 @@ -package mapwriter; - -import java.util.Map; - -import mapwriter.region.MwChunk; -import mapwriter.tasks.SaveChunkTask; -import mapwriter.tasks.UpdateSurfaceChunksTask; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.storage.ExtendedBlockStorage; - -public class ChunkManager { - public Mw mw; - private boolean closed = false; - private CircularHashMap chunkMap = new CircularHashMap(); - - private static final int VISIBLE_FLAG = 0x01; - private static final int VIEWED_FLAG = 0x02; - - public ChunkManager(Mw mw) { - this.mw = mw; - } - - public synchronized void close() { - this.closed = true; - this.saveChunks(); - this.chunkMap.clear(); - } - - // create MwChunk from Minecraft chunk. - // only MwChunk's should be used in the background thread. - // TODO: make this a full copy of chunk data to prevent possible race conditions - public static MwChunk copyToMwChunk(Chunk chunk) { - - byte[][] msbArray = new byte[16][]; - byte[][] lsbArray = new byte[16][]; - byte[][] metaArray = new byte[16][]; - byte[][] lightingArray = new byte[16][]; - - ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); - if (storageArrays != null) { - for (ExtendedBlockStorage storage : storageArrays) { - if (storage != null) { - int y = (storage.getYLocation() >> 4) & 0xf; - lsbArray[y] = storage.getBlockLSBArray(); - msbArray[y] = (storage.getBlockMSBArray() != null) ? storage.getBlockMSBArray().data : null; - metaArray[y] = (storage.getMetadataArray() != null) ? storage.getMetadataArray().data : null; - lightingArray[y] = (storage.getBlocklightArray() != null) ? storage.getBlocklightArray().data : null; - } - } - } - - return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.worldObj.provider.dimensionId, - msbArray, lsbArray, metaArray, lightingArray, chunk.getBiomeArray()); - } - - public synchronized void addChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - this.chunkMap.put(chunk, 0); - } - } - - public synchronized void removeChunk(Chunk chunk) { - if (!this.closed && (chunk != null)) { - if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? - int flags = this.chunkMap.get(chunk); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(chunk); - } - this.chunkMap.remove(chunk); - } - } - - public synchronized void saveChunks() { - for (Map.Entry entry : this.chunkMap.entrySet()) { - int flags = entry.getValue(); - if ((flags & VIEWED_FLAG) != 0) { - this.addSaveChunkTask(entry.getKey()); - } - } - } - - public void updateUndergroundChunks() { - int chunkArrayX = (this.mw.playerXInt >> 4) - 1; - int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; - MwChunk[] chunkArray = new MwChunk[9]; - for (int z = 0; z < 3; z++) { - for (int x = 0; x < 3; x++) { - Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( - chunkArrayX + x, - chunkArrayZ + z - ); - if (!chunk.isEmpty()) { - chunkArray[(z * 3) + x] = copyToMwChunk(chunk); - } - } - } - } - - public void updateSurfaceChunks() { - int chunksToUpdate = Math.min(this.chunkMap.size(), this.mw.chunksPerTick); - MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; - for (int i = 0; i < chunksToUpdate; i++) { - Map.Entry entry = this.chunkMap.getNextEntry(); - if (entry != null) { - // if this chunk is within a certain distance to the player then - // add it to the viewed set - Chunk chunk = entry.getKey(); - int flags = entry.getValue(); - if (MwUtil.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= this.mw.maxChunkSaveDistSq) { - flags |= (VISIBLE_FLAG | VIEWED_FLAG); - } else { - flags &= ~VISIBLE_FLAG; - } - entry.setValue(flags); - - if ((flags & VISIBLE_FLAG) != 0) { - chunkArray[i] = copyToMwChunk(chunk); - } else { - chunkArray[i] = null; - } - } - } - - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - public void onTick() { - if (!this.closed) { - if ((this.mw.tickCounter & 0xf) == 0) { - this.updateUndergroundChunks(); - } else { - this.updateSurfaceChunks(); - } - } - } - - public void forceChunks(MwChunk[] chunkArray){ - this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); - } - - private void addSaveChunkTask(Chunk chunk) { - if ((this.mw.multiplayer && this.mw.regionFileOutputEnabledMP) || - (!this.mw.multiplayer && this.mw.regionFileOutputEnabledSP)) { - if (!chunk.isEmpty()) { - this.mw.executor.addTask(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); - } - } - } -} diff --git a/src/main/java/mapwriter/CircularHashMap.java b/src/main/java/mapwriter/CircularHashMap.java deleted file mode 100644 index 30e1c73..0000000 --- a/src/main/java/mapwriter/CircularHashMap.java +++ /dev/null @@ -1,194 +0,0 @@ -package mapwriter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class CircularHashMap { - /* A hash map where each node is linked to the previous and next nodes - * in the order of insertion. - * - * The 'head' node is the most recently added node. Its next pointer - * links to the first node added, forming a circle. - * - * The getNextEntry and getPrevEntry methods use an internal pointer to - * the 'current' node, and return either the current nodes 'next' or - * 'prev' node respectively. - * The current node becomes the node that was returned, such that repeated - * calls traverse all nodes in the map. - * - * Most methods are similar to those in the java.util.Map interface. - * The CircularHashMap class does not implement Map however as some of the - * required methods seemed unnecessary. - */ - - private Map nodeMap = new HashMap(); - private Node headNode = null; - private Node currentNode = null; - - public class Node implements Map.Entry{ - private final K key; - private V value; - private Node next; - private Node prev; - - Node(K key, V value) { - this.key = key; - this.value = value; - this.next = this; - this.prev = this; - } - - @Override - public K getKey() { - return this.key; - } - - @Override - public V getValue() { - return this.value; - } - - @Override - public V setValue(V value) { - V oldValue = this.value; - this.value = value; - return oldValue; - } - } - - public V put(K key, V value) { - Node node = this.nodeMap.get(key); - if (node == null) { - // add new node - node = new Node(key, value); - this.nodeMap.put(key, node); - - if (this.headNode == null) { - node.next = node; - node.prev = node; - - } else { - node.next = this.headNode.next; - node.prev = this.headNode; - - this.headNode.next.prev = node; - this.headNode.next = node; - } - - if (this.currentNode == null) { - this.currentNode = node; - } - - this.headNode = node; - - } else { - // update node - node.value = value; - } - return value; - } - - public V remove(Object key) { - Node node = this.nodeMap.get(key); - V value = null; - if (node != null) { - if (this.headNode == node) { - this.headNode = node.next; - if (this.headNode == node) { - this.headNode = null; - } - } - if (this.currentNode == node) { - this.currentNode = node.next; - if (this.currentNode == node) { - this.currentNode = null; - } - } - - node.prev.next = node.next; - node.next.prev = node.prev; - node.next = null; - node.prev = null; - value = node.value; - - this.nodeMap.remove(key); - } - return value; - } - - public void clear() { - for (Node node : this.nodeMap.values()) { - node.next = null; - node.prev = null; - } - this.nodeMap.clear(); - this.headNode = null; - this.currentNode = null; - } - - public boolean containsKey(Object key) { - return this.nodeMap.containsKey(key); - } - - public int size() { - return this.nodeMap.size(); - } - - public Set keySet() { - return this.nodeMap.keySet(); - } - - public Collection values() { - Collection list = new ArrayList(); - for (Node node : this.nodeMap.values()) { - list.add(node.value); - } - return list; - } - - public Collection> entrySet() { - return new ArrayList>(this.nodeMap.values()); - } - - public V get(Object key) { - Node node = this.nodeMap.get(key); - return (node != null) ? node.value : null; - } - - public boolean isEmpty() { - return this.nodeMap.isEmpty(); - } - - // - // interface to traverse circular nodes - // - - public Map.Entry getNextEntry() { - if (this.currentNode != null) { - this.currentNode = this.currentNode.next; - } - return this.currentNode; - } - - public Map.Entry getPrevEntry() { - if (this.currentNode != null) { - this.currentNode = this.currentNode.prev; - } - return this.currentNode; - } - - public void rewind() { - this.currentNode = (this.headNode != null) ? this.headNode.next : null; - } - - public boolean setPosition(K key) { - Node node = this.nodeMap.get(key); - if (node != null) { - this.currentNode = node; - } - return (node != null); - } -} diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java deleted file mode 100644 index 11d41ad..0000000 --- a/src/main/java/mapwriter/Mw.java +++ /dev/null @@ -1,741 +0,0 @@ -package mapwriter; - -import mapwriter.forge.MwConfig; -import mapwriter.forge.MwForge; -import mapwriter.forge.MwKeyHandler; -import mapwriter.gui.MwGui; -import mapwriter.gui.MwGuiMarkerDialog; -import mapwriter.map.*; -import mapwriter.overlay.OverlaySlime; -import mapwriter.region.BlockColours; -import mapwriter.region.RegionManager; -import mapwriter.tasks.CloseRegionManagerTask; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGameOver; -import net.minecraft.client.settings.KeyBinding; -import net.minecraft.server.integrated.IntegratedServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/* - -data transfers ---------------- -chunk image (16x16 int[]) -> texture (512x512 GL texture) | every chunk update -region file png -> texture (512x512 GL texture) | on region load (slow, disk access) -texture (512x512 GL texture) -> region file png | on region unload (slow, disk access) -chunk (Chunk object) -> anvil save file | on chunk unload, separate thread handled by minecraft - -background thread ------------------- -performs all data transfers except Chunk->Anvil, which is handled by ThreadedFileIOBase in minecraft. -regions created in main thread when necessary, but filled from the background thread. - -initialization --------------- -init() - Called once only. - - registers event and key handlers - - loads configuration - - inits marker manager - - inits commands - - inits chunkQueue - -onClientLoggedIn() - Called upon entry to each world. - - inits executor - - inits overlay - - inits anvil save handler - - inits regionMap - -onConnectionClosed() - Called on every exit from world. - - closes chunkLoader - - closes regionMap - - closes overlay - - saves markermanager - - saves config - - closes executor - - flush chunkQueue - -Every hook and event handler should be enclosed in an 'if (this.ready)' statement to ensure that all -components are initialised. -One exception is the fillChunk handler which adds chunks to the chunkQueue so that they can be processed -after initialization. This is so that no chunks are skipped if the chunks are loaded before the player is -logged in. - -*/ - -public class Mw { - - public Minecraft mc = null; - - // server information - public String worldName = "default"; - private String serverName = "default"; - private int serverPort = 0; - - // configuration files (global and world specific) - public MwConfig config; - public MwConfig worldConfig = null; - - // directories - private final File configDir; - private final File saveDir; - public File worldDir = null; - public File imageDir = null; - - // configuration options - public boolean linearTextureScalingEnabled = true; - public int coordsMode = 0; - public boolean undergroundMode = false; - public boolean teleportEnabled = true; - public String teleportCommand = "tp"; - public int defaultTeleportHeight = 80; - public int maxZoom = 5; - public int minZoom = -5; - public boolean useSavedBlockColours = false; - public int maxChunkSaveDistSq = 128 * 128; - public boolean mapPixelSnapEnabled = true; - public int textureSize = 2048; - public int configTextureSize = 2048; - public int maxDeathMarkers = 3; - public int chunksPerTick = 5; - public boolean portNumberInWorldNameEnabled = true; - public String saveDirOverride = ""; - public boolean regionFileOutputEnabledSP = true; - public boolean regionFileOutputEnabledMP = true; - public int backgroundTextureMode = 0; - //public boolean lightingEnabled = false; - - // flags and counters - private boolean onPlayerDeathAlreadyFired = false; - public boolean ready = false; - public boolean multiplayer = false; - public int tickCounter = 0; - - // list of available dimensions - public List dimensionList = new ArrayList(); - - // player position and heading - public double playerX = 0.0; - public double playerZ = 0.0; - public double playerY = 0.0; - public int playerXInt = 0; - public int playerYInt = 0; - public int playerZInt = 0; - public double playerHeading = 0.0; - public int playerDimension = 0; - public double mapRotationDegrees = 0.0; - - // constants - public final static String catWorld = "world"; - public final static String catMarkers = "markers"; - public final static String catOptions = "options"; - public final static String worldDirConfigName = "mapwriter.cfg"; - public final static String blockColourSaveFileName = "MapWriterBlockColours.txt"; - public final static String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; - - // instances of components - public MapTexture mapTexture = null; - public UndergroundTexture undergroundMapTexture = null; - public BackgroundExecutor executor = null; - public MiniMap miniMap = null; - public MarkerManager markerManager = null; - public BlockColours blockColours = null; - public RegionManager regionManager = null; - public ChunkManager chunkManager = null; - public Trail playerTrail = null; - - public static Mw instance; - - public Mw(MwConfig config) { - // client only initialization - // oops, no idea why I was using a ModLoader method to get the Minecraft instance before - this.mc = Minecraft.getMinecraft(); - - // load config - this.config = config; - - // create base save directory - this.saveDir = new File(this.mc.mcDataDir, "saves"); - this.configDir = new File(this.mc.mcDataDir, "config"); - - this.ready = false; - - RegionManager.logger = MwForge.logger; - - instance = this; - } - - public String getWorldName() { - String worldName; - if (this.multiplayer) { - if (this.portNumberInWorldNameEnabled) { - worldName = String.format("%s_%d", this.serverName, this.serverPort); - } else { - worldName = String.format("%s", this.serverName); - } - - } else { - // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it - // is set statically to "MpServer". - IntegratedServer server = this.mc.getIntegratedServer(); - worldName = (server != null) ? server.getFolderName() : "sp_world"; - } - - // strip invalid characters from the server name so that it - // can't be something malicious like '..\..\..\windows\' - worldName = MwUtil.mungeString(worldName); - - // if something went wrong make sure the name is not blank - // (causes crash on start up due to empty configuration section) - if (worldName == "") { - worldName = "default"; - } - return worldName; - } - - public void loadConfig() { - this.config.load(); - this.linearTextureScalingEnabled = this.config.getOrSetBoolean(catOptions, "linearTextureScaling", this.linearTextureScalingEnabled); - this.useSavedBlockColours = this.config.getOrSetBoolean(catOptions, "useSavedBlockColours", this.useSavedBlockColours); - this.teleportEnabled = this.config.getOrSetBoolean(catOptions, "teleportEnabled", this.teleportEnabled); - this.teleportCommand = this.config.get(catOptions, "teleportCommand", this.teleportCommand).getString(); - this.coordsMode = this.config.getOrSetInt(catOptions, "coordsMode", this.coordsMode, 0, 2); - this.maxChunkSaveDistSq = this.config.getOrSetInt(catOptions, "maxChunkSaveDistSq", this.maxChunkSaveDistSq, 1, 256 * 256); - this.mapPixelSnapEnabled = this.config.getOrSetBoolean(catOptions, "mapPixelSnapEnabled", this.mapPixelSnapEnabled); - this.maxDeathMarkers = this.config.getOrSetInt(catOptions, "maxDeathMarkers", this.maxDeathMarkers, 0, 1000); - this.chunksPerTick = this.config.getOrSetInt(catOptions, "chunksPerTick", this.chunksPerTick, 1, 500); - this.saveDirOverride = this.config.get(catOptions, "saveDirOverride", this.saveDirOverride).getString(); - this.portNumberInWorldNameEnabled = config.getOrSetBoolean(catOptions, "portNumberInWorldNameEnabled", this.portNumberInWorldNameEnabled); - this.undergroundMode = this.config.getOrSetBoolean(catOptions, "undergroundMode", this.undergroundMode); - this.regionFileOutputEnabledSP = this.config.getOrSetBoolean(catOptions, "regionFileOutputEnabledSP", this.regionFileOutputEnabledSP); - this.regionFileOutputEnabledMP = this.config.getOrSetBoolean(catOptions, "regionFileOutputEnabledMP", this.regionFileOutputEnabledMP); - this.backgroundTextureMode = this.config.getOrSetInt(catOptions, "backgroundTextureMode", this.backgroundTextureMode, 0, 1); - //this.lightingEnabled = this.config.getOrSetBoolean(catOptions, "lightingEnabled", this.lightingEnabled); - - this.maxZoom = this.config.getOrSetInt(catOptions, "zoomOutLevels", this.maxZoom, 1, 256); - this.minZoom = -this.config.getOrSetInt(catOptions, "zoomInLevels", -this.minZoom, 1, 256); - - this.configTextureSize = this.config.getOrSetInt(catOptions, "textureSize", this.configTextureSize, 1024, 8192); - this.setTextureSize(); - } - - public void loadWorldConfig() { - // load world specific config file - File worldConfigFile = new File(this.worldDir, worldDirConfigName); - this.worldConfig = new MwConfig(worldConfigFile); - this.worldConfig.load(); - - this.dimensionList.clear(); - this.worldConfig.getIntList(catWorld, "dimensionList", this.dimensionList); - this.addDimension(0); - this.cleanDimensionList(); - } - - public void saveConfig() { - this.config.setBoolean(catOptions, "linearTextureScaling", this.linearTextureScalingEnabled); - this.config.setBoolean(catOptions, "useSavedBlockColours", this.useSavedBlockColours); - this.config.setInt(catOptions, "textureSize", this.configTextureSize); - this.config.setInt(catOptions, "coordsMode", this.coordsMode); - this.config.setInt(catOptions, "maxChunkSaveDistSq", this.maxChunkSaveDistSq); - this.config.setBoolean(catOptions, "mapPixelSnapEnabled", this.mapPixelSnapEnabled); - this.config.setInt(catOptions, "maxDeathMarkers", this.maxDeathMarkers); - this.config.setInt(catOptions, "chunksPerTick", this.chunksPerTick); - this.config.setBoolean(catOptions, "undergroundMode", this.undergroundMode); - this.config.setInt(catOptions, "backgroundTextureMode", this.backgroundTextureMode); - //this.config.setBoolean(catOptions, "lightingEnabled", this.lightingEnabled); - - this.config.save(); - } - - public void saveWorldConfig() { - this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); - this.worldConfig.save(); - } - - public void setTextureSize() { - if (this.configTextureSize != this.textureSize) { - int maxTextureSize = Render.getMaxTextureSize(); - int textureSize = 1024; - while ((textureSize <= maxTextureSize) && (textureSize <= this.configTextureSize)) { - textureSize *= 2; - } - textureSize /= 2; - - MwUtil.log("GL reported max texture size = %d", maxTextureSize); - MwUtil.log("texture size from config = %d", this.configTextureSize); - MwUtil.log("setting map texture size to = %d", textureSize); - - this.textureSize = textureSize; - if (this.ready) { - // if we are already up and running need to close and reinitialize the map texture and - // region manager. - this.reloadMapTexture(); - } - } - } - - // update the saved player position and orientation - // called every tick - public void updatePlayer() { - // get player pos - this.playerX = (double) this.mc.thePlayer.posX; - this.playerY = (double) this.mc.thePlayer.posY; - this.playerZ = (double) this.mc.thePlayer.posZ; - this.playerXInt = (int) Math.floor(this.playerX); - this.playerYInt = (int) Math.floor(this.playerY); - this.playerZInt = (int) Math.floor(this.playerZ); - - // rotationYaw of 0 points due north, we want it to point due east instead - // so add pi/2 radians (90 degrees) - this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); - this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; - - // set by onWorldLoad - //this.playerDimension = this.mc.theWorld.provider.dimensionId; - } - - public void addDimension(int dimension) { - int i = this.dimensionList.indexOf(dimension); - if (i < 0) { - this.dimensionList.add(dimension); - } - } - - public void cleanDimensionList() { - List dimensionListCopy = new ArrayList(this.dimensionList); - this.dimensionList.clear(); - for (int dimension : dimensionListCopy) { - this.addDimension(dimension); - } - } - - public void toggleMarkerMode() { - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - } - - // cheap and lazy way to teleport... - public void teleportTo(int x, int y, int z) { - if (this.teleportEnabled) { - this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", this.teleportCommand, x, y, z)); - } else { - MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void warpTo(String name) { - if (this.teleportEnabled) { - //MwUtil.printBoth(String.format("warping to %s", name)); - this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); - } else { - MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); - } - } - - public void teleportToMapPos(MapView mapView, int x, int y, int z) { - if (!this.teleportCommand.equals("warp")) { - double scale = mapView.getDimensionScaling(this.playerDimension); - this.teleportTo((int) (x / scale), y, (int) (z / scale)); - } else { - MwUtil.printBoth("teleport command is set to 'warp', can only warp to markers"); - } - } - - public void teleportToMarker(Marker marker) { - if (this.teleportCommand.equals("warp")) { - this.warpTo(marker.name); - } else if (marker.dimension == this.playerDimension) { - this.teleportTo(marker.x, marker.y, marker.z); - } else { - MwUtil.printBoth("cannot teleport to marker in different dimension"); - } - } - - public void loadBlockColourOverrides(BlockColours bc) { - File f = new File(this.configDir, blockColourOverridesFileName); - if (f.isFile()) { - MwUtil.logInfo("loading block colour overrides file %s", f); - bc.loadFromFile(f); - } else { - MwUtil.logInfo("recreating block colour overrides file %s", f); - BlockColours.writeOverridesFile(f); - if (f.isFile()) { - bc.loadFromFile(f); - } else { - MwUtil.logError("could not load block colour overrides from file %s", f); - } - } - } - - public void saveBlockColours(BlockColours bc) { - File f = new File(this.configDir, blockColourSaveFileName); - MwUtil.logInfo("saving block colours to '%s'", f); - bc.saveToFile(f); - } - - public void reloadBlockColours() { - BlockColours bc = new BlockColours(); - File f = new File(this.configDir, blockColourSaveFileName); - if (this.useSavedBlockColours && f.isFile()) { - // load block colours from file - MwUtil.logInfo("loading block colours from %s", f); - bc.loadFromFile(f); - this.loadBlockColourOverrides(bc); - } else { - // generate block colours from current texture pack - MwUtil.logInfo("generating block colours"); - // block type overrides need to be loaded before the block colours are generated - this.loadBlockColourOverrides(bc); - BlockColourGen.genBlockColours(bc); - // load overrides again to override block and biome colours - this.loadBlockColourOverrides(bc); - this.saveBlockColours(bc); - } - this.blockColours = bc; - } - - public void reloadMapTexture() { - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.executor.close(); - MapTexture oldMapTexture = this.mapTexture; - MapTexture newMapTexture = new MapTexture(this.textureSize, this.linearTextureScalingEnabled); - this.mapTexture = newMapTexture; - if (oldMapTexture != null) { - oldMapTexture.close(); - } - this.executor = new BackgroundExecutor(); - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, this.minZoom, this.maxZoom); - - UndergroundTexture oldTexture = this.undergroundMapTexture; - UndergroundTexture newTexture = new UndergroundTexture(this, this.textureSize, this.linearTextureScalingEnabled); - this.undergroundMapTexture = newTexture; - if (oldTexture != null) { - this.undergroundMapTexture.close(); - } - } - - public void setCoordsMode(int mode) { - this.coordsMode = Math.min(Math.max(0, mode), 2); - } - - public int toggleCoords() { - this.setCoordsMode((this.coordsMode + 1) % 3); - return this.coordsMode; - } - - public void toggleUndergroundMode() { - this.undergroundMode = !this.undergroundMode; - this.miniMap.view.setUndergroundMode(this.undergroundMode); - } - - public void setServerDetails(String hostname, int port) { - this.serverName = hostname; - this.serverPort = port; - } - - //////////////////////////////// - // Initialization and Cleanup - //////////////////////////////// - - public void load() { - - if (this.ready) { - return; - } - - if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { - MwUtil.log("Mw.load: world or player is null, cannot load yet"); - return; - } - - MwUtil.log("Mw.load: loading..."); - - IntegratedServer server = this.mc.getIntegratedServer(); - this.multiplayer = (server == null); - - this.loadConfig(); - - this.worldName = this.getWorldName(); - - // get world and image directories - File saveDir = this.saveDir; - if (this.saveDirOverride.length() > 0) { - File d = new File(this.saveDirOverride); - if (d.isDirectory()) { - saveDir = d; - } else { - MwUtil.log("error: no such directory %s", this.saveDirOverride); - } - } - - if (this.multiplayer) { - this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), this.worldName); - } else { - this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), this.worldName); - } - - this.loadWorldConfig(); - - // create directories - this.imageDir = new File(this.worldDir, "images"); - if (!this.imageDir.exists()) { - this.imageDir.mkdirs(); - } - if (!this.imageDir.isDirectory()) { - MwUtil.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); - } - - this.tickCounter = 0; - this.onPlayerDeathAlreadyFired = false; - - //this.multiplayer = !this.mc.isIntegratedServerRunning(); - - // marker manager only depends on the config being loaded - this.markerManager = new MarkerManager(); - this.markerManager.load(this.worldConfig, catMarkers); - - this.playerTrail = new Trail(this, "player"); - - // executor does not depend on anything - this.executor = new BackgroundExecutor(); - - // mapTexture depends on config being loaded - this.mapTexture = new MapTexture(this.textureSize, this.linearTextureScalingEnabled); - this.undergroundMapTexture = new UndergroundTexture(this, this.textureSize, this.linearTextureScalingEnabled); - this.reloadBlockColours(); - // region manager depends on config, mapTexture, and block colours - this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, this.minZoom, this.maxZoom); - // overlay manager depends on mapTexture - this.miniMap = new MiniMap(this); - this.miniMap.view.setDimension(this.mc.thePlayer.dimension); - - this.chunkManager = new ChunkManager(this); - - this.ready = true; - - //if (!zoomLevelsExist) { - //printBoth("recreating zoom levels"); - //this.regionManager.recreateAllZoomLevels(); - //} - } - - public void close() { - - MwUtil.log("Mw.close: closing..."); - - if (this.ready) { - this.ready = false; - - this.chunkManager.close(); - this.chunkManager = null; - - // close all loaded regions, saving modified images. - // this will create extra tasks that need to be completed. - this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); - this.regionManager = null; - - MwUtil.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); - if (this.executor.close()) { - MwUtil.log("error: timeout waiting for tasks to finish"); - } - MwUtil.log("done"); - - this.playerTrail.close(); - - this.markerManager.save(this.worldConfig, catMarkers); - this.markerManager.clear(); - - // close overlay - this.miniMap.close(); - this.miniMap = null; - - this.undergroundMapTexture.close(); - this.mapTexture.close(); - - this.saveWorldConfig(); - this.saveConfig(); - - this.tickCounter = 0; - - OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in - } - } - - //////////////////////////////// - // Event handlers - //////////////////////////////// - - public void onWorldLoad(World world) { - //MwUtil.log("onWorldLoad: %s, name %s, dimension %d", - // world, - // world.getWorldInfo().getWorldName(), - // world.provider.dimensionId); - - this.playerDimension = world.provider.dimensionId; - if (this.ready) { - this.addDimension(this.playerDimension); - this.miniMap.view.setDimension(this.playerDimension); - } - } - - public void onWorldUnload(World world) { - //MwUtil.log("onWorldUnload: %s, name %s, dimension %d", - // world, - // world.getWorldInfo().getWorldName(), - // world.provider.dimensionId); - } - - public void onTick() { - this.load(); - if (this.ready && (this.mc.thePlayer != null)) { - - this.updatePlayer(); - - if (this.undergroundMode && ((this.tickCounter % 30) == 0)) { - this.undergroundMapTexture.update(); - } - - // check if the game over screen is being displayed and if so - // (thanks to Chrixian for this method of checking when the player is dead) - if (this.mc.currentScreen instanceof GuiGameOver) { - if (!this.onPlayerDeathAlreadyFired) { - this.onPlayerDeath(); - this.onPlayerDeathAlreadyFired = true; - } - } else if (!(this.mc.currentScreen instanceof MwGui)) { - // if the player is not dead - this.onPlayerDeathAlreadyFired = false; - // if in game (no gui screen) center the minimap on the player and render it. - this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); - this.miniMap.drawCurrentMap(); - } - - // process background tasks - int maxTasks = 50; - while (!this.executor.processTaskQueue() && (maxTasks > 0)) { - maxTasks--; - } - - this.chunkManager.onTick(); - - // update GL texture of mapTexture if updated - this.mapTexture.processTextureUpdates(); - - // let the renderEngine know we have changed the bound texture. - //this.mc.renderEngine.resetBoundTexture(); - - //if (this.tickCounter % 100 == 0) { - // MwUtil.log("tick %d", this.tickCounter); - //} - this.playerTrail.onTick(); - - this.tickCounter++; - } - } - - // add chunk to the set of loaded chunks - public void onChunkLoad(Chunk chunk) { - this.load(); - if ((chunk != null) && (chunk.worldObj instanceof net.minecraft.client.multiplayer.WorldClient)) { - if (this.ready) { - this.chunkManager.addChunk(chunk); - } else { - MwUtil.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); - } - } - } - - // remove chunk from the set of loaded chunks. - // convert to mwchunk and write chunk to region file if in multiplayer. - public void onChunkUnload(Chunk chunk) { - if (this.ready && (chunk != null) && (chunk.worldObj instanceof net.minecraft.client.multiplayer.WorldClient)) { - this.chunkManager.removeChunk(chunk); - } - } - - // from onTick when mc.currentScreen is an instance of GuiGameOver - // it's the only option to detect death client side - public void onPlayerDeath() { - if (this.ready && (this.maxDeathMarkers > 0)) { - this.updatePlayer(); - int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - this.maxDeathMarkers + 1; - for (int i = 0; i < deleteCount; i++) { - // delete the first marker found in the group "playerDeaths". - // as new markers are only ever appended to the marker list this will delete the - // earliest death marker added. - this.markerManager.delMarker(null, "playerDeaths"); - } - this.markerManager.addMarker(MwUtil.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); - this.markerManager.setVisibleGroupName("playerDeaths"); - this.markerManager.update(); - } - } - - public void onKeyDown(KeyBinding kb) { - // make sure not in GUI element (e.g. chat box) - if ((this.mc.currentScreen == null) && (this.ready)) { - //Mw.log("client tick: %s key pressed", kb.keyDescription); - - if (kb == MwKeyHandler.keyMapMode) { - // map mode toggle - this.miniMap.nextOverlayMode(1); - - } else if (kb == MwKeyHandler.keyMapGui) { - // open map gui - this.mc.displayGuiScreen(new MwGui(this)); - - } else if (kb == MwKeyHandler.keyNewMarker) { - // open new marker dialog - String group = this.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - null, - this.markerManager, - "", - group, - this.playerXInt, - this.playerYInt, - this.playerZInt, - this.playerDimension - ) - ); - - } else if (kb == MwKeyHandler.keyNextGroup) { - // toggle marker mode - this.markerManager.nextGroup(); - this.markerManager.update(); - this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); - - } else if (kb == MwKeyHandler.keyTeleport) { - // set or remove marker - Marker marker = this.markerManager.getNearestMarkerInDirection( - this.playerXInt, - this.playerZInt, - this.playerHeading); - if (marker != null) { - this.teleportToMarker(marker); - } - } else if (kb == MwKeyHandler.keyZoomIn) { - // zoom in - this.miniMap.view.adjustZoomLevel(-1); - } else if (kb == MwKeyHandler.keyZoomOut) { - // zoom out - this.miniMap.view.adjustZoomLevel(1); - } else if (kb == MwKeyHandler.keyUndergroundMode) { - this.toggleUndergroundMode(); - } - } - } -} diff --git a/src/main/java/mapwriter/MwUtil.java b/src/main/java/mapwriter/MwUtil.java deleted file mode 100644 index b6d66f8..0000000 --- a/src/main/java/mapwriter/MwUtil.java +++ /dev/null @@ -1,121 +0,0 @@ -package mapwriter; - -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.regex.Pattern; - -import mapwriter.forge.MwForge; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityClientPlayerMP; -import net.minecraft.util.ChatComponentText; -import net.minecraft.world.chunk.Chunk; - -public class MwUtil { - - public final static Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); - - public static void logInfo(String s, Object...args) { - MwForge.logger.info(String.format(s, args)); - } - - public static void logWarning(String s, Object...args) { - MwForge.logger.warn(String.format(s, args)); - } - - public static void logError(String s, Object...args) { - MwForge.logger.error(String.format(s, args)); - } - - public static void debug(String s, Object...args) { - MwForge.logger.debug(String.format(s, args)); - } - - public static void log(String s, Object...args) { - logInfo(String.format(s, args)); - } - - public static String mungeString(String s) { - s = s.replace('.', '_'); - s = s.replace('-', '_'); - s = s.replace(' ', '_'); - s = s.replace('/', '_'); - s = s.replace('\\', '_'); - return patternInvalidChars.matcher(s).replaceAll(""); - } - - public static File getFreeFilename(File dir, String baseName, String ext) { - int i = 0; - File outputFile; - if (dir != null) { - outputFile = new File(dir, baseName + "." + ext); - } else { - outputFile = new File(baseName + "." + ext); - } - while (outputFile.exists() && (i < 1000)) { - if (dir != null) { - outputFile = new File(dir, baseName + "." + i + "." + ext); - } else { - outputFile = new File(baseName + "." + i + "." + ext); - } - i++; - } - return (i < 1000) ? outputFile : null; - } - - public static void printBoth(String msg) { - EntityClientPlayerMP thePlayer = Minecraft.getMinecraft().thePlayer; - if (thePlayer != null) { - thePlayer.addChatMessage(new ChatComponentText(msg)); - } - MwUtil.log("%s", msg); - } - - public static File getDimensionDir(File worldDir, int dimension) { - File dimDir; - if (dimension != 0) { - dimDir = new File(worldDir, "DIM" + dimension); - } else { - dimDir = worldDir; - } - return dimDir; - } - - public static IntBuffer allocateDirectIntBuffer(int size) { - return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - } - - // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) - // works by making sure all bits to the right of the highest set bit are 1, then - // adding 1 to get the answer. - public static int nextHighestPowerOf2(int v) { - // decrement by 1 (to handle cases where v is already a power of two) - v--; - - // set all bits to the right of the uppermost set bit. - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - // v |= v >> 32; // uncomment for 64 bit input values - - // add 1 to get the power of two result - return v + 1; - } - - public static String getCurrentDateString() { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); - return dateFormat.format(new Date()); - } - - public static int distToChunkSq(int x, int z, Chunk chunk) { - int dx = (chunk.xPosition << 4) + 8 - x; - int dz = (chunk.zPosition << 4) + 8 - z; - return (dx * dx) + (dz * dz); - } -} diff --git a/src/main/java/mapwriter/Render.java b/src/main/java/mapwriter/Render.java deleted file mode 100644 index 433612a..0000000 --- a/src/main/java/mapwriter/Render.java +++ /dev/null @@ -1,380 +0,0 @@ -package mapwriter; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.Tessellator; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -/* -MwRender contains most of the code for drawing the overlay. -This includes: - - loading textures from images - - saving textures to images - - allocating and setting up GL textures - - drawing coloured and textured quads (using minecraft Tesselator class) - -*/ - -public class Render { - public static double zDepth = 0.0D; - public static final double circleSteps = 30.0; - - public static void setColourWithAlphaPercent(int colour, int alphaPercent) { - setColour(((((alphaPercent * 0xff) / 100) & 0xff) << 24) | (colour & 0xffffff)); - } - - public static void setColour(int colour) { - GL11.glColor4f( - (float) ((colour >> 16) & 0xff) / 255.0f, - (float) ((colour >> 8) & 0xff) / 255.0f, - (float) ((colour) & 0xff) / 255.0f, - (float) ((colour >> 24) & 0xff) / 255.0f); - } - - public static void resetColour() { - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - } - - public static int multiplyColours(int c1, int c2) { - float c1A = (float) ((c1 >> 24) & 0xff); - float c1R = (float) ((c1 >> 16) & 0xff); - float c1G = (float) ((c1 >> 8) & 0xff); - float c1B = (float) ((c1 >> 0) & 0xff); - float c2A = (float) ((c2 >> 24) & 0xff); - float c2R = (float) ((c2 >> 16) & 0xff); - float c2G = (float) ((c2 >> 8) & 0xff); - float c2B = (float) ((c2 >> 0) & 0xff); - int r = (int) (c1R * c2R / 255.0f) & 0xff; - int g = (int) (c1G * c2G / 255.0f) & 0xff; - int b = (int) (c1B * c2B / 255.0f) & 0xff; - int a = (int) (c1A * c2A / 255.0f) & 0xff; - return (a << 24) | (r << 16) | (g << 8) | b; - } - - public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) { - int p00 = pixels[offset]; - int p01 = pixels[offset + 1]; - int p10 = pixels[offset + scanSize]; - int p11 = pixels[offset + scanSize + 1]; - - // ignore alpha channel - int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); - r >>= 2; - int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); - g >>= 2; - int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); - b >>= 2; - return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); - } - - public static int getAverageColourOfArray(int[] pixels) { - int count = 0; - double totalA = 0.0; - double totalR = 0.0; - double totalG = 0.0; - double totalB = 0.0; - for (int pixel : pixels) { - double a = (double) ((pixel >> 24) & 0xff); - double r = (double) ((pixel >> 16) & 0xff); - double g = (double) ((pixel >> 8) & 0xff); - double b = (double) ((pixel >> 0) & 0xff); - - totalA += a; - totalR += r * a / 255.0; - totalG += g * a / 255.0; - totalB += b * a / 255.0; - - count++; - } - - totalR = totalR * 255.0 / totalA; - totalG = totalG * 255.0 / totalA; - totalB = totalB * 255.0 / totalA; - totalA = totalA / ((double) count); - - return ((((int) (totalA)) & 0xff) << 24) | - ((((int) (totalR)) & 0xff) << 16) | - ((((int) (totalG)) & 0xff) << 8) | - ((((int) (totalB)) & 0xff)); - } - - public static int adjustPixelBrightness(int colour, int brightness) { - int r = ((colour >> 16) & 0xff); - int g = ((colour >> 8) & 0xff); - int b = ((colour >> 0) & 0xff); - r = Math.min(Math.max(0, r + brightness), 0xff); - g = Math.min(Math.max(0, g + brightness), 0xff); - b = Math.min(Math.max(0, b + brightness), 0xff); - return (colour & 0xff000000) | (r << 16) | (g << 8) | (b); - } - - public static int getTextureWidth() { - return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); - } - - public static int getTextureHeight() { - return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); - } - - public static int getBoundTextureId() { - return GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); - } - - public static void printBoundTextureInfo(int texture) { - int w = getTextureWidth(); - int h = getTextureHeight(); - int depth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL12.GL_TEXTURE_DEPTH); - int format = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); - MwUtil.log("texture %d parameters: width=%d, height=%d, depth=%d, format=%08x", texture, w, h, depth, format); - } - - public static int getMaxTextureSize() { - return GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE); - } - - /* - Drawing Methods - - Note that EntityRenderer.setupOverlayRendering must be called before drawing for the scene - to appear correctly on the overlay. - If these functions are called from the hookUpdateCameraAndRender method of Mw this - will have already been done. - */ - - // draw rectangle with texture stretched to fill the shape - public static void drawTexturedRect(double x, double y, double w, double h) { - drawTexturedRect(x, y, w, h, 0.0D, 0.0D, 1.0D, 1.0D); - } - - // draw rectangle with texture UV coordinates specified (so only part of the texture fills the rectangle). - public static void drawTexturedRect(double x, double y, double w, double h, double u1, double v1, double u2, double v2) { - try { - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); - tes.addVertexWithUV(x + w, y, zDepth, u2, v1); - tes.addVertexWithUV(x, y, zDepth, u1, v1); - tes.addVertexWithUV(x, y + h, zDepth, u1, v2); - tes.addVertexWithUV(x + w, y + h, zDepth, u2, v2); - tes.draw(); - GL11.glDisable(GL11.GL_BLEND); - } catch (NullPointerException e) { - MwUtil.log("MwRender.drawTexturedRect: null pointer exception"); - } - } - - public static void drawArrow(double x, double y, double angle, double length) { - // angle the back corners will be drawn at relative to the pointing angle - double arrowBackAngle = 0.75D * Math.PI; - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLE_FAN); - tes.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); - tes.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); - tes.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); - tes.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); - tes.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); - } - - public static void drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLES); - tes.addVertex(x1, y1, zDepth); - tes.addVertex(x2, y2, zDepth); - tes.addVertex(x3, y3, zDepth); - tes.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); - } - - public static void drawRect(double x, double y, double w, double h) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawingQuads(); - tes.addVertex(x + w, y, zDepth); - tes.addVertex(x, y, zDepth); - tes.addVertex(x, y + h, zDepth); - tes.addVertex(x + w, y + h, zDepth); - tes.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); - } - - public static void drawCircle(double x, double y, double r) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLE_FAN); - tes.addVertex(x, y, zDepth); - // for some the circle is only drawn if theta is decreasing rather than ascending - double end = Math.PI * 2.0; - double incr = end / circleSteps; - for (double theta = -incr; theta < end; theta += incr) { - tes.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); - } - tes.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); - } - - public static void drawCircleBorder(double x, double y, double r, double width) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator tes = Tessellator.instance; - tes.startDrawing(GL11.GL_TRIANGLE_STRIP); - // for some the circle is only drawn if theta is decreasing rather than ascending - double end = Math.PI * 2.0; - double incr = end / circleSteps; - double r2 = r + width; - for (double theta = -incr; theta < end; theta += incr) { - tes.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); - tes.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); - } - tes.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_BLEND); - } - - public static void drawRectBorder(double x, double y, double w, double h, double bw) { - // top border - Render.drawRect(x - bw, y - bw, w + bw + bw, bw); - // bottom border - Render.drawRect(x - bw, y + h, w + bw + bw, bw); - // left border - Render.drawRect(x - bw, y, bw, h); - // right border - Render.drawRect(x + w, y, bw, h); - } - - public static void drawString(int x, int y, int colour, String formatString, Object...args) { - Minecraft mc = Minecraft.getMinecraft(); - //mc.renderEngine.resetBoundTexture(); - FontRenderer fr = mc.fontRenderer; - String s = String.format(formatString, args); - fr.drawStringWithShadow(s, x, y, colour); - } - - public static void drawCentredString(int x, int y, int colour, String formatString, Object...args) { - Minecraft mc = Minecraft.getMinecraft(); - //mc.renderEngine.resetBoundTexture(); - FontRenderer fr = mc.fontRenderer; - String s = String.format(formatString, args); - int w = fr.getStringWidth(s); - fr.drawStringWithShadow(s, x - (w / 2), y, colour); - } - - public static void setCircularStencil(double x, double y, double r) { - GL11.glEnable(GL11.GL_DEPTH_TEST); - // disable drawing to the color buffer. - // circle will only be drawn to depth buffer. - GL11.glColorMask(false, false, false, false); - // enable writing to depth buffer - GL11.glDepthMask(true); - - // Clearing the depth buffer causes problems with shader mods. - // I guess we just have to hope that the rest of the depth buffer - // contains z values greater than 2000 at this stage in the frame - // render. - // It would be much easier to use the stencil buffer instead, but it is - // not specifically requested in the Minecraft LWJGL display setup code. - // So the stencil buffer is only available on GL implementations that - // set it up by default. - - // clear depth buffer to z = 3000.0 - //GL11.glClearDepth(3000.0); - //GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); - - // always write to depth buffer - GL11.glDepthFunc(GL11.GL_ALWAYS); - - // draw stencil pattern (filled circle at z = 1000.0) - Render.setColour(0xffffffff); - Render.zDepth = 1000.0; - Render.drawCircle(x, y, r); - Render.zDepth = 0.0; - - // re-enable drawing to colour buffer - GL11.glColorMask(true, true, true, true); - // disable drawing to depth buffer - GL11.glDepthMask(false); - // only draw pixels with z values that are greater - // than the value in the depth buffer. - // The overlay is drawn at 2000 so this will pass inside - // the circle (2000 > 1000) but not outside (2000 <= 3000). - GL11.glDepthFunc(GL11.GL_GREATER); - } - - public static void disableStencil() { - GL11.glDepthMask(true); - GL11.glDepthFunc(GL11.GL_LEQUAL); - GL11.glDisable(GL11.GL_DEPTH_TEST); - } - - // A better implementation of a circular stencil using the stencil buffer - // rather than the depth buffer can be found below. It works only on GL - // implementations that attach a stencil buffer by default (e.g. Intel, but - // not on Nvidia). - // - // To fix this we would need to change the display create line in - // 'Minecraft.java' file from: - // Display.create((new PixelFormat()).withDepthBits(24)); - // to: - // Display.create((new PixelFormat()).withDepthBits(24).withStencilBits(8)); - // - // Then we could use the stencil buffer and the the circular map would have - // far less problems. - // - // I suppose it would also be possible to detect the number of stencil bits - // available at runtime using GL11.glGetInteger(GL11.GL_STENCIL_BITS) and - // only use the depth buffer stencil algorithm if it returns 0. But this - // doesn't solve the problem of the stencil buffer not being initialized by - // default on some systems. - - /*public static void setCircularStencil(double x, double y, double r) { - GL11.glEnable(GL11.GL_STENCIL_TEST); - // disable drawing to the color and depth buffers. - // circle will only be drawn to stencil buffer. - GL11.glColorMask(false, false, false, false); - GL11.glDepthMask(false); - // set up stencil func and op so that a 1 is always written to the stencil buffer - // whenever a pixel is drawn. - GL11.glStencilFunc(GL11.GL_NEVER, 1, 0x01); - // replace stencil buffer value with 1 whenever stencil test fails. - // keep stencil buffer value otherwise. - GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_KEEP, GL11.GL_KEEP); - // enable writing to 8 bits of the stencil buffer - GL11.glStencilMask(0x01); - // clear stencil buffer, with mask 0xff - GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); - // draw stencil pattern - Render.setColour(0xffffffff); - Render.drawCircle(x, y, r); - - // re-enable drawing to colour and depth buffers - GL11.glColorMask(true, true, true, true); - // probably shouldn't enable? -> GL11.glDepthMask(true); - // disable writing to stencil buffer - GL11.glStencilMask(0x00); - // draw only when stencil buffer value == 1 (inside circle) - GL11.glStencilFunc(GL11.GL_EQUAL, 1, 0x01); - } - - public static void disableStencil() { - GL11.glDisable(GL11.GL_STENCIL_TEST); - }*/ -} \ No newline at end of file diff --git a/src/main/java/mapwriter/Texture.java b/src/main/java/mapwriter/Texture.java deleted file mode 100644 index b4944b4..0000000 --- a/src/main/java/mapwriter/Texture.java +++ /dev/null @@ -1,155 +0,0 @@ -package mapwriter; - -import java.nio.IntBuffer; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -public class Texture { - - private int id; - public final int w; - public final int h; - private final IntBuffer pixelBuf; - - // allocate new texture and fill from IntBuffer - public Texture(int w, int h, int fillColour, int minFilter, int maxFilter, int textureWrap) { - this.id = GL11.glGenTextures(); - this.w = w; - this.h = h; - this.pixelBuf = MwUtil.allocateDirectIntBuffer(w * h); - this.fillRect(0, 0, w, h, fillColour); - this.pixelBuf.position(0); - this.bind(); - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, w, h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - this.setTexParameters(minFilter, maxFilter, textureWrap); - } - - public Texture(int w, int h, int fillColour) { - this(w, h, fillColour, GL11.GL_LINEAR, GL11.GL_NEAREST, GL12.GL_CLAMP_TO_EDGE); - } - - // create from existing texture - public Texture(int id) { - this.id = id; - this.bind(); - this.w = Render.getTextureWidth(); - this.h = Render.getTextureHeight(); - this.pixelBuf = MwUtil.allocateDirectIntBuffer(this.w * this.h); - this.getPixelsFromExistingTexture(); - MwUtil.log("created new MwTexture from GL texture id %d (%dx%d) (%d pixels)", this.id, this.w, this.h, this.pixelBuf.limit()); - } - - // free up the resources used by the GL texture - public synchronized void close() { - if (this.id != 0) { - try { - GL11.glDeleteTextures(this.id); - } catch (NullPointerException e) { - MwUtil.log("MwTexture.close: null pointer exception (texture %d)", this.id); - } - this.id = 0; - } - } - - public void setPixelBufPosition(int i) { - this.pixelBuf.position(i); - } - - public void pixelBufPut(int pixel) { - this.pixelBuf.put(pixel); - } - - public synchronized void fillRect(int x, int y, int w, int h, int colour) { - int offset = (y * this.w) + x; - for (int j = 0; j < h; j++) { - this.pixelBuf.position(offset + (j * this.w)); - for (int i = 0; i < w; i++) { - this.pixelBuf.put(colour); - } - } - } - - // Copy a rectangular sub-region of dimensions 'w' x 'h' from the pixel buffer to the array 'pixels'. - public synchronized void getRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { - int bufOffset = (y * this.w) + x; - for (int i = 0; i < h; i++) { - this.pixelBuf.position(bufOffset + (i * this.w)); - this.pixelBuf.get(pixels, offset + (i * scanSize), w); - } - } - - // Copy a rectangular sub-region of dimensions 'w' x 'h' from the array 'pixels' to the pixel buffer. - public synchronized void setRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { - int bufOffset = (y * this.w) + x; - for (int i = 0; i < h; i++) { - this.pixelBuf.position(bufOffset + (i * this.w)); - this.pixelBuf.put(pixels, offset + (i * scanSize), w); - } - } - - public synchronized void setRGB(int x, int y, int colour) { - this.pixelBuf.put((y * this.w) + x, colour); - } - - public synchronized int getRGB(int x, int y) { - return this.pixelBuf.get((y * this.w) + x); - } - - public void bind() { - GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.id); - } - - // set texture scaling and wrapping parameters - public void setTexParameters(int minFilter, int maxFilter, int textureWrap) { - this.bind(); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, textureWrap); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, textureWrap); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, minFilter); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, maxFilter); - } - - public void setLinearScaling(boolean enabled) { - this.bind(); - if (enabled) { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - } else { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); - } - } - - // update texture from pixels in pixelBuf - public synchronized void updateTextureArea(int x, int y, int w, int h) { - try { - this.bind(); - GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, this.w); - this.pixelBuf.position((y * this.w) + x); - GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); - } catch (NullPointerException e) { - MwUtil.log("MwTexture.updatePixels: null pointer exception (texture %d)", this.id); - } - } - - public synchronized void updateTexture() { - this.bind(); - this.pixelBuf.position(0); - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, this.w, this.h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - } - - // copy pixels from GL texture to pixelBuf - private synchronized void getPixelsFromExistingTexture() { - try { - this.bind(); - this.pixelBuf.clear(); - GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); - // getTexImage does not seem to advance the buffer position, so flip does not work here - // this.pixelBuf.flip() - this.pixelBuf.limit(this.w * this.h); - } catch (NullPointerException e) { - MwUtil.log("MwTexture.getPixels: null pointer exception (texture %d)", this.id); - } - } -} diff --git a/src/main/java/mapwriter/api/IMwChunkOverlay.java b/src/main/java/mapwriter/api/IMwChunkOverlay.java deleted file mode 100644 index 4fa51d8..0000000 --- a/src/main/java/mapwriter/api/IMwChunkOverlay.java +++ /dev/null @@ -1,12 +0,0 @@ -package mapwriter.api; - -import java.awt.Point; - -public interface IMwChunkOverlay { - public Point getCoordinates(); - public int getColor(); - public float getFilling(); - public boolean hasBorder(); - public float getBorderWidth(); - public int getBorderColor(); -} diff --git a/src/main/java/mapwriter/api/IMwDataProvider.java b/src/main/java/mapwriter/api/IMwDataProvider.java deleted file mode 100644 index 5ff9505..0000000 --- a/src/main/java/mapwriter/api/IMwDataProvider.java +++ /dev/null @@ -1,31 +0,0 @@ -package mapwriter.api; - -import java.util.ArrayList; - -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; - -public interface IMwDataProvider { - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ); - - //Returns what should be added to the status bar by the addon. - public String getStatusString(int dim, int bX, int bY, int bZ); - - //Call back for middle click. - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview); - - //Callback for dimension change on the map - public void onDimensionChanged(int dimension, MapView mapview); - - public void onMapCenterChanged(double vX, double vZ, MapView mapview); - - public void onZoomChanged(int level, MapView mapview); - - public void onOverlayActivated(MapView mapview); - - public void onOverlayDeactivated(MapView mapview); - - public void onDraw(MapView mapview, MapMode mapmode); - - public boolean onMouseInput(MapView mapview, MapMode mapmode); -} diff --git a/src/main/java/mapwriter/api/MwAPI.java b/src/main/java/mapwriter/api/MwAPI.java deleted file mode 100644 index 01efc6d..0000000 --- a/src/main/java/mapwriter/api/MwAPI.java +++ /dev/null @@ -1,85 +0,0 @@ -package mapwriter.api; - -import java.util.ArrayList; -import java.util.Collection; - -import com.google.common.collect.HashBiMap; - -public class MwAPI { - - private static HashBiMap dataProviders = HashBiMap.create(); - private static IMwDataProvider currentProvider = null; - private static ArrayList providerKeys = new ArrayList(); - - public static void registerDataProvider(String name, IMwDataProvider handler){ - dataProviders.put(name, handler); - providerKeys.add(name); - } - - public static Collection getDataProviders(){ - return dataProviders.values(); - } - - // Returns the data provider based on its name // - public static IMwDataProvider getDataProvider(String name){ - return dataProviders.get(name); - } - - // Returns the name based on the data provider // - public static String getProviderName(IMwDataProvider provider){ - return dataProviders.inverse().get(provider); - } - - public static IMwDataProvider getCurrentDataProvider(){ - return currentProvider; - } - - public static String getCurrentProviderName(){ - if (currentProvider != null) - return getProviderName(currentProvider); - else - return "None"; - } - - public static IMwDataProvider setCurrentDataProvider(String name){ - currentProvider = dataProviders.get(name); - return currentProvider; - } - - public static IMwDataProvider setCurrentDataProvider(IMwDataProvider provider){ - currentProvider = provider; - return currentProvider; - } - - public static IMwDataProvider setNextProvider(){ - if (currentProvider != null){ - int index = providerKeys.indexOf(getCurrentProviderName()); - if (index + 1 >= providerKeys.size()){ - currentProvider = null; - } else { - String nextKey = providerKeys.get(index + 1); - currentProvider = getDataProvider(nextKey); - } - } else { - if (providerKeys.size() > 0) - currentProvider = getDataProvider(providerKeys.get(0)); - } - return currentProvider; - } - - public static IMwDataProvider setPrevProvider(){ - if (currentProvider != null){ - int index = providerKeys.indexOf(getCurrentProviderName()); - if (index - 1 < 0){ - currentProvider = null; - } else { - String prevKey = providerKeys.get(index - 1); - currentProvider = getDataProvider(prevKey); - } - } else { - if (providerKeys.size() > 0) - currentProvider = getDataProvider(providerKeys.get(providerKeys.size() - 1)); - } - return currentProvider; - } -} diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java deleted file mode 100644 index 2ffdb17..0000000 --- a/src/main/java/mapwriter/forge/ClientProxy.java +++ /dev/null @@ -1,37 +0,0 @@ -package mapwriter.forge; - -import java.io.File; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.overlay.OverlayGrid; -import mapwriter.overlay.OverlaySlime; -import net.minecraft.client.Minecraft; -import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.common.FMLCommonHandler; - -public class ClientProxy extends CommonProxy { - - private MwConfig config; - - public void preInit(File configFile) { - this.config = new MwConfig(configFile); - } - - public void load() { - Mw mw = new Mw(this.config); - MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); - FMLCommonHandler.instance().bus().register(new MwKeyHandler()); - // temporary workaround for user defined key bindings not being loaded - // at game start. see https://github.com/MinecraftForge/FML/issues/378 - // for more info. - Minecraft.getMinecraft().gameSettings.loadOptions(); - } - - public void postInit() { - MwAPI.registerDataProvider("Slime", new OverlaySlime()); - MwAPI.registerDataProvider("Grid", new OverlayGrid()); - //MwAPI.registerDataProvider("Checker", new OverlayChecker()); - //MwAPI.setCurrentDataProvider("Slime"); - } -} diff --git a/src/main/java/mapwriter/forge/CommonProxy.java b/src/main/java/mapwriter/forge/CommonProxy.java deleted file mode 100644 index 6ef4209..0000000 --- a/src/main/java/mapwriter/forge/CommonProxy.java +++ /dev/null @@ -1,9 +0,0 @@ -package mapwriter.forge; - -import java.io.File; - -public class CommonProxy { - public void preInit(File configFile) {} - public void load() {} - public void postInit() {} -} diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java deleted file mode 100644 index 69e38c3..0000000 --- a/src/main/java/mapwriter/forge/EventHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -package mapwriter.forge; - -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import mapwriter.Mw; -import mapwriter.overlay.OverlaySlime; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraftforge.client.event.ClientChatReceivedEvent; -import net.minecraftforge.event.world.ChunkEvent; -import net.minecraftforge.event.world.WorldEvent; - -public class EventHandler { - - Mw mw; - - public EventHandler(Mw mw) { - this.mw = mw; - } - - @SubscribeEvent - public void eventChunkLoad(ChunkEvent.Load event){ - if(event.world.isRemote){ - this.mw.onChunkLoad(event.getChunk()); - } - } - - @SubscribeEvent - public void eventChunkUnload(ChunkEvent.Unload event){ - if(event.world.isRemote){ - this.mw.onChunkUnload(event.getChunk()); - } - } - - @SubscribeEvent - public void eventWorldLoad(WorldEvent.Load event){ - if(event.world.isRemote){ - this.mw.onWorldLoad(event.world); - } - } - - @SubscribeEvent - public void eventWorldUnload(WorldEvent.Unload event){ - if(event.world.isRemote){ - this.mw.onWorldUnload(event.world); - } - } - - @SubscribeEvent - public void onClientChat(ClientChatReceivedEvent event){ - if(OverlaySlime.seedFound || !OverlaySlime.seedAsked) return; - try{ //I don't want to crash the game when we derp up in here - if(event.message instanceof ChatComponentTranslation){ - ChatComponentTranslation component = (ChatComponentTranslation) event.message; - if(component.getKey().equals("commands.seed.success")){ - OverlaySlime.setSeed((Long) component.getFormatArgs()[0]); - event.setCanceled(true); //Don't let the player see this seed message, They didn't do /seed, we did - } - }else if(event.message instanceof ChatComponentText){ - ChatComponentText component = (ChatComponentText) event.message; - String msg = component.getUnformattedText(); - if(msg.startsWith("Seed: ")){ //Because bukkit... - OverlaySlime.setSeed(Long.parseLong(msg.substring(6))); - event.setCanceled(true); //Don't let the player see this seed message, They didn't do /seed, we did - } - } - }catch(Exception e){ - //e.printStackTrace(); - } - } -} diff --git a/src/main/java/mapwriter/forge/MwConfig.java b/src/main/java/mapwriter/forge/MwConfig.java deleted file mode 100644 index 35673db..0000000 --- a/src/main/java/mapwriter/forge/MwConfig.java +++ /dev/null @@ -1,135 +0,0 @@ -package mapwriter.forge; - -import java.io.File; -import java.util.List; - -import mapwriter.MwUtil; -import net.minecraftforge.common.config.Configuration; - -public class MwConfig extends Configuration { - - public MwConfig(File file) { - super(file, true); - } - - public boolean getOrSetBoolean(String category, String key, boolean defaultValue) { - return this.get(category, key, defaultValue ? 1 : 0).getInt() != 0; - } - - public void setBoolean(String category, String key, boolean value) { - this.get(category, key, value).set(value ? 1 : 0); - } - - public int getOrSetInt(String category, String key, int defaultValue, int minValue, int maxValue) { - int value = this.get(category, key, defaultValue).getInt(); - return Math.min(Math.max(minValue, value), maxValue); - } - - public void setInt(String category, String key, int value) { - this.get(category, key, value).set(value); - } - - public long getColour(String category, String key) { - long value = -1; - if (this.hasKey(category, key)) { - try { - String valueString = this.get(category, key, "").getString(); - if (valueString.length() > 0) { - value = Long.parseLong(valueString, 16); - value &= 0xffffffffL; - } - } catch (NumberFormatException e) { - MwUtil.log("error: could not read colour from config file %s:%s", category, key); - value = -1; - } - } - return value; - } - - public int getColour(String category, String key, int value) { - long valueLong = this.getColour(category, key); - if (valueLong >= 0L) { - value = (int) (valueLong & 0xffffffffL); - } - return value; - } - - public int getOrSetColour(String category, String key, int value) { - long valueLong = this.getColour(category, key); - if (valueLong >= 0L) { - value = (int) (valueLong & 0xffffffffL); - } else { - this.setColour(category, key, value); - } - return value; - } - - public void setColour(String category, String key, int n) { - this.get(category, key, "00000000").set(String.format("%08x", n)); - } - - public void setColour(String category, String key, int n, String comment) { - this.get(category, key, "00000000", comment).set(String.format("%08x", n)); - } - - public String getSingleWord(String category, String key) { - String value = ""; - if (this.hasKey(category, key)) { - value = this.get(category, key, value).getString().trim(); - int firstSpace = value.indexOf(' '); - if (firstSpace >= 0) { - value = value.substring(0, firstSpace); - } - } - return value; - } - - public void setSingleWord(String category, String key, String value, String comment) { - if ((comment != null) && (comment.length() > 0)) { - value = value + " # " + comment; - } - this.get(category, key, value).set(value); - } - - public void getIntList(String category, String key, List list) { - // convert List of integers to integer array to pass as default value - int size = list.size(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) { - array[i] = list.get(i); - } - - // get integer array from config file - int[] arrayFromConfig = null; - try { - arrayFromConfig = this.get(category, key, array).getIntList(); - } catch (Exception e) { - e.printStackTrace(); - arrayFromConfig = null; - } - if (arrayFromConfig != null) { - array = arrayFromConfig; - } - - // convert integer array back to List of integers - list.clear(); - for (int i = 0; i < array.length; i++) { - list.add(array[i]); - } - } - - public void setIntList(String category, String key, List list) { - // convert List of integers to integer array - int size = list.size(); - String[] array = new String[size]; - for (int i = 0; i < size; i++) { - array[i] = list.get(i).toString(); - } - // write integer array to config file - try { - this.get(category, key, array).set(array); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java deleted file mode 100644 index 9d1d26a..0000000 --- a/src/main/java/mapwriter/forge/MwForge.java +++ /dev/null @@ -1,77 +0,0 @@ -package mapwriter.forge; - -import java.net.InetSocketAddress; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import mapwriter.Mw; -import net.minecraft.client.Minecraft; -import net.minecraftforge.client.event.RenderGameOverlayEvent; -import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Mod; -import cpw.mods.fml.common.Mod.EventHandler; -import cpw.mods.fml.common.Mod.Instance; -import cpw.mods.fml.common.SidedProxy; -import cpw.mods.fml.common.event.FMLInitializationEvent; -import cpw.mods.fml.common.event.FMLPostInitializationEvent; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import cpw.mods.fml.common.network.FMLNetworkEvent; - -@Mod(modid="MapWriter", name="MapWriter", version="2.1.2", acceptableRemoteVersions="*") -public class MwForge { - - @Instance("MapWriter") - public static MwForge instance; - - @SidedProxy(clientSide="mapwriter.forge.ClientProxy", serverSide="mapwriter.forge.CommonProxy") - public static CommonProxy proxy; - - public static Logger logger = LogManager.getLogger("MapWriter"); - - @EventHandler - public void preInit(FMLPreInitializationEvent event) { - FMLCommonHandler.instance().bus().register(this); - MinecraftForge.EVENT_BUS.register(this); - proxy.preInit(event.getSuggestedConfigurationFile()); - } - - @EventHandler - public void load(FMLInitializationEvent event) { - proxy.load(); - } - - @EventHandler - public void postInit(FMLPostInitializationEvent event) { - proxy.postInit(); - } - - @SubscribeEvent - public void renderMap(RenderGameOverlayEvent.Post event){ - if(event.type == RenderGameOverlayEvent.ElementType.ALL){ - Mw.instance.onTick(); - } - } - - @SubscribeEvent - public void onConnected(FMLNetworkEvent.ClientConnectedToServerEvent event){ - if (!event.isLocal) { - InetSocketAddress address = (InetSocketAddress) event.manager.getSocketAddress(); - Mw.instance.setServerDetails(address.getHostName(), address.getPort()); - } - } - - @SubscribeEvent - public void onTick(TickEvent.ClientTickEvent event){ - if (event.phase == TickEvent.Phase.START){ - // run the cleanup code when Mw is loaded and the player becomes null. - // a bit hacky, but simpler than checking if the connection has closed. - if ((Mw.instance.ready) && (Minecraft.getMinecraft().thePlayer == null)) { - Mw.instance.close(); - } - } - } -} diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java deleted file mode 100644 index 32e3ca2..0000000 --- a/src/main/java/mapwriter/forge/MwKeyHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -package mapwriter.forge; - -import mapwriter.Mw; -import net.minecraft.client.settings.KeyBinding; - -import org.lwjgl.input.Keyboard; - -import cpw.mods.fml.client.registry.ClientRegistry; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.InputEvent; - -public class MwKeyHandler { - - public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); - public static KeyBinding keyNewMarker = new KeyBinding("key.mw_new_marker", Keyboard.KEY_INSERT, "Mapwriter"); - public static KeyBinding keyMapMode = new KeyBinding("key.mw_next_map_mode", Keyboard.KEY_N, "Mapwriter"); - public static KeyBinding keyNextGroup = new KeyBinding("key.mw_next_marker_group", Keyboard.KEY_COMMA, "Mapwriter"); - public static KeyBinding keyTeleport = new KeyBinding("key.mw_teleport", Keyboard.KEY_PERIOD, "Mapwriter"); - public static KeyBinding keyZoomIn = new KeyBinding("key.mw_zoom_in", Keyboard.KEY_PRIOR, "Mapwriter"); - public static KeyBinding keyZoomOut = new KeyBinding("key.mw_zoom_out", Keyboard.KEY_NEXT, "Mapwriter"); - public static KeyBinding keyUndergroundMode = new KeyBinding("key.mw_underground_mode", Keyboard.KEY_U, "Mapwriter"); - //public static KeyBinding keyQuickLargeMap = new KeyBinding("key.mw_quick_large_map", Keyboard.KEY_NONE); - - public MwKeyHandler(){ - ClientRegistry.registerKeyBinding(keyMapGui); - ClientRegistry.registerKeyBinding(keyNewMarker); - ClientRegistry.registerKeyBinding(keyMapMode); - ClientRegistry.registerKeyBinding(keyNextGroup); - ClientRegistry.registerKeyBinding(keyTeleport); - ClientRegistry.registerKeyBinding(keyZoomIn); - ClientRegistry.registerKeyBinding(keyZoomOut); - ClientRegistry.registerKeyBinding(keyUndergroundMode); - } - - @SubscribeEvent - public void onKeyPress(InputEvent.KeyInputEvent event){ - if(keyMapGui.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyMapGui.getKeyCode(), false); - Mw.instance.onKeyDown(keyMapGui); - } - if(keyNewMarker.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyNewMarker.getKeyCode(), false); - Mw.instance.onKeyDown(keyNewMarker); - } - if(keyMapMode.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyMapMode.getKeyCode(), false); - Mw.instance.onKeyDown(keyMapMode); - } - if(keyNextGroup.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyNextGroup.getKeyCode(), false); - Mw.instance.onKeyDown(keyNextGroup); - } - if(keyTeleport.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyTeleport.getKeyCode(), false); - Mw.instance.onKeyDown(keyTeleport); - } - if(keyZoomIn.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyZoomIn.getKeyCode(), false); - Mw.instance.onKeyDown(keyZoomIn); - } - if(keyZoomOut.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyZoomOut.getKeyCode(), false); - Mw.instance.onKeyDown(keyZoomOut); - } - if(keyUndergroundMode.getIsKeyPressed()){ - KeyBinding.setKeyBindState(keyUndergroundMode.getKeyCode(), false); - Mw.instance.onKeyDown(keyUndergroundMode); - } - } -} diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java deleted file mode 100644 index bb331f9..0000000 --- a/src/main/java/mapwriter/gui/MwGui.java +++ /dev/null @@ -1,641 +0,0 @@ -package mapwriter.gui; - -import java.awt.Point; - -import mapwriter.Mw; -import mapwriter.MwUtil; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.forge.MwKeyHandler; -import mapwriter.map.MapRenderer; -import mapwriter.map.MapView; -import mapwriter.map.Marker; -import mapwriter.map.mapmode.FullScreenMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.tasks.MergeTask; -import mapwriter.tasks.RebuildRegionsTask; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGui extends GuiScreen { - private Mw mw; - private MapMode mapMode; - private MapView mapView; - private MapRenderer map; - - private final static double PAN_FACTOR = 0.3D; - - private static final int menuY = 5; - private static final int menuX = 5; - - private int mouseLeftHeld = 0; - //private int mouseRightHeld = 0; - //private int mouseMiddleHeld = 0; - private int mouseLeftDragStartX = 0; - private int mouseLeftDragStartY = 0; - private double viewXStart; - private double viewZStart; - private Marker movingMarker = null; - private int movingMarkerXStart = 0; - private int movingMarkerZStart = 0; - private int mouseBlockX = 0; - private int mouseBlockY = 0; - private int mouseBlockZ = 0; - - private int exit = 0; - - private Label helpLabel; - private Label optionsLabel; - private Label dimensionLabel; - private Label groupLabel; - private Label overlayLabel; - - class Label { - int x = 0, y = 0, w = 1, h = 12; - public Label() { - } - - public void draw(int x, int y, String s) { - this.x = x; - this.y = y; - this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; - MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); - MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); - } - - public void drawToRightOf(Label label, String s) { - this.draw(label.x + label.w + 5, label.y, s); - } - - public boolean posWithin(int x, int y) { - return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); - } - } - - public MwGui(Mw mw) { - this.mw = mw; - this.mapMode = new FullScreenMapMode(mw.config); - this.mapView = new MapView(this.mw); - this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); - - this.mapView.setDimension(this.mw.miniMap.view.getDimension()); - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - this.mapView.setZoomLevel(0); - - this.helpLabel = new Label(); - this.optionsLabel = new Label(); - this.dimensionLabel = new Label(); - this.groupLabel = new Label(); - this.overlayLabel = new Label(); - } - - public MwGui(Mw mw, int dim, int x, int z){ - this(mw); - this.mapView.setDimension(dim); - this.mapView.setViewCentreScaled(x, z, dim); - this.mapView.setZoomLevel(0); - } - - // called when gui is displayed and every time the screen - // is resized - public void initGui() { - } - - // called when a button is pressed - protected void actionPerformed(GuiButton button) { - - } - - @Override - public boolean doesGuiPauseGame() - { - return false; - } - - public void exitGui() { - //MwUtil.log("closing GUI"); - // set the mini map dimension to the GUI map dimension when closing - this.mw.miniMap.view.setDimension(this.mapView.getDimension()); - this.mapMode.close(); - Keyboard.enableRepeatEvents(false); - this.mc.displayGuiScreen((GuiScreen) null); - this.mc.setIngameFocus(); - this.mc.getSoundHandler().resumeSounds(); - } - - // get a marker near the specified block pos if it exists. - // the maxDistance is based on the view width so that you need to click closer - // to a marker when zoomed in to select it. - public Marker getMarkerNearScreenPos(int x, int y) { - Marker nearMarker = null; - for (Marker marker : this.mw.markerManager.visibleMarkerList) { - if (marker.screenPos != null) { - if (marker.screenPos.distanceSq(x, y) < 6.0) { - nearMarker = marker; - } - } - } - return nearMarker; - } - - public int getHeightAtBlockPos(int bX, int bZ) { - int bY = 0; - int worldDimension = this.mw.mc.theWorld.provider.dimensionId; - if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { - bY = this.mw.mc.theWorld.getChunkFromBlockCoords(bX, bZ).getHeightValue(bX & 0xf, bZ & 0xf); - } - return bY; - } - - public boolean isPlayerNearScreenPos(int x, int y) { - Point.Double p = this.map.playerArrowScreenPos; - return p.distanceSq(x, y) < 9.0; - } - - public void deleteSelectedMarker() { - if (this.mw.markerManager.selectedMarker != null) { - //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); - this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); - this.mw.markerManager.update(); - this.mw.markerManager.selectedMarker = null; - } - } - - public void mergeMapViewToImage() { - this.mw.chunkManager.saveChunks(); - this.mw.executor.addTask(new MergeTask(this.mw.regionManager, - (int) this.mapView.getX(), - (int) this.mapView.getZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension(), - this.mw.worldDir, - this.mw.worldDir.getName())); - - MwUtil.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); - } - - public void regenerateView() { - MwUtil.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ())); - this.mw.reloadBlockColours(); - this.mw.executor.addTask(new RebuildRegionsTask( - this.mw, - (int) this.mapView.getMinX(), - (int) this.mapView.getMinZ(), - (int) this.mapView.getWidth(), - (int) this.mapView.getHeight(), - this.mapView.getDimension())); - } - - // c is the ascii equivalent of the key typed. - // key is the lwjgl key code. - protected void keyTyped(char c, int key) { - //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); - switch(key) { - case Keyboard.KEY_ESCAPE: - this.exitGui(); - break; - - case Keyboard.KEY_DELETE: - this.deleteSelectedMarker(); - break; - - case Keyboard.KEY_SPACE: - // next marker group - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - break; - - case Keyboard.KEY_C: - // cycle selected marker colour - if (this.mw.markerManager.selectedMarker != null) { - this.mw.markerManager.selectedMarker.colourNext(); - } - break; - - case Keyboard.KEY_N: - // select next visible marker - this.mw.markerManager.selectNextMarker(); - break; - - case Keyboard.KEY_HOME: - // centre map on player - this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); - break; - - case Keyboard.KEY_END: - // centre map on selected marker - if (this.mw.markerManager.selectedMarker != null) { - this.mapView.setViewCentreScaled( - this.mw.markerManager.selectedMarker.x, - this.mw.markerManager.selectedMarker.z, - 0 - ); - } - break; - - case Keyboard.KEY_P: - this.mergeMapViewToImage(); - this.exitGui(); - break; - - case Keyboard.KEY_T: - if (this.mw.markerManager.selectedMarker != null) { - this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); - this.exitGui(); - } else { - this.mc.displayGuiScreen( - new MwGuiTeleportDialog( - this, - this.mw, - this.mapView, - this.mouseBlockX, - this.mw.defaultTeleportHeight, - this.mouseBlockZ - ) - ); - } - break; - - case Keyboard.KEY_LEFT: - this.mapView.panView(-PAN_FACTOR, 0); - break; - case Keyboard.KEY_RIGHT: - this.mapView.panView(PAN_FACTOR, 0); - break; - case Keyboard.KEY_UP: - this.mapView.panView(0, -PAN_FACTOR); - break; - case Keyboard.KEY_DOWN: - this.mapView.panView(0, PAN_FACTOR); - break; - - case Keyboard.KEY_R: - this.regenerateView(); - this.exitGui(); - break; - - //case Keyboard.KEY_9: - // MwUtil.log("refreshing maptexture"); - // this.mw.mapTexture.updateTexture(); - // break; - - default: - if (key == MwKeyHandler.keyMapGui.getKeyCode()) { - // exit on the next tick - this.exit = 1; - } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { - this.mapView.adjustZoomLevel(-1); - } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { - this.mapView.adjustZoomLevel(1); - } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { - this.mw.markerManager.nextGroup(); - this.mw.markerManager.update(); - } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { - this.mw.toggleUndergroundMode(); - this.mapView.setUndergroundMode(this.mw.undergroundMode); - } - break; - } - } - - // override GuiScreen's handleMouseInput to process - // the scroll wheel. - @Override - public void handleMouseInput() { - if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) - return; - - int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - int direction = Mouse.getEventDWheel(); - if (direction != 0) { - this.mouseDWheelScrolled(x, y, direction); - } - super.handleMouseInput(); - } - - // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB - protected void mouseClicked(int x, int y, int button) { - //MwUtil.log("MwGui.mouseClicked(%d, %d, %d)", x, y, button); - - //int bX = this.mouseToBlockX(x); - //int bZ = this.mouseToBlockZ(y); - //int bY = this.getHeightAtBlockPos(bX, bZ); - - Marker marker = this.getMarkerNearScreenPos(x, y); - Marker prevMarker = this.mw.markerManager.selectedMarker; - - if (button == 0) { - if (this.dimensionLabel.posWithin(x, y)) { - this.mc.displayGuiScreen( - new MwGuiDimensionDialog( - this, - this.mw, - this.mapView, - this.mapView.getDimension() - ) - ); - } else if (this.optionsLabel.posWithin(x, y)) { - this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); - } else { - this.mouseLeftHeld = 1; - this.mouseLeftDragStartX = x; - this.mouseLeftDragStartY = y; - this.mw.markerManager.selectedMarker = marker; - - if ((marker != null) && (prevMarker == marker)) { - // clicked previously selected marker. - // start moving the marker. - this.movingMarker = marker; - this.movingMarkerXStart = marker.x; - this.movingMarkerZStart = marker.z; - } - } - - } else if (button == 1) { - //this.mouseRightHeld = 1; - if ((marker != null) && (prevMarker == marker)) { - // right clicked previously selected marker. - // edit the marker - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - marker - ) - ); - - } else if (marker == null) { - // open new marker dialog - String group = this.mw.markerManager.getVisibleGroupName(); - if (group.equals("none")) { - group = "group"; - } - - int mx, my, mz; - if (this.isPlayerNearScreenPos(x, y)) { - // marker at player's locations - mx = this.mw.playerXInt; - my = this.mw.playerYInt; - mz = this.mw.playerZInt; - - } else { - // marker at mouse pointer location - mx = this.mouseBlockX; - my = (this.mouseBlockY > 0) ? this.mouseBlockY : this.mw.defaultTeleportHeight; - mz = this.mouseBlockZ; - } - this.mc.displayGuiScreen( - new MwGuiMarkerDialog( - this, - this.mw.markerManager, - "", - group, - mx, my, mz, - this.mapView.getDimension() - ) - ); - } - } - - else if (button == 2) { - Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); - } - - this.viewXStart = this.mapView.getX(); - this.viewZStart = this.mapView.getZ(); - //this.viewSizeStart = this.mapManager.getViewSize(); - } - - // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB - // not called on mouse movement. - protected void mouseMovedOrUp(int x, int y, int button) { - //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); - if (button == 0) { - this.mouseLeftHeld = 0; - this.movingMarker = null; - } else if (button == 1) { - //this.mouseRightHeld = 0; - } - } - - // zoom on mouse direction wheel scroll - public void mouseDWheelScrolled(int x, int y, int direction) { - Marker marker = this.getMarkerNearScreenPos(x, y); - if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { - if (direction > 0) { - marker.colourNext(); - } else { - marker.colourPrev(); - } - - } else if (this.dimensionLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mapView.nextDimension(this.mw.dimensionList, n); - - } else if (this.groupLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - this.mw.markerManager.nextGroup(n); - this.mw.markerManager.update(); - } else if (this.overlayLabel.posWithin(x, y)) { - int n = (direction > 0) ? 1 : -1; - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); - - if (n == 1) - MwAPI.setNextProvider(); - else - MwAPI.setPrevProvider(); - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); - - } else { - int zF = (direction > 0) ? -1 : 1; - this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); - } - } - - // called every frame - public void updateScreen() { - //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); - // need to wait one tick before exiting so that the game doesn't - // handle the 'm' key and re-open the gui. - // there should be a better way. - if (this.exit > 0) { - this.exit++; - } - if (this.exit > 2) { - this.exitGui(); - } - super.updateScreen(); - } - - public void drawStatus(int bX, int bY, int bZ) { - String s; - if (bY != 0) { - s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); - } else { - s = String.format("cursor: (%d, ?, %d)", bX, bZ); - } - if (this.mc.theWorld != null) { - if (!this.mc.theWorld.getChunkFromBlockCoords(bX, bZ).isEmpty()) { - s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(bX, bZ).biomeName); - } - } - - /*if (this.mw.markerManager.selectedMarker != null) { - s += ", current marker: " + this.mw.markerManager.selectedMarker.name; - }*/ - - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) - s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); - - drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); - this.drawCenteredString(this.fontRendererObj, - s, this.width / 2, this.height - 18, 0xffffff); - } - - public void drawHelp() { - drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); - this.fontRendererObj.drawSplitString( - "Keys:\n\n" + - " Space\n" + - " Delete\n" + - " C\n" + - " Home\n" + - " End\n" + - " N\n" + - " T\n" + - " P\n" + - " R\n" + - " U\n\n" + - "Left click drag or arrow keys pan the map.\n" + - "Mouse wheel or Page Up/Down zooms map.\n" + - "Right click map to create a new marker.\n" + - "Left click drag a selected marker to move it.\n" + - "Mouse wheel over selected marker to cycle colour.\n" + - "Mouse wheel over dimension or group box to cycle.\n", - 15, 24, this.width - 30, 0xffffff); - this.fontRendererObj.drawSplitString( - "| Next marker group\n" + - "| Delete selected marker\n" + - "| Cycle selected marker colour\n" + - "| Centre map on player\n" + - "| Centre map on selected marker\n" + - "| Select next marker\n" + - "| Teleport to cursor or selected marker\n" + - "| Save PNG of visible map area\n" + - "| Regenerate visible map area from region files\n" + - "| Underground map mode\n", - 75, 42, this.width - 90, 0xffffff); - } - - public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { - String desc = String.format("(%d, %d, %d)", mX, mY, mZ); - int stringW = Math.max( - this.fontRendererObj.getStringWidth(title), - this.fontRendererObj.getStringWidth(desc)); - - x = Math.min(x, this.width - (stringW + 16)); - y = Math.min(Math.max(10, y), this.height - 14); - - drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); - this.drawString(this.fontRendererObj, - title, - x + 10, y - 8, 0xffffff); - this.drawString(this.fontRendererObj, - desc, - x + 10, y + 4, 0xcccccc); - } - - // also called every frame - public void drawScreen(int mouseX, int mouseY, float f) { - - this.drawDefaultBackground(); - double xOffset = 0.0; - double yOffset = 0.0; - //double zoomFactor = 1.0; - - if (this.mouseLeftHeld > 2) { - xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; - yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; - - if (this.movingMarker != null) { - double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); - this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); - this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); - } else { - this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); - } - } - - if (this.mouseLeftHeld > 0) { - this.mouseLeftHeld++; - } - - // draw the map - this.map.draw(); - - // let the renderEngine know we have changed the texture. - //this.mc.renderEngine.resetBoundTexture(); - - // get the block the mouse is currently hovering over - Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); - this.mouseBlockX = p.x; - this.mouseBlockZ = p.y; - this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); - - // draw name of marker under mouse cursor - Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); - if (marker != null) { - this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); - } - - // draw name of player under mouse cursor - if (this.isPlayerNearScreenPos(mouseX, mouseY)) { - this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayName(), - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt); - } - - // draw status message - this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); - - // draw labels - this.helpLabel.draw(menuX, menuY, "[help]"); - this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); - String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); - this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); - String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); - this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); - String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); - this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); - - // help message on mouse over - if (this.helpLabel.posWithin(mouseX, mouseY)) { - this.drawHelp(); - } - - super.drawScreen(mouseX, mouseY, f); - } -} - diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java deleted file mode 100644 index 18d8c84..0000000 --- a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java +++ /dev/null @@ -1,35 +0,0 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import mapwriter.map.MapView; -import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGuiDimensionDialog extends MwGuiTextDialog { - - final Mw mw; - final MapView mapView; - final int dimension; - - public MwGuiDimensionDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int dimension) { - super(parentScreen, "Set dimension to:", "" + dimension, "invalid dimension"); - this.mw = mw; - this.mapView = mapView; - this.dimension = dimension; - } - - @Override - public boolean submit() { - boolean done = false; - int dimension = this.getInputAsInt(); - if (this.inputValid) { - this.mapView.setDimensionAndAdjustZoom(dimension); - this.mw.miniMap.view.setDimension(dimension); - this.mw.addDimension(dimension); - done = true; - } - return done; - } -} diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java deleted file mode 100644 index 2e57115..0000000 --- a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java +++ /dev/null @@ -1,105 +0,0 @@ -package mapwriter.gui; - -import mapwriter.map.Marker; -import mapwriter.map.MarkerManager; -import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGuiMarkerDialog extends MwGuiTextDialog { - private final MarkerManager markerManager; - private Marker editingMarker; - private String markerName = "name"; - private String markerGroup = "group"; - private int markerX = 0; - private int markerY = 80; - private int markerZ = 0; - private int state = 0; - private int dimension = 0; - - public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) { - super(parentScreen, "Marker Name:", markerName, "marker must have a name"); - this.markerManager = markerManager; - this.markerName = markerName; - this.markerGroup = markerGroup; - this.markerX = x; - this.markerY = y; - this.markerZ = z; - this.editingMarker = null; - this.dimension = dimension; - } - - public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) { - super(parentScreen, "Edit Marker Name:", editingMarker.name, "marker must have a name"); - this.markerManager = markerManager; - this.editingMarker = editingMarker; - this.markerName = editingMarker.name; - this.markerGroup = editingMarker.groupName; - this.markerX = editingMarker.x; - this.markerY = editingMarker.y; - this.markerZ = editingMarker.z; - this.dimension = editingMarker.dimension; - } - - @Override - public boolean submit() { - boolean done = false; - switch(this.state) { - case 0: - this.markerName = this.getInputAsString(); - if (this.inputValid) { - this.title = "Marker Group:"; - this.setText(this.markerGroup); - this.error = "marker must have a group name"; - this.state++; - } - break; - case 1: - this.markerGroup = this.getInputAsString(); - if (this.inputValid) { - this.title = "Marker X:"; - this.setText("" + this.markerX); - this.error = "invalid value"; - this.state++; - } - break; - case 2: - this.markerX = this.getInputAsInt(); - if (this.inputValid) { - this.title = "Marker Y:"; - this.setText("" + this.markerY); - this.error = "invalid value"; - this.state++; - } - break; - case 3: - this.markerY = this.getInputAsInt(); - if (this.inputValid) { - this.title = "Marker Z:"; - this.setText("" + this.markerZ); - this.error = "invalid value"; - this.state++; - } - break; - case 4: - this.markerZ = this.getInputAsInt(); - if (this.inputValid) { - done = true; - int colour = Marker.getCurrentColour(); - if (this.editingMarker != null) { - colour = this.editingMarker.colour; - this.markerManager.delMarker(this.editingMarker); - this.editingMarker = null; - } - this.markerManager.addMarker(this.markerName, this.markerGroup, - this.markerX, this.markerY, this.markerZ, - this.dimension, colour); - this.markerManager.setVisibleGroupName(this.markerGroup); - this.markerManager.update(); - } - break; - } - return done; - } -} diff --git a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java deleted file mode 100644 index a1e35a5..0000000 --- a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java +++ /dev/null @@ -1,232 +0,0 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiSlot; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.util.ResourceLocation; - -public class MwGuiOptionSlot extends GuiSlot { - - //private GuiScreen parentScreen; - private Minecraft mc; - private Mw mw; - - private int mouseX = 0; - private int mouseY = 0; - - private int miniMapPositionIndex = 0; - private static final String[] miniMapPositionStringArray = { - "unchanged", - "top right", - "top left", - "bottom right", - "bottom left" - }; - private static final String[] coordsModeStringArray = { - "disabled", - "small", - "large" - }; - private static final String[] backgroundModeStringArray = { - "none", - "static", - "panning" - }; - - private GuiButton[] buttons = new GuiButton[12]; - - static final ResourceLocation WIDGET_TEXTURE_LOC = new ResourceLocation("textures/gui/widgets.png"); - - public void updateButtonLabel(int i) { - switch(i) { - case 0: - this.buttons[i].displayString = "Draw coords: " + coordsModeStringArray[this.mw.coordsMode]; - break; - case 1: - this.buttons[i].displayString = "Circular mode: " + this.mw.miniMap.smallMapMode.circular; - break; - case 2: - this.buttons[i].displayString = "Texture size: " + this.mw.configTextureSize; - break; - case 3: - this.buttons[i].displayString = "Texture scaling: " + (this.mw.linearTextureScalingEnabled ? "linear" : "nearest"); - break; - case 4: - this.buttons[i].displayString = "Trail markers: " + (this.mw.playerTrail.enabled); - break; - case 5: - this.buttons[i].displayString = "Map colours: " + (this.mw.useSavedBlockColours ? "frozen" : "auto"); - break; - case 6: - this.buttons[i].displayString = "Max draw distance: " + Math.round(Math.sqrt(this.mw.maxChunkSaveDistSq)); - break; - case 7: - this.buttons[i].displayString = "Mini map size: " + this.mw.miniMap.smallMapMode.heightPercent; - break; - case 8: - this.buttons[i].displayString = "Mini map position: " + miniMapPositionStringArray[this.miniMapPositionIndex]; - break; - case 9: - this.buttons[i].displayString = "Map pixel snapping: " + (this.mw.mapPixelSnapEnabled ? "enabled" : "disabled"); - break; - case 10: - this.buttons[i].displayString = "Max death markers: " + this.mw.maxDeathMarkers; - break; - case 11: - this.buttons[i].displayString = "Background mode: " + backgroundModeStringArray[this.mw.backgroundTextureMode]; - break; - //case 11: - // this.buttons[i].displayString = "Map Lighting: " + (this.mw.lightingEnabled ? "enabled" : "disabled"); - // break; - default: - break; - } - } - - public MwGuiOptionSlot(GuiScreen parentScreen, Minecraft mc, Mw mw) { - // GuiSlot(minecraft, width, height, top, bottom, slotHeight) - super(mc, parentScreen.width, parentScreen.height, 16, parentScreen.height - 32, 25); - //this.parentScreen = parentScreen; - this.mw = mw; - this.mc = mc; - for (int i = 0; i < this.buttons.length; i++) { - this.buttons[i] = new GuiButton(300 + i, 0, 0, ""); - this.updateButtonLabel(i); - } - } - - protected boolean keyTyped(char c, int k) { - return false; - } - - @Override - protected int getSize() { - // number of slots - return this.buttons.length; - } - - @Override - protected void elementClicked(int i, boolean doubleClicked, int x, int y) { - switch(i) { - case 0: - // toggle coords - this.mw.toggleCoords(); - break; - case 1: - // toggle circular - this.mw.miniMap.toggleRotating(); - break; - case 2: - // toggle texture size - this.mw.configTextureSize *= 2; - if (this.mw.configTextureSize > 4096) { - this.mw.configTextureSize = 1024; - } - break; - case 3: - // linear scaling - this.mw.linearTextureScalingEnabled = !this.mw.linearTextureScalingEnabled; - this.mw.mapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); - //this.mw.undergroundMapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); - break; - case 4: - // player trail - this.mw.playerTrail.enabled = !this.mw.playerTrail.enabled; - break; - case 5: - // map colours - this.mw.useSavedBlockColours = !this.mw.useSavedBlockColours; - // reload block colours before saving in case player changed - // texture packs before pressing button. - this.mw.reloadBlockColours(); - break; - case 6: - // toggle max chunk save dist - int d = Math.round((float) Math.sqrt(this.mw.maxChunkSaveDistSq)); - d += 32; - if (d > 256) { - d = 64; - } - this.mw.maxChunkSaveDistSq = d * d; - break; - case 7: - this.mw.miniMap.smallMapMode.toggleHeightPercent(); - break; - case 8: - this.miniMapPositionIndex++; - if (this.miniMapPositionIndex >= miniMapPositionStringArray.length) { - // don't go back to the "unchanged" setting - this.miniMapPositionIndex = 1; - } - switch (this.miniMapPositionIndex) { - case 1: - // top right position - this.mw.miniMap.smallMapMode.setMargins(10, -1, -1, 10); - break; - case 2: - // top left position - this.mw.miniMap.smallMapMode.setMargins(10, -1, 10, -1); - break; - case 3: - // bottom right position - this.mw.miniMap.smallMapMode.setMargins(-1, 40, -1, 10); - break; - case 4: - // bottom left position - this.mw.miniMap.smallMapMode.setMargins(-1, 40, 10, -1); - break; - default: - break; - } - case 9: - // map scroll pixel snapping - this.mw.mapPixelSnapEnabled = !this.mw.mapPixelSnapEnabled; - break; - case 10: - // max death markers - this.mw.maxDeathMarkers++; - if (this.mw.maxDeathMarkers > 10) { - this.mw.maxDeathMarkers = 0; - } - break; - case 11: - // background texture mode - this.mw.backgroundTextureMode = (this.mw.backgroundTextureMode + 1) % 3; - break; - //case 11: - // // lighting - // this.mw.lightingEnabled = !this.mw.lightingEnabled; - // break; - default: - break; - } - this.updateButtonLabel(i); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float f) { - this.mouseX = mouseX; - this.mouseY = mouseY; - super.drawScreen(mouseX, mouseY, f); - } - - @Override - protected boolean isSelected(int i) { - return false; - } - - @Override - protected void drawBackground() { - } - - @Override - protected void drawSlot(int i, int x, int y, int i4, Tessellator tessellator, int i5, int i6){ - GuiButton button = buttons[i]; - button.xPosition = x; - button.yPosition = y; - button.drawButton(this.mc, this.mouseX, this.mouseY); - } -} diff --git a/src/main/java/mapwriter/gui/MwGuiOptions.java b/src/main/java/mapwriter/gui/MwGuiOptions.java deleted file mode 100644 index 52709fa..0000000 --- a/src/main/java/mapwriter/gui/MwGuiOptions.java +++ /dev/null @@ -1,51 +0,0 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; - -public class MwGuiOptions extends GuiScreen { - - private final Mw mw; - private final GuiScreen parentScreen; - private MwGuiOptionSlot optionSlot = null; - - public MwGuiOptions(GuiScreen parentScreen, Mw mw) { - this.mw = mw; - this.parentScreen = parentScreen; - } - - @SuppressWarnings("unchecked") - public void initGui() { - this.optionSlot = new MwGuiOptionSlot(this, this.mc, this.mw); - this.optionSlot.registerScrollButtons(7, 8); - - this.buttonList.add(new GuiButton(200, (this.width / 2) - 50, this.height - 28, 100, 20, "Done")); - } - - protected void actionPerformed(GuiButton button) { - if (button.id == 200) { - // done - // reconfigure texture size - this.mw.setTextureSize(); - this.mc.displayGuiScreen(this.parentScreen); - } - } - - public void drawScreen(int mouseX, int mouseY, float f) { - this.drawDefaultBackground(); - this.optionSlot.drawScreen(mouseX, mouseY, f); - this.drawCenteredString(this.fontRendererObj, "MapWriter Options", this.width / 2, 10, 0xffffff); - super.drawScreen(mouseX, mouseY, f); - } - - protected void mouseClicked(int x, int y, int button) { - super.mouseClicked(x, y, button); - } - - protected void keyTyped(char c, int k) { - if (this.optionSlot.keyTyped(c, k)) { - super.keyTyped(c, k); - } - } -} diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java deleted file mode 100644 index 77e965e..0000000 --- a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java +++ /dev/null @@ -1,37 +0,0 @@ -package mapwriter.gui; - -import mapwriter.Mw; -import mapwriter.map.MapView; -import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class MwGuiTeleportDialog extends MwGuiTextDialog { - - final Mw mw; - final MapView mapView; - final int teleportX, teleportZ; - - public MwGuiTeleportDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int x, int y, int z) { - super(parentScreen, "Teleport Height:", "" + y, "invalid height"); - this.mw = mw; - this.mapView = mapView; - this.teleportX = x; - this.teleportZ = z; - this.backToGameOnSubmit = true; - } - - @Override - public boolean submit() { - boolean done = false; - int height = this.getInputAsInt(); - if (this.inputValid) { - height = Math.min(Math.max(0, height), 255); - this.mw.defaultTeleportHeight = height; - this.mw.teleportToMapPos(this.mapView, this.teleportX, height, this.teleportZ); - done = true; - } - return done; - } -} diff --git a/src/main/java/mapwriter/gui/MwGuiTextDialog.java b/src/main/java/mapwriter/gui/MwGuiTextDialog.java deleted file mode 100644 index 42e7c73..0000000 --- a/src/main/java/mapwriter/gui/MwGuiTextDialog.java +++ /dev/null @@ -1,158 +0,0 @@ -package mapwriter.gui; - -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; - -import org.lwjgl.input.Keyboard; - -public class MwGuiTextDialog extends GuiScreen { - - private final GuiScreen parentScreen; - - String title; - String text; - String error; - GuiTextField textField = null; - boolean inputValid = false; - boolean showError = false; - boolean backToGameOnSubmit = false; - static final int textDialogWidthPercent = 50; - static final int textDialogTitleY = 80; - static final int textDialogY = 92; - static final int textDialogErrorY = 108; - - public MwGuiTextDialog(GuiScreen parentScreen, String title, String text, String error) { - this.parentScreen = parentScreen; - this.title = title; - this.text = text; - this.error = error; - } - - private void newTextField() { - if (this.textField != null) { - this.text = this.textField.getText(); - } - int w = this.width * textDialogWidthPercent / 100; - this.textField = new GuiTextField(this.fontRendererObj, - (this.width - w) / 2 + 5, - textDialogY, - w - 10, - 12); - this.textField.setMaxStringLength(32); - this.textField.setFocused(true); - this.textField.setCanLoseFocus(false); - //this.textField.setEnableBackgroundDrawing(false); - this.textField.setText(this.text); - } - - public void setText(String s) { - this.textField.setText(s); - this.text = s; - } - - public String getInputAsString() { - String s = this.textField.getText().trim(); - this.inputValid = (s.length() > 0); - this.showError = !this.inputValid; - return s; - } - - public int getInputAsInt() { - String s = this.getInputAsString(); - int value = 0; - try { - value = Integer.parseInt(s); - this.inputValid = true; - this.showError = false; - } catch (NumberFormatException e) { - this.inputValid = false; - this.showError = true; - } - return value; - } - - public int getInputAsHexInt() { - String s = this.getInputAsString(); - int value = 0; - try { - value = Integer.parseInt(s, 16); - this.inputValid = true; - this.showError = false; - } catch (NumberFormatException e) { - this.inputValid = false; - this.showError = true; - } - return value; - } - - public boolean submit() { - return false; - } - - public void initGui() { - this.newTextField(); - } - - public void drawScreen(int mouseX, int mouseY, float f) { - - if (this.parentScreen != null) { - this.parentScreen.drawScreen(mouseX, mouseY, f); - } else { - this.drawDefaultBackground(); - } - - int w = this.width * textDialogWidthPercent / 100; - drawRect( - (this.width - w) / 2, - textDialogTitleY - 4, - (this.width - w) / 2 + w, - textDialogErrorY + 14, - 0x80000000); - this.drawCenteredString( - this.fontRendererObj, - this.title, - this.width / 2, - textDialogTitleY, - 0xffffff); - this.textField.drawTextBox(); - if (this.showError) { - this.drawCenteredString( - this.fontRendererObj, - this.error, - this.width / 2, - textDialogErrorY, - 0xffffff); - } - - super.drawScreen(mouseX, mouseY, f); - } - - protected void mouseClicked(int x, int y, int button) { - super.mouseClicked(x, y, button); - } - - protected void keyTyped(char c, int key) { - switch (key) { - case Keyboard.KEY_ESCAPE: - this.mc.displayGuiScreen(this.parentScreen); - break; - - case Keyboard.KEY_RETURN: - // when enter pressed, submit current input - if (this.submit()) { - if (!this.backToGameOnSubmit) { - this.mc.displayGuiScreen(this.parentScreen); - } else { - this.mc.displayGuiScreen(null); - } - } - break; - - default: - // other characters are processed by the text box - this.textField.textboxKeyTyped(c, key); - this.text = this.textField.getText(); - break; - } - } -} diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java deleted file mode 100644 index 40458fc..0000000 --- a/src/main/java/mapwriter/map/MapRenderer.java +++ /dev/null @@ -1,319 +0,0 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.Mw; -import mapwriter.Render; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.api.MwAPI; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - -public class MapRenderer { - private Mw mw; - private MapMode mapMode; - private MapView mapView; - // accessed by the MwGui to check whether the mouse cursor is near the - // player arrow on the rendered map - public Point.Double playerArrowScreenPos = new Point.Double(0, 0); - - private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); - private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); - private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); - private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); - private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); - - public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { - this.mw = mw; - this.mapMode = mapMode; - this.mapView = mapView; - } - - private void drawMap() { - - int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); - double tSize = (double) this.mw.textureSize; - double zoomScale = (double) (1 << regionZoomLevel); - - // if the texture UV coordinates do not line up with the texture pixels then the texture - // will look blurry when it is drawn to the screen. - // to fix this we round the texture coordinates to the nearest pixel boundary. - // this is unnecessary when zoomed in as the texture will be upscaled and look blurry - // anyway, so it is disabled in this case. - // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture - // pixel boundaries when zoomed in. - - double u, v, w, h; - if ((!this.mapMode.circular) && (this.mw.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { - u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; - v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; - w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; - h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; - } else { - double tSizeInBlocks = tSize * zoomScale; - u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; - v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; - w = (this.mapView.getWidth() / tSizeInBlocks); - h = (this.mapView.getHeight() / tSizeInBlocks); - } - - GL11.glPushMatrix(); - - if (this.mapMode.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - if (this.mapMode.circular) { - Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); - } - - if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { - // draw the underground map - this.mw.undergroundMapTexture.requestView(this.mapView); - // underground map needs to have a black background - Render.setColourWithAlphaPercent(0x000000, this.mapMode.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); - this.mw.undergroundMapTexture.bind(); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } else { - // draw the surface map - MapViewRequest req = new MapViewRequest(this.mapView); - this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); - - // draw the background texture - if (this.mw.backgroundTextureMode > 0) { - double bu1 = 0.0; double bu2 = 1.0; - double bv1 = 0.0; double bv2 = 1.0; - if (this.mw.backgroundTextureMode == 2) { - // background moves with map if mode is 2 - double bSize = tSize / 256.0; - bu1 = u * bSize; bu2 = (u + w) * bSize; - bv1 = v * bSize; bv2 = (v + h) * bSize; - } - this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - bu1, bv1, bu2, bv2 - ); - } else { - // mode 0, no background texture - Render.setColourWithAlphaPercent(0x000000, this.mapMode.alphaPercent); - Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); - } - - // only draw surface map if the request is loaded (view requests are - // loaded by the background thread) - if (this.mw.mapTexture.isLoaded(req)) { - this.mw.mapTexture.bind(); - Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); - Render.drawTexturedRect( - this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, - u, v, u + w, v + h - ); - } - } - - // draw ProfMobius chunk overlay - IMwDataProvider provider = this.drawOverlay(); - - // overlay onDraw event - if (provider != null) { - GL11.glPushMatrix(); - provider.onDraw(this.mapView, this.mapMode); - GL11.glPopMatrix(); - } - - if (this.mapMode.circular) { - Render.disableStencil(); - } - - GL11.glPopMatrix(); - } - - private void drawBorder() { - if (this.mapMode.circular) { - this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); - } else { - this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); - } - Render.setColour(0xffffffff); - Render.drawTexturedRect( - this.mapMode.x / 0.75, this.mapMode.y / 0.75, - this.mapMode.w / 0.75, this.mapMode.h / 0.75, - 0.0, 0.0, 1.0, 1.0 - ); - } - - private void drawPlayerArrow() { - GL11.glPushMatrix(); - double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); - Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); - this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); - - // the arrow only needs to be rotated if the map is NOT rotated - GL11.glTranslated(p.x, p.y, 0.0); - if (!this.mapMode.rotate) { - GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - double arrowSize = this.mapMode.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); - Render.drawTexturedRect( - -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - GL11.glPopMatrix(); - } - - private void drawIcons() { - GL11.glPushMatrix(); - - if (this.mapMode.rotate) { - GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); - } - - // draw markers - this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); - - // draw player trail - if (this.mw.playerTrail.enabled) { - this.mw.playerTrail.draw(this.mapMode, this.mapView); - } - - // draw north arrow - if (this.mapMode.rotate) { - double y = this.mapMode.h / 2.0; - double arrowSize = this.mapMode.playerArrowSize; - Render.setColour(0xffffffff); - this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); - Render.drawTexturedRect( - -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, - 0.0, 0.0, 1.0, 1.0 - ); - } - - GL11.glPopMatrix(); - - // outside of the matrix pop as theplayer arrow - // needs to be drawn without rotation - this.drawPlayerArrow(); - } - - private void drawCoords() { - // draw coordinates - if (this.mapMode.coordsEnabled) { - GL11.glPushMatrix(); - GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); - if (this.mw.coordsMode != 2) { - GL11.glScalef(0.5f, 0.5f, 1.0f); - } - int offset = 0; - if (this.mw.coordsMode > 0) { - Render.drawCentredString(0, 0, this.mapMode.textColour, - "%d, %d, %d", - this.mw.playerXInt, - this.mw.playerYInt, - this.mw.playerZInt - ); - offset += 12; - } - if (this.mw.undergroundMode) { - Render.drawCentredString( - 0, offset, this.mapMode.textColour,"underground mode" - ); - } - GL11.glPopMatrix(); - } - } - - private IMwDataProvider drawOverlay() { - // draw overlays from registered providers - //for (IMwDataProvider provider : MwAPI.getDataProviders()) - IMwDataProvider provider = MwAPI.getCurrentDataProvider(); - if (provider != null) { - ArrayList overlays = provider.getChunksOverlay( - this.mapView.getDimension(), - this.mapView.getX(), this.mapView.getZ(), - this.mapView.getMinX(), this.mapView.getMinZ(), - this.mapView.getMaxX(), this.mapView.getMaxZ() - ); - if (overlays != null) { - for (IMwChunkOverlay overlay : overlays) { - paintChunk(this.mapMode, this.mapView, overlay); - } - } - } - return provider; - } - - public void draw() { - - this.mapMode.setScreenRes(); - this.mapView.setMapWH(this.mapMode); - this.mapView.setTextureSize(this.mw.textureSize); - - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - - // translate to center of minimap - // z is -2000 so that it is drawn above the 3D world, but below GUI - // elements which are typically at -3000 - GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); - - // draw background, the map texture, and enabled overlays - this.drawMap(); - - if (this.mapMode.borderMode > 0) { - this.drawBorder(); - } - this.drawIcons(); - - this.drawCoords(); - - // some shader mods seem to need depth testing re-enabled - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glPopMatrix(); - } - - private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ - int chunkX = overlay.getCoordinates().x; - int chunkZ = overlay.getCoordinates().y; - float filling = overlay.getFilling(); - - Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); - Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); - - topCorner.x = Math.max(mapMode.x, topCorner.x); - topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); - topCorner.y = Math.max(mapMode.y, topCorner.y); - topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); - - botCorner.x = Math.max(mapMode.x, botCorner.x); - botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); - botCorner.y = Math.max(mapMode.y, botCorner.y); - botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); - - double sizeX = (botCorner.x - topCorner.x) * filling; - double sizeY = (botCorner.y - topCorner.y) * filling; - double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; - double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; - - if (overlay.hasBorder()) { - Render.setColour(overlay.getBorderColor()); - Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); - } - - Render.setColour(overlay.getColor()); - Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); - } -} - diff --git a/src/main/java/mapwriter/map/MapTexture.java b/src/main/java/mapwriter/map/MapTexture.java deleted file mode 100644 index 921f4e3..0000000 --- a/src/main/java/mapwriter/map/MapTexture.java +++ /dev/null @@ -1,169 +0,0 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.BackgroundExecutor; -import mapwriter.Texture; -import mapwriter.region.Region; -import mapwriter.region.RegionManager; - -import org.lwjgl.opengl.GL11; - -public class MapTexture extends Texture { - - public int textureRegions; - public int textureSize; - - private MapViewRequest loadedView = null; - private MapViewRequest requestedView = null; - - private Region[] regionArray; - - // accessed from both render and background thread. - // make sure all methods using it are synchronized. - //private int[] regionModifiedArray; - - private class Rect { - final int x, y, w, h; - Rect(int x, int y, int w, int h) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } - } - - private List textureUpdateQueue = new ArrayList(); - - public MapTexture(int textureSize, boolean linearScaling) { - super(textureSize, textureSize, 0x00000000, GL11.GL_LINEAR, GL11.GL_LINEAR, GL11.GL_REPEAT); - - this.setLinearScaling(linearScaling); - - this.textureRegions = textureSize >> Region.SHIFT; - this.textureSize = textureSize; - this.regionArray = new Region[this.textureRegions * this.textureRegions]; - } - - public void requestView(MapViewRequest req, BackgroundExecutor executor, RegionManager regionManager) { - if ((this.requestedView == null) || (!this.requestedView.equals(req))) { - this.requestedView = req; - executor.addTask(new MapUpdateViewTask(this, regionManager, req)); - } - } - - public void processTextureUpdates() { - synchronized (this.textureUpdateQueue) { - for (Rect rect : this.textureUpdateQueue) { - //MwUtil.log("MwMapTexture.processTextureUpdates: %d %d %d %d", rect.x, rect.y, rect.w, rect.h); - this.updateTextureArea(rect.x, rect.y, rect.w, rect.h); - } - this.textureUpdateQueue.clear(); - } - } - - public void setLoaded(MapViewRequest req) { - this.loadedView = req; - } - - public boolean isLoaded(MapViewRequest req) { - return (this.loadedView != null) && (this.loadedView.mostlyEquals(req)); - } - - // - // methods below this point run in the background thread - // - - public synchronized void setRGBOpaque(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { - // TODO: Remove the need for this function. It would better if the - // region pixels were stored as normal pixels (without the height in - // the alpha channel). Then we could just directly copy the pixels - // to the texture pixelBuf. - int bufOffset = (y * this.w) + x; - for (int i = 0; i < h; i++) { - this.setPixelBufPosition(bufOffset + (i * this.w)); - int rowOffset = offset + (i * scanSize); - for (int j = 0; j < w; j++) { - int colour = pixels[rowOffset + j]; - if(colour != 0) { - colour |= 0xff000000; - } - this.pixelBufPut(colour); - } - } - } - - public void addTextureUpdate(int x, int z, int w, int h) { - synchronized (this.textureUpdateQueue) { - this.textureUpdateQueue.add(new Rect(x, z, w, h)); - } - } - - public void updateTextureFromRegion(Region region, int x, int z, int w, int h) { - int tx = (x >> region.zoomLevel) & (this.w - 1); - int ty = (z >> region.zoomLevel) & (this.h - 1); - int tw = (w >> region.zoomLevel); - int th = (h >> region.zoomLevel); - - // make sure we don't write outside texture - tw = Math.min(tw, this.w - tx); - th = Math.min(th, this.h - th); - - //MwUtil.log("updateTextureFromRegion: region %s, %d %d %d %d -> %d %d %d %d", region, x, z, w, h, tx, ty, tw, th); - - int[] pixels = region.getPixels(); - if (pixels != null) { - this.setRGBOpaque(tx, ty, tw, th, pixels, region.getPixelOffset(x, z), Region.SIZE); - } else { - this.fillRect(tx, ty, tw, th, 0x00000000); - } - - this.addTextureUpdate(tx, ty, tw, th); - } - - public int getRegionIndex(int x, int z, int zoomLevel) { - x = (x >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); - z = (z >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); - return (z * this.textureRegions) + x; - } - - public boolean loadRegion(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) { - //MwUtil.log("mapTexture.loadRegion %d %d %d %d", x, z, zoomLevel, dimension); - boolean loaded = false; - int index = this.getRegionIndex(x, z, zoomLevel); - Region currentRegion = this.regionArray[index]; - if ((currentRegion == null) || (!currentRegion.equals(x, z, zoomLevel, dimension))) { - Region newRegion = regionManager.getRegion(x, z, zoomLevel, dimension); - this.regionArray[index] = newRegion; - this.updateTextureFromRegion( - newRegion, newRegion.x, newRegion.z, newRegion.size, newRegion.size - ); - //regionManager.logInfo("regionArray[%d] = %s", index, newRegion); - loaded = true; - } - return loaded; - } - - public int loadRegions(RegionManager regionManager, MapViewRequest req) { - int size = Region.SIZE << req.zoomLevel; - int loadedCount = 0; - for (int z = req.zMin; z <= req.zMax; z += size) { - for (int x = req.xMin; x <= req.xMax; x += size) { - if (this.loadRegion(regionManager, x, z, req.zoomLevel, req.dimension)) { - loadedCount++; - } - } - } - return loadedCount; - } - - public void updateArea(RegionManager regionManager, int x, int z, int w, int h, int dimension) { - for (int i = 0; i < this.regionArray.length; i++) { - Region region = this.regionArray[i]; - if ((region != null) && (region.isAreaWithin(x, z, w, h, dimension))) { - this.updateTextureFromRegion(region, x, z, w, h); - } - } - } -} diff --git a/src/main/java/mapwriter/map/MapUpdateViewTask.java b/src/main/java/mapwriter/map/MapUpdateViewTask.java deleted file mode 100644 index 4a91042..0000000 --- a/src/main/java/mapwriter/map/MapUpdateViewTask.java +++ /dev/null @@ -1,31 +0,0 @@ -package mapwriter.map; - -import mapwriter.region.RegionManager; -import mapwriter.tasks.Task; - -public class MapUpdateViewTask extends Task { - final MapViewRequest req; - RegionManager regionManager; - MapTexture mapTexture; - - // chunkmanager will need to keep a list of chunks to update. - // it should also keep a 2D chunkSum array so that only modified chunks are updated. - public MapUpdateViewTask(MapTexture mapTexture, RegionManager regionManager, MapViewRequest req) { - - this.mapTexture = mapTexture; - this.regionManager = regionManager; - this.req = req; - } - - @Override - public void run() { - // load regions for view - this.mapTexture.loadRegions(this.regionManager, this.req); - } - - @Override - public void onComplete() { - // set currentView in mapTexture to requestedView - this.mapTexture.setLoaded(this.req); - } -} diff --git a/src/main/java/mapwriter/map/MapView.java b/src/main/java/mapwriter/map/MapView.java deleted file mode 100644 index c2c335a..0000000 --- a/src/main/java/mapwriter/map/MapView.java +++ /dev/null @@ -1,271 +0,0 @@ -package mapwriter.map; - -import java.util.List; - -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.map.mapmode.MapMode; - -public class MapView { - - private int zoomLevel = 0; - private int dimension = 0; - private int textureSize = 2048; - - // the position of the centre of the 'view' of the map using game (block) coordinates - private double x = 0; - private double z = 0; - - // width and height of map to display in pixels - private int mapW = 0; - private int mapH = 0; - - // the width and height of the map in blocks at zoom level 0. - // updated when map width, map height, or texture size changes. - private int baseW = 1; - private int baseH = 1; - - // the width and height of the map in blocks at the current - // zoom level. - private double w = 1; - private double h = 1; - - private int minZoom; - private int maxZoom; - - private boolean undergroundMode; - - public MapView(Mw mw) { - this.minZoom = mw.minZoom; - this.maxZoom = mw.maxZoom; - this.undergroundMode = mw.undergroundMode; - this.setZoomLevel(0); - this.setViewCentre(mw.playerX, mw.playerZ); - } - - public void setViewCentre(double vX, double vZ) { - this.x = vX; - this.z = vZ; - - if (MwAPI.getCurrentDataProvider() != null) { - MwAPI.getCurrentDataProvider().onMapCenterChanged(vX, vZ, this); - } - - } - - public double getX() { - return this.x; - } - - public double getZ() { - return this.z; - } - - public double getWidth() { - return this.w; - } - - public double getHeight() { - return this.h; - } - - public void panView(double relX, double relZ) { - this.setViewCentre( - this.x + (relX * this.w), - this.z + (relZ * this.h) - ); - } - - public int setZoomLevel(int zoomLevel) { - //MwUtil.log("MapView.setZoomLevel(%d)", zoomLevel); - int prevZoomLevel = this.zoomLevel; - if (this.undergroundMode) { - this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), 0); - } else { - this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), this.maxZoom); - } - if (prevZoomLevel != this.zoomLevel) { - this.updateZoom(); - } - return this.zoomLevel; - } - - private void updateZoom() { - if (this.zoomLevel >= 0) { - this.w = this.baseW << this.zoomLevel; - this.h = this.baseH << this.zoomLevel; - } else { - this.w = this.baseW >> (-this.zoomLevel); - this.h = this.baseH >> (-this.zoomLevel); - } - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onZoomChanged(this.getZoomLevel(), this); - } - - public int adjustZoomLevel(int n) { - return this.setZoomLevel(this.zoomLevel + n); - } - - public int getZoomLevel() { - return this.zoomLevel; - } - - public int getRegionZoomLevel() { - return Math.max(0, this.zoomLevel); - } - - // bX and bZ are the coordinates of the block the zoom is centred on. - // The relative position of the block in the view will remain the same - // as before the zoom. - public void zoomToPoint(int newZoomLevel, double bX, double bZ) { - int prevZoomLevel = this.zoomLevel; - newZoomLevel = this.setZoomLevel(newZoomLevel); - double zF = Math.pow(2, newZoomLevel - prevZoomLevel); - this.setViewCentre( - bX - ((bX - this.x) * zF), - bZ - ((bZ - this.z) * zF)); - } - - public void setDimension(int dimension) { - double scale = 1.0; - if (dimension != this.dimension) { - if ((this.dimension != -1) && (dimension == -1)) { - scale = 0.125; - } else if ((this.dimension == -1) && (dimension != -1)) { - scale = 8.0; - } - this.dimension = dimension; - this.setViewCentre(this.x * scale, this.z * scale); - } - - if (MwAPI.getCurrentDataProvider() != null) - MwAPI.getCurrentDataProvider().onDimensionChanged(this.dimension, this); - } - - public void setDimensionAndAdjustZoom(int dimension) { - int zoomLevelChange = 0; - if ((this.dimension != -1) && (dimension == -1)) { - zoomLevelChange = -3; - } else if ((this.dimension == -1) && (dimension != -1)) { - zoomLevelChange = 3; - } - this.setZoomLevel(this.getZoomLevel() + zoomLevelChange); - this.setDimension(dimension); - } - - public void nextDimension(List dimensionList, int n) { - int i = dimensionList.indexOf(this.dimension); - i = Math.max(0, i); - int size = dimensionList.size(); - int dimension = dimensionList.get((i + size + n) % size); - this.setDimensionAndAdjustZoom(dimension); - } - - public int getDimension() { - return this.dimension; - } - - public void setMapWH(int w, int h) { - if ((this.mapW != w) || (this.mapH != h)) { - this.mapW = w; - this.mapH = h; - this.updateBaseWH(); - } - } - - public void setMapWH(MapMode mapMode) { - this.setMapWH(mapMode.wPixels, mapMode.hPixels); - } - - public double getMinX() { - return this.x - (this.w / 2); - } - - public double getMaxX() { - return this.x + (this.w / 2); - } - - public double getMinZ() { - return this.z - (this.h / 2); - } - - public double getMaxZ() { - return this.z + (this.h / 2); - } - - public double getDimensionScaling(int playerDimension) { - double scale; - if ((this.dimension != -1) && (playerDimension == -1)) { - scale = 8.0; - } else if ((this.dimension == -1) && (playerDimension != -1)) { - scale = 0.125; - } else { - scale = 1.0; - } - return scale; - } - - public void setViewCentreScaled(double vX, double vZ, int playerDimension) { - double scale = this.getDimensionScaling(playerDimension); - this.setViewCentre(vX * scale, vZ * scale); - } - - public void setTextureSize(int n) { - if (this.textureSize != n) { - this.textureSize = n; - this.updateBaseWH(); - } - } - - private void updateBaseWH() { - int w = this.mapW; - int h = this.mapH; - int halfTextureSize = this.textureSize / 2; - - // if we cannot display the map at 1x1 pixel per block, then - // try 2x2 pixels per block, then 4x4 and so on - while ((w > halfTextureSize) || (h > halfTextureSize)) { - w /= 2; - h /= 2; - } - - //MwUtil.log("MapView.updateBaseWH: map = %dx%d, tsize = %d, base = %dx%d", this.mapW, this.mapH, this.textureSize, w, h); - - this.baseW = w; - this.baseH = h; - - this.updateZoom(); - } - - public int getPixelsPerBlock() { - return this.mapW / this.baseW; - } - - public boolean isBlockWithinView(double bX, double bZ, boolean circular) { - boolean inside; - if (!circular) { - inside = (bX > this.getMinX()) || (bX < this.getMaxX()) || - (bZ > this.getMinZ()) || (bZ < this.getMaxZ()); - } else { - double x = (bX - this.x); - double z = (bZ - this.z); - double r = this.getHeight() / 2; - inside = ((x * x) + (z * z)) < (r * r); - } - return inside; - } - - public boolean getUndergroundMode() { - return this.undergroundMode; - } - - public void setUndergroundMode(boolean enabled) { - if (enabled) { - if (this.zoomLevel >= 0) { - this.setZoomLevel(-1); - } - } - this.undergroundMode = enabled; - } -} diff --git a/src/main/java/mapwriter/map/MapViewRequest.java b/src/main/java/mapwriter/map/MapViewRequest.java deleted file mode 100644 index 4c0b777..0000000 --- a/src/main/java/mapwriter/map/MapViewRequest.java +++ /dev/null @@ -1,33 +0,0 @@ -package mapwriter.map; - -import mapwriter.region.Region; - -public class MapViewRequest { - public final int xMin, xMax, zMin, zMax, zoomLevel, dimension; - - public MapViewRequest(MapView view) { - this.zoomLevel = view.getRegionZoomLevel(); - int size = Region.SIZE << this.zoomLevel; - this.xMin = ((int) view.getMinX()) & (-size); - this.zMin = ((int) view.getMinZ()) & (-size); - this.xMax = ((int) view.getMaxX()) & (-size); - this.zMax = ((int) view.getMaxZ()) & (-size); - this.dimension = view.getDimension(); - } - - public boolean equals(MapViewRequest req) { - return (req != null) && - (req.zoomLevel == this.zoomLevel) && - (req.dimension == this.dimension) && - (req.xMin == this.xMin) && - (req.xMax == this.xMax) && - (req.zMin == this.zMin) && - (req.zMax == this.zMax); - } - - public boolean mostlyEquals(MapViewRequest req) { - return (req != null) && - (req.zoomLevel == this.zoomLevel) && - (req.dimension == this.dimension); - } -} diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java deleted file mode 100644 index e195865..0000000 --- a/src/main/java/mapwriter/map/Marker.java +++ /dev/null @@ -1,79 +0,0 @@ -package mapwriter.map; - -import java.awt.Point; - -import mapwriter.Render; -import mapwriter.map.mapmode.MapMode; - -public class Marker { - public final String name; - public final String groupName; - public int x; - public int y; - public int z; - public int dimension; - public int colour; - - public Point.Double screenPos = new Point.Double(0, 0); - - private static int[] colours = new int[] { - 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, - 0xff8000, 0x8000ff}; - // static so that current index is shared between all markers - private static int colourIndex = 0; - - public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { - this.name = name; - this.x = x; - this.y = y; - this.z = z; - this.dimension = dimension; - this.colour = colour; - this.groupName = groupName; - } - - public String getString() { - return String.format("%s %s (%d, %d, %d) %d %06x", - this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); - } - - public static int getCurrentColour() { - return 0xff000000 | colours[colourIndex]; - } - - public void colourNext() { - colourIndex = (colourIndex + 1) % colours.length; - this.colour = getCurrentColour(); - } - - public void colourPrev() { - colourIndex = (colourIndex + colours.length - 1) % colours.length; - this.colour = getCurrentColour(); - } - - public void draw(MapMode mapMode, MapView mapView, int borderColour) { - double scale = mapView.getDimensionScaling(this.dimension); - Point.Double p = mapMode.getClampedScreenXY(mapView, this.x * scale, this.z * scale); - this.screenPos.setLocation(p.x + mapMode.xTranslation, p.y + mapMode.yTranslation); - - // draw a coloured rectangle centered on the calculated (x, y) - double mSize = mapMode.markerSize; - double halfMSize = mapMode.markerSize / 2.0; - Render.setColour(borderColour); - Render.drawRect(p.x - halfMSize, p.y - halfMSize, mSize, mSize); - Render.setColour(this.colour); - Render.drawRect(p.x - halfMSize + 0.5, p.y - halfMSize + 0.5, mSize - 1.0, mSize - 1.0); - } - - // arraylist.contains was producing unexpected results in some situations - // rather than figure out why i'll just control how two markers are compared - @Override - public boolean equals(final Object o) { - if (this == o) { return true; } - if (o instanceof Marker) { - Marker m = (Marker) o; - return (name == m.name) && (groupName == m.groupName) && (x == m.x) && (y == m.y) && (z == m.z) && (dimension == m.dimension); - } - return false; - } -} \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java deleted file mode 100644 index 83e49d5..0000000 --- a/src/main/java/mapwriter/map/MarkerManager.java +++ /dev/null @@ -1,279 +0,0 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.MwUtil; -import mapwriter.forge.MwConfig; -import mapwriter.map.mapmode.MapMode; - -public class MarkerManager { - - public List markerList = new ArrayList(); - public List groupList = new ArrayList(); - - public List visibleMarkerList = new ArrayList(); - - private String visibleGroupName = "none"; - - public Marker selectedMarker = null; - - public MarkerManager() { - } - - public void load(MwConfig config, String category) { - this.markerList.clear(); - - if (config.hasCategory(category)) { - int markerCount = config.get(category, "markerCount", 0).getInt(); - this.visibleGroupName = config.get(category, "visibleGroup", "").getString(); - - if (markerCount > 0) { - for (int i = 0; i < markerCount; i++) { - String key = "marker" + i; - String value = config.get(category, key, "").getString(); - Marker marker = this.stringToMarker(value); - if (marker != null) { - this.addMarker(marker); - } else { - MwUtil.log("error: could not load " + key + " from config file"); - } - } - } - } - - this.update(); - } - - public void save(MwConfig config, String category) { - config.get(category, "markerCount", 0).set(this.markerList.size()); - config.get(category, "visibleGroup", "").set(this.visibleGroupName); - - int i = 0; - for (Marker marker : this.markerList) { - String key = "marker" + i; - String value = this.markerToString(marker); - config.get(category, key, "").set(value); - i++; - } - } - - public void setVisibleGroupName(String groupName) { - if (groupName != null) { - this.visibleGroupName = MwUtil.mungeString(groupName); - } else { - this.visibleGroupName = "none"; - } - } - - public String getVisibleGroupName() { - return this.visibleGroupName; - } - - public void clear() { - this.markerList.clear(); - this.groupList.clear(); - this.visibleMarkerList.clear(); - this.visibleGroupName = "none"; - } - - public String markerToString(Marker marker) { - return String.format("%s:%d:%d:%d:%d:%06x:%s", - marker.name, - marker.x, marker.y, marker.z, - marker.dimension, - marker.colour & 0xffffff, - marker.groupName - ); - } - - public Marker stringToMarker(String s) { - // new style delimited with colons - String[] split = s.split(":"); - if (split.length != 7) { - // old style was space delimited - split = s.split(" "); - } - Marker marker = null; - if (split.length == 7) { - try { - int x = Integer.parseInt(split[1]); - int y = Integer.parseInt(split[2]); - int z = Integer.parseInt(split[3]); - int dimension = Integer.parseInt(split[4]); - int colour = 0xff000000 | Integer.parseInt(split[5], 16); - - marker = new Marker(split[0], split[6], x, y, z, dimension, colour); - - } catch (NumberFormatException e) { - marker = null; - } - } else { - MwUtil.log("Marker.stringToMarker: invalid marker '%s'", s); - } - return marker; - } - - public void addMarker(Marker marker) { - this.markerList.add(marker); - } - - public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { - name = name.replace(":", ""); - groupName = groupName.replace(":", ""); - this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); - } - - // returns true if the marker exists in the arraylist. - // safe to pass null. - public boolean delMarker(Marker markerToDelete) { - return this.markerList.remove(markerToDelete); - } - - // deletes the first marker with matching name and group. - // if null is passed as either name or group it means "any". - public boolean delMarker(String name, String group) { - Marker markerToDelete = null; - for (Marker marker : this.markerList) { - if (((name == null) || marker.name.equals(name)) && - ((group == null) || marker.groupName.equals(group))) { - markerToDelete = marker; - break; - } - } - // will return false if a marker matching the criteria is not found - // (i.e. if markerToDelete is null) - return this.delMarker(markerToDelete); - } - - /*public boolean delGroup(String groupName) { - boolean error = !this.groupList.remove(groupName); - Iterator it = this.markerMap.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - Marker marker = (Marker) entry.getValue(); - if (marker.groupName.equals(groupName)) { - it.remove(); - } - } - if (groupName == this.visibleGroupName) { - this.nextGroup(); - } - return error; - }*/ - - public void update() { - this.visibleMarkerList.clear(); - this.groupList.clear(); - this.groupList.add("none"); - this.groupList.add("all"); - for (Marker marker : this.markerList) { - if (marker.groupName.equals(this.visibleGroupName) || this.visibleGroupName.equals("all")) { - this.visibleMarkerList.add(marker); - } - if (!this.groupList.contains(marker.groupName)) { - this.groupList.add(marker.groupName); - } - } - if (!this.groupList.contains(this.visibleGroupName)) { - this.visibleGroupName = "none"; - } - } - - public void nextGroup(int n) { - if (this.groupList.size() > 0) { - int i = this.groupList.indexOf(this.visibleGroupName); - int size = this.groupList.size(); - if (i != -1) { - i = (i + size + n) % size; - } else { - i = 0; - } - this.visibleGroupName = this.groupList.get(i); - } else { - this.visibleGroupName = "none"; - this.groupList.add("none"); - } - } - - public void nextGroup() { - this.nextGroup(1); - } - - public int countMarkersInGroup(String group) { - int count = 0; - if (group.equals("all")) { - count = this.markerList.size(); - } else { - for (Marker marker : this.markerList) { - if (marker.groupName.equals(group)) { - count++; - } - } - } - return count; - } - - public void selectNextMarker() { - if (this.visibleMarkerList.size() > 0) { - int i = 0; - if (this.selectedMarker != null) { - i = this.visibleMarkerList.indexOf(this.selectedMarker); - if (i == -1) { - i = 0; - } - } - i = (i + 1) % this.visibleMarkerList.size(); - this.selectedMarker = this.visibleMarkerList.get(i); - } else { - this.selectedMarker = null; - } - } - - public Marker getNearestMarker(int x, int z, int maxDistance) { - int nearestDistance = maxDistance * maxDistance; - Marker nearestMarker = null; - for (Marker marker : this.visibleMarkerList) { - int dx = x - marker.x; - int dz = z - marker.z; - int d = (dx * dx) + (dz * dz); - if (d < nearestDistance) { - nearestMarker = marker; - nearestDistance = d; - } - } - return nearestMarker; - } - - public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) { - int nearestDistance = 10000 * 10000; - Marker nearestMarker = null; - for (Marker marker : this.visibleMarkerList) { - int dx = marker.x - x; - int dz = marker.z - z; - int d = (dx * dx) + (dz * dz); - double angle = Math.atan2(dz, dx); - // use cos instead of abs as it will wrap at 2 * Pi. - // cos will be closer to 1.0 the closer desiredAngle and angle are. - // 0.8 is the threshold corresponding to a maximum of - // acos(0.8) = 37 degrees difference between the two angles. - if ((Math.cos(desiredAngle - angle) > 0.8D) && (d < nearestDistance) && (d > 4)) { - nearestMarker = marker; - nearestDistance = d; - } - } - return nearestMarker; - } - - public void drawMarkers(MapMode mapMode, MapView mapView) { - for (Marker marker : this.visibleMarkerList) { - // only draw markers that were set in the current dimension - if (mapView.getDimension() == marker.dimension) { - marker.draw(mapMode, mapView, 0xff000000); - } - } - if (this.selectedMarker != null) { - this.selectedMarker.draw(mapMode, mapView, 0xffffffff); - } - } -} diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java deleted file mode 100644 index feacec3..0000000 --- a/src/main/java/mapwriter/map/MiniMap.java +++ /dev/null @@ -1,99 +0,0 @@ -package mapwriter.map; - -import java.util.ArrayList; -import java.util.List; - -import mapwriter.Mw; -import mapwriter.map.mapmode.LargeMapMode; -import mapwriter.map.mapmode.MapMode; -import mapwriter.map.mapmode.SmallMapMode; - -public class MiniMap { - private Mw mw; - - public static final String catSmallMap = "smallMap"; - public static final String catLargeMap = "largeMap"; - public static final String catUndergroundMap = "undergroundMap"; - - public MapMode smallMapMode; - public MapMode largeMapMode; - public MapMode guiMapMode; - - public MapView view; - - public MapRenderer smallMap; - public MapRenderer largeMap; - - private List mapList; - private MapRenderer currentMap = null; - - public int modeIndex = 0; - - public MiniMap(Mw mw) { - this.mw = mw; - - // load config file options - this.modeIndex = mw.config.getOrSetInt(Mw.catOptions, "overlayModeIndex", this.modeIndex, 0, 1000); - int zoomLevel = mw.config.getOrSetInt(Mw.catOptions, "overlayZoomLevel", 0, mw.minZoom, mw.maxZoom); - - // map view shared between large and small map modes - this.view = new MapView(mw); - this.view.setZoomLevel(zoomLevel); - - // small map mode - this.smallMapMode = new SmallMapMode(this.mw.config); - this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); - - // large map mode - this.largeMapMode = new LargeMapMode(this.mw.config); - this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); - - this.mapList = new ArrayList(); - - // add small, large and underground map modes if they - // are enabled. - if (this.smallMapMode.enabled) { - this.mapList.add(this.smallMap); - } - if (this.largeMapMode.enabled) { - this.mapList.add(this.largeMap); - } - // add a null entry (hides the overlay when selected) - this.mapList.add(null); - - // sanitize overlayModeIndex loaded from config - this.nextOverlayMode(0); - this.currentMap = this.mapList.get(this.modeIndex); - } - - public void close() { - this.mapList.clear(); - this.currentMap = null; - - this.smallMapMode.close(); - this.largeMapMode.close(); - - this.mw.config.setInt(Mw.catOptions, "overlayModeIndex", this.modeIndex); - this.mw.config.setInt(Mw.catOptions, "overlayZoomLevel", this.view.getZoomLevel()); - } - - // toggle between small map, underground map and no map - public MapRenderer nextOverlayMode(int increment) { - int size = this.mapList.size(); - this.modeIndex = (this.modeIndex + size + increment) % size; - this.currentMap = this.mapList.get(this.modeIndex); - return this.currentMap; - } - - public void toggleRotating() { - boolean rotate = this.smallMapMode.toggleRotating(); - this.largeMapMode.setRotating(rotate); - } - - // draw the map overlay, player arrow, and markers - public void drawCurrentMap() { - if (this.currentMap != null) { - this.currentMap.draw(); - } - } -} \ No newline at end of file diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java deleted file mode 100644 index 641d3a4..0000000 --- a/src/main/java/mapwriter/map/Trail.java +++ /dev/null @@ -1,98 +0,0 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.LinkedList; - -import mapwriter.Mw; -import mapwriter.Render; -import mapwriter.map.mapmode.MapMode; - -public class Trail { - - class TrailMarker { - - double x, y, z, heading; - int alphaPercent; - - static final int borderColour = 0xff000000; - static final int colour = 0xff00ffff; - - public TrailMarker(double x, double y, double z, double heading) { - this.set(x, y, z, heading); - } - - public void set(double x, double y, double z, double heading) { - this.x = x; - this.y = y; - this.z = z; - this.heading = heading; - this.alphaPercent = 100; - } - - public void draw(MapMode mapMode, MapView mapView) { - if (mapView.isBlockWithinView(this.x, this.z, mapMode.circular)) { - Point.Double p = mapMode.blockXZtoScreenXY(mapView, this.x, this.z); - - // draw a coloured arrow centered on the calculated (x, y) - Render.setColourWithAlphaPercent(borderColour, this.alphaPercent); - Render.drawArrow(p.x, p.y, this.heading, mapMode.trailMarkerSize); - Render.setColourWithAlphaPercent(colour, this.alphaPercent); - Render.drawArrow(p.x, p.y, this.heading, mapMode.trailMarkerSize - 1.0); - } - } - } - - private Mw mw; - public LinkedList trailMarkerList = new LinkedList(); - public int maxLength = 30; - public String name; - public boolean enabled; - public long lastMarkerTime = 0; - public long intervalMillis = 5000; - - public Trail(Mw mw, String name) { - this.mw = mw; - this.name = name; - this.enabled = this.mw.config.getOrSetBoolean(Mw.catOptions, this.name + "TrailEnabled", false); - this.maxLength = this.mw.config.getOrSetInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength, 1, 200); - this.intervalMillis = (long) this.mw.config.getOrSetInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis, 100, 360000); - } - - public void close() { - this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); - this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); - this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); - this.trailMarkerList.clear(); - } - - // for other types of trails will need to extend Trail and override this method - public void onTick() { - long time = System.currentTimeMillis(); - if ((time - this.lastMarkerTime) > this.intervalMillis) { - this.lastMarkerTime = time; - this.addMarker(this.mw.playerX, this.mw.playerY, this.mw.playerZ, this.mw.playerHeading); - } - } - - public void addMarker(double x, double y, double z, double heading) { - this.trailMarkerList.add(new TrailMarker(x, y, z, heading)); - // remove elements from beginning of list until the list has at most - // maxTrailLength elements - while (this.trailMarkerList.size() > this.maxLength) { - this.trailMarkerList.poll(); - } - int i = this.maxLength - this.trailMarkerList.size(); - for (TrailMarker marker : this.trailMarkerList) { - marker.alphaPercent = (i * 100) / this.maxLength; - i++; - } - } - - public void draw(MapMode mapMode, MapView mapView) { - for (TrailMarker marker : this.trailMarkerList) { - marker.draw(mapMode, mapView); - } - } - - -} diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java deleted file mode 100644 index f8d603b..0000000 --- a/src/main/java/mapwriter/map/UndergroundTexture.java +++ /dev/null @@ -1,220 +0,0 @@ -package mapwriter.map; - -import java.awt.Point; -import java.util.Arrays; - -import mapwriter.Mw; -import mapwriter.Texture; -import mapwriter.region.ChunkRender; -import mapwriter.region.IChunk; -import net.minecraft.block.Block; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.world.chunk.Chunk; - -import org.lwjgl.opengl.GL11; - -public class UndergroundTexture extends Texture { - - private Mw mw; - private int px = 0; - private int py = 0; - private int pz = 0; - private int dimension = 0; - private int updateX; - private int updateZ; - private byte[][] updateFlags = new byte[9][256]; - private Point[] loadedChunkArray; - private int textureSize; - private int textureChunks; - private int[] pixels; - - class RenderChunk implements IChunk { - Chunk chunk; - - public RenderChunk(Chunk chunk) { - this.chunk = chunk; - } - - @Override - public int getMaxY() { - return this.chunk.getTopFilledSegment() + 15; - } - - @Override - public int getBlockAndMetadata(int x, int y, int z) { - Block block = this.chunk.getBlock(x, y, z); - int blockid = Block.blockRegistry.getIDForObject(block); - int meta = this.chunk.getBlockMetadata(x, y, z); - return ((blockid & 0xfff) << 4) | (meta & 0xf); - } - - @Override - public int getBiome(int x, int z) { - return (int) this.chunk.getBiomeArray()[(z * 16) + x]; - } - - @Override - public int getLightValue(int x, int y, int z) { - return this.chunk.getBlockLightValue(x, y, z, 0); - } - } - - public UndergroundTexture(Mw mw, int textureSize, boolean linearScaling) { - super(textureSize, textureSize, 0x00000000, GL11.GL_NEAREST, GL11.GL_NEAREST, GL11.GL_REPEAT); - this.setLinearScaling(false); - this.textureSize = textureSize; - this.textureChunks = textureSize >> 4; - this.loadedChunkArray = new Point[this.textureChunks * this.textureChunks]; - this.pixels = new int[textureSize * textureSize]; - Arrays.fill(this.pixels, 0xff000000); - this.mw = mw; - } - - public void clear() { - Arrays.fill(this.pixels, 0xff000000); - this.updateTexture(); - } - - public void clearChunkPixels(int cx, int cz) { - int tx = (cx << 4) & (this.textureSize - 1); - int tz = (cz << 4) & (this.textureSize - 1); - for (int j = 0; j < 16; j++) { - int offset = ((tz + j) * this.textureSize) + tx; - Arrays.fill(this.pixels, offset, offset + 16, 0xff000000); - } - this.updateTextureArea(tx, tz, 16, 16); - } - - void renderToTexture(int y) { - this.setPixelBufPosition(0); - for (int i = 0; i < this.pixels.length; i++) { - int colour = this.pixels[i]; - int height = (colour >> 24) & 0xff; - int alpha = (y >= height) ? 255 - ((y - height) * 8) : 0; - if (alpha < 0) { - alpha = 0; - } - this.pixelBufPut(((alpha << 24) & 0xff000000) | (colour & 0xffffff)); - } - this.updateTexture(); - } - - public int getLoadedChunkOffset(int cx, int cz) { - int cxOffset = cx & (this.textureChunks - 1); - int czOffset = cz & (this.textureChunks - 1); - return (czOffset * this.textureChunks) + cxOffset; - } - - public void requestView(MapView view) { - int cxMin = ((int) view.getMinX()) >> 4; - int czMin = ((int) view.getMinZ()) >> 4; - int cxMax = ((int) view.getMaxX()) >> 4; - int czMax = ((int) view.getMaxZ()) >> 4; - for (int cz = czMin; cz <= czMax; cz++) { - for (int cx = cxMin; cx <= cxMax; cx++) { - Point requestedChunk = new Point(cx, cz); - int offset = this.getLoadedChunkOffset(cx, cz); - Point currentChunk = this.loadedChunkArray[offset]; - if ((currentChunk == null) || !currentChunk.equals(requestedChunk)) { - this.clearChunkPixels(cx, cz); - this.loadedChunkArray[offset] = requestedChunk; - } - } - } - } - - public boolean isChunkInTexture(int cx, int cz) { - Point requestedChunk = new Point(cx, cz); - int offset = this.getLoadedChunkOffset(cx, cz); - Point chunk = this.loadedChunkArray[offset]; - return (chunk != null) && chunk.equals(requestedChunk); - } - - public void update() { - this.clearFlags(); - - if (this.dimension != this.mw.playerDimension) { - this.clear(); - this.dimension = this.mw.playerDimension; - } - this.px = this.mw.playerXInt; - this.py = this.mw.playerYInt; - this.pz = this.mw.playerZInt; - - this.updateX = (this.px >> 4) - 1; - this.updateZ = (this.pz >> 4) - 1; - - this.processBlock( - this.px - (this.updateX << 4), - this.py, - this.pz - (this.updateZ << 4) - ); - - int cxMax = this.updateX + 2; - int czMax = this.updateZ + 2; - WorldClient world = this.mw.mc.theWorld; - int flagOffset = 0; - for (int cz = this.updateZ; cz <= czMax; cz++) { - for (int cx = this.updateX; cx <= cxMax; cx++) { - if (this.isChunkInTexture(cx, cz)) { - Chunk chunk = world.getChunkFromChunkCoords(cx, cz); - int tx = (cx << 4) & (this.textureSize - 1); - int tz = (cz << 4) & (this.textureSize - 1); - int pixelOffset = (tz * this.textureSize) + tx; - byte[] mask = this.updateFlags[flagOffset]; - ChunkRender.renderUnderground( - this.mw.blockColours, - new RenderChunk(chunk), - this.pixels, pixelOffset, this.textureSize, - this.py, mask - ); - } - flagOffset += 1; - } - } - - this.renderToTexture(this.py + 1); - } - - private void clearFlags() { - for (byte[] chunkFlags : this.updateFlags) { - Arrays.fill(chunkFlags, ChunkRender.FLAG_UNPROCESSED); - } - } - - private void processBlock(int xi, int y, int zi) { - int x = (this.updateX << 4) + xi; - int z = (this.updateZ << 4) + zi; - - int xDist = this.px - x; - int zDist = this.pz - z; - - if (((xDist * xDist) + (zDist * zDist)) <= 256) { - if (this.isChunkInTexture(x >> 4, z >> 4)) { - int chunkOffset = ((zi >> 4) * 3) + (xi >> 4); - int columnXi = xi & 0xf; - int columnZi = zi & 0xf; - int columnOffset = (columnZi << 4) + columnXi; - byte columnFlag = this.updateFlags[chunkOffset][columnOffset]; - - if (columnFlag == ChunkRender.FLAG_UNPROCESSED) { - // if column not yet processed - WorldClient world = this.mw.mc.theWorld; - Block block = world.getBlock(x, y, z); - if ((block == null) || !block.isOpaqueCube()) { - // if block is not opaque - this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_NON_OPAQUE; - this.processBlock(xi + 1, y, zi); - this.processBlock(xi - 1, y, zi); - this.processBlock(xi, y, zi + 1); - this.processBlock(xi, y, zi - 1); - } else { - // block is opaque - this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_OPAQUE; - } - } - } - } - } - -} diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java deleted file mode 100644 index 6a99055..0000000 --- a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java +++ /dev/null @@ -1,26 +0,0 @@ -package mapwriter.map.mapmode; - -import mapwriter.forge.MwConfig; - -public class FullScreenMapMode extends MapMode { - public FullScreenMapMode(MwConfig config) { - super(config, "fullScreenMap"); - - this.heightPercent = -1; - this.marginTop = 0; - this.marginBottom = 0; - this.marginLeft = 0; - this.marginRight = 0; - - this.borderMode = 0; - this.playerArrowSize = 5; - this.markerSize = 5; - this.alphaPercent = 100; - - this.rotate = false; - this.circular = false; - this.coordsEnabled = false; - - this.loadConfig(); - } -} diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java deleted file mode 100644 index 191ee8b..0000000 --- a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java +++ /dev/null @@ -1,22 +0,0 @@ -package mapwriter.map.mapmode; - -import mapwriter.forge.MwConfig; - -public class LargeMapMode extends MapMode { - public LargeMapMode(MwConfig config) { - super(config, "largeMap"); - - this.heightPercent = -1; - this.marginTop = 10; - this.marginBottom = 40; - this.marginLeft = 40; - this.marginRight = 40; - - this.playerArrowSize = 5; - this.markerSize = 5; - - this.coordsEnabled = true; - - this.loadConfig(); - } -} diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java deleted file mode 100644 index eec53bb..0000000 --- a/src/main/java/mapwriter/map/mapmode/MapMode.java +++ /dev/null @@ -1,254 +0,0 @@ -package mapwriter.map.mapmode; - -import java.awt.Point; - -import mapwriter.forge.MwConfig; -import mapwriter.map.MapView; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ScaledResolution; - -public class MapMode { - private final MwConfig config; - public final String configCategory; - - private int sw = 320; - private int sh = 240; - private double screenScalingFactor = 1.0; - - // calculated before every frame drawn by updateMapDimensions - public int xTranslation = 0; - public int yTranslation = 0; - public int x = -25; - public int y = -25; - public int w = 50; - public int h = 50; - public int wPixels = 50; - public int hPixels = 50; - - // config settings - public boolean enabled = true; - public boolean rotate = true; - public boolean circular = true; - public boolean coordsEnabled = false; - public int borderMode = 1; - public int playerArrowSize = 5; - public int markerSize = 5; - public int trailMarkerSize = 3; - public int alphaPercent = 100; - - public int marginTop = 0; - public int marginBottom = 0; - public int marginLeft = 0; - public int marginRight = 0; - public int heightPercent = -1; - - public int textX = 0; - public int textY = 0; - public int textColour = 0xffffffff; - - public MapMode(MwConfig config, String configCategory) { - this.config = config; - this.configCategory = configCategory; - } - - public void loadConfig() { - // get options from config file - this.enabled = this.config.getOrSetBoolean(this.configCategory, "enabled", this.enabled); - this.playerArrowSize = this.config.getOrSetInt(this.configCategory, "playerArrowSize", this.playerArrowSize, 1, 20); - this.markerSize = this.config.getOrSetInt(this.configCategory, "markerSize", this.markerSize, 1, 20); - this.alphaPercent = this.config.getOrSetInt(this.configCategory, "alphaPercent", this.alphaPercent, 0, 100); - - this.heightPercent = this.config.getOrSetInt(this.configCategory, "heightPercent", this.heightPercent, 0, 100); - this.marginTop = this.config.getOrSetInt(this.configCategory, "marginTop", this.marginTop, -1, 320); - this.marginBottom = this.config.getOrSetInt(this.configCategory, "marginBottom", this.marginBottom, -1, 320); - this.marginLeft = this.config.getOrSetInt(this.configCategory, "marginLeft", this.marginLeft, -1, 320); - this.marginRight = this.config.getOrSetInt(this.configCategory, "marginRight", this.marginRight, -1, 320); - - this.rotate = this.config.getOrSetBoolean(this.configCategory, "rotate", this.rotate); - this.circular = this.config.getOrSetBoolean(this.configCategory, "circular", this.circular); - this.coordsEnabled = this.config.getOrSetBoolean(this.configCategory, "coordsEnabled", this.coordsEnabled); - this.borderMode = this.config.getOrSetInt(this.configCategory, "borderMode", this.borderMode, 0, 1); - - this.trailMarkerSize = Math.max(1, this.markerSize - 1); - } - - public void saveConfig() { - this.config.setBoolean(this.configCategory, "enabled", this.enabled); - this.config.setInt(this.configCategory, "heightPercent", this.heightPercent); - this.config.setInt(this.configCategory, "marginTop", this.marginTop); - this.config.setInt(this.configCategory, "marginBottom", this.marginBottom); - this.config.setInt(this.configCategory, "marginLeft", this.marginLeft); - this.config.setInt(this.configCategory, "marginRight", this.marginRight); - this.config.setBoolean(this.configCategory, "rotate", this.rotate); - this.config.setBoolean(this.configCategory, "circular", this.circular); - } - - public void close() { - this.saveConfig(); - } - - public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { - if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { - this.sw = sw; - this.sh = sh; - this.screenScalingFactor = scaling; - this.update(); - } - } - - public void setScreenRes() { - Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution sRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); - } - - public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { - this.marginTop = marginTop; - this.marginBottom = marginBottom; - this.marginLeft = marginLeft; - this.marginRight = marginRight; - this.update(); - } - - public void setHeightPercent(int heightPercent) { - this.heightPercent = heightPercent; - this.update(); - } - - public void toggleHeightPercent() { - int i = (this.heightPercent / 5) + 1; - if (i > 12) { - i = 1; - } - this.setHeightPercent(i * 5); - } - - private void update() { - int size = (this.sh * this.heightPercent) / 100; - int x, y; - - // calculate map x position and width - if ((this.marginLeft >= 0) && (this.marginRight >= 0)) { - x = this.marginLeft; - this.w = this.sw - this.marginLeft - this.marginRight; - } else if (this.marginLeft >= 0) { - x = this.marginLeft; - this.w = size; - } else if (this.marginRight >= 0) { - x = this.sw - size - this.marginRight; - this.w = size; - } else { - x = (this.sw - size) / 2; - this.w = size; - } - - // calculate map y position and height - if ((this.marginTop >= 0) && (this.marginBottom >= 0)) { - y = this.marginTop; - this.h = this.sh - this.marginTop - this.marginBottom; - } else if (this.marginTop >= 0) { - y = this.marginTop; - this.h = size; - } else if (this.marginBottom >= 0) { - y = this.sh - size - this.marginBottom; - this.h = size; - } else { - y = (this.sh - size) / 2; - this.h = size; - } - - // make sure width and height are multiples of 2 - this.w &= -2; - this.h &= -2; - - this.xTranslation = x + (this.w >> 1); - this.yTranslation = y + (this.h >> 1); - - if (this.circular) { - this.w = this.h; - } - - this.x = -(this.w >> 1); - this.y = -(this.h >> 1); - - this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); - this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); - - // calculate coords display location - this.textX = 0; - this.textY = (this.h >> 1) + 4; - - //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); - //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", - // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); - } - - public void setRotating(boolean enabled) { - this.rotate = enabled; - this.circular = enabled; - this.update(); - } - - public boolean toggleRotating() { - this.setRotating(!this.rotate); - return this.rotate; - } - - public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { - double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); - double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); - int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); - int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); - return new Point(bx, bz); - } - - public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { - double xNorm = (bX - mapView.getX()) / mapView.getWidth(); - double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); - return new Point.Double(this.w * xNorm, this.h * zNorm); - } - - public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { - double xRel = (bX - mapView.getX()) / mapView.getWidth(); - double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); - double limit = 0.49; - - if (!this.circular) { - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - if (zRel < -limit) { - xRel = -limit * xRel / zRel; - zRel = -limit; - } - if (zRel > limit) { - xRel = limit * xRel / zRel; - zRel = limit; - } - if (xRel < -limit) { - zRel = -limit * zRel / xRel; - xRel = -limit; - } - if (xRel > limit) { - zRel = limit * zRel / xRel; - xRel = limit; - } - } else { - double dSq = (xRel * xRel) + (zRel * zRel); - if (dSq > (limit * limit)) { - double a = Math.atan2(zRel, xRel); - xRel = limit * Math.cos(a); - zRel = limit * Math.sin(a); - } - } - - // multiply by the overlay size and add the overlay position to - // get the position within the overlay in screen coordinates - return new Point.Double(this.w * xRel, this.h * zRel); - } -} diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java deleted file mode 100644 index 20f4fd8..0000000 --- a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java +++ /dev/null @@ -1,22 +0,0 @@ -package mapwriter.map.mapmode; - -import mapwriter.forge.MwConfig; - -public class SmallMapMode extends MapMode { - public SmallMapMode(MwConfig config) { - super(config, "smallMap"); - - this.heightPercent = 30; - this.marginTop = 10; - this.marginBottom = -1; - this.marginLeft = -1; - this.marginRight = 10; - - this.playerArrowSize = 4; - this.markerSize = 3; - - this.coordsEnabled = true; - - this.loadConfig(); - } -} diff --git a/src/main/java/mapwriter/overlay/OverlayChecker.java b/src/main/java/mapwriter/overlay/OverlayChecker.java deleted file mode 100644 index 62c6847..0000000 --- a/src/main/java/mapwriter/overlay/OverlayChecker.java +++ /dev/null @@ -1,115 +0,0 @@ -package mapwriter.overlay; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.util.MathHelper; - -public class OverlayChecker implements IMwDataProvider { - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - - public ChunkOverlay(int x, int z){ - this.coord = new Point(x, z); - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return 0x90ffffff; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - - // We should pass the center of the map too to reduce the display like in this case - // and the zoom lvl, to provide higher level informations - - int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; - int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; - int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; - int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; - int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; - int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; - - int limitMinX = Math.max(minChunkX, cX - 100); - int limitMaxX = Math.min(maxChunkX, cX + 100); - int limitMinZ = Math.max(minChunkZ, cZ - 100); - int limitMaxZ = Math.min(maxChunkZ, cZ + 100); - - ArrayList chunks = new ArrayList(); - for (int x = limitMinX; x <= limitMaxX; x++) - for (int z = limitMinZ; z <= limitMaxZ; z++){ - if ((x+z)%2 == 0) - chunks.add(new ChunkOverlay(x, z)); - }; - - return chunks; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onOverlayActivated(MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub - - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/src/main/java/mapwriter/overlay/OverlayGrid.java b/src/main/java/mapwriter/overlay/OverlayGrid.java deleted file mode 100644 index 68ae31b..0000000 --- a/src/main/java/mapwriter/overlay/OverlayGrid.java +++ /dev/null @@ -1,109 +0,0 @@ -package mapwriter.overlay; - -import java.awt.Point; -import java.util.ArrayList; - -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.util.MathHelper; - -public class OverlayGrid implements IMwDataProvider { - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - - public ChunkOverlay(int x, int z){ - this.coord = new Point(x, z); - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return 0x00ffffff; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; - int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; - int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; - int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; - int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; - int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; - - int limitMinX = Math.max(minChunkX, cX - 100); - int limitMaxX = Math.min(maxChunkX, cX + 100); - int limitMinZ = Math.max(minChunkZ, cZ - 100); - int limitMaxZ = Math.min(maxChunkZ, cZ + 100); - - ArrayList chunks = new ArrayList(); - for (int x = limitMinX; x <= limitMaxX; x++) - for (int z = limitMinZ; z <= limitMaxZ; z++) - chunks.add(new ChunkOverlay(x, z)); - - return chunks; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onOverlayActivated(MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub - - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java deleted file mode 100644 index 5233a0d..0000000 --- a/src/main/java/mapwriter/overlay/OverlaySlime.java +++ /dev/null @@ -1,157 +0,0 @@ -package mapwriter.overlay; - -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityClientPlayerMP; -import net.minecraft.util.MathHelper; - -import java.awt.*; -import java.util.ArrayList; -import java.util.Random; - -public class OverlaySlime implements IMwDataProvider { - - public static boolean seedFound = false; - public static boolean seedAsked = false; - private static long seed = -1; - - public static void setSeed(long seed){ - OverlaySlime.seed = seed; - OverlaySlime.seedFound = true; - } - - public static void askSeed(){ - EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; - if(player == null) return; - player.sendChatMessage("/seed"); //Send the /seed command to the server - seedAsked = true; - } - - public static void reset(){ - seedFound = false; - seedAsked = false; - seed = -1; - } - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - - public ChunkOverlay(int x, int z){ - this.coord = new Point(x, z); - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return 0x5000ff00; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - - // We should pass the center of the map too to reduce the display like in this case - // and the zoom lvl, to provide higher level informations - - if (Minecraft.getMinecraft().thePlayer.getEntityWorld().provider.dimensionId != dim) - return new ArrayList(); - - int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; - int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; - int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; - int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; - int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; - int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; - - int limitMinX = Math.max(minChunkX, cX - 100); - int limitMaxX = Math.min(maxChunkX, cX + 100); - int limitMinZ = Math.max(minChunkZ, cZ - 100); - int limitMaxZ = Math.min(maxChunkZ, cZ + 100); - - if(!seedFound && !seedAsked){ - //We don't have the seed and we didn't ask for it yet. Let's go! - askSeed(); - } - - ArrayList chunks = new ArrayList(); - if(seedFound){ //If we know the seed, then add the overlay - for (int x = limitMinX; x <= limitMaxX; x++) - for (int z = limitMinZ; z <= limitMaxZ; z++){ - - Random rnd = new Random(seed + - (long) (x * x * 0x4c1906) + - (long) (x * 0x5ac0db) + - (long) (z * z) * 0x4307a7L + - (long) (z * 0x5f24f) ^ 0x3ad8025f); - if (rnd.nextInt(10) == 0){ - chunks.add(new ChunkOverlay(x, z)); - } - } - } - - return chunks; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onOverlayActivated(MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - // TODO Auto-generated method stub - - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub - - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java deleted file mode 100644 index 0a32a37..0000000 --- a/src/main/java/mapwriter/region/BlockColours.java +++ /dev/null @@ -1,464 +0,0 @@ -package mapwriter.region; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Scanner; - -public class BlockColours { - - public static final int MAX_BLOCKS = 4096; - public static final int MAX_META = 16; - public static final int MAX_BIOMES = 256; - - public static final String biomeSectionString = "[biomes]"; - public static final String blockSectionString = "[blocks]"; - - private int[] bcArray = new int[MAX_BLOCKS * MAX_META]; - private int[] waterMultiplierArray = new int[MAX_BIOMES]; - private int[] grassMultiplierArray = new int[MAX_BIOMES]; - private int[] foliageMultiplierArray = new int[MAX_BIOMES]; - - public enum BlockType { - NORMAL, - GRASS, - LEAVES, - FOLIAGE, - WATER, - OPAQUE - } - - private BlockType[] blockTypeArray = new BlockType[MAX_BLOCKS * MAX_META]; - - public BlockColours() { - Arrays.fill(this.bcArray, 0); - Arrays.fill(this.waterMultiplierArray, 0xffffff); - Arrays.fill(this.grassMultiplierArray, 0xffffff); - Arrays.fill(this.foliageMultiplierArray, 0xffffff); - Arrays.fill(this.blockTypeArray, BlockType.NORMAL); - } - - public int getColour(int blockAndMeta) { - return this.bcArray[blockAndMeta & 0xffff]; - } - - public void setColour(int blockAndMeta, int colour) { - this.bcArray[blockAndMeta & 0xffff] = colour; - } - - public int getColour(int blockID, int meta) { - return this.bcArray[((blockID & 0xfff) << 4) | (meta & 0xf)]; - } - - public void setColour(int blockID, int meta, int colour) { - this.bcArray[((blockID & 0xfff) << 4) | (meta & 0xf)] = colour; - } - - private int getGrassColourMultiplier(int biome) { - return (this.grassMultiplierArray != null) && (biome >= 0) && (biome < this.grassMultiplierArray.length) ? - this.grassMultiplierArray[biome] : 0xffffff; - } - - private int getWaterColourMultiplier(int biome) { - return (this.waterMultiplierArray != null) && (biome >= 0) && (biome < this.waterMultiplierArray.length) ? - this.waterMultiplierArray[biome] : 0xffffff; - } - - private int getFoliageColourMultiplier(int biome) { - return (this.foliageMultiplierArray != null) && (biome >= 0) && (biome < this.foliageMultiplierArray.length) ? - this.foliageMultiplierArray[biome] : 0xffffff; - } - - public int getBiomeColour(int blockAndMeta, int biome) { - blockAndMeta &= 0xffff; - int colourMultiplier; - switch(this.blockTypeArray[blockAndMeta]) { - case GRASS: - colourMultiplier = getGrassColourMultiplier(biome); - break; - case LEAVES: - case FOLIAGE: - colourMultiplier = getFoliageColourMultiplier(biome); - break; - case WATER: - colourMultiplier = getWaterColourMultiplier(biome); - break; - default: - colourMultiplier = 0xffffff; - break; - } - return colourMultiplier; - } - - public void setBiomeWaterShading(int biomeID, int colour) { - this.waterMultiplierArray[biomeID & 0xff] = colour; - } - - public void setBiomeGrassShading(int biomeID, int colour) { - this.grassMultiplierArray[biomeID & 0xff] = colour; - } - - public void setBiomeFoliageShading(int biomeID, int colour) { - this.foliageMultiplierArray[biomeID & 0xff] = colour; - } - - private static BlockType getBlockTypeFromString(String typeString) { - BlockType blockType = BlockType.NORMAL; - if (typeString.equalsIgnoreCase("normal")) { - blockType = BlockType.NORMAL; - } else if (typeString.equalsIgnoreCase("grass")) { - blockType = BlockType.GRASS; - } else if (typeString.equalsIgnoreCase("leaves")) { - blockType = BlockType.LEAVES; - } else if (typeString.equalsIgnoreCase("foliage")) { - blockType = BlockType.FOLIAGE; - } else if (typeString.equalsIgnoreCase("water")) { - blockType = BlockType.WATER; - } else if (typeString.equalsIgnoreCase("opaque")) { - blockType = BlockType.OPAQUE; - } else { - RegionManager.logWarning("unknown block type '%s'", typeString); - } - return blockType; - } - - private static String getBlockTypeAsString(BlockType blockType) { - String s = "normal"; - switch (blockType) { - case NORMAL: - s = "normal"; - break; - case GRASS: - s = "grass"; - break; - case LEAVES: - s = "leaves"; - break; - case FOLIAGE: - s = "foliage"; - break; - case WATER: - s = "water"; - break; - case OPAQUE: - s = "opaque"; - break; - } - return s; - } - - public BlockType getBlockType(int blockAndMeta) { - return this.blockTypeArray[blockAndMeta & 0xffff]; - } - - public BlockType getBlockType(int blockId, int meta) { - return this.blockTypeArray[((blockId & 0xfff) << 4) | (meta & 0xf)]; - } - - public void setBlockType(int blockId, int meta, BlockType type) { - this.blockTypeArray[((blockId & 0xfff) << 4) | (meta & 0xf)] = type; - } - - public void setBlockType(int blockAndMeta, BlockType type) { - this.blockTypeArray[blockAndMeta & 0xffff] = type; - } - - public static int getColourFromString(String s) { - return (int) (Long.parseLong(s, 16) & 0xffffffffL); - } - - // - // Methods for loading block colours from file: - // - - // read biome colour multiplier values. - // line format is: - // biome - // accepts "*" wildcard for biome id (meaning for all biomes). - private void loadBiomeLine(String[] split) { - try { - int startBiomeId = 0; - int endBiomeId = MAX_BIOMES; - if (!split[1].equals("*")) { - startBiomeId = Integer.parseInt(split[1]); - endBiomeId = startBiomeId + 1; - } - - if ((startBiomeId >= 0) && (startBiomeId < MAX_BIOMES)) { - int waterMultiplier = getColourFromString(split[2]) & 0xffffff; - int grassMultiplier = getColourFromString(split[3]) & 0xffffff; - int foliageMultiplier = getColourFromString(split[4]) & 0xffffff; - - for (int biomeId = startBiomeId; biomeId < endBiomeId; biomeId++) { - this.setBiomeWaterShading(biomeId, waterMultiplier); - this.setBiomeGrassShading(biomeId, grassMultiplier); - this.setBiomeFoliageShading(biomeId, foliageMultiplier); - } - } else { - RegionManager.logWarning("biome ID '%d' out of range", startBiomeId); - } - - } catch (NumberFormatException e) { - RegionManager.logWarning("invalid biome colour line '%s %s %s %s %s'", split[0], split[1], split[2], split[3], split[4]); - } - } - - // read block colour values. - // line format is: - // block - // the biome id, meta value, and colour code are in hex. - // accepts "*" wildcard for biome id and meta (meaning for all blocks and/or meta values). - private void loadBlockLine(String[] split, boolean isBlockColourLine) { - try { - int startBlockId = 0; - int endBlockId = MAX_BLOCKS; - if (!split[1].equals("*")) { - startBlockId = Integer.parseInt(split[1]); - endBlockId = startBlockId + 1; - } - - int startBlockMeta = 0; - int endBlockMeta = MAX_META; - if (!split[2].equals("*")) { - startBlockMeta = Integer.parseInt(split[2]); - endBlockMeta = startBlockMeta + 1; - } - - if ((startBlockId >= 0) && (startBlockId < MAX_BLOCKS) && (startBlockMeta >= 0) && (startBlockMeta < MAX_META)) { - if (isBlockColourLine) { - // block colour line - int colour = getColourFromString(split[3]); - - for (int blockId = startBlockId; blockId < endBlockId; blockId++) { - for (int blockMeta = startBlockMeta; blockMeta < endBlockMeta; blockMeta++) { - this.setColour(blockId, blockMeta, colour); - } - } - } else { - // block type line - BlockType type = getBlockTypeFromString(split[3]); - - for (int blockId = startBlockId; blockId < endBlockId; blockId++) { - for (int blockMeta = startBlockMeta; blockMeta < endBlockMeta; blockMeta++) { - this.setBlockType(blockId, blockMeta, type); - } - } - } - } - - } catch (NumberFormatException e) { - RegionManager.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); - } - } - - public void loadFromFile(File f) { - Scanner fin = null; - try { - fin = new Scanner(new FileReader(f)); - - while (fin.hasNextLine()) { - // get next line and remove comments (part of line after #) - String line = fin.nextLine().split("#")[0].trim(); - if (line.length() > 0) { - String[] lineSplit = line.split(" "); - if (lineSplit[0].equals("biome") && (lineSplit.length == 5)) { - this.loadBiomeLine(lineSplit); - } else if (lineSplit[0].equals("block") && (lineSplit.length == 4)) { - this.loadBlockLine(lineSplit, true); - } else if (lineSplit[0].equals("blocktype") && (lineSplit.length == 4)) { - this.loadBlockLine(lineSplit, false); - } else { - RegionManager.logWarning("invalid map colour line '%s'", line); - } - } - } - } catch (IOException e) { - RegionManager.logError("loading block colours: no such file '%s'", f); - - } finally { - if (fin != null) { - fin.close(); - } - } - } - - // - // Methods for saving block colours to file. - // - - // save biome colour multipliers to a file. - public void saveBiomes(Writer fout) throws IOException { - fout.write("biome * ffffff ffffff ffffff\n"); - - for (int biomeId = 0; biomeId < MAX_BIOMES; biomeId++) { - int waterMultiplier = this.getWaterColourMultiplier(biomeId) & 0xffffff; - int grassMultiplier = this.getGrassColourMultiplier(biomeId) & 0xffffff; - int foliageMultiplier = this.getFoliageColourMultiplier(biomeId) & 0xffffff; - - // don't add lines that are covered by the default. - if ((waterMultiplier != 0xffffff) || (grassMultiplier != 0xffffff) || (foliageMultiplier != 0xffffff)) { - fout.write(String.format("biome %d %06x %06x %06x\n", biomeId, waterMultiplier, grassMultiplier, foliageMultiplier)); - } - } - } - - private static String getMostOccurringKey(Map map, String defaultItem) { - // find the most commonly occurring key in a hash map. - // only return a key if there is more than 1. - int maxCount = 1; - String mostOccurringKey = defaultItem; - for (Entry entry : map.entrySet()) { - String key = entry.getKey(); - int count = entry.getValue(); - - if (count > maxCount) { - maxCount = count; - mostOccurringKey = key; - } - } - - return mostOccurringKey; - } - - // to use the least number of lines possible find the most commonly occurring - // item for the 16 different meta values of a block. - // an 'item' is either a block colour or a block type. - // the most commonly occurring item is then used as the wildcard entry for - // the block, and all non matching items added afterwards. - private static void writeMinimalBlockLines(Writer fout, String lineStart, String[] items, String defaultItem) throws IOException { - - Map frequencyMap = new HashMap(); - - // first count the number of occurrences of each item. - for (String item : items) { - int count = 0; - if (frequencyMap.containsKey(item)) { - count = frequencyMap.get(item); - } - frequencyMap.put(item, count + 1); - } - - // then find the most commonly occurring item. - String mostOccurringItem = getMostOccurringKey(frequencyMap, defaultItem); - - // only add a wildcard line if it actually saves lines. - if (!mostOccurringItem.equals(defaultItem)) { - fout.write(String.format("%s * %s\n", lineStart, mostOccurringItem)); - } - - // add lines for items that don't match the wildcard line. - for (int i = 0; i < items.length; i++) { - if (!items[i].equals(mostOccurringItem) && !items[i].equals(defaultItem)) { - fout.write(String.format("%s %d %s\n", lineStart, i, items[i])); - } - } - } - - public void saveBlocks(Writer fout) throws IOException { - fout.write("block * * 00000000\n"); - - String[] colours = new String[MAX_META]; - - for (int blockId = 0; blockId < MAX_BLOCKS; blockId++) { - // build a 16 element list of block colours - for (int meta = 0; meta < MAX_META; meta++) { - colours[meta] = String.format("%08x", this.getColour(blockId, meta)); - } - // write a minimal representation to the file - String lineStart = String.format("block %d", blockId); - writeMinimalBlockLines(fout, lineStart, colours, "00000000"); - } - } - - public void saveBlockTypes(Writer fout) throws IOException { - fout.write("blocktype * * normal\n"); - - String[] blockTypes = new String[MAX_META]; - - for (int blockId = 0; blockId < MAX_BLOCKS; blockId++) { - // build a 16 element list of block types - for (int meta = 0; meta < MAX_META; meta++) { - BlockType bt = this.getBlockType(blockId, meta); - blockTypes[meta] = getBlockTypeAsString(bt); - } - // write a minimal representation to the file - String lineStart = String.format("blocktype %d", blockId); - writeMinimalBlockLines(fout, lineStart, blockTypes, "normal"); - } - } - - // save block colours and biome colour multipliers to a file. - public void saveToFile(File f) { - Writer fout = null; - try { - fout = new OutputStreamWriter(new FileOutputStream(f)); - this.saveBiomes(fout); - this.saveBlockTypes(fout); - this.saveBlocks(fout); - - } catch (IOException e) { - RegionManager.logError("saving block colours: could not write to '%s'", f); - - } finally { - if (fout != null) { - try { - fout.close(); - } catch (IOException e) {} - } - } - } - - public static void writeOverridesFile(File f) { - Writer fout = null; - try { - fout = new OutputStreamWriter(new FileOutputStream(f)); - - fout.write( - "block 37 * 60ffff00 # make dandelions more yellow\n" + - "block 38 * 60ff0000 # make roses more red\n" + - "blocktype 2 * grass # grass block\n" + - "blocktype 8 * water # still water block\n" + - "blocktype 9 * water # flowing water block\n" + - "blocktype 18 * leaves # leaves block\n" + - "blocktype 18 1 opaque # pine leaves (not biome colorized)\n" + - "blocktype 18 2 opaque # birch leaves (not biome colorized)\n" + - "blocktype 31 * grass # tall grass block\n" + - "blocktype 106 * foliage # vines block\n" + - "blocktype 169 * grass # biomes o plenty holy grass\n" + - "blocktype 1920 * grass # biomes o plenty plant\n" + - "blocktype 1923 * opaque # biomes o plenty leaves 1\n" + - "blocktype 1924 * opaque # biomes o plenty leaves 2\n" + - "blocktype 1925 * foliage # biomes o plenty foliage\n" + - "blocktype 1926 * opaque # biomes o plenty fruit leaf block\n" + - "blocktype 1932 * foliage # biomes o plenty tree moss\n" + - "blocktype 1962 * leaves # biomes o plenty colorized leaves\n" + - "blocktype 2164 * leaves # twilight forest leaves\n" + - "blocktype 2177 * leaves # twilight forest magic leaves\n" + - "blocktype 2204 * leaves # extrabiomesXL green leaves\n" + - "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" + - "blocktype 3257 * opaque # natura berry bush\n" + - "blocktype 3272 * opaque # natura darkwood leaves\n" + - "blocktype 3259 * leaves # natura flora leaves\n" + - "blocktype 3278 * opaque # natura rare leaves\n" + - "blocktype 3258 * opaque # natura sakura leaves\n" - ); - - } catch (IOException e) { - RegionManager.logError("saving block overrides: could not write to '%s'", f); - - } finally { - if (fout != null) { - try { - fout.close(); - } catch (IOException e) {} - } - } - } -} diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java deleted file mode 100644 index 6dc7934..0000000 --- a/src/main/java/mapwriter/region/ChunkRender.java +++ /dev/null @@ -1,211 +0,0 @@ -package mapwriter.region; - -public class ChunkRender { - - public static final byte FLAG_UNPROCESSED = 0; - public static final byte FLAG_NON_OPAQUE = 1; - public static final byte FLAG_OPAQUE = 2; - - - // values that change how height shading algorithm works - public static final double brightenExponent = 0.35; - public static final double darkenExponent = 0.35; - public static final double brightenAmplitude = 0.7; - public static final double darkenAmplitude = 1.4; - - // get the height shading of a pixel. - // requires the pixel to the west and the pixel to the north to have their - // heights stored in the alpha channel to work. - // the "height" of a pixel is the y value of the first opaque block in - // the block column that created the pixel. - // height values of 0 and 255 are ignored as these are used as the clear - // values for pixels. - public static double getHeightShading(int height, int heightW, int heightN) { - int samples = 0; - int heightDiff = 0; - - if ((heightW > 0) && (heightW < 255)) { - heightDiff += height - heightW; - samples++; - } - - if ((heightN > 0) && (heightN < 255)) { - heightDiff += height - heightN; - samples++; - } - - double heightDiffFactor = 0.0; - if (samples > 0) { - heightDiffFactor = (double) heightDiff / ((double) samples * 255.0); - } - - // emphasize small differences in height, but as the difference in height increases, - // don't increase so much - // TODO: probably more accurate to use atan here rather than a fractional - // exponent. - return (heightDiffFactor >= 0.0) ? - Math.pow(heightDiffFactor, brightenExponent) * brightenAmplitude : - -Math.pow(-heightDiffFactor, darkenExponent) * darkenAmplitude; - } - - // calculate the colour of a pixel by alpha blending the colour of each block - // in a column until an opaque block is reached. - // y is topmost block height to start rendering at. - // for maps without a ceiling y is simply the height of the highest block in that chunk. - // for maps with a ceiling y is the height of the first non opaque block starting from - // the ceiling. - // - // for every block in the column starting from the highest: - // - get the block colour - // - get the biome shading - // - extract colour components as doubles in the range [0.0, 1.0] - // - the shaded block colour is simply the block colour multiplied - // by the biome shading for each component - // - this shaded block colour is alpha blended with the running - // colour for this column - // - // so the final map colour is an alpha blended stack of all the - // individual shaded block colours in the sequence [yStart .. yEnd] - // - // note that the "front to back" alpha blending algorithm is used - // rather than the more common "back to front". - // - public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, int z, int heightW, int heightN) { - double a = 1.0; - double r = 0.0; - double g = 0.0; - double b = 0.0; - for (; y > 0; y--) { - int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - - int c1 = bc.getColour(blockAndMeta); - int alpha = (c1 >> 24) & 0xff; - // no need to process block if it is transparent - if (alpha > 0) { - int biome = chunk.getBiome(x, z); - int c2 = bc.getBiomeColour(blockAndMeta, biome); - - // extract colour components as normalized doubles - double c1A = (double) (alpha) / 255.0; - double c1R = (double) ((c1 >> 16) & 0xff) / 255.0; - double c1G = (double) ((c1 >> 8) & 0xff) / 255.0; - double c1B = (double) ((c1 >> 0) & 0xff) / 255.0; - - // c2A is implicitly 1.0 (opaque) - double c2R = (double) ((c2 >> 16) & 0xff) / 255.0; - double c2G = (double) ((c2 >> 8) & 0xff) / 255.0; - double c2B = (double) ((c2 >> 0) & 0xff) / 255.0; - - // alpha blend and multiply - r = r + (a * c1A * c1R * c2R); - g = g + (a * c1A * c1G * c2G); - b = b + (a * c1A * c1B * c2B); - a = a * (1.0 - c1A); - } - // break when an opaque block is encountered - if (alpha == 0xff) { - break; - } - } - - /* - // darken blocks depending on how far away they are from this depth slice - if (depth != 0) { - int bottomOfSlice = maxHeight - ((depth + 1) * maxHeight / Mw.HEIGHT_LEVELS) - 1; - if (yRange[0] < bottomOfSlice) { - shading *= 1.0 - 2.0 * ((double) (bottomOfSlice - yRange[0]) / (double) maxHeight); - } - }*/ - - double heightShading = getHeightShading(y, heightW, heightN); - int lightValue = chunk.getLightValue(x, y + 1, z); - double lightShading = (double) lightValue / 15.0; - double shading = (heightShading + 1.0) * lightShading; - - // apply the shading - r = Math.min(Math.max(0.0, r * shading), 1.0); - g = Math.min(Math.max(0.0, g * shading), 1.0); - b = Math.min(Math.max(0.0, b * shading), 1.0); - - // now we have our final RGB values as doubles, convert to a packed ARGB pixel. - return ((y & 0xff) << 24) | - ((((int) (r * 255.0)) & 0xff) << 16) | - ((((int) (g * 255.0)) & 0xff) << 8) | - ((((int) (b * 255.0)) & 0xff)); - } - - static int getPixelHeightN(int[] pixels, int offset, int scanSize) { - return (offset >= scanSize) ? ((pixels[offset - scanSize] >> 24) & 0xff) : -1; - } - - static int getPixelHeightW(int[] pixels, int offset, int scanSize) { - return ((offset & (scanSize - 1)) >= 1) ? ((pixels[offset - 1] >> 24) & 0xff) : -1; - } - - public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, boolean dimensionHasCeiling) { - int chunkMaxY = chunk.getMaxY(); - for (int z = 0; z < MwChunk.SIZE; z++) { - for (int x = 0; x < MwChunk.SIZE; x++) { - // for the nether dimension search for the first non-opaque - // block below the ceiling. - // cannot use y = chunkMaxY as the nether sometimes spawns - // mushrooms above the ceiling height. this fixes the - // rectangular grey areas (ceiling bedrock) on the nether map. - int y; - if (dimensionHasCeiling) { - for (y = 127; y >= 0; y--) { - int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; - if (alpha != 0xff) { - break; - } - } - } else { - y = chunkMaxY; - } - - int pixelOffset = offset + (z * scanSize) + x; - pixels[pixelOffset] = getColumnColour( - bc, chunk, x, y, z, - getPixelHeightW(pixels, pixelOffset, scanSize), - getPixelHeightN(pixels, pixelOffset, scanSize) - ); - } - } - } - - public static void renderUnderground(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, int startY, byte[] mask) { - startY = Math.min(Math.max(0, startY), 255); - for (int z = 0; z < MwChunk.SIZE; z++) { - for (int x = 0; x < MwChunk.SIZE; x++) { - - // only process columns where the mask bit is set. - // process all columns if mask is null. - if ((mask != null) && ((mask[(z * 16) + x]) != FLAG_NON_OPAQUE)) { - continue; - } - - // get the last non transparent block before the first opaque block searching - // towards the sky from startY - int lastNonTransparentY = startY; - for (int y = startY; y < chunk.getMaxY(); y++) { - int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); - int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; - if (alpha == 0xff) { - break; - } - if (alpha > 0) { - lastNonTransparentY = y; - } - } - - int pixelOffset = offset + (z * scanSize) + x; - pixels[pixelOffset] = getColumnColour( - bc, chunk, x, lastNonTransparentY, z, - getPixelHeightW(pixels, pixelOffset, scanSize), - getPixelHeightN(pixels, pixelOffset, scanSize) - ); - } - } - } -} diff --git a/src/main/java/mapwriter/region/IChunk.java b/src/main/java/mapwriter/region/IChunk.java deleted file mode 100644 index f85bf4b..0000000 --- a/src/main/java/mapwriter/region/IChunk.java +++ /dev/null @@ -1,8 +0,0 @@ -package mapwriter.region; - -public interface IChunk { - public int getBlockAndMetadata(int x, int y, int z); - public int getBiome(int x, int z); - public int getLightValue(int x, int y, int z); - public int getMaxY(); -} diff --git a/src/main/java/mapwriter/region/MergeToImage.java b/src/main/java/mapwriter/region/MergeToImage.java deleted file mode 100644 index 79ac3cb..0000000 --- a/src/main/java/mapwriter/region/MergeToImage.java +++ /dev/null @@ -1,92 +0,0 @@ -package mapwriter.region; - -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; - -import javax.imageio.ImageIO; - -public class MergeToImage { - public static final int MAX_WIDTH = 8192; - public static final int MAX_HEIGHT = 8192; - - public static BufferedImage mergeRegions(RegionManager regionManager, int x, int z, int w, int h, int dimension) { - // create the image and graphics context - // this is the most likely place to run out of memory - BufferedImage mergedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); - - // copy region PNGs to the image - for (int zi = 0; zi < h; zi += Region.SIZE) { - for (int xi = 0; xi < w; xi += Region.SIZE) { - //MwUtil.log("merging region (%d,%d)", rX << Mw.REGION_SHIFT, rZ << Mw.REGION_SHIFT); - - // get region pixels - Region region = regionManager.getRegion(x + xi, z + zi, 0, dimension); - int[] regionPixels = region.surfacePixels.getPixels(); - if (regionPixels != null) { - mergedImage.setRGB(xi, zi, Region.SIZE, Region.SIZE, regionPixels, 0, Region.SIZE); - } - } - } - - return mergedImage; - } - - public static boolean writeImage(BufferedImage img, File f) { - boolean error = true; - try { - ImageIO.write(img, "png", f); - error = false; - } catch (IOException e) { - } - return error; - } - - public static int merge(RegionManager regionManager, int xCentre, int zCentre, int w, int h, int dimension, File dir, String basename) { - - // round up to nearest 512 block boundary - w = ((w + Region.SIZE - 1) & Region.MASK); - h = ((h + Region.SIZE - 1) & Region.MASK); - - // clamp to an integer between 512 and 8192 inclusive - w = Math.max(Region.SIZE, w); - h = Math.max(Region.SIZE, h); - - int xMin = xCentre - (w / 2); - int zMin = zCentre - (h / 2); - - // round to nearest region boundary - xMin = Math.round(((float) xMin) / ((float) Region.SIZE)) * Region.SIZE; - zMin = Math.round(((float) zMin) / ((float) Region.SIZE)) * Region.SIZE; - - int xMax = xMin + w; - int zMax = zMin + h; - - RegionManager.logInfo("merging area starting at (%d,%d), %dx%d blocks", - xMin, zMin, w, h); - - - int countZ = 0; - int count = 0; - for (int z = zMin; z < zMax; z += MAX_WIDTH) { - int imgH = Math.min(zMax - z, MAX_HEIGHT); - int countX = 0; - for (int x = xMin; x < xMax; x += MAX_WIDTH) { - int imgW = Math.min(xMax - x, MAX_WIDTH); - - String imgName = String.format("%s.%d.%d.png", basename, countX, countZ); - File f = new File(dir, imgName); - RegionManager.logInfo("merging regions to image %s", f); - - BufferedImage img = mergeRegions(regionManager, x, z, imgW, imgH, dimension); - writeImage(img, f); - - countX++; - count++; - } - countZ++; - } - - return count; - } -} diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java deleted file mode 100644 index 7a0ab72..0000000 --- a/src/main/java/mapwriter/region/MwChunk.java +++ /dev/null @@ -1,234 +0,0 @@ -package mapwriter.region; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class MwChunk implements IChunk { - public static final int SIZE = 16; - - public final int x; - public final int z; - public final int dimension; - - public final byte[][] msbArray; - public final byte[][] lsbArray; - public final byte[][] metaArray; - public final byte[][] lightingArray; - - public final byte[] biomeArray; - - public final int maxY; - - public MwChunk(int x, int z, int dimension, byte[][] msbArray, byte[][] lsbArray, byte[][] metaArray, byte[][] lightingArray, byte[] biomeArray) { - this.x = x; - this.z = z; - this.dimension = dimension; - this.msbArray = msbArray; - this.lsbArray = lsbArray; - this.metaArray = metaArray; - this.biomeArray = biomeArray; - this.lightingArray = lightingArray; - int maxY = 0; - for (int y = 0; y < 16; y++) { - if (lsbArray[y] != null) { - maxY = (y << 4) + 15; - } - } - this.maxY = maxY; - } - - public String toString() { - return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); - } - - // load from anvil file - public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { - - byte[] biomeArray = null; - byte[][] msbArray = new byte[16][]; - byte[][] lsbArray = new byte[16][]; - byte[][] metaArray = new byte[16][]; - byte[][] lightingArray = new byte[16][]; - - DataInputStream dis = null; - RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); - if (!regionFile.isOpen()) { - if (regionFile.exists()) { - regionFile.open(); - } - } - - if (regionFile.isOpen()) { - dis = regionFile.getChunkDataInputStream(x & 31, z & 31); - } - - if (dis != null) { - try { - - //chunk NBT structure: - // - //COMPOUND "" - //COMPOUND "level" - // INT "xPos" - // INT "zPos" - // LONG "LastUpdate" - // BYTE "TerrainPopulated" - // BYTE_ARRAY "Biomes" - // INT_ARRAY "HeightMap" - // LIST(COMPOUND) "Sections" - // BYTE "Y" - // BYTE_ARRAY "Blocks" - // BYTE_ARRAY "Add" - // BYTE_ARRAY "Data" - // BYTE_ARRAY "BlockLight" - // BYTE_ARRAY "SkyLight" - // END - // LIST(COMPOUND) "Entities" - // LIST(COMPOUND) "TileEntities" - // LIST(COMPOUND) "TileTicks" - //END - //END - - Nbt root = Nbt.readNextElement(dis); - Nbt level = root.getChild("Level"); - - int xNbt = level.getChild("xPos").getInt(); - int zNbt = level.getChild("zPos").getInt(); - if ((xNbt != x) || (zNbt != z)) { - RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); - } - - Nbt sections = level.getChild("Sections"); - - // loop through each of the sections (16 x 16 x 16 block volumes) present - for (int i = 0; i < sections.size(); i++) { - Nbt section = sections.getChild(i); - if (!section.isNull()) { - int y = section.getChild("Y").getByte(); - lsbArray[y & 0xf] = section.getChild("Blocks").getByteArray(); - msbArray[y & 0xf] = section.getChild("Add").getByteArray(); - metaArray[y & 0xf] = section.getChild("Data").getByteArray(); - } - } - biomeArray = level.getChild("Biomes").getByteArray(); - - } catch (IOException e) { - RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); - } finally { - try { dis.close(); } - catch (IOException e) { - RegionManager.logError("MwChunk.read: %s while closing input stream", e); - } - } - //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); - } else { - //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); - } - - return new MwChunk(x, z, dimension, msbArray, lsbArray, metaArray, lightingArray, biomeArray); - } - - public boolean isEmpty() { - return (this.maxY <= 0); - } - - public int getBiome(int x, int z) { - return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; - } - - public int getLightValue(int x, int y, int z) { - //int yi = (y >> 4) & 0xf; - //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; - - //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); - return 15; - } - - public int getMaxY() { - return this.maxY; - } - - public int getBlockAndMetadata(int x, int y, int z) { - int yi = (y >> 4) & 0xf; - int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); - - int lsb = ((this.lsbArray != null) && (this.lsbArray[yi] != null)) ? this.lsbArray[yi][offset] : 0; - int msb = ((this.msbArray != null) && (this.msbArray[yi] != null)) ? this.msbArray[yi][offset >> 1] : 0; - int meta = ((this.metaArray != null) && (this.metaArray[yi] != null)) ? this.metaArray[yi][offset >> 1] : 0; - - return ((offset & 1) == 1) ? - ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : - ((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f); - } - - public Nbt getNbt() { - Nbt sections = new Nbt(Nbt.TAG_LIST, "Sections", null); - - for (int y = 0; y < 16; y++) { - Nbt section = new Nbt(Nbt.TAG_COMPOUND, "", null); - - section.addChild(new Nbt(Nbt.TAG_BYTE, "Y", (byte) y)); - - if ((this.lsbArray != null) && (this.lsbArray[y] != null)) { - section.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Blocks", this.lsbArray[y])); - } - if ((this.msbArray != null) && (this.msbArray[y] != null)) { - section.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Add", this.msbArray[y])); - } - if ((this.metaArray != null) && (this.metaArray[y] != null)) { - section.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Data", this.metaArray[y])); - } - - sections.addChild(section); - } - - Nbt level = new Nbt(Nbt.TAG_COMPOUND, "Level", null); - level.addChild(new Nbt(Nbt.TAG_INT, "xPos", this.x)); - level.addChild(new Nbt(Nbt.TAG_INT, "zPos", this.z)); - level.addChild(sections); - - if (this.biomeArray != null) { - level.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Biomes", this.biomeArray)); - } - - Nbt root = new Nbt(Nbt.TAG_COMPOUND, "", null); - root.addChild(level); - - return root; - } - - public synchronized boolean write(RegionFileCache regionFileCache) { - boolean error = false; - RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); - if (!regionFile.isOpen()) { - error = regionFile.open(); - } - if (!error) { - DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); - if (dos != null) { - Nbt chunkNbt = this.getNbt(); - try { - //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); - chunkNbt.writeElement(dos); - } catch (IOException e) { - RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); - error = true; - } finally { - try { dos.close(); } - catch (IOException e) { - RegionManager.logError("%s while closing chunk data output stream", e); - } - } - } else { - RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); - } - } else { - RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); - } - - return error; - } -} diff --git a/src/main/java/mapwriter/region/Nbt.java b/src/main/java/mapwriter/region/Nbt.java deleted file mode 100644 index 62603cf..0000000 --- a/src/main/java/mapwriter/region/Nbt.java +++ /dev/null @@ -1,364 +0,0 @@ -package mapwriter.region; - - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Nbt { - - // each NBT element has the structure: - // byte tag_id - // short name_length - // byte[name_length] name - // - // use int for tag ID's rather than byte so we can have -1 as - // a 'null' or empty element - // - // tag ID's: - public static final byte TAG_END = 0x00; - public static final byte TAG_BYTE = 0x01; - public static final byte TAG_SHORT = 0x02; - public static final byte TAG_INT = 0x03; - public static final byte TAG_LONG = 0x04; - public static final byte TAG_FLOAT = 0x05; - public static final byte TAG_DOUBLE = 0x06; - public static final byte TAG_BYTE_ARRAY = 0x07; // INT length, then length BYTE's - public static final byte TAG_STRING = 0x08; // SHORT length, UTF-8 string - public static final byte TAG_LIST = 0x09; // BYTE entry id, INT entry count, entries (without tag or name) - public static final byte TAG_COMPOUND = 0x0a; // fully formed tags, ending at TAG_END - public static final byte TAG_INT_ARRAY = 0x0b; // INT length, length INT's - - public static final byte TAG_NULL = -1; - - public static Nbt nullElement = new Nbt(TAG_NULL, "", null); - - public byte tagID; - public String name; - private Object data; - - public Nbt(byte tagID, String name, Object data) { - this.tagID = tagID; - this.name = name; - this.data = data; - } - - public boolean isNull() { - return (this.tagID == TAG_NULL); - } - - public void addChild(Nbt child) { - // for list structures - if (this.tagID == TAG_LIST) { - if (this.data == null) { - this.data = new ArrayList(); - } - @SuppressWarnings("unchecked") - List childrenList = (List) this.data; - childrenList.add(child); - } - - // for compound structures - if (this.tagID == TAG_COMPOUND) { - if (this.data == null) { - this.data = new HashMap(); - } - @SuppressWarnings("unchecked") - Map childrenMap = (Map) this.data; - childrenMap.put(child.name, child); - } - } - - // getChild methods allow for invocation chaining. - // e.g. int child10Data = elem.getChildOrEmpty(10).getInt() - - // for lists, get the child element at index 'index' - public Nbt getChild(int index) { - Nbt child = null; - if ((this.tagID == TAG_LIST) && (this.data != null)) { - @SuppressWarnings("unchecked") - List childrenList = (List) this.data; - if ((index >= 0) && (index < childrenList.size())) { - child = childrenList.get(index); - } - } - return (child != null) ? (child) : (nullElement); - } - - // for compound tags, returns the child with name 'name' - public Nbt getChild(String name) { - Nbt child = null; - if ((this.tagID == TAG_COMPOUND) && (this.data != null)) { - @SuppressWarnings("unchecked") - Map childrenMap = (Map) this.data; - child = childrenMap.get(name); - } - return (child != null) ? (child) : (nullElement); - } - - // for lists, get number of children - public int size() { - int size = 0; - if ((this.tagID == TAG_LIST) && (this.data != null)) { - @SuppressWarnings("unchecked") - List childrenList = (List) this.data; - size = childrenList.size(); - } - return size; - } - - /*public static String readString(DataInputStream dis) throws IOException { - int stringLength = (int) dis.readShort(); - byte[] stringBytes = null; - String s = ""; - if (stringLength > 0) { - stringBytes = new byte[stringLength]; - s = dis.readUTF(); - try { - s = new String(stringBytes, "UTF8"); - } catch (Exception e) { - e.printStackTrace(); - s = ""; - } - } - return s; - } - - public static void writeString(DataOutputStream dos, String s) throws IOException { - dos.writeShort((short) s.length()); - byte[] stringBytes = null; - try { - dos.write(s.getBytes("UTF8")); - } catch (Exception e) { - e.printStackTrace(); - } - }*/ - - public static Nbt readNextElement(DataInputStream dis) throws IOException { - byte tagID; - String name = ""; - - // fully formed tag - tagID = (byte) dis.readByte(); - if (tagID != TAG_END) { - // END tags do not have a name - name = dis.readUTF(); - } - - return readElementData(dis, tagID, name); - } - - // parse the next nbt tag in the data buffer - public static Nbt readElementData(DataInputStream dis, byte tagID, String name) throws IOException{ - Nbt elem = null; - switch (tagID) { - case TAG_END: - //System.out.format("encountered end tag at %d\n", buffer.position()); - break; - case TAG_BYTE: - elem = new Nbt(tagID, name, new Byte(dis.readByte())); - break; - case TAG_SHORT: - elem = new Nbt(tagID, name, new Short(dis.readShort())); - break; - case TAG_INT: - elem = new Nbt(tagID, name, new Integer(dis.readInt())); - break; - case TAG_FLOAT: - elem = new Nbt(tagID, name, new Float(dis.readFloat())); - break; - case TAG_LONG: - elem = new Nbt(tagID, name, new Long(dis.readLong())); - break; - case TAG_DOUBLE: - elem = new Nbt(tagID, name, new Double(dis.readDouble())); - break; - - case TAG_BYTE_ARRAY: - int baLength = dis.readInt(); - byte[] byteArray = null; - if (baLength > 0) { - byteArray = new byte[baLength]; - dis.readFully(byteArray); - } - elem = new Nbt(tagID, name, byteArray); - break; - - case TAG_INT_ARRAY: - int iaLength = dis.readInt(); - int[] intArray = null; - if (iaLength > 0) { - intArray = new int[iaLength]; - for (int i = 0; i < iaLength; i++) { - intArray[i] = dis.readInt(); - } - } - elem = new Nbt(tagID, name, intArray); - break; - - case TAG_STRING: - elem = new Nbt(tagID, name, dis.readUTF()); - break; - - case TAG_LIST: - byte childType = dis.readByte(); - int listLength = dis.readInt(); - elem = new Nbt(tagID, name, null); - //System.out.format("encountered list tag at %d, childType %d, length %d\n", buffer.position(), childType, listLength); - for (int i = 0; i < listLength; i++) { - Nbt child = readElementData(dis, childType, ""); - elem.addChild(child); - } - break; - - case TAG_COMPOUND: - elem = new Nbt(tagID, name, null); - boolean end = false; - while (!end) { - Nbt child = readNextElement(dis); - if (child.isNull()) { - end = true; - } else { - elem.addChild(child); - } - } - break; - - default: - System.out.format("error: encountered unknown tag id\n"); - break; - } - - return (elem != null) ? elem : nullElement; - } - - public byte getByte() { - return ((this.tagID == TAG_BYTE) && (this.data != null)) ? ((Byte) this.data) : ((byte) 0); - } - - public short getShort() { - return ((this.tagID == TAG_SHORT) && (this.data != null)) ? ((Short) this.data) : ((short) 0); - } - - public int getInt() { - return ((this.tagID == TAG_INT) && (this.data != null)) ? ((Integer) this.data) : ((int) 0); - } - - public long getLong() { - return ((this.tagID == TAG_LONG) && (this.data != null)) ? ((Long) this.data) : ((long) 0); - } - - public float getFloat() { - return ((this.tagID == TAG_FLOAT) && (this.data != null)) ? ((Float) this.data) : ((float) 0); - } - - public double getDouble() { - return ((this.tagID == TAG_DOUBLE) && (this.data != null)) ? ((Double) this.data) : ((double) 0); - } - - public byte[] getByteArray() { - return ((this.tagID == TAG_BYTE_ARRAY) && (this.data != null)) ? ((byte[]) this.data) : (null); - } - - public int[] getIntArray() { - return ((this.tagID == TAG_INT_ARRAY) && (this.data != null)) ? ((int[]) this.data) : (null); - } - - public String getString() { - return ((this.tagID == TAG_STRING) && (this.data != null)) ? ((String) this.data) : (null); - } - - - public void writeElement(DataOutputStream dos) throws IOException{ - dos.writeByte(this.tagID); - if (this.tagID != TAG_END) { - dos.writeUTF(this.name); - this.writeElementData(dos); - } - } - - public void writeElementData(DataOutputStream dos) throws IOException { - //Mw.log("Nbt.writeElementData: %02x '%s'", this.tagID, this.name); - switch (this.tagID) { - case TAG_END: - break; - case TAG_BYTE: - dos.writeByte(this.getByte()); - break; - case TAG_SHORT: - dos.writeShort(this.getShort()); - break; - case TAG_INT: - dos.writeInt(this.getInt()); - break; - case TAG_FLOAT: - dos.writeFloat(this.getFloat()); - break; - case TAG_LONG: - dos.writeLong(this.getLong()); - break; - case TAG_DOUBLE: - dos.writeDouble(this.getDouble()); - break; - - case TAG_BYTE_ARRAY: - byte[] byteArray = this.getByteArray(); - if (byteArray != null) { - dos.writeInt(byteArray.length); - dos.write(byteArray); - } else { - dos.writeInt(0); - } - break; - - case TAG_INT_ARRAY: - int[] intArray = this.getIntArray(); - if (intArray != null) { - dos.writeInt(intArray.length); - for (int i = 0; i < intArray.length; i++) { - dos.writeInt(intArray[i]); - } - } else { - dos.writeInt(0); - } - break; - - case TAG_STRING: - dos.writeUTF(this.getString()); - break; - - case TAG_LIST: - int listLength = this.size(); - if (this.size() > 0) { - dos.writeByte(this.getChild(0).tagID); - dos.writeInt(listLength); - for (int i = 0; i < listLength; i++) { - this.getChild(i).writeElementData(dos); - } - } else { - dos.writeByte(TAG_BYTE); - dos.writeInt(0); - } - break; - - case TAG_COMPOUND: - @SuppressWarnings("unchecked") - Map childrenMap = (Map) this.data; - for (Nbt child : childrenMap.values()) { - if (child != null) { - child.writeElement(dos); - } - } - dos.writeByte(TAG_END); - break; - - default: - System.out.format("error: encountered unknown tag id\n"); - break; - } - } -} \ No newline at end of file diff --git a/src/main/java/mapwriter/region/Region.java b/src/main/java/mapwriter/region/Region.java deleted file mode 100644 index 29e3491..0000000 --- a/src/main/java/mapwriter/region/Region.java +++ /dev/null @@ -1,169 +0,0 @@ -package mapwriter.region; - -import java.io.File; - -/* - MwRegion class - Represents a 32x32 chunk area (512x512 blocks). -*/ -public class Region { - - public RegionManager regionManager; - - public static final int SHIFT = 9; - public static final int SIZE = 1 << SHIFT; - public static final int MASK = -SIZE; - - public final int x; - public final int z; - public final int dimension; - public final int zoomLevel; - public final Long key; - public final int size; - - public SurfacePixels surfacePixels; - - public Region(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) { - - this.regionManager = regionManager; - - this.zoomLevel = Math.min(Math.max(0, zoomLevel), regionManager.maxZoom); - this.dimension = dimension; - this.size = Region.SIZE << zoomLevel; - this.x = x & (-this.size); - this.z = z & (-this.size); - - this.key = getKey(this.x, this.z, this.zoomLevel, this.dimension); - - File surfaceImageFile = this.getImageFile(); - this.surfacePixels = new SurfacePixels(this, surfaceImageFile); - } - - public void close() { - this.surfacePixels.close(); - } - - public void clear() { - this.surfacePixels.clear(); - } - - public String toString() { - return String.format("(%d,%d) z%d dim%d", this.x, this.z, this.zoomLevel, this.dimension); - } - - private static File addDimensionDirToPath(File dir, int dimension) { - if (dimension != 0) { - dir = new File(dir, "DIM" + dimension); - } - return dir; - } - - public File getImageFile() { - File dimDir = addDimensionDirToPath(this.regionManager.imageDir, this.dimension); - File zoomDir = new File(dimDir, "z" + this.zoomLevel); - - zoomDir.mkdirs(); - - String filename = String.format("%d.%d.png", - this.x >> (Region.SHIFT + this.zoomLevel), - this.z >> (Region.SHIFT + this.zoomLevel) - ); - - return new File(zoomDir, filename); - } - - public boolean equals(int x, int z, int zoomLevel, int dimension) { - x &= -this.size; - z &= -this.size; - return (this.x == x) && (this.z == z) && (this.zoomLevel == zoomLevel) && (this.dimension == dimension); - } - - @Override - public boolean equals(Object o) { - boolean equal = false; - if (o != null) { - if (o instanceof Region) { - Region region = (Region) o; - equal = this.equals(region.x, region.z, region.zoomLevel, region.dimension); - } - } - return equal; - } - - public static Long getKey(int x, int z, int zoomLevel, int dimension) { - x = (x >> (Region.SHIFT + zoomLevel)) & 0xffff; - z = (z >> (Region.SHIFT + zoomLevel)) & 0xffff; - zoomLevel = zoomLevel & 0xff; - dimension = dimension & 0xff; - return Long.valueOf( - (((long) dimension) << 40) | - (((long) zoomLevel) << 32) | - (((long) z) << 16) | - ((long) x)); - } - - public int getPixelOffset(int x, int z) { - return (((z >> this.zoomLevel) & (Region.SIZE - 1)) << Region.SHIFT) + - ((x >> this.zoomLevel) & (Region.SIZE - 1)); - } - - public int[] getPixels() { - return this.surfacePixels.getPixels(); - } - - public boolean isAreaWithin(int x, int z, int w, int h, int dimension) { - return (x >= this.x) && (z >= this.z) && - ((x + w) <= (this.x + this.size)) && ((z + h) <= (this.z + this.size)) && - (dimension == this.dimension); - } - - // scale an area of pixels by half in this region and write them - // to the pixels of the next zoom level region. - // x, z, w, h, in world block coordinates - // returns the region the scaled pixels were written to, or null - // on failure. - public Region updateNextZoomLevel(int x, int z, int w, int h) { - int[] srcPixels = this.surfacePixels.getPixels(); - Region dstRegion = null; - if (srcPixels != null) { - int dstZoomLevel = this.zoomLevel + 1; - if (dstZoomLevel <= this.regionManager.maxZoom) { - dstRegion = this.regionManager.getRegion(x, z, dstZoomLevel, this.dimension); - int dstW = Math.max(1, (w >> dstRegion.zoomLevel)); - int dstH = Math.max(1, (h >> dstRegion.zoomLevel)); - - // AND srcX and srcZ by -2 (0xfffffffe) to make sure that - // they are always even. This prevents out of bounds exceptions - // at higher zoom levels. - int srcX = (x >> this.zoomLevel) & (Region.SIZE - 1) & (-2); - int srcZ = (z >> this.zoomLevel) & (Region.SIZE - 1) & (-2); - int dstX = (x >> dstRegion.zoomLevel) & (Region.SIZE - 1); - int dstZ = (z >> dstRegion.zoomLevel) & (Region.SIZE - 1); - - dstRegion.surfacePixels.updateScaled(srcPixels, srcX, srcZ, dstX, dstZ, dstW, dstH); - } - } - - return dstRegion; - } - - // update all higher zoom level regions that this region - // lies within - public void updateZoomLevels(int x, int z, int w, int h) { - Region nextRegion = this; - while (nextRegion != null) { - nextRegion = nextRegion.updateNextZoomLevel(x, z, w, h); - } - } - - // update this entire region in the next zoom level - public void updateZoomLevels() { - this.updateZoomLevels(this.x, this.z, this.size, this.size); - } - - public void updateChunk(MwChunk chunk) { - if (this.zoomLevel == 0) { - this.surfacePixels.updateChunk(chunk); - } - } -} diff --git a/src/main/java/mapwriter/region/RegionFile.java b/src/main/java/mapwriter/region/RegionFile.java deleted file mode 100644 index 2804783..0000000 --- a/src/main/java/mapwriter/region/RegionFile.java +++ /dev/null @@ -1,372 +0,0 @@ -package mapwriter.region; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -/* -Anvil region file reader/writer implementation. -This code is very similar to RegionFile and RegionFileChunkBuffer from Minecraft. -Not sure if it would have been better just to use the Minecraft code. -*/ - -public class RegionFile { - - private final File file; - private int lengthInSectors = 0; - private RandomAccessFile fin = null; - - private Section[] chunkSectionsArray = new Section[4096]; - private int[] timestampArray = new int[4096]; - private List filledSectorArray = null; - - private class Section { - final int startSector; - final int length; - Section(int startSector, int length) { - this.startSector = startSector; - this.length = length; - } - Section(int sectorAndSize) { - this((sectorAndSize >> 8) & 0xffffff, sectorAndSize & 0xff); - } - int getSectorAndSize() { - return (this.startSector << 8) | (this.length & 0xff); - } - } - - public RegionFile(File file) { - this.file = file; - } - - public String toString() { - return String.format("%s", this.file); - } - - public boolean exists() { - return this.file.isFile(); - } - - public boolean isOpen() { - return (this.fin != null); - } - - // set the corresponding bits in filledSectorArray to 'filled' - // for 'count' sectors, starting at 'firstSector'. - private void setFilledSectorArray(Section section, boolean filled) { - int endSector = section.startSector + section.length; - int sectorsToAppend = endSector + 1 - this.filledSectorArray.size(); - for (int i = 0; i < sectorsToAppend; i++) { - this.filledSectorArray.add(Boolean.valueOf(false)); - } - for (int i = section.startSector; i < endSector; i++) { - if (filled && this.filledSectorArray.get(i)) { - RegionManager.logError("sector %d already filled, possible chunk overlap", i); - } - this.filledSectorArray.set(i, Boolean.valueOf(filled)); - } - } - - private boolean checkSectionOverlaps(Section section) { - // get end sector, limiting to length of the filled sector array as all sectors past the - // end of the file are assumed free. - int endSector = Math.min(section.startSector + section.length, this.filledSectorArray.size()); - boolean overlaps = false; - for (int i = section.startSector; i < endSector; i++) { - if (this.filledSectorArray.get(i)) { - overlaps = true; - } - } - return overlaps; - } - - private Section getFreeSection(int requiredLength) { - int start = 0; - int length = 0; - int closestStart = 0; - int closestLength = Integer.MAX_VALUE; - // start at 2 to skip headers - int i; - for (i = 2; i < this.filledSectorArray.size(); i++) { - if (this.filledSectorArray.get(i)) { - // sector filled - // if the length of the empty block we found is greater than or - // equal to the required length, and is closer to the required - // length than the previous found length, then set this as the - // new closest length. - // the idea is to use an empty block of exactly the required - // length, rather than one that is larger. - if ((length >= requiredLength) && (length < closestLength)) { - closestLength = length; - closestStart = start; - // if we find an empty block of exactly the correct length - // then exit the loop. - if (closestLength == requiredLength) { - break; - } - } - length = 0; - } else { - // sector empty - if (length == 0) { - start = i; - } - length++; - } - } - - if (closestStart <= 0) { - // append to end of file - closestStart = i; - } - - return new Section(closestStart, requiredLength); - } - - public void printInfo() { - int freeCount = 0; - int filledCount = 0; - // start at 2 to skip headers - for (int i = 2; i < this.filledSectorArray.size(); i++) { - if (this.filledSectorArray.get(i)) { - filledCount++; - } else { - freeCount++; - } - } - RegionManager.logInfo("Region File %s: filled sectors = %d, free sectors = %d", this, filledCount, freeCount); - - String s = ""; - int i; - for (i = 0; i < this.filledSectorArray.size(); i++) { - if ((i & 31) == 0) { - s = String.format("%04x:", i); - } - s += this.filledSectorArray.get(i) ? '1' : '0'; - if ((i & 31) == 31) { - RegionManager.logInfo("%s", s); - } - } - if ((i & 31) != 31) { - RegionManager.logInfo("%s", s); - } - } - - private Section getChunkSection(int x, int z) { - return this.chunkSectionsArray[((z & 31) << 5) | (x & 31)]; - } - - private void updateChunkSection(int x, int z, Section newSection) throws IOException { - int chunkIndex = ((z & 31) << 5) | (x & 31); - this.fin.seek(chunkIndex * 4); - if ((newSection != null) && (newSection.length > 0)) { - this.fin.writeInt(newSection.getSectorAndSize()); - } else { - this.fin.writeInt(0); - } - - this.chunkSectionsArray[chunkIndex] = newSection; - } - - public boolean open() { - File dir = this.file.getParentFile(); - if (dir.exists()) { - if (!dir.isDirectory()) { - RegionManager.logError("path %s exists and is not a directory", dir); - return true; - } - } else { - if (!dir.mkdirs()) { - RegionManager.logError("could not create directory %s", dir); - return true; - } - } - try { - this.fin = new RandomAccessFile(this.file, "rw"); - - // seek to start - this.fin.seek(0); - - this.lengthInSectors = (int) ((this.fin.length() + 4095L) / 4096L); - - this.filledSectorArray = new ArrayList(); - - Arrays.fill(this.chunkSectionsArray, null); - Arrays.fill(this.timestampArray, 0); - - if (this.lengthInSectors < 3) { - // no chunk data - // fill chunk and timestamp tables with 0's - for (int i = 0; i < 2048; i++) { - this.fin.writeInt(0); - } - } else { - // add a section for each chunk - for (int i = 0; i < 1024; i++) { - Section section = new Section(this.fin.readInt()); - if (section.length > 0) { - // make sure chunk does not overlap another - if (!checkSectionOverlaps(section)) { - this.chunkSectionsArray[i] = section; - this.setFilledSectorArray(section, true); - } else { - RegionManager.logError("chunk %d overlaps another chunk, file may be corrupt", i); - } - } - } - for (int i = 0; i < 1024; i++) { - this.timestampArray[i] = this.fin.readInt(); - } - } - - //this.printInfo(); - - } catch (Exception e) { - this.fin = null; - RegionManager.logError("exception when opening region file '%s': %s", this.file, e); - - } - - return this.fin == null; - } - - public void close() { - if (this.fin != null) { - try { this.fin.close(); } - catch (IOException e) {} - } - } - - public DataInputStream getChunkDataInputStream(int x, int z) { - DataInputStream dis = null; - if (this.fin != null) { - Section section = getChunkSection(x, z); - if ((section != null) && (section.length > 0)) { - int offset = section.startSector * 4096; - try { - // read length of following data (includes version byte) and compressed data version byte - this.fin.seek(offset); - int length = this.fin.readInt(); - byte version = this.fin.readByte(); - // version 1 = gzip compressed, version 2 = zlib/inflater compressed - if ((length > 1) && ((length + 4) < (section.length * 4096)) && (version == 2)) { - // read the compressed data - byte[] compressedChunkData = new byte[length - 1]; - this.fin.read(compressedChunkData); - // create a buffered inflater stream on the compressed data - dis = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(compressedChunkData)))); - } else { - RegionManager.logError("data length (%d) or version (%d) invalid for chunk (%d, %d)", length, version, x, z); - } - } catch (Exception e) { - RegionManager.logError("exception while reading chunk (%d, %d): %s", x, z, e); - dis = null; - } - } - } - return dis; - } - - // basically an in memory byte array that writes its contents - // to a file when it is closed. - private class RegionFileChunkBuffer extends ByteArrayOutputStream { - private final int x; - private final int z; - private final RegionFile regionFile; - - public RegionFileChunkBuffer(RegionFile regionFile, int x, int z) { - super(8096); - this.regionFile = regionFile; - this.x = x; - this.z = z; - } - - public void close() { - this.regionFile.writeCompressedChunk(this.x, this.z, this.buf, this.count); - } - } - - public DataOutputStream getChunkDataOutputStream(int x, int z) { - return new DataOutputStream(new DeflaterOutputStream(new RegionFileChunkBuffer(this, x, z))); - } - - /*private int padToSectorSize() throws IOException { - // pad with 0 so that the file length is a multiple of 4096 bytes - long paddedLength = (this.length + 4095L) & (-4096L); - this.fin.seek(this.length); - for (long i = this.length; i < paddedLength; i++) { - this.fin.writeByte(0); - } - this.length = paddedLength; - return (int) (paddedLength / 4096); - }*/ - - private void writeChunkDataToSection(Section section, byte[] compressedChunkData, int length) throws IOException { - this.fin.seek(((long) section.startSector) * 4096L); - // write version and length - this.fin.writeInt(length + 1); - this.fin.writeByte(2); - // write compressed data - this.fin.write(compressedChunkData, 0, length); - - int endSector = section.startSector + section.length; - if ((endSector + 1) > this.lengthInSectors) { - this.lengthInSectors = endSector + 1; - } - } - - private boolean writeCompressedChunk(int x, int z, byte[] compressedChunkData, int length) { - // if larger than the existing chunk data or chunk does not exist then need to find the - // first possible file position to write to. This will either be a contiguous strip of - // free sectors longer than the length of the chunk data, or the end of the file (append). - - if (length <= 0) { - RegionManager.logWarning("not writing chunk (%d, %d) with length %d", x, z, length); - return true; - } - - // free the section this chunk currently occupies - Section currentSection = this.getChunkSection(x, z); - if (currentSection != null) { - this.setFilledSectorArray(currentSection, false); - } - - int requiredSectors = (length + 5 + 4095) / 4096; - Section newSection; - - if ((currentSection != null) && (requiredSectors <= currentSection.length)) { - // if the chunk still fits in it's current location don't move - //RegionManager.logInfo("chunk (%d, %d) fits in current location %d", x, z, currentSection.startSector); - newSection = new Section(currentSection.startSector, requiredSectors); - } else { - // otherwise find a free section large enough to hold the chunk data - newSection = getFreeSection(requiredSectors); - } - - // set the new section to filled - this.setFilledSectorArray(newSection, true); - - boolean error = true; - try { - //RegionManager.logInfo("writing %d bytes to sector %d for chunk (%d, %d)", length, newSection.startSector, x, z); - this.writeChunkDataToSection(newSection, compressedChunkData, length); - // update the header - this.updateChunkSection(x, z, newSection); - error = false; - } catch (IOException e) { - RegionManager.logError("could not write chunk (%d, %d) to region file: %s", x, z, e); - } - - return error; - } -} diff --git a/src/main/java/mapwriter/region/RegionFileCache.java b/src/main/java/mapwriter/region/RegionFileCache.java deleted file mode 100644 index 1b2cdd8..0000000 --- a/src/main/java/mapwriter/region/RegionFileCache.java +++ /dev/null @@ -1,76 +0,0 @@ -package mapwriter.region; - -import java.io.File; -import java.util.LinkedHashMap; -import java.util.Map; - -public class RegionFileCache { - - // simple Least Recently Used (LRU) cache implementation - class LruCache extends LinkedHashMap { - private static final long serialVersionUID = 1L; - static final int MAX_REGION_FILES_OPEN = 8; - - public LruCache() { - // initial capacity, loading factor, true for access time ordering - super(MAX_REGION_FILES_OPEN * 2, 0.5f, true); - } - - // called on every put and putAll call, the entry 'entry' is removed - // if this function returns true. - @Override - protected boolean removeEldestEntry(Map.Entry entry) { - boolean ret = false; - if (this.size() > MAX_REGION_FILES_OPEN) { - RegionFile regionFile = entry.getValue(); - regionFile.close(); - ret = true; - } - return ret; - } - } - - private LruCache regionFileCache = new LruCache(); - private File worldDir; - - public RegionFileCache(File worldDir) { - this.worldDir = worldDir; - } - - public void close() { - for (RegionFile regionFile : regionFileCache.values()) { - regionFile.close(); - } - this.regionFileCache.clear(); - } - - public File getRegionFilePath(int x, int z, int dimension) { - File dir = this.worldDir; - if (dimension != 0) { - dir = new File(dir, "DIM" + dimension); - } - dir = new File(dir, "region"); - - String filename = String.format("r.%d.%d.mca", - x >> Region.SHIFT, - z >> Region.SHIFT); - - return new File(dir, filename); - } - - public boolean regionFileExists(int x, int z, int dimension) { - File regionFilePath = getRegionFilePath(x, z, dimension); - return regionFilePath.isFile(); - } - - public RegionFile getRegionFile(int x, int z, int dimension) { - File regionFilePath = getRegionFilePath(x, z, dimension); - String key = regionFilePath.toString(); - RegionFile regionFile = this.regionFileCache.get(key); - if (regionFile == null) { - regionFile = new RegionFile(regionFilePath); - this.regionFileCache.put(key, regionFile); - } - return regionFile; - } -} diff --git a/src/main/java/mapwriter/region/RegionManager.java b/src/main/java/mapwriter/region/RegionManager.java deleted file mode 100644 index 7d9d7c6..0000000 --- a/src/main/java/mapwriter/region/RegionManager.java +++ /dev/null @@ -1,157 +0,0 @@ -package mapwriter.region; - -import java.io.File; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.logging.log4j.Logger; - -public class RegionManager { - - // simple Least Recently Used (LRU) cache implementation - class LruCache extends LinkedHashMap { - private final static long serialVersionUID = 1L; - private final static int MAX_LOADED_REGIONS = 64; - - public LruCache() { - // initial capacity, loading factor, true for access time ordering - super(MAX_LOADED_REGIONS * 2, 0.5f, true); - } - - // called on every put and putAll call, the entry 'entry' is removed - // if this function returns true. - @Override - protected boolean removeEldestEntry(Map.Entry entry) { - boolean ret = false; - if (this.size() > MAX_LOADED_REGIONS) { - Region region = entry.getValue(); - region.close(); - ret = true; - } - return ret; - } - } - - private final LruCache regionMap; - - public final File worldDir; - public final File imageDir; - public BlockColours blockColours; - public static Logger logger; - public final RegionFileCache regionFileCache; - - public int maxZoom; - public int minZoom; - - public static void logInfo(String s, Object...args) { - if (logger != null) { - logger.info(String.format(s, args)); - } - } - - public static void logWarning(String s, Object...args) { - if (logger != null) { - logger.warn(String.format(s, args)); - } - } - - public static void logError(String s, Object...args) { - if (logger != null) { - logger.error(String.format(s, args)); - } - } - - public RegionManager(File worldDir, File imageDir, BlockColours blockColours, int minZoom, int maxZoom) { - this.worldDir = worldDir; - this.imageDir = imageDir; - this.blockColours = blockColours; - this.regionMap = new LruCache(); - this.regionFileCache = new RegionFileCache(worldDir); - this.minZoom = minZoom; - this.maxZoom = maxZoom; - } - - public void close() { - for (Region region : this.regionMap.values()) { - if (region != null) { - region.close(); - } - } - this.regionMap.clear(); - this.regionFileCache.close(); - } - - private static int incrStatsCounter(Map h, String key) { - int n = 1; - if (h.containsKey(key)) { - n = h.get(key) + 1; - } - h.put(key, n); - return n; - } - - public void printLoadedRegionStats() { - logInfo("loaded region listing:"); - Map stats = new HashMap(); - for (Region region : this.regionMap.values()) { - logInfo(" %s", region); - incrStatsCounter(stats, String.format("dim%d", region.dimension)); - incrStatsCounter(stats, String.format("zoom%d", region.zoomLevel)); - incrStatsCounter(stats, "total"); - } - logInfo("loaded region stats:"); - for (Entry e : stats.entrySet()) { - logInfo(" %s: %d", e.getKey(), e.getValue()); - } - } - - // must not return null - public Region getRegion(int x, int z, int zoomLevel, int dimension) { - Region region = this.regionMap.get(Region.getKey(x, z, zoomLevel, dimension)); - if (region == null) { - // add region - region = new Region(this, x, z, zoomLevel, dimension); - this.regionMap.put(region.key, region); - } - return region; - } - - public void updateChunk(MwChunk chunk) { - Region region = this.getRegion(chunk.x << 4, chunk.z << 4, 0, chunk.dimension); - region.updateChunk(chunk); - } - - public void rebuildRegions(int xStart, int zStart, int w, int h, int dimension) { - // read all zoom level 0 regions - // then find all regions with a backing image at zoom level 0 - - xStart &= Region.MASK; - zStart &= Region.MASK; - w = (w + Region.SIZE) & Region.MASK; - h = (h + Region.SIZE) & Region.MASK; - - logInfo("rebuilding regions from (%d, %d) to (%d, %d)", xStart, zStart, xStart + w, zStart + h); - - for (int rX = xStart; rX < (xStart + w); rX += Region.SIZE) { - for (int rZ = zStart; rZ < (zStart + h); rZ += Region.SIZE) { - Region region = this.getRegion(rX, rZ, 0, dimension); - if (this.regionFileCache.regionFileExists(rX, rZ, dimension)) { - region.clear(); - for (int cz = 0; cz < 32; cz++) { - for (int cx = 0; cx < 32; cx++) { - // load chunk from anvil file - MwChunk chunk = MwChunk.read( - (region.x >> 4) + cx, (region.z >> 4) + cz, - region.dimension, this.regionFileCache - ); - region.updateChunk(chunk); - } - } - } - region.updateZoomLevels(); - } - } - } -} diff --git a/src/main/java/mapwriter/region/SurfacePixels.java b/src/main/java/mapwriter/region/SurfacePixels.java deleted file mode 100644 index 4755434..0000000 --- a/src/main/java/mapwriter/region/SurfacePixels.java +++ /dev/null @@ -1,159 +0,0 @@ -package mapwriter.region; - -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import javax.imageio.ImageIO; - -public class SurfacePixels { - - protected Region region; - protected File filename; - protected int[] pixels = null; - protected boolean cannotLoad = false; - protected int updateCount = 0; - - public SurfacePixels(Region region, File filename) { - this.region = region; - this.filename = filename; - } - - public void clear() { - if (this.pixels != null) { - Arrays.fill(this.pixels, 0); - } - } - - public void close() { - if (this.updateCount > 0) { - this.save(); - } - this.pixels = null; - } - - private void save() { - if (this.pixels != null) { - saveImage(this.filename, this.pixels, Region.SIZE, Region.SIZE); - this.cannotLoad = false; - } - this.updateCount = 0; - } - - private void load() { - if (!this.cannotLoad) { - this.pixels = loadImage(this.filename, Region.SIZE, Region.SIZE); - if (this.pixels != null) { - // set opaque black pixels to transparent so that - // background texture shows - for (int i = 0; i < this.pixels.length; i++) { - int colour = this.pixels[i]; - if (colour == 0xff000000) { - this.pixels[i] = 0; - } - } - } else { - this.cannotLoad = true; - } - this.updateCount = 0; - } - } - - public int[] getPixels() { - if (this.pixels == null) { - this.load(); - } - return this.pixels; - } - - public int[] getOrAllocatePixels() { - this.getPixels(); - if (this.pixels == null) { - this.pixels = new int[Region.SIZE * Region.SIZE]; - this.clear(); - } - return this.pixels; - } - - public void updateChunk(MwChunk chunk) { - int x = (chunk.x << 4); - int z = (chunk.z << 4); - int offset = this.region.getPixelOffset(x, z); - int[] pixels = this.getOrAllocatePixels(); - // TODO: refactor so that blockColours can be accessed - // more directly - ChunkRender.renderSurface( - this.region.regionManager.blockColours, - chunk, pixels, offset, Region.SIZE, - (chunk.dimension == -1) // use ceiling algorithm for nether - ); - this.region.updateZoomLevels(x, z, MwChunk.SIZE, MwChunk.SIZE); - this.updateCount++; - } - - // get the averaged colour of a 2x2 pixel area in the given pixels - public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) { - int p00 = pixels[offset]; - int p01 = pixels[offset + 1]; - int p10 = pixels[offset + scanSize]; - int p11 = pixels[offset + scanSize + 1]; - - // ignore alpha channel - int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); - r >>= 2; - int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); - g >>= 2; - int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); - b >>= 2; - return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); - } - - // update an area of pixels in this region from an area of pixels in srcPixels, - // scaling the pixels by 50%. - public void updateScaled(int[] srcPixels, int srcX, int srcZ, int dstX, int dstZ, int dstW, int dstH) { - int[] dstPixels = this.getOrAllocatePixels(); - for (int j = 0; j < dstH; j++) { - for (int i = 0; i < dstW; i++) { - int srcOffset = ((srcZ + (j * 2)) << Region.SHIFT) + (srcX + (i * 2)); - int dstPixel = getAverageOfPixelQuad(srcPixels, srcOffset, Region.SIZE); - dstPixels[((dstZ + j) << Region.SHIFT) + (dstX + i)] = dstPixel; - } - } - this.updateCount++; - } - - public static void saveImage(File filename, int[] pixels, int w, int h) { - BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - img.setRGB(0, 0, w, h, pixels, 0, w); - - try { - //MwUtil.log("writing region %s to %s", this, this.imageFile); - ImageIO.write(img, "png", filename); - } catch (IOException e) { - RegionManager.logError("saveImage: error: could not write image to %s", filename); - } - } - - public static int[] loadImage(File filename, int w, int h) { - BufferedImage img = null; - try { - img = ImageIO.read(filename); - } catch (IOException e) { - img = null; - } - int[] pixels = null; - if (img != null) { - if ((img.getWidth() == w) && (img.getHeight() == h)) { - pixels = new int[w * h]; - img.getRGB(0, 0, w, h, pixels, 0, w); - } else { - RegionManager.logWarning( - "loadImage: image '%s' does not match expected dimensions (got %dx%d expected %dx%d)", - filename, img.getWidth(), img.getHeight(), w, h - ); - } - } - return pixels; - } -} diff --git a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java deleted file mode 100644 index 6880844..0000000 --- a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java +++ /dev/null @@ -1,21 +0,0 @@ -package mapwriter.tasks; - -import mapwriter.region.RegionManager; - -public class CloseRegionManagerTask extends Task { - - private final RegionManager regionManager; - - public CloseRegionManagerTask(RegionManager regionManager) { - this.regionManager = regionManager; - } - - @Override - public void run() { - this.regionManager.close(); - } - - @Override - public void onComplete() { - } -} diff --git a/src/main/java/mapwriter/tasks/MergeTask.java b/src/main/java/mapwriter/tasks/MergeTask.java deleted file mode 100644 index 7f23cc3..0000000 --- a/src/main/java/mapwriter/tasks/MergeTask.java +++ /dev/null @@ -1,43 +0,0 @@ -package mapwriter.tasks; - -import java.io.File; - -import mapwriter.MwUtil; -import mapwriter.region.MergeToImage; -import mapwriter.region.RegionManager; - -public class MergeTask extends Task { - - final RegionManager regionManager; - final File outputDir; - final String basename; - final int x, z, w, h, dimension; - String msg = ""; - - public MergeTask(RegionManager regionManager, int x, int z, int w, int h, int dimension, File outputDir, String basename) { - this.regionManager = regionManager; - this.x = x; - this.z = z; - this.w = w; - this.h = h; - this.dimension = dimension; - this.outputDir = outputDir; - this.basename = basename; - } - - @Override - public void run() { - int count = MergeToImage.merge(this.regionManager, this.x, this.z, this.w, this.h, this.dimension, this.outputDir, this.basename); - if (count > 0) { - this.msg = String.format("successfully wrote merged images to directory %s", this.outputDir); - } else { - this.msg = String.format("merge error: could not write images to directory %s", this.outputDir); - } - } - - @Override - public void onComplete() { - MwUtil.printBoth(this.msg); - } - -} diff --git a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java deleted file mode 100644 index 9e8823f..0000000 --- a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java +++ /dev/null @@ -1,36 +0,0 @@ -package mapwriter.tasks; - -import mapwriter.Mw; -import mapwriter.MwUtil; -import mapwriter.region.BlockColours; -import mapwriter.region.RegionManager; - -public class RebuildRegionsTask extends Task { - - final RegionManager regionManager; - final BlockColours blockColours; - final int x, z, w, h, dimension; - String msg = ""; - - public RebuildRegionsTask(Mw mw, int x, int z, int w, int h, int dimension) { - this.regionManager = mw.regionManager; - this.blockColours = mw.blockColours; - this.x = x; - this.z = z; - this.w = w; - this.h = h; - this.dimension = dimension; - } - - @Override - public void run() { - this.regionManager.blockColours = blockColours; - this.regionManager.rebuildRegions(this.x, this.z, this.w, this.h, this.dimension); - } - - @Override - public void onComplete() { - MwUtil.printBoth("rebuild task complete"); - } - -} diff --git a/src/main/java/mapwriter/tasks/SaveChunkTask.java b/src/main/java/mapwriter/tasks/SaveChunkTask.java deleted file mode 100644 index b90fbc3..0000000 --- a/src/main/java/mapwriter/tasks/SaveChunkTask.java +++ /dev/null @@ -1,23 +0,0 @@ -package mapwriter.tasks; - -import mapwriter.region.MwChunk; -import mapwriter.region.RegionManager; - -public class SaveChunkTask extends Task { - private final MwChunk chunk; - private final RegionManager regionManager; - - public SaveChunkTask(MwChunk chunk, RegionManager regionManager) { - this.chunk = chunk; - this.regionManager = regionManager; - } - - @Override - public void run() { - this.chunk.write(this.regionManager.regionFileCache); - } - - @Override - public void onComplete() { - } -} diff --git a/src/main/java/mapwriter/tasks/Task.java b/src/main/java/mapwriter/tasks/Task.java deleted file mode 100644 index d2eff63..0000000 --- a/src/main/java/mapwriter/tasks/Task.java +++ /dev/null @@ -1,43 +0,0 @@ -package mapwriter.tasks; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -public abstract class Task implements Runnable { - - // the task stores its own future - private Future future = null; - - // called by processTaskQueue after the thread completes - public abstract void onComplete(); - - // the method that runs in a separate thread - // must not access future in run() - public abstract void run(); - - // methods to access the tasks Future variable - public final Future getFuture() { - return this.future; - } - - public final void setFuture(Future future) { - this.future = future; - } - - public final boolean isDone() { - return (this.future != null) ? this.future.isDone() : false; - } - - public final void printException() { - if (this.future != null) { - try { - this.future.get(); - } catch (ExecutionException e) { - Throwable rootException = e.getCause(); - rootException.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java deleted file mode 100644 index b71c00d..0000000 --- a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java +++ /dev/null @@ -1,38 +0,0 @@ -package mapwriter.tasks; - -import mapwriter.Mw; -import mapwriter.map.MapTexture; -import mapwriter.region.MwChunk; -import mapwriter.region.RegionManager; - -public class UpdateSurfaceChunksTask extends Task { - MwChunk[] chunkArray; - RegionManager regionManager; - MapTexture mapTexture; - - public UpdateSurfaceChunksTask(Mw mw, MwChunk[] chunkArray) { - this.mapTexture = mw.mapTexture; - this.regionManager = mw.regionManager; - this.chunkArray = chunkArray; - } - - @Override - public void run() { - for (MwChunk chunk : this.chunkArray) { - if (chunk != null) { - // update the chunk in the region pixels - this.regionManager.updateChunk(chunk); - // copy updated region pixels to maptexture - this.mapTexture.updateArea( - this.regionManager, - chunk.x << 4, chunk.z << 4, - MwChunk.SIZE, MwChunk.SIZE, chunk.dimension - ); - } - } - } - - @Override - public void onComplete() { - } -} diff --git a/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java b/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java index dc83da7..c8ae674 100644 --- a/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java +++ b/src/main/java/mcp/mobius/opis/events/OpisServerTickHandler.java @@ -1,43 +1,30 @@ package mcp.mobius.opis.events; -import java.util.ArrayList; -import java.util.HashMap; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; +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 mcp.mobius.mobiuscore.profiler.ProfilerSection; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.holders.newtypes.DataDimension; -import mcp.mobius.opis.data.holders.newtypes.DataPacket; -import mcp.mobius.opis.data.holders.newtypes.DataPacket250; -import mcp.mobius.opis.data.holders.newtypes.DataThread; -import mcp.mobius.opis.data.holders.newtypes.DataTiming; -import mcp.mobius.opis.data.holders.newtypes.NexusData; -import mcp.mobius.opis.data.holders.stats.StatsChunk; +import mcp.mobius.opis.data.holders.newtypes.*; import mcp.mobius.opis.data.managers.ChunkManager; import mcp.mobius.opis.data.managers.EntityManager; import mcp.mobius.opis.data.managers.StringCache; import mcp.mobius.opis.data.managers.TileEntityManager; import mcp.mobius.opis.data.profilers.ProfilerPacket; import mcp.mobius.opis.data.profilers.ProfilerTick; -import mcp.mobius.opis.gui.overlay.OverlayStatus; +import mcp.mobius.opis.modOpis; 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.server.NetDataCommand; import mcp.mobius.opis.network.packets.server.NetDataList; import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.rcon.RConHandler; -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 mcp.mobius.mobiuscore.monitors.MonitoredEntityList; -import mcp.mobius.mobiuscore.monitors.MonitoredTileList; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraftforge.common.DimensionManager; + +import java.util.ArrayList; +import java.util.HashMap; public enum OpisServerTickHandler{ INSTANCE; @@ -54,16 +41,6 @@ public enum OpisServerTickHandler{ @SubscribeEvent public void tickEnd(TickEvent.ServerTickEvent event) { - - /* - if (System.nanoTime() - timer500 > 500000000){ - timer500 = System.nanoTime(); - - for (Player player : PlayerTracker.instance().playersSwing){ - PacketDispatcher.sendPacketToPlayer(Packet_DataValue.create(DataReq.VALUE_TIMING_TICK, TickProfiler.instance().stats), player); - } - } - */ StringCache.INSTANCE.syncNewCache(); @@ -126,9 +103,7 @@ public enum OpisServerTickHandler{ 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())); - - updatePlayers(); - + 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()))); @@ -161,21 +136,5 @@ public enum OpisServerTickHandler{ } } } - - private void updatePlayers(){ - for (EntityPlayerMP player : PlayerTracker.INSTANCE.playerOverlayStatus.keySet()){ - - if (PlayerTracker.INSTANCE.playerOverlayStatus.get(player) == OverlayStatus.CHUNKSTATUS){ - PacketManager.validateAndSend(new NetDataCommand(Message.LIST_CHUNK_LOADED_CLEAR), player); - PacketManager.splitAndSend(Message.LIST_CHUNK_LOADED, ChunkManager.INSTANCE.getLoadedChunks(PlayerTracker.INSTANCE.playerDimension.get(player)), player); - } - - if (PlayerTracker.INSTANCE.playerOverlayStatus.get(player) == OverlayStatus.MEANTIME){ - ArrayList timingChunks = ChunkManager.INSTANCE.getTopChunks(100); - //OpisPacketHandler.validateAndSend(Packet_DataList.create(DataReq.LIST_TIMING_CHUNK, timingChunks), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_CHUNK, timingChunks), player); - } - } - } } diff --git a/src/main/java/mcp/mobius/opis/events/PlayerTracker.java b/src/main/java/mcp/mobius/opis/events/PlayerTracker.java index 28587fa..592724b 100644 --- a/src/main/java/mcp/mobius/opis/events/PlayerTracker.java +++ b/src/main/java/mcp/mobius/opis/events/PlayerTracker.java @@ -1,30 +1,25 @@ package mcp.mobius.opis.events; -import java.util.HashMap; -import java.util.HashSet; - import com.mojang.authlib.GameProfile; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.holders.basetypes.SerialLong; import mcp.mobius.opis.data.holders.newtypes.PlayerStatus; import mcp.mobius.opis.data.managers.StringCache; -import mcp.mobius.opis.gui.overlay.OverlayStatus; +import mcp.mobius.opis.modOpis; 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.enums.PlayerEv; 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 net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.event.entity.living.LivingDeathEvent; + +import java.util.HashMap; +import java.util.HashSet; //public class PlayerTracker implements IPlayerTracker{ public enum PlayerTracker{ @@ -35,7 +30,6 @@ public enum 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 playerOverlayStatus = new HashMap(); public HashMap playerDimension = new HashMap(); public HashMap playerTab = new HashMap(); private HashSet playerPrivileged = new HashSet(); @@ -105,7 +99,6 @@ public enum PlayerTracker{ @SubscribeEvent public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event){ - this.playerOverlayStatus.remove(event.player); this.playerDimension.remove(event.player); //this.playersOpis.remove(player); this.playersSwing.remove(event.player); diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/OverlayLoadedChunks.java b/src/main/java/mcp/mobius/opis/gui/overlay/OverlayLoadedChunks.java deleted file mode 100644 index 460ceb4..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/OverlayLoadedChunks.java +++ /dev/null @@ -1,286 +0,0 @@ -package mcp.mobius.opis.gui.overlay; - -import java.awt.Point; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -import javax.swing.table.DefaultTableModel; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.Minecraft; -import net.minecraft.util.MathHelper; -import net.minecraft.world.ChunkCoordIntPair; -import mapwriter.Mw; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import mcp.mobius.opis.api.IMessageHandler; -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.SerialInt; -import mcp.mobius.opis.data.holders.basetypes.TicketData; -import mcp.mobius.opis.data.holders.stats.StatsChunk; -import mcp.mobius.opis.data.managers.ChunkManager; -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.widgets.LayoutBase; -import mcp.mobius.opis.gui.widgets.LayoutCanvas; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -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.PacketReqChunks; -import mcp.mobius.opis.network.packets.client.PacketReqData; -import mcp.mobius.opis.swing.widgets.JTableStats; - -public enum OverlayLoadedChunks implements IMwDataProvider, IMessageHandler { - INSTANCE; - - public class TicketTable extends ViewTable{ - MapView mapView; - MapMode mapMode; - OverlayLoadedChunks overlay; - - public TicketTable(IWidget parent, OverlayLoadedChunks overlay) { - super(parent); - this.overlay = overlay; - } - - public void setMap(MapView mapView, MapMode mapMode){ - this.mapView = mapView; - this.mapMode = mapMode; - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - CoordinatesChunk coord = ((TicketData)row.getObject()).coord; - - if (this.mapView.getX() != coord.x || this.mapView.getZ() != coord.z || this.mapView.getDimension() != coord.dim){ - this.mapView.setDimension(coord.dim); - this.mapView.setViewCentre(coord.x, coord.z); - this.overlay.requestChunkUpdate(this.mapView.getDimension(), - MathHelper.ceiling_double_int(this.mapView.getX()) >> 4, - MathHelper.ceiling_double_int(this.mapView.getZ()) >> 4); - } else { - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_BLOCK, new CoordinatesBlock(coord))); - Minecraft.getMinecraft().setIngameFocus(); - } - } - } - } - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - boolean forced; - - public ChunkOverlay(int x, int z, boolean forced){ - this.coord = new Point(x, z); - this.forced = forced; - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { return this.forced ? 0x500000ff : 0x5000ff00; } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return 0xff000000; } - - } - - //public static OverlayLoadedChunks instance = new OverlayLoadedChunks(); - //private OverlayLoadedChunks(){}; - - CoordinatesChunk selectedChunk = null; - public boolean showList = false; - public LayoutCanvas canvas = null; - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - ArrayList overlays = new ArrayList(); - - for (CoordinatesChunk chunk : ChunkManager.INSTANCE.getLoadedChunks()){ - overlays.add(new ChunkOverlay(chunk.chunkX, chunk.chunkZ, chunk.metadata == 0 ? false : true)); - } - return overlays; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { - int xChunk = bX >> 4; - int zChunk = bZ >> 4; - - for (CoordinatesChunk chunk : ChunkManager.INSTANCE.getLoadedChunks()){ - if (chunk.chunkX == xChunk && chunk.chunkZ == zChunk && chunk.metadata == 0) - return ", Game loaded"; - - else if (chunk.chunkX == xChunk && chunk.chunkZ == zChunk && chunk.metadata == 1) - return ", Force loaded"; - } - - return ""; - } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview) { - int chunkX = bX >> 4; - int chunkZ = bZ >> 4; - this.requestChunkUpdate(dim, chunkX, chunkZ); - } - - private void requestChunkUpdate(int dim, int chunkX, int chunkZ){ - ArrayList chunks = new ArrayList(); - //HashSet chunkCoords = new HashSet(); - - for (int x = -5; x <= 5; x++){ - for (int z = -5; z <= 5; z++){ - chunks.add(new CoordinatesChunk(dim, chunkX + x, chunkZ + z)); - if (chunks.size() >= 1){ - PacketManager.sendToServer(new PacketReqChunks(dim, chunks)); - chunks.clear(); - } - } - } - - /* - for (int x = -5; x <= 5; x++){ - for (int z = -5; z <= 5; z++){ - CoordinatesChunk coord = new CoordinatesChunk(dim, chunkX + x, chunkZ + z); - chunks.add(coord); - chunkCoords.add(coord.toChunkCoordIntPair()); - } - } - - if (chunks.size() > 0){ - Mw.instance.chunkManager.addForcedChunks(chunkCoords); - PacketDispatcher.sendPacketToServer(Packet_ReqChunks.create(dim, chunks)); - } - */ - - if (chunks.size() > 0) - PacketManager.sendToServer(new PacketReqChunks(dim, chunks)); - } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_LOADED, new SerialInt(dimension))); - } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - } - - @Override - public void onOverlayActivated(MapView mapview) { - this.selectedChunk = null; - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_LOADED, new SerialInt(mapview.getDimension()))); - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_TICKETS)); - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - this.showList = false; - this.selectedChunk = null; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_UNREGISTER)); - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - if (mapmode.marginLeft != 0){ - this.canvas.hide(); - return; - } - - if (!this.showList) - this.canvas.hide(); - else{ - this.canvas.show(); - this.canvas.draw(); - } - } - - @SideOnly(Side.CLIENT) - public void setupTable(ArrayList tickets){ - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - LayoutBase layout = (LayoutBase)this.canvas.addWidget("Table", new LayoutBase(null)); - //layout.setGeometry(new WidgetGeometry(100.0,0.0,300.0,100.0,CType.RELXY, CType.REL_Y, WAlign.RIGHT, WAlign.TOP)); - layout.setGeometry(new WidgetGeometry(100.0,0.0,30.0,100.0,CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.TOP)); - layout.setBackgroundColors(0x90202020, 0x90202020); - - TicketTable table = (TicketTable)layout.addWidget("Table_", new TicketTable(null, this)); - - table.setGeometry(new WidgetGeometry(0.0,0.0,100.0,100.0,CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.TOP)); - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oPos", "\u00a7a\u00a7oMod", "\u00a7a\u00a7oChunks") - .setColumnsTitle("Pos", "Mod", "Chunks") - .setColumnsWidth(50,25,25) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - - for (TicketData data : tickets) - //table.addRow(data, String.format("[%s %s %s]", data.coord.dim, data.coord.chunkX, data.coord.chunkZ), "\u00a79\u00a7o" + data.modID, String.valueOf(data.nchunks)); - table.addRow(data, String.format("[%s %s %s]", data.coord.dim, data.coord.chunkX, data.coord.chunkZ), data.modID, String.valueOf(data.nchunks)); - - this.showList = true; - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - if (this.canvas != null && this.canvas.shouldRender() && ((LayoutCanvas)this.canvas).hasWidgetAtCursor()){ - ((TicketTable)this.canvas.getWidget("Table").getWidget("Table_")).setMap(mapview, mapmode); - this.canvas.handleMouseInput(); - return true; - } - return false; - } - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_CHUNK_TICKETS:{ - ArrayList arr = new ArrayList(); - for (ISerializable s : rawdata.array) - arr.add((TicketData)s); - - this.setupTable(arr); - - break; - } - default: - return false; - - } - return true; - } -} diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/OverlayMeanTime.java b/src/main/java/mcp/mobius/opis/gui/overlay/OverlayMeanTime.java deleted file mode 100644 index 84930a8..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/OverlayMeanTime.java +++ /dev/null @@ -1,341 +0,0 @@ -package mcp.mobius.opis.gui.overlay; - -import java.awt.Point; -import java.util.ArrayList; - -import org.lwjgl.input.Mouse; - -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; -import net.minecraft.util.MathHelper; -import cpw.mods.fml.common.registry.LanguageRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.api.IMessageHandler; -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.SerialInt; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; -import mcp.mobius.opis.data.managers.ChunkManager; -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.widgets.LayoutBase; -import mcp.mobius.opis.gui.widgets.LayoutCanvas; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -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.PacketReqChunks; -import mcp.mobius.opis.network.packets.client.PacketReqData; - -public enum OverlayMeanTime implements IMwDataProvider, IMessageHandler{ - INSTANCE; - - public class EntitiesTable extends ViewTable{ - MapView mapView; - MapMode mapMode; - OverlayMeanTime overlay; - - public EntitiesTable(IWidget parent, OverlayMeanTime overlay) { - super(parent); - this.overlay = overlay; - } - - public void setMap(MapView mapView, MapMode mapMode){ - this.mapView = mapView; - this.mapMode = mapMode; - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - CoordinatesBlock coord = ((DataBlockTileEntity)row.getObject()).pos; - - if (this.mapView.getX() != coord.x || this.mapView.getZ() != coord.z){ - this.mapView.setViewCentre(coord.x, coord.z); - this.overlay.requestChunkUpdate(this.mapView.getDimension(), - MathHelper.ceiling_double_int(this.mapView.getX()) >> 4, - MathHelper.ceiling_double_int(this.mapView.getZ()) >> 4); - } - else{ - //modOpis.selectedBlock = coord; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_BLOCK, coord)); - Minecraft.getMinecraft().setIngameFocus(); - } - } - } - } - - public class ChunkOverlay implements IMwChunkOverlay{ - - Point coord; - int nentities; - double time; - double minTime; - double maxTime; - boolean selected; - - public ChunkOverlay(int x, int z, int nentities, double time, double mintime, double maxtime, boolean selected){ - this.coord = new Point(x, z); - this.nentities = nentities; - this.time = time; - this.minTime = mintime; - this.maxTime = maxtime; - this.selected = selected; - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { - //System.out.printf("%s\n", this.maxTime); - double scaledTime = this.time / this.maxTime; - int red = MathHelper.ceiling_double_int(scaledTime * 255.0); - int blue = 255 - MathHelper.ceiling_double_int(scaledTime * 255.0); - //System.out.printf("%s\n", red); - - return (200 << 24) + (red << 16) + (blue); - } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return this.selected ? 0xffffffff : 0xff000000; } - - } - - CoordinatesChunk selectedChunk = null; - public boolean showList = false; - public LayoutCanvas canvas = null; - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - ArrayList overlays = new ArrayList(); - - double minTime = 9999; - double maxTime = 0; - - for (CoordinatesChunk chunk : ChunkManager.INSTANCE.getChunkMeanTime().keySet()){ - minTime = Math.min(minTime, ChunkManager.INSTANCE.getChunkMeanTime().get(chunk).getDataSum()); - maxTime = Math.max(maxTime, ChunkManager.INSTANCE.getChunkMeanTime().get(chunk).getDataSum()); - } - - for (CoordinatesChunk chunk : ChunkManager.INSTANCE.getChunkMeanTime().keySet()){ - if (this.selectedChunk != null) - overlays.add(new ChunkOverlay(chunk.chunkX, chunk.chunkZ, ChunkManager.INSTANCE.getChunkMeanTime().get(chunk).tileEntities, ChunkManager.INSTANCE.getChunkMeanTime().get(chunk).getDataSum(), minTime, maxTime, chunk.equals(this.selectedChunk))); - else - overlays.add(new ChunkOverlay(chunk.chunkX, chunk.chunkZ, ChunkManager.INSTANCE.getChunkMeanTime().get(chunk).tileEntities, ChunkManager.INSTANCE.getChunkMeanTime().get(chunk).getDataSum(), minTime, maxTime, false)); - } - return overlays; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { - int xChunk = bX >> 4; - int zChunk = bZ >> 4; - CoordinatesChunk chunkCoord = new CoordinatesChunk(dim, xChunk, zChunk); - - if (ChunkManager.INSTANCE.getChunkMeanTime().containsKey(chunkCoord)) - if (modOpis.microseconds) - return String.format(" | %.3f \u00B5s", ChunkManager.INSTANCE.getChunkMeanTime().get(chunkCoord).getDataSum()/1000.0); - else - return String.format(", %.5f ms", ChunkManager.INSTANCE.getChunkMeanTime().get(chunkCoord).getDataSum()/1000.0/1000.0); - - else - return ""; - } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview) { - this.showList = false; - - int chunkX = bX >> 4; - int chunkZ = bZ >> 4; - CoordinatesChunk clickedChunk = new CoordinatesChunk(dim, chunkX, chunkZ); - - if (ChunkManager.INSTANCE.getChunkMeanTime().containsKey(clickedChunk)){ - if (this.selectedChunk == null) - this.selectedChunk = clickedChunk; - else if (this.selectedChunk.equals(clickedChunk)) - this.selectedChunk = null; - else - this.selectedChunk = clickedChunk; - } else { - this.selectedChunk = null; - } - - if (this.selectedChunk != null) - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_TILEENTS, this.selectedChunk)); - - //ArrayList chunks = new ArrayList(); - //for (int x = -5; x <= 5; x++) - // for (int z = -5; z <= 5; z++) - // chunks.add(new CoordinatesChunk(dim, x, z)); - //PacketDispatcher.sendPacketToServer(Packet_ReqChunks.create(chunks)); - - } - - public void setSelectedChunk(int dim, int chunkX, int chunkZ){ - this.selectedChunk = new CoordinatesChunk(dim, chunkX, chunkZ); - - if (this.selectedChunk != null) - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_TILEENTS, this.selectedChunk)); - } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { - PacketManager.sendToServer(new PacketReqData(Message.OVERLAY_CHUNK_TIMING, new SerialInt(dimension))); - } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) { - } - - @Override - public void onZoomChanged(int level, MapView mapview) { - } - - @Override - public void onOverlayActivated(MapView mapview) { - this.selectedChunk = null; - PacketManager.sendToServer(new PacketReqData(Message.OVERLAY_CHUNK_TIMING, new SerialInt(mapview.getDimension()))); - } - - @Override - public void onOverlayDeactivated(MapView mapview) { - this.showList = false; - this.selectedChunk = null; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_UNREGISTER)); - } - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - if (mapmode.marginLeft != 0){ - this.canvas.hide(); - return; - } - - if (!this.showList) - this.canvas.hide(); - else{ - this.canvas.show(); - this.canvas.draw(); - } - - } - - @SideOnly(Side.CLIENT) - public void setupTable(ArrayList entities){ - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - LayoutBase layout = (LayoutBase)this.canvas.addWidget("Table", new LayoutBase(null)); - //layout.setGeometry(new WidgetGeometry(100.0,0.0,300.0,100.0,CType.RELXY, CType.REL_Y, WAlign.RIGHT, WAlign.TOP)); - layout.setGeometry(new WidgetGeometry(100.0,0.0,30.0,100.0,CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.TOP)); - layout.setBackgroundColors(0x90202020, 0x90202020); - - EntitiesTable table = (EntitiesTable)layout.addWidget("Table_", new EntitiesTable(null, this)); - - table.setGeometry(new WidgetGeometry(0.0,0.0,100.0,100.0,CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.TOP)); - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Type", "Pos", "Update Time") - .setColumnsWidth(50,25,25) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - for (ISerializable uncasted : entities){ - - DataBlockTileEntity data = (DataBlockTileEntity)uncasted; - - ItemStack is; - String name = String.format("te.%d.%d", data.id, data.meta); - - try{ - is = new ItemStack(Block.getBlockById(data.id), 1, data.meta); - name = is.getDisplayName(); - } catch (Exception e) { } - - /* - if (name.equals(data.getType())) - name = LanguageRegistry.instance().getStringLocalization(data.getType()); - if (name.isEmpty()) - name = data.getType(); - */ - - if (modOpis.microseconds) - table.addRow(data, name, String.format("[ %s %s %s ]", data.pos.x, data.pos.y, data.pos.z), data.update.asMillisecond().toString()); - else - table.addRow(data, name, String.format("[ %s %s %s ]", data.pos.x, data.pos.y, data.pos.z), data.update.toString()); - } - - this.showList = true; - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - if (this.canvas != null && this.canvas.shouldRender() && ((LayoutCanvas)this.canvas).hasWidgetAtCursor()){ - ((EntitiesTable)this.canvas.getWidget("Table").getWidget("Table_")).setMap(mapview, mapmode); - this.canvas.handleMouseInput(); - return true; - } - return false; - } - - private void requestChunkUpdate(int dim, int chunkX, int chunkZ){ - ArrayList chunks = new ArrayList(); - - for (int x = -5; x <= 5; x++){ - for (int z = -5; z <= 5; z++){ - chunks.add(new CoordinatesChunk(dim, chunkX + x, chunkZ + z)); - if (chunks.size() >= 1){ - PacketManager.sendToServer(new PacketReqChunks(dim, chunks)); - chunks.clear(); - } - } - } - - if (chunks.size() > 0) - PacketManager.sendToServer(new PacketReqChunks(dim, chunks)); - } - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_CHUNK_TILEENTS:{ - this.setupTable(rawdata.array); - break; - } - default: - return false; - } - - - return true; - } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/OverlayStatus.java b/src/main/java/mcp/mobius/opis/gui/overlay/OverlayStatus.java deleted file mode 100644 index 1bf8903..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/OverlayStatus.java +++ /dev/null @@ -1,6 +0,0 @@ -package mcp.mobius.opis.gui.overlay; - -public enum OverlayStatus { - CHUNKSTATUS, - MEANTIME; -} diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/OverlayElement.java b/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/OverlayElement.java deleted file mode 100644 index a69afe5..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/OverlayElement.java +++ /dev/null @@ -1,47 +0,0 @@ -package mcp.mobius.opis.gui.overlay.entperchunk; - -import java.awt.Point; - -import net.minecraft.util.MathHelper; -import mapwriter.api.IMwChunkOverlay; - -public class OverlayElement implements IMwChunkOverlay { - - Point coord; - int minEnts; - int maxEnts; - int ents; - boolean selected; - - public OverlayElement(int x, int z, int minEnts, int maxEnts, int ents, boolean selected){ - this.coord = new Point(x, z); - this.minEnts = minEnts; - this.maxEnts = maxEnts; - this.ents = ents; - this.selected = selected; - } - - @Override - public Point getCoordinates() { return this.coord; } - - @Override - public int getColor() { - double scaledAmount = (double)this.ents / (double)this.maxEnts; - int red = MathHelper.ceiling_double_int(scaledAmount * 255.0); - int blue = 255 - MathHelper.ceiling_double_int(scaledAmount * 255.0); - - return (200 << 24) + (red << 16) + (blue); } - - @Override - public float getFilling() { return 1.0f; } - - @Override - public boolean hasBorder() { return true; } - - @Override - public float getBorderWidth() { return 0.5f; } - - @Override - public int getBorderColor() { return this.selected ? 0xffffffff : 0xff000000; } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/OverlayEntityPerChunk.java b/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/OverlayEntityPerChunk.java deleted file mode 100644 index a2ef634..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/OverlayEntityPerChunk.java +++ /dev/null @@ -1,307 +0,0 @@ -package mcp.mobius.opis.gui.overlay.entperchunk; - -import java.awt.Point; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.MathHelper; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import mapwriter.api.IMwChunkOverlay; -import mapwriter.api.IMwDataProvider; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import mcp.mobius.opis.api.IMessageHandler; -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.newtypes.DataChunkEntities; -import mcp.mobius.opis.data.holders.newtypes.DataEntity; -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.widgets.LayoutBase; -import mcp.mobius.opis.gui.widgets.LayoutCanvas; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -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.PacketReqChunks; -import mcp.mobius.opis.network.packets.client.PacketReqData; - -public enum OverlayEntityPerChunk implements IMwDataProvider, IMessageHandler { - INSTANCE; - - class ReducedData implements Comparable{ - CoordinatesChunk chunk; - int amount; - - public ReducedData(CoordinatesChunk chunk, int amount){ - this.chunk = chunk; - this.amount = amount; - } - - @Override - public int compareTo(Object arg0) { - return ((ReducedData)arg0).amount - this.amount; - } - - } - - public boolean showList = false; - public LayoutCanvas canvas = null; - public HashMap overlayData = new HashMap(); - public ArrayList reducedData = new ArrayList(); - public ArrayList entStats = new ArrayList(); - public CoordinatesChunk selectedChunk = null; - - public void setEntStats(ArrayList data){ - this.entStats.clear(); - for (ISerializable stat : data) - this.entStats.add((DataEntity)stat); - } - - public void reduceData(){ - this.reducedData.clear(); - for (CoordinatesChunk chunk : this.overlayData.keySet()) - this.reducedData.add(new ReducedData(chunk, this.overlayData.get(chunk))); - Collections.sort(this.reducedData); - } - - @Override - public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { - ArrayList overlays = new ArrayList(); - - int minEnts = 9999; - int maxEnts = 0; - - for (CoordinatesChunk chunk : overlayData.keySet()){ - minEnts = Math.min(minEnts, overlayData.get(chunk)); - maxEnts = Math.max(maxEnts, overlayData.get(chunk)); - } - - for (CoordinatesChunk chunk : overlayData.keySet()){ - if (chunk.dim == dim) - if (this.selectedChunk != null) - overlays.add(new OverlayElement(chunk.toChunkCoordIntPair().chunkXPos, chunk.toChunkCoordIntPair().chunkZPos, minEnts, maxEnts, overlayData.get(chunk), chunk.equals(this.selectedChunk))); - else - overlays.add(new OverlayElement(chunk.toChunkCoordIntPair().chunkXPos, chunk.toChunkCoordIntPair().chunkZPos, minEnts, maxEnts, overlayData.get(chunk), false)); - } - return overlays; - } - - @Override - public String getStatusString(int dim, int bX, int bY, int bZ) { - CoordinatesChunk chunk = new CoordinatesChunk(dim, bX >> 4, bZ >> 4); - if (this.overlayData.containsKey(chunk)) - return String.format(", entities: %d", this.overlayData.get(chunk)); - else - return ", entities: 0"; - } - - @Override - public void onMiddleClick(int dim, int bX, int bZ, MapView mapview) { - this.showList = false; - - int chunkX = bX >> 4; - int chunkZ = bZ >> 4; - CoordinatesChunk clickedChunk = new CoordinatesChunk(dim, chunkX, chunkZ); - CoordinatesChunk prevSelected = this.selectedChunk; - - if (this.overlayData.containsKey(clickedChunk)){ - if (this.selectedChunk == null) - this.selectedChunk = clickedChunk; - else if (this.selectedChunk.equals(clickedChunk)) - this.selectedChunk = null; - else - this.selectedChunk = clickedChunk; - } else { - this.selectedChunk = null; - } - - if (this.selectedChunk == null) - this.showList = true; - - if (prevSelected == null && this.selectedChunk != null) - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_ENTITIES, this.selectedChunk)); - - else if (this.selectedChunk != null && !this.selectedChunk.equals(prevSelected)) - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_ENTITIES, this.selectedChunk)); - - else if (this.selectedChunk == null) - PacketManager.sendToServer(new PacketReqData(Message.OVERLAY_CHUNK_ENTITIES)); - } - - @Override - public void onDimensionChanged(int dimension, MapView mapview) { - //PacketDispatcher.sendPacketToServer(Packet_ReqData.create("overlay:chunk:entities")); - } - - @Override - public void onMapCenterChanged(double vX, double vZ, MapView mapview) {} - - @Override - public void onZoomChanged(int level, MapView mapview) {} - - @Override - public void onOverlayActivated(MapView mapview) { - PacketManager.sendToServer(new PacketReqData(Message.OVERLAY_CHUNK_ENTITIES)); - } - - @Override - public void onOverlayDeactivated(MapView mapview) {} - - @Override - public void onDraw(MapView mapview, MapMode mapmode) { - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - if (mapmode.marginLeft != 0){ - this.canvas.hide(); - return; - } - - if (!this.showList) - this.canvas.hide(); - else{ - this.canvas.show(); - this.canvas.draw(); - } - } - - @SideOnly(Side.CLIENT) - public void setupChunkTable(){ - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - if (this.canvas.hasWidget("Table")) - this.canvas.delWidget("Table"); - - LayoutBase layout = (LayoutBase)this.canvas.addWidget("Table", new LayoutBase(null)); - //layout.setGeometry(new WidgetGeometry(100.0,0.0,300.0,100.0,CType.RELXY, CType.REL_Y, WAlign.RIGHT, WAlign.TOP)); - layout.setGeometry(new WidgetGeometry(100.0,0.0,20.0,100.0,CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.TOP)); - layout.setBackgroundColors(0x90202020, 0x90202020); - - TableChunks table = (TableChunks)layout.addWidget("Table_", new TableChunks(null, this)); - - table.setGeometry(new WidgetGeometry(0.0,0.0,100.0,100.0,CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.TOP)); - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Pos", "N Entities") - .setColumnsWidth(75,25) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - int nrows = 0; - for (ReducedData data : this.reducedData){ - table.addRow(data, data.chunk.toString(), String.valueOf(data.amount)); - nrows++; - if (nrows > 100) break; - } - - this.showList = true; - } - - @SideOnly(Side.CLIENT) - public void setupEntTable(){ - if (this.canvas == null) - this.canvas = new LayoutCanvas(); - - if (this.canvas.hasWidget("Table")) - this.canvas.delWidget("Table"); - - LayoutBase layout = (LayoutBase)this.canvas.addWidget("Table", new LayoutBase(null)); - //layout.setGeometry(new WidgetGeometry(100.0,0.0,300.0,100.0,CType.RELXY, CType.REL_Y, WAlign.RIGHT, WAlign.TOP)); - layout.setGeometry(new WidgetGeometry(100.0,0.0,20.0,100.0,CType.RELXY, CType.RELXY, WAlign.RIGHT, WAlign.TOP)); - layout.setBackgroundColors(0x90202020, 0x90202020); - - TableEntities table = (TableEntities)layout.addWidget("Table_", new TableEntities(null, this)); - - table.setGeometry(new WidgetGeometry(0.0,0.0,100.0,100.0,CType.RELXY, CType.RELXY, WAlign.LEFT, WAlign.TOP)); - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Name", "Pos") - .setColumnsWidth(75,25) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - int nrows = 0; - for (DataEntity data : this.entStats){ - //String[] namelst = data.getName().split("\\."); - //String name = namelst[namelst.length - 1]; - - String name = data.name.toString(); - - table.addRow(data, name, String.format("[ %d %d %d ]", data.pos.x, data.pos.y, data.pos.z)); - nrows++; - if (nrows > 100) break; - } - - this.showList = true; - } - - @Override - public boolean onMouseInput(MapView mapview, MapMode mapmode) { - if (this.canvas != null && this.canvas.shouldRender() && ((LayoutCanvas)this.canvas).hasWidgetAtCursor()){ - - if (this.canvas.getWidget("Table").getWidget("Table_") instanceof TableEntities) - ((TableEntities)this.canvas.getWidget("Table").getWidget("Table_")).setMap(mapview, mapmode); - else - ((TableChunks)this.canvas.getWidget("Table").getWidget("Table_")).setMap(mapview, mapmode); - - this.canvas.handleMouseInput(); - return true; - } - return false; - } - - public void requestChunkUpdate(int dim, int chunkX, int chunkZ){ - ArrayList chunks = new ArrayList(); - //HashSet chunkCoords = new HashSet(); - - for (int x = -5; x <= 5; x++){ - for (int z = -5; z <= 5; z++){ - chunks.add(new CoordinatesChunk(dim, chunkX + x, chunkZ + z)); - if (chunks.size() >= 1){ - PacketManager.sendToServer(new PacketReqChunks(dim, chunks)); - chunks.clear(); - } - } - } - - if (chunks.size() > 0) - PacketManager.sendToServer(new PacketReqChunks(dim, chunks)); - } - - @Override - public boolean handleMessage(Message msg, PacketBase rawdata) { - switch(msg){ - case LIST_CHUNK_ENTITIES:{ - this.setEntStats(rawdata.array); - this.setupEntTable(); - break; - } - case OVERLAY_CHUNK_ENTITIES:{ - HashMap chunkStatus = new HashMap(); - for (ISerializable s : rawdata.array){ - chunkStatus.put(((DataChunkEntities)s).chunk, ((DataChunkEntities)s).entities); - } - this.overlayData = chunkStatus; - this.reduceData(); - this.setupChunkTable(); - } - - default: - return false; - } - - - return true; - } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/TableChunks.java b/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/TableChunks.java deleted file mode 100644 index 0139848..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/TableChunks.java +++ /dev/null @@ -1,48 +0,0 @@ -package mcp.mobius.opis.gui.overlay.entperchunk; - -import net.minecraft.util.MathHelper; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.gui.events.MouseEvent; -import mcp.mobius.opis.gui.interfaces.IWidget; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk.ReducedData; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import mcp.mobius.opis.network.PacketManager; -import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.network.packets.client.PacketReqData; - -public class TableChunks extends ViewTable { - MapView mapView; - MapMode mapMode; - OverlayEntityPerChunk overlay; - - public TableChunks(IWidget parent, OverlayEntityPerChunk overlay) { - super(parent); - this.overlay = overlay; - } - - public void setMap(MapView mapView, MapMode mapMode){ - this.mapView = mapView; - this.mapMode = mapMode; - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - CoordinatesBlock coord = ((ReducedData)row.getObject()).chunk.asCoordinatesBlock(); - this.overlay.selectedChunk = ((ReducedData)row.getObject()).chunk; - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_ENTITIES, this.overlay.selectedChunk)); - this.overlay.showList = false; - - this.mapView.setDimension(coord.dim); - this.mapView.setViewCentre(coord.x, coord.z); - this.overlay.requestChunkUpdate(this.mapView.getDimension(), - MathHelper.ceiling_double_int(this.mapView.getX()) >> 4, - MathHelper.ceiling_double_int(this.mapView.getZ()) >> 4); - - } - } -} diff --git a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/TableEntities.java b/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/TableEntities.java deleted file mode 100644 index 5a0c34a..0000000 --- a/src/main/java/mcp/mobius/opis/gui/overlay/entperchunk/TableEntities.java +++ /dev/null @@ -1,46 +0,0 @@ -package mcp.mobius.opis.gui.overlay.entperchunk; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.MathHelper; -import mapwriter.map.MapView; -import mapwriter.map.mapmode.MapMode; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.holders.basetypes.TargetEntity; -import mcp.mobius.opis.data.holders.newtypes.DataEntity; -import mcp.mobius.opis.gui.events.MouseEvent; -import mcp.mobius.opis.gui.interfaces.IWidget; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk.ReducedData; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import mcp.mobius.opis.network.PacketManager; -import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.network.packets.client.PacketReqData; - -public class TableEntities extends ViewTable { - MapView mapView; - MapMode mapMode; - OverlayEntityPerChunk overlay; - - public TableEntities(IWidget parent, OverlayEntityPerChunk overlay) { - super(parent); - this.overlay = overlay; - } - - public void setMap(MapView mapView, MapMode mapMode){ - this.mapView = mapView; - this.mapMode = mapMode; - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - //CoordinatesBlock coord = ((EntityStats)row.getObject()).getCoord(); - //PacketDispatcher.sendPacketToServer(Packet_ReqTeleport.create(coord)); - int eid = ((DataEntity)row.getObject()).eid; - int dim = ((DataEntity)row.getObject()).pos.dim; - PacketManager.sendToServer(new PacketReqData(Message.COMMAND_TELEPORT_TO_ENTITY, new TargetEntity(eid, dim))); - Minecraft.getMinecraft().setIngameFocus(); - } - } -} diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenChunks.java.bak b/src/main/java/mcp/mobius/opis/gui/screens/ScreenChunks.java.bak deleted file mode 100644 index 324de56..0000000 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenChunks.java.bak +++ /dev/null @@ -1,78 +0,0 @@ -package mcp.mobius.opis.gui.screens; - -import java.util.ArrayList; - -import net.minecraft.client.gui.GuiScreen; -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.gui.MwGui; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.ChunkStats; -import mcp.mobius.opis.data.holders.CoordinatesBlock; -import mcp.mobius.opis.data.holders.CoordinatesChunk; -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.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import mcp.mobius.opis.overlay.OverlayMeanTime; - -public class ScreenChunks extends ScreenBase { - - public class ChunksTable extends ViewTable{ - public ChunksTable(IWidget parent) { - super(parent); - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - CoordinatesChunk coord = ((ChunkStats)row.getObject()).getChunk(); - OverlayMeanTime.instance().setSelectedChunk(coord.dim, coord.chunkX, coord.chunkZ); - MwAPI.setCurrentDataProvider(OverlayMeanTime.instance()); - this.mc.displayGuiScreen(new MwGui(Mw.instance, coord.dim, coord.x, coord.z)); - } - } - } - - - - public ScreenChunks(GuiScreen parent, ArrayList chunks) { - super(parent); - - ChunksTable table = (ChunksTable)this.getRoot().addWidget("Table", new ChunksTable(null)); - - table.setGeometry(new WidgetGeometry(50.0, 50.0, 80.0, 80.0,CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Dim", "Pos", "N TEs", "N Ents", "Update Time") - .setColumnsWidth(20, 20, 20, 20, 20) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - for (ChunkStats data : chunks){ - if (modOpis.microseconds) - table.addRow(data, - String.format("%3d", data.getChunk().dim), - String.format("[ %4d %4d ]", data.getChunk().chunkX, data.getChunk().chunkZ), - String.format("%d", data.tileEntities), - String.format("%d", data.entities), - //String.format("%.5f ms",data.updateTime/1000.0)); - String.format("%.5f \u00B5s",data.getDataSum())); - else - table.addRow(data, - String.format("%3d", data.getChunk().dim), - String.format("[ %4d %4d ]", data.getChunk().chunkX, data.getChunk().chunkZ), - String.format("%d", data.tileEntities), - String.format("%d", data.entities), - String.format("%.5f ms",data.getDataSum()/1000.0)); - } - - } - - -} diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenEntity.java.bak b/src/main/java/mcp/mobius/opis/gui/screens/ScreenEntity.java.bak deleted file mode 100644 index c8d43a1..0000000 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenEntity.java.bak +++ /dev/null @@ -1,82 +0,0 @@ -package mcp.mobius.opis.gui.screens; - -import java.util.ArrayList; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import cpw.mods.fml.common.network.PacketDispatcher; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.CoordinatesBlock; -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.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import mcp.mobius.opis.network.client.Packet_ReqTeleport; -import mcp.mobius.opis.network.client.Packet_ReqTeleportEID; -import mcp.mobius.opis.data.holders.EntityStats; - -public class ScreenEntity extends ScreenBase { - - public class EntitiesTable extends ViewTable{ - public EntitiesTable(IWidget parent) { - super(parent); - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - int eid = ((EntityStats)row.getObject()).getID(); - int dim = ((EntityStats)row.getObject()).getCoord().dim; - PacketDispatcher.sendPacketToServer(Packet_ReqTeleportEID.create(eid, dim)); - Minecraft.getMinecraft().setIngameFocus(); - } - } - } - - - - public ScreenEntity(GuiScreen parent, ArrayList stat) { - super(parent); - - EntitiesTable table = (EntitiesTable)this.getRoot().addWidget("Table", new EntitiesTable(null)); - - table.setGeometry(new WidgetGeometry(50.0, 50.0, 80.0, 80.0,CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Type", "ID", "Dim", "Pos", "Update Time", "Data") - .setColumnsWidth(30, 15, 15, 15, 15, 10) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - for (EntityStats data : stat){ - - //String[] namelst = data.getName().split("\\."); - //String name = namelst[namelst.length - 1]; - String name = data.getName(); - - if(modOpis.microseconds) - table.addRow(data, - name, - String.valueOf(data.getID()), - String.format("%3d", data.getCoord().dim), - String.format("[ %4d %4d %4d ]", data.getCoord().x, data.getCoord().y, data.getCoord().z), - String.format("%.3f \u00B5s",data.getGeometricMean()), - String.valueOf(data.getNData())); - else - table.addRow(data, - name, - String.valueOf(data.getID()), - String.format("%3d", data.getCoord().dim), - String.format("[ %4d %4d %4d ]", data.getCoord().x, data.getCoord().y, data.getCoord().z), - String.format("%.5f ms",data.getGeometricMean()/1000.0), - String.valueOf(data.getNData())); - } - - } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenEntityAmount.java.bak b/src/main/java/mcp/mobius/opis/gui/screens/ScreenEntityAmount.java.bak deleted file mode 100644 index f65cee8..0000000 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenEntityAmount.java.bak +++ /dev/null @@ -1,37 +0,0 @@ -package mcp.mobius.opis.gui.screens; - -import java.util.ArrayList; -import java.util.HashMap; - -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.gui.interfaces.CType; -import mcp.mobius.opis.gui.interfaces.WAlign; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import net.minecraft.client.gui.GuiScreen; - -public class ScreenEntityAmount extends ScreenBase { - - public ScreenEntityAmount(GuiScreen parent, HashMap stat) { - super(parent); - - ViewTable table = (ViewTable)this.getRoot().addWidget("Table", new ViewTable(null)); - - table.setGeometry(new WidgetGeometry(50.0, 50.0, 80.0, 80.0,CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Type", "Amount") - .setColumnsWidth(50, 50) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - for (String name : stat.keySet()){ - //String[] namelst = name.split("\\."); - //String nameshort = namelst[namelst.length - 1]; - - table.addRow(new Object(), name, String.valueOf(stat.get(name))); - } - } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenMods.java.bak b/src/main/java/mcp/mobius/opis/gui/screens/ScreenMods.java.bak deleted file mode 100644 index 6710744..0000000 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenMods.java.bak +++ /dev/null @@ -1,82 +0,0 @@ -package mcp.mobius.opis.gui.screens; - -import java.util.ArrayList; -import java.util.Collections; - -import net.minecraft.client.gui.GuiScreen; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.stats.StatsMod; -import mcp.mobius.opis.gui.interfaces.CType; -import mcp.mobius.opis.gui.interfaces.WAlign; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; - -public class ScreenMods extends ScreenBase { - - public ScreenMods(GuiScreen parent, ArrayList mods) { - super(parent); - - Collections.sort(mods); - - ViewTable table = (ViewTable)this.getRoot().addWidget("Table", new ViewTable(null)); - - table.setGeometry(new WidgetGeometry(50.0, 50.0, 80.0, 80.0,CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - /* - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - .setColumnsTitle("Mod", "N tiles", "Total", "Mean time", "Geom", "Min", "Max", "Mode", "Variance") - .setColumnsWidth(20, 10, 10, 10, 10, 10, 10, 10, 10) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - */ - - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - .setColumnsTitle("Mod", "N tiles", "Total", "Mean time", "Median", "Max") - .setColumnsWidth(25, 15, 15, 15, 15, 15) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - /* - for (ModStats data : mods){ - table.addRow(data, - String.format("%s", data.getModID()), - String.format("%d", data.ntes), - String.format("%.5f ms", data.total / 1000.0), - String.format("%.5f ms", data.meanTime / 1000.0), - String.format("%.5f ms", data.meanGeom / 1000.0), - String.format("%.5f ms", data.minTime / 1000.0), - String.format("%.5f ms", data.maxTime / 1000.0), - String.format("%.5f ms", data.mode / 1000.0), - String.format("%.5f ms", data.variance / 1000.0) - ); - } - */ - - for (StatsMod data : mods){ - if (modOpis.microseconds) - table.addRow(data, - String.format("%s", data.getModID()), - String.format("%d", data.ntes), - //String.format("%.5f ms", data.total / 1000.0), - //String.format("%.5f ms", data.meanTime / 1000.0), - //String.format("%.5f ms", data.median / 1000.0), - //String.format("%.5f ms", data.maxTime / 1000.0) - String.format("%.3f \u00B5s", data.total), - String.format("%.3f \u00B5s", data.meanTime), - String.format("%.3f \u00B5s", data.median), - String.format("%.3f \u00B5s", data.maxTime) - ); - else - table.addRow(data, - String.format("%s", data.getModID()), - String.format("%d", data.ntes), - String.format("%.5f ms", data.total / 1000.0), - String.format("%.5f ms", data.meanTime / 1000.0), - String.format("%.5f ms", data.median / 1000.0), - String.format("%.5f ms", data.maxTime / 1000.0) - ); - } - - } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenTickHandler.java.bak b/src/main/java/mcp/mobius/opis/gui/screens/ScreenTickHandler.java.bak deleted file mode 100644 index d2535c7..0000000 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenTickHandler.java.bak +++ /dev/null @@ -1,43 +0,0 @@ -package mcp.mobius.opis.gui.screens; - -import java.util.ArrayList; - -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.TickHandlerStats; -import mcp.mobius.opis.gui.interfaces.CType; -import mcp.mobius.opis.gui.interfaces.WAlign; -import mcp.mobius.opis.gui.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import net.minecraft.client.gui.GuiScreen; - -public class ScreenTickHandler extends ScreenBase { - - public ScreenTickHandler(GuiScreen parent, ArrayList stat) { - super(parent); - - ViewTable table = (ViewTable)this.getRoot().addWidget("Table", new ViewTable(null)); - - table.setGeometry(new WidgetGeometry(50.0, 50.0, 80.0, 80.0,CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Name", "Update Time") - .setColumnsWidth(50,50) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - for (TickHandlerStats data : stat){ - - if(modOpis.microseconds) - table.addRow(data, - data.getName(), - String.format("%.3f \u00B5s",data.getGeometricMean())); - else - table.addRow(data, - data.getName(), - String.format("%.5f ms",data.getGeometricMean()/1000.0)); - } - - } - -} diff --git a/src/main/java/mcp/mobius/opis/gui/screens/ScreenTileEntity.java.bak b/src/main/java/mcp/mobius/opis/gui/screens/ScreenTileEntity.java.bak deleted file mode 100644 index c08ae21..0000000 --- a/src/main/java/mcp/mobius/opis/gui/screens/ScreenTileEntity.java.bak +++ /dev/null @@ -1,91 +0,0 @@ -package mcp.mobius.opis.gui.screens; - -import java.util.ArrayList; - -import cpw.mods.fml.common.registry.LanguageRegistry; -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.gui.MwGui; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.data.holders.CoordinatesBlock; -import mcp.mobius.opis.data.holders.TileEntityStats; -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.widgets.WidgetGeometry; -import mcp.mobius.opis.gui.widgets.tableview.TableRow; -import mcp.mobius.opis.gui.widgets.tableview.ViewTable; -import mcp.mobius.opis.overlay.OverlayMeanTime; -import mcp.mobius.opis.tools.ModIdentification; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; - -public class ScreenTileEntity extends ScreenBase { - - public class EntitiesTable extends ViewTable{ - public EntitiesTable(IWidget parent) { - super(parent); - } - - @Override - public void onMouseClick(MouseEvent event){ - TableRow row = this.getRow(event.x, event.y); - if (row != null){ - CoordinatesBlock coord = ((TileEntityStats)row.getObject()).getCoordinates(); - OverlayMeanTime.instance().setSelectedChunk(coord.dim, coord.x >> 4, coord.z >> 4); - MwAPI.setCurrentDataProvider(OverlayMeanTime.instance()); - this.mc.displayGuiScreen(new MwGui(Mw.instance, coord.dim, coord.x, coord.z)); - } - } - } - - - - public ScreenTileEntity(GuiScreen parent, ArrayList tes) { - super(parent); - - EntitiesTable table = (EntitiesTable)this.getRoot().addWidget("Table", new EntitiesTable(null)); - - table.setGeometry(new WidgetGeometry(50.0, 50.0, 80.0, 80.0,CType.RELXY, CType.RELXY, WAlign.CENTER, WAlign.CENTER)); - - table.setColumnsAlign(WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER, WAlign.CENTER) - //.setColumnsTitle("\u00a7a\u00a7oType", "\u00a7a\u00a7oPos", "\u00a7a\u00a7oUpdate Time") - .setColumnsTitle("Type", "Mod", "Dim", "Pos", "Update Time") - .setColumnsWidth(30, 20, 15, 15, 20) - .setRowColors(0xff808080, 0xff505050) - .setFontSize(1.0f); - - for (TileEntityStats data : tes){ - - ItemStack is; - String name = String.format("te.%d.%d", data.getID(), data.getMeta()); - String modID = ""; - - try{ - is = new ItemStack(data.getID(), 1, data.getMeta()); - name = is.getDisplayName(); - modID = ModIdentification.idFromStack(is); - } catch (Exception e) { } - - if(modOpis.microseconds) - table.addRow(data, - name, - modID, - String.format("%3d", data.getCoordinates().dim), - String.format("[ %4d %4d %4d ]", data.getCoordinates().x, data.getCoordinates().y, data.getCoordinates().z), - String.format("%.3f \u00B5s",data.getGeometricMean())); - else - table.addRow(data, - name, - modID, - String.format("%3d", data.getCoordinates().dim), - String.format("[ %4d %4d %4d ]", data.getCoordinates().x, data.getCoordinates().y, data.getCoordinates().z), - String.format("%.5f ms",data.getGeometricMean()/1000.0)); - } - - } - -} diff --git a/src/main/java/mcp/mobius/opis/modOpis.java b/src/main/java/mcp/mobius/opis/modOpis.java index 2982500..b5d9659 100644 --- a/src/main/java/mcp/mobius/opis/modOpis.java +++ b/src/main/java/mcp/mobius/opis/modOpis.java @@ -1,57 +1,5 @@ package mcp.mobius.opis; -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.config.Configuration; -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.commands.client.CommandOpis; -import mcp.mobius.opis.commands.server.CommandAddPrivileged; -import mcp.mobius.opis.commands.server.CommandAmountEntities; -import mcp.mobius.opis.commands.server.CommandChunkList; -import mcp.mobius.opis.commands.server.CommandEntityCreate; -import mcp.mobius.opis.commands.server.CommandFrequency; -import mcp.mobius.opis.commands.server.CommandHelp; -import mcp.mobius.opis.commands.server.CommandKill; -import mcp.mobius.opis.commands.server.CommandKillAll; -import mcp.mobius.opis.commands.server.CommandReset; -import mcp.mobius.opis.commands.server.CommandRmPrivileged; -import mcp.mobius.opis.commands.server.CommandStart; -import mcp.mobius.opis.commands.server.CommandStop; -import mcp.mobius.opis.commands.server.CommandTicks; -import mcp.mobius.opis.commands.server.CommandTimingEntities; -import mcp.mobius.opis.commands.server.CommandTimingTileEntities; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.profilers.ProfilerDimBlockTick; -import mcp.mobius.opis.data.profilers.ProfilerDimTick; -import mcp.mobius.opis.data.profilers.ProfilerEntityUpdate; -import mcp.mobius.opis.data.profilers.ProfilerEvent; -import mcp.mobius.opis.data.profilers.ProfilerNetworkTick; -import mcp.mobius.opis.data.profilers.ProfilerPacket; -import mcp.mobius.opis.data.profilers.ProfilerRenderBlock; -import mcp.mobius.opis.data.profilers.ProfilerRenderEntity; -import mcp.mobius.opis.data.profilers.ProfilerRenderTileEntity; -import mcp.mobius.opis.data.profilers.ProfilerTick; -import mcp.mobius.opis.data.profilers.ProfilerTileEntityUpdate; -import mcp.mobius.opis.events.OpisClientEventHandler; -import mcp.mobius.opis.events.OpisClientTickHandler; -import mcp.mobius.opis.events.OpisServerEventHandler; -import mcp.mobius.opis.events.OpisServerTickHandler; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.helpers.ModIdentification; -import mcp.mobius.opis.network.PacketManager; -import mcp.mobius.opis.network.enums.AccessLevel; -import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.proxy.ProxyServer; -import mcp.mobius.opis.tools.BlockDebug; -import mcp.mobius.opis.tools.BlockLag; -import mcp.mobius.opis.tools.TileDebug; -import mcp.mobius.opis.tools.TileLag; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; @@ -62,6 +10,27 @@ import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.registry.GameRegistry; +import mcp.mobius.mobiuscore.profiler.ProfilerSection; +import mcp.mobius.opis.commands.client.CommandOpis; +import mcp.mobius.opis.commands.server.*; +import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; +import mcp.mobius.opis.data.profilers.*; +import mcp.mobius.opis.events.*; +import mcp.mobius.opis.helpers.ModIdentification; +import mcp.mobius.opis.network.PacketManager; +import mcp.mobius.opis.network.enums.AccessLevel; +import mcp.mobius.opis.network.enums.Message; +import mcp.mobius.opis.proxy.ProxyServer; +import mcp.mobius.opis.tools.BlockDebug; +import mcp.mobius.opis.tools.BlockLag; +import mcp.mobius.opis.tools.TileDebug; +import mcp.mobius.opis.tools.TileLag; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Configuration; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; @Mod(modid="Opis", name="Opis", version="1.2.4", dependencies="required-after:MobiusCore@[1.2.4]", acceptableRemoteVersions="*") //@Mod(modid="Opis", name="Opis", version="1.3.0", dependencies="required-after:MobiusCore@[1.2.4]", acceptableRemoteVersions="*") @@ -118,7 +87,6 @@ public class modOpis { try{ minOverlays = AccessLevel.valueOf(config.get("ACCESS_RIGHTS", "overlays", "NONE", commentOverlays).getString()); } catch (IllegalArgumentException e){} Message.setTablesMinimumLevel(minTables); - Message.setOverlaysMinimumLevel(minOverlays); Message.setOpisMinimumLevel(openOpis); for (String s : users) diff --git a/src/main/java/mcp/mobius/opis/network/PacketManager.java b/src/main/java/mcp/mobius/opis/network/PacketManager.java index 7234277..d0c4bf5 100644 --- a/src/main/java/mcp/mobius/opis/network/PacketManager.java +++ b/src/main/java/mcp/mobius/opis/network/PacketManager.java @@ -1,41 +1,28 @@ package mcp.mobius.opis.network; -import static cpw.mods.fml.relauncher.Side.CLIENT; -import static cpw.mods.fml.relauncher.Side.SERVER; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelHandler.Sharable; -import io.netty.channel.SimpleChannelInboundHandler; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.ConcurrentModificationException; -import java.util.EnumMap; - -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; - import com.google.common.collect.HashBasedTable; import com.google.common.collect.Maps; import com.google.common.collect.Table.Cell; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; - +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.FMLEmbeddedChannel; +import cpw.mods.fml.common.network.FMLIndexedMessageToMessageCodec; +import cpw.mods.fml.common.network.FMLOutboundHandler; +import cpw.mods.fml.common.network.NetworkRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; import mcp.mobius.mobiuscore.profiler.ProfilerSection; 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.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.DataEntity; -import mcp.mobius.opis.data.holders.newtypes.DataEntityPerClass; -import mcp.mobius.opis.data.holders.newtypes.DataEvent; -import mcp.mobius.opis.data.holders.newtypes.DataNetworkTick; -import mcp.mobius.opis.data.holders.newtypes.DataTiming; +import mcp.mobius.opis.data.holders.newtypes.*; import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.data.managers.ChunkManager; import mcp.mobius.opis.data.managers.EntityManager; @@ -48,24 +35,25 @@ import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.network.packets.server.NetDataCommand; import mcp.mobius.opis.network.packets.server.NetDataList; import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.packets.server.PacketChunks; import mcp.mobius.opis.network.rcon.RConHandler; -import mcp.mobius.opis.network.rcon.server.RConServer; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.network.FMLEmbeddedChannel; -import cpw.mods.fml.common.network.FMLIndexedMessageToMessageCodec; -import cpw.mods.fml.common.network.FMLOutboundHandler; -import cpw.mods.fml.common.network.NetworkRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S02PacketChat; import net.minecraft.util.ChatComponentText; import net.minecraftforge.common.util.FakePlayer; +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 @@ -87,7 +75,6 @@ public class PacketManager codec.addDiscriminator(2, NetDataCommand.class); codec.addDiscriminator(3, NetDataList.class); codec.addDiscriminator(4, NetDataValue.class); - codec.addDiscriminator(5, PacketChunks.class); channels.putAll(NetworkRegistry.INSTANCE.newChannel("Opis", codec)); diff --git a/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java b/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java index 65fcc3f..90f07ff 100644 --- a/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java +++ b/src/main/java/mcp/mobius/opis/network/ServerMessageHandler.java @@ -1,45 +1,30 @@ package mcp.mobius.opis.network; -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.logging.log4j.Level; - -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.monster.EntityMob; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; import cpw.mods.fml.relauncher.Side; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.basetypes.AmountHolder; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesChunk; -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.basetypes.TargetEntity; +import mcp.mobius.opis.data.holders.basetypes.*; import mcp.mobius.opis.data.holders.newtypes.DataBlockTick; -import mcp.mobius.opis.data.holders.newtypes.DataChunkEntities; -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.newtypes.DataTiming; import mcp.mobius.opis.data.holders.stats.StatsChunk; -import mcp.mobius.opis.data.managers.ChunkManager; -import mcp.mobius.opis.data.managers.EntityManager; -import mcp.mobius.opis.data.managers.MetaManager; -import mcp.mobius.opis.data.managers.StringCache; -import mcp.mobius.opis.data.managers.TileEntityManager; +import mcp.mobius.opis.data.managers.*; import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.gui.overlay.OverlayStatus; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.server.NetDataCommand; import mcp.mobius.opis.network.packets.server.NetDataList; import mcp.mobius.opis.network.packets.server.NetDataValue; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.data.holders.basetypes.TicketData; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.monster.EntityMob; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import org.apache.logging.log4j.Level; + +import java.util.ArrayList; public class ServerMessageHandler { @@ -54,35 +39,12 @@ public class ServerMessageHandler { public void handle(Message maintype, ISerializable param1, ISerializable param2, EntityPlayerMP player){ String name = player.getGameProfile().getName(); - - if (maintype == Message.OVERLAY_CHUNK_ENTITIES){ - this.handleOverlayChunkEntities((CoordinatesChunk)param1, player); - } - - else if (maintype == Message.OVERLAY_CHUNK_TIMING){ - ArrayList timingChunks = ChunkManager.INSTANCE.getTopChunks(100); - PacketManager.validateAndSend(new NetDataList(Message.LIST_TIMING_CHUNK, timingChunks), player); - } - - else if (maintype == Message.LIST_CHUNK_TILEENTS){ - PacketManager.validateAndSend(new NetDataList(Message.LIST_CHUNK_TILEENTS, TileEntityManager.INSTANCE.getTileEntitiesInChunk((CoordinatesChunk)param1)), player); - } - - else if (maintype == Message.LIST_CHUNK_ENTITIES){ - PacketManager.validateAndSend(new NetDataList(Message.LIST_CHUNK_ENTITIES, EntityManager.INSTANCE.getEntitiesInChunk((CoordinatesChunk)param1)), player); - } - else if (maintype == Message.LIST_CHUNK_LOADED){ - PlayerTracker.INSTANCE.playerOverlayStatus.put(player, OverlayStatus.CHUNKSTATUS); + 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_CHUNK_TICKETS){ - //PacketManager.sendToPlayer(new PacketTickets(ChunkManager.INSTANCE.getTickets()), player); - PacketManager.validateAndSend(new NetDataList(Message.LIST_CHUNK_TICKETS, new ArrayList(ChunkManager.INSTANCE.getTickets())), player); - } + } else if (maintype == Message.LIST_TIMING_TILEENTS){ ArrayList timingTileEnts = TileEntityManager.INSTANCE.getWorses(100); @@ -139,7 +101,6 @@ public class ServerMessageHandler { } else if (maintype == Message.COMMAND_UNREGISTER){ - PlayerTracker.INSTANCE.playerOverlayStatus.remove(player); PlayerTracker.INSTANCE.playerDimension.remove(player); } @@ -238,16 +199,4 @@ public class ServerMessageHandler { } } - public void handleOverlayChunkEntities(CoordinatesChunk coord, EntityPlayerMP player){ - - HashMap> entities = EntityManager.INSTANCE.getAllEntitiesPerChunk(); - //HashMap perChunk = new HashMap(); - ArrayList perChunk = new ArrayList(); - - for (CoordinatesChunk chunk : entities.keySet()) - perChunk.add(new DataChunkEntities(chunk, entities.get(chunk).size())); - - PacketManager.validateAndSend(new NetDataList(Message.OVERLAY_CHUNK_ENTITIES, perChunk), player); - } - } 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 70fa29b..287a72a 100644 --- a/src/main/java/mcp/mobius/opis/network/enums/Message.java +++ b/src/main/java/mcp/mobius/opis/network/enums/Message.java @@ -1,20 +1,17 @@ package mcp.mobius.opis.network.enums; -import static mcp.mobius.opis.network.enums.AccessLevel.*; +import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.swing.SelectedTab; +import net.minecraft.entity.player.EntityPlayerMP; import java.util.EnumSet; -import net.minecraft.entity.player.EntityPlayerMP; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.swing.SelectedTab; +import static mcp.mobius.opis.network.enums.AccessLevel.PRIVILEGED; public enum Message { - - LIST_CHUNK_TILEENTS, - LIST_CHUNK_ENTITIES, + LIST_CHUNK_LOADED, LIST_CHUNK_LOADED_CLEAR, - LIST_CHUNK_TICKETS, LIST_TIMING_TILEENTS, LIST_TIMING_TILEENTS_PER_CLASS, LIST_TIMING_ENTITIES, @@ -40,19 +37,6 @@ public enum Message { VALUE_TIMING_WORLDTICK, VALUE_TIMING_ENTUPDATE, VALUE_TIMING_NETWORK, - /* - VALUE_TIMING_TICK, //OUTDATED - - - VALUE_AMOUNT_TILEENTS(EnumSet.of(SelectedTab.SUMMARY)), //OUTDATED - VALUE_AMOUNT_ENTITIES(EnumSet.of(SelectedTab.SUMMARY)), //OUTDATED - VALUE_AMOUNT_HANDLERS(EnumSet.of(SelectedTab.SUMMARY)), - VALUE_AMOUNT_UPLOAD (EnumSet.of(SelectedTab.SUMMARY)), //OUTDATED - VALUE_AMOUNT_DOWNLOAD(EnumSet.of(SelectedTab.SUMMARY)), //OUTDATED - - VALUE_CHUNK_FORCED (EnumSet.of(SelectedTab.SUMMARY)), //OUTDATED - VALUE_CHUNK_LOADED (EnumSet.of(SelectedTab.SUMMARY)), //OUTDATED - */ STATUS_START, STATUS_STOP, @@ -86,9 +70,6 @@ public enum Message { 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 - OVERLAY_CHUNK_ENTITIES, - OVERLAY_CHUNK_TIMING, - CLIENT_START_PROFILING, CLIENT_STOP_PROFILING, CLIENT_RESET_PROFILING, @@ -149,8 +130,7 @@ public enum Message { } public static void setTablesMinimumLevel(AccessLevel level){ - Message.LIST_CHUNK_TILEENTS.setAccessLevel(level); - Message.LIST_CHUNK_ENTITIES.setAccessLevel(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); @@ -170,14 +150,7 @@ public enum Message { Message.LIST_ORPHAN_TILEENTS.setAccessLevel(level); Message.LIST_THREADS.setAccessLevel(level); } - - public static void setOverlaysMinimumLevel(AccessLevel level){ - Message.OVERLAY_CHUNK_ENTITIES.setAccessLevel(level); - Message.OVERLAY_CHUNK_TIMING.setAccessLevel(level); - Message.LIST_CHUNK_LOADED.setAccessLevel(level); - Message.LIST_CHUNK_TICKETS.setAccessLevel(level); - } - + public static void setOpisMinimumLevel(AccessLevel level){ Message.COMMAND_OPEN_SWING.setAccessLevel(level); } diff --git a/src/main/java/mcp/mobius/opis/network/packets/server/PacketChunks.java b/src/main/java/mcp/mobius/opis/network/packets/server/PacketChunks.java deleted file mode 100644 index f11e2ee..0000000 --- a/src/main/java/mcp/mobius/opis/network/packets/server/PacketChunks.java +++ /dev/null @@ -1,38 +0,0 @@ -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 mapwriter.Mw; -import mapwriter.region.MwChunk; -import mcp.mobius.opis.network.PacketBase; - -public class PacketChunks extends PacketBase{ - - public int dim; - public MwChunk[] chunks; - - @Override - public void encode(ByteArrayDataOutput output) { - // TODO Auto-generated method stub - - } - - @Override - public void decode(ByteArrayDataInput input) { - // TODO Auto-generated method stub - - } - - @Override - @SideOnly(Side.CLIENT) - public void actionClient(World world, EntityPlayer player){ - Mw.instance.chunkManager.forceChunks(this.chunks); - } - -} 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 2b0db40..0280a75 100644 --- a/src/main/java/mcp/mobius/opis/network/rcon/RConHandler.java +++ b/src/main/java/mcp/mobius/opis/network/rcon/RConHandler.java @@ -1,34 +1,28 @@ package mcp.mobius.opis.network.rcon; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.net.ConnectException; - -import javax.net.ssl.SSLException; - -import io.nettyopis.buffer.ByteBuf; -import io.nettyopis.channel.ChannelFuture; -import io.nettyopis.channel.ChannelFutureListener; -import io.nettyopis.channel.ChannelHandlerContext; -import net.minecraftforge.common.util.FakePlayer; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.events.PlayerTracker; -import mcp.mobius.opis.network.PacketBase; -import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.network.packets.client.PacketReqChunks; -import mcp.mobius.opis.network.packets.client.PacketReqData; -import mcp.mobius.opis.network.packets.server.NetDataCommand; -import mcp.mobius.opis.network.packets.server.NetDataList; -import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.packets.server.PacketChunks; -import mcp.mobius.opis.network.rcon.nexus.EventTimerRing; -import mcp.mobius.opis.network.rcon.nexus.NexusClient; -import mcp.mobius.opis.network.rcon.nexus.NexusInboundHandler; - import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; +import io.nettyopis.buffer.ByteBuf; +import io.nettyopis.channel.ChannelFuture; +import io.nettyopis.channel.ChannelFutureListener; +import io.nettyopis.channel.ChannelHandlerContext; +import mcp.mobius.opis.events.PlayerTracker; +import mcp.mobius.opis.modOpis; +import mcp.mobius.opis.network.PacketBase; +import mcp.mobius.opis.network.packets.client.PacketReqChunks; +import mcp.mobius.opis.network.packets.client.PacketReqData; +import mcp.mobius.opis.network.packets.server.NetDataCommand; +import mcp.mobius.opis.network.packets.server.NetDataList; +import mcp.mobius.opis.network.packets.server.NetDataValue; +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(); @@ -44,7 +38,6 @@ public class RConHandler { packetTypes.put((byte)2, NetDataCommand.class); packetTypes.put((byte)3, NetDataList.class); packetTypes.put((byte)4, NetDataValue.class); - packetTypes.put((byte)5, PacketChunks.class); } public static void sendToAllNexus(PacketBase packet){ 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 eaccd90..bdda225 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 @@ -1,51 +1,19 @@ package mcp.mobius.opis.network.rcon.nexus; import io.nettyopis.bootstrap.Bootstrap; -import io.nettyopis.bootstrap.ServerBootstrap; -import io.nettyopis.channel.ChannelFuture; -import io.nettyopis.channel.ChannelHandlerContext; -import io.nettyopis.channel.ChannelInitializer; -import io.nettyopis.channel.ChannelOption; -import io.nettyopis.channel.EventLoopGroup; +import io.nettyopis.channel.*; import io.nettyopis.channel.nio.NioEventLoopGroup; import io.nettyopis.channel.socket.SocketChannel; -import io.nettyopis.channel.socket.nio.NioServerSocketChannel; import io.nettyopis.channel.socket.nio.NioSocketChannel; import io.nettyopis.handler.ssl.SslContext; import io.nettyopis.handler.ssl.util.InsecureTrustManagerFactory; -import io.nettyopis.handler.ssl.util.SelfSignedCertificate; -import io.nettyopis.handler.timeout.ReadTimeoutHandler; -import io.nettyopis.handler.timeout.WriteTimeoutHandler; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.ref.WeakReference; -import java.net.ConnectException; -import java.security.cert.CertificateException; -import java.util.Properties; +import mcp.mobius.opis.modOpis; import javax.net.ssl.SSLException; - -import net.minecraftforge.common.util.FakePlayer; - -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; - -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.network.packets.client.PacketReqChunks; -import mcp.mobius.opis.network.packets.client.PacketReqData; -import mcp.mobius.opis.network.packets.server.NetDataCommand; -import mcp.mobius.opis.network.packets.server.NetDataList; -import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.packets.server.PacketChunks; -import mcp.mobius.opis.network.rcon.server.RConHandshakeDecoder; -import mcp.mobius.opis.network.rcon.server.RConHandshakeHandler; -import mcp.mobius.opis.network.rcon.server.RConServer; +import java.io.*; +import java.lang.ref.WeakReference; +import java.net.ConnectException; +import java.util.Properties; public class NexusClient implements Runnable { 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 a33cf22..d6bf0fb 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 @@ -1,53 +1,20 @@ package mcp.mobius.opis.network.rcon.server; -import static cpw.mods.fml.relauncher.Side.SERVER; - -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Timer; - -import javax.net.ssl.SSLException; - -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; - -import cpw.mods.fml.common.network.FMLOutboundHandler; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.common.util.FakePlayer; -import mcp.mobius.opis.modOpis; -import mcp.mobius.opis.network.PacketBase; -import mcp.mobius.opis.network.packets.client.PacketReqChunks; -import mcp.mobius.opis.network.packets.client.PacketReqData; -import mcp.mobius.opis.network.packets.server.NetDataCommand; -import mcp.mobius.opis.network.packets.server.NetDataList; -import mcp.mobius.opis.network.packets.server.NetDataValue; -import mcp.mobius.opis.network.packets.server.PacketChunks; -import mcp.mobius.opis.network.rcon.RConHandler; import io.nettyopis.bootstrap.ServerBootstrap; -import io.nettyopis.buffer.ByteBuf; -import io.nettyopis.channel.Channel; import io.nettyopis.channel.ChannelFuture; -import io.nettyopis.channel.ChannelHandlerContext; -import io.nettyopis.channel.ChannelInboundHandlerAdapter; import io.nettyopis.channel.ChannelInitializer; import io.nettyopis.channel.ChannelOption; import io.nettyopis.channel.EventLoopGroup; import io.nettyopis.channel.nio.NioEventLoopGroup; import io.nettyopis.channel.socket.SocketChannel; import io.nettyopis.channel.socket.nio.NioServerSocketChannel; -import io.nettyopis.handler.codec.compression.JdkZlibDecoder; -import io.nettyopis.handler.codec.compression.JdkZlibEncoder; -import io.nettyopis.handler.codec.compression.ZlibCodecFactory; -import io.nettyopis.handler.codec.compression.ZlibDecoder; -import io.nettyopis.handler.codec.compression.ZlibWrapper; import io.nettyopis.handler.ssl.SslContext; import io.nettyopis.handler.ssl.util.SelfSignedCertificate; -import io.nettyopis.handler.timeout.IdleStateHandler; import io.nettyopis.handler.timeout.ReadTimeoutHandler; -import io.nettyopis.util.ReferenceCountUtil; +import mcp.mobius.opis.modOpis; + +import javax.net.ssl.SSLException; +import java.security.cert.CertificateException; public class RConServer implements Runnable { diff --git a/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java b/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java index 684887c..4ea6732 100644 --- a/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java +++ b/src/main/java/mcp/mobius/opis/proxy/ProxyClient.java @@ -1,33 +1,17 @@ package mcp.mobius.opis.proxy; -import java.awt.Font; -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.logging.log4j.Level; - import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.util.ResourceLocation; -import mapwriter.api.MwAPI; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.MessageHandlerRegistrar; import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.client.DataCache; -import mcp.mobius.opis.data.holders.basetypes.SerialLong; -import mcp.mobius.opis.data.holders.newtypes.DataTiming; -import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.data.managers.ChunkManager; import mcp.mobius.opis.data.managers.MetaManager; import mcp.mobius.opis.data.managers.StringCache; import mcp.mobius.opis.gui.font.Fonts; import mcp.mobius.opis.gui.font.TrueTypeFont; -import mcp.mobius.opis.gui.overlay.OverlayLoadedChunks; -import mcp.mobius.opis.gui.overlay.OverlayMeanTime; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; -import mcp.mobius.opis.gui.screens.ScreenBase; +import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SwingUI; @@ -42,17 +26,13 @@ import mcp.mobius.opis.swing.panels.timingclient.PanelEventClient; import mcp.mobius.opis.swing.panels.timingclient.PanelRenderEntities; import mcp.mobius.opis.swing.panels.timingclient.PanelRenderHandlers; import mcp.mobius.opis.swing.panels.timingclient.PanelRenderTileEnts; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingChunks; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingEntities; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingEntitiesPerClass; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingEvents; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingHandlers; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingTileEnts; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingTileEntsPerClass; +import mcp.mobius.opis.swing.panels.timingserver.*; import mcp.mobius.opis.swing.panels.tracking.PanelAmountEntities; import mcp.mobius.opis.swing.panels.tracking.PanelAmountTileEnts; import mcp.mobius.opis.swing.panels.tracking.PanelDimensions; 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{ @@ -60,19 +40,6 @@ public class ProxyClient extends ProxyServer implements IMessageHandler{ @Override public void init(){ - //MwAPI.registerDataProvider("Loaded chunks", OverlayLoadedChunks.instance); - MwAPI.registerDataProvider("Loaded chunks", OverlayLoadedChunks.INSTANCE); - MwAPI.registerDataProvider("Mean time", OverlayMeanTime.INSTANCE); - MwAPI.registerDataProvider("Ent per chunk", OverlayEntityPerChunk.INSTANCE); - - //fontMC12 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 12, false); - //fontMC24 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 24, false); - //fontMC8 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 8, true); - //fontMC12 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 12, true); - //fontMC16 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 16, true); - //fontMC18 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 18, true); - //fontMC24 = Fonts.createFont(new ResourceLocation("opis", "fonts/Minecraftia.ttf"), 24, true); - //fontMC8 = Fonts.loadSystemFont("Monospace", 12, true, Font.TRUETYPE_FONT | Font.BOLD); fontMC8 = Fonts.createFont(new ResourceLocation("opis", "fonts/LiberationMono-Bold.ttf"), 14, true); IMessageHandler panelSummary = (IMessageHandler)TabPanelRegistrar.INSTANCE.registerTab(new PanelSummary(), "Summary"); @@ -186,11 +153,6 @@ public class ProxyClient extends ProxyServer implements IMessageHandler{ 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.OVERLAY_CHUNK_ENTITIES, OverlayEntityPerChunk.INSTANCE); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_ENTITIES, OverlayEntityPerChunk.INSTANCE); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_TICKETS, OverlayLoadedChunks.INSTANCE); - MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_TILEENTS, OverlayMeanTime.INSTANCE); MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_TIMING_CHUNK, ChunkManager.INSTANCE); MessageHandlerRegistrar.INSTANCE.registerHandler(Message.LIST_CHUNK_LOADED, ChunkManager.INSTANCE); diff --git a/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java b/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java index ddfe155..2a6139d 100644 --- a/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java +++ b/src/main/java/mcp/mobius/opis/proxy/ProxyServer.java @@ -1,15 +1,8 @@ package mcp.mobius.opis.proxy; -import java.util.ArrayList; -import java.util.HashMap; - -import mcp.mobius.opis.modOpis; import mcp.mobius.opis.api.IMessageHandler; -import mcp.mobius.opis.gui.overlay.OverlayStatus; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; -import mcp.mobius.opis.network.rcon.nexus.NexusClient; -import mcp.mobius.opis.network.rcon.server.RConServer; public class ProxyServer implements IMessageHandler{ 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 c339e80..d6e9162 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.gui.MwGui; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; @@ -13,10 +10,8 @@ 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.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.TargetEntity; import mcp.mobius.opis.data.holders.newtypes.DataEntity; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; import net.minecraft.client.Minecraft; public class ActionPlayers implements ActionListener { @@ -29,15 +24,6 @@ public class ActionPlayers implements ActionListener { if (table == null || table.getSelectedRow() == -1) return; int indexData = table.convertRowIndexToModel(table.getSelectedRow()); DataEntity data = (DataEntity)table.getTableData().get(indexData); - - if (e.getSource() == panel.getBtnCenter()){ - CoordinatesBlock coord = data.pos; - PacketManager.sendToServer(new PacketReqData(Message.OVERLAY_CHUNK_ENTITIES)); - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_ENTITIES, data.pos.asCoordinatesChunk())); - OverlayEntityPerChunk.INSTANCE.selectedChunk = coord.asCoordinatesChunk(); - MwAPI.setCurrentDataProvider(OverlayEntityPerChunk.INSTANCE); - Minecraft.getMinecraft().displayGuiScreen(new MwGui(Mw.instance, coord.dim, coord.x, coord.z)); - } if (e.getSource() == panel.getBtnTeleport()){ int eid = data.eid; 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 0c88a59..39a6c27 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.gui.MwGui; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; @@ -14,8 +11,6 @@ import mcp.mobius.opis.swing.widgets.JTableStats; import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.stats.StatsChunk; -import mcp.mobius.opis.gui.overlay.OverlayMeanTime; -import net.minecraft.client.Minecraft; public class ActionTimingChunks implements ActionListener { @@ -27,12 +22,6 @@ public class ActionTimingChunks implements ActionListener { if (table == null || table.getSelectedRow() == -1) return; int indexData = table.convertRowIndexToModel(table.getSelectedRow()); StatsChunk data = (StatsChunk)table.getTableData().get(indexData); - - if (e.getSource() == panel.getBtnCenter()){ - OverlayMeanTime.INSTANCE.setSelectedChunk(data.getChunk().dim, data.getChunk().chunkX, data.getChunk().chunkZ); - MwAPI.setCurrentDataProvider(OverlayMeanTime.INSTANCE); - Minecraft.getMinecraft().displayGuiScreen(new MwGui(Mw.instance, data.getChunk().dim, data.getChunk().x + 8, data.getChunk().z + 8)); - } 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 8f53b85..34e7755 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.gui.MwGui; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; @@ -13,10 +10,8 @@ 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.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.TargetEntity; import mcp.mobius.opis.data.holders.newtypes.DataEntity; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; import net.minecraft.client.Minecraft; public class ActionTimingEntities implements ActionListener { @@ -30,15 +25,6 @@ public class ActionTimingEntities implements ActionListener { int indexData = table.convertRowIndexToModel(table.getSelectedRow()); DataEntity data = (DataEntity)table.getTableData().get(indexData); - if (e.getSource() == panel.getBtnCenter()){ - CoordinatesBlock coord = data.pos; - PacketManager.sendToServer(new PacketReqData(Message.OVERLAY_CHUNK_ENTITIES)); - PacketManager.sendToServer(new PacketReqData(Message.LIST_CHUNK_ENTITIES, data.pos.asCoordinatesChunk())); - MwAPI.setCurrentDataProvider(OverlayEntityPerChunk.INSTANCE); - OverlayEntityPerChunk.INSTANCE.selectedChunk = coord.asCoordinatesChunk(); - Minecraft.getMinecraft().displayGuiScreen(new MwGui(Mw.instance, coord.dim, coord.x, coord.z)); - } - if (e.getSource() == panel.getBtnTeleport()){ int eid = data.eid; int dim = data.pos.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 ba6b363..735d6e1 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import mapwriter.Mw; -import mapwriter.api.MwAPI; -import mapwriter.gui.MwGui; import mcp.mobius.opis.modOpis; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; @@ -16,7 +13,6 @@ 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 mcp.mobius.opis.gui.overlay.OverlayMeanTime; import net.minecraft.client.Minecraft; public class ActionTimingTileEnts implements ActionListener { @@ -30,13 +26,6 @@ public class ActionTimingTileEnts implements ActionListener { int indexData = table.convertRowIndexToModel(table.getSelectedRow()); DataBlockTileEntity data = (DataBlockTileEntity)table.getTableData().get(indexData); - if (e.getSource() == panel.getBtnCenter()){ - CoordinatesBlock coord = data.pos; - OverlayMeanTime.INSTANCE.setSelectedChunk(coord.dim, coord.x >> 4, coord.z >> 4); - MwAPI.setCurrentDataProvider(OverlayMeanTime.INSTANCE); - Minecraft.getMinecraft().displayGuiScreen(new MwGui(Mw.instance, coord.dim, coord.x, coord.z)); - } - if (e.getSource() == panel.getBtnTeleport()){ CoordinatesBlock coord = data.pos; modOpis.selectedBlock = coord; 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 2ec930c..2b4e129 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 @@ -21,20 +21,15 @@ import javax.swing.table.DefaultTableModel; public class PanelTimingChunks extends JPanelMsgHandler implements ITabPanel{ private JButtonAccess btnRun; private JButtonAccess btnTeleport; - private JButtonAccess btnCenter; /** * Create the panel. */ public PanelTimingChunks() { - setLayout(new MigLayout("", "[][][grow][]", "[][grow]")); - - btnCenter = new JButtonAccess("Center Map", AccessLevel.NONE); - add(btnCenter, "cell 0 0"); - btnCenter.addActionListener(new ActionTimingChunks()); + setLayout(new MigLayout("", "[][grow][]", "[][grow]")); btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 1 0"); + add(btnTeleport, "cell 0 0"); btnTeleport.addActionListener(new ActionTimingChunks()); btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); @@ -53,7 +48,6 @@ public class PanelTimingChunks extends JPanelMsgHandler implements ITabPanel{ public JButton getBtnRun() {return btnRun;} public JButton getBtnTeleport() {return btnTeleport;} - public JButton getBtnCenter() {return btnCenter;} @Override public boolean handleMessage(Message msg, PacketBase rawdata) { 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 35eeece..5b5c82c 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 @@ -23,25 +23,20 @@ public class PanelTimingEntities extends JPanelMsgHandler implements ITabPanel{ private JButtonAccess btnRun; private JButtonAccess btnPull; private JButtonAccess btnTeleport; - private JButtonAccess btnCenter; private JLabel lblSummary; /** * Create the panel. */ public PanelTimingEntities() { - setLayout(new MigLayout("", "[][][][grow][]", "[][grow][]")); - - btnCenter = new JButtonAccess("Center Map", AccessLevel.NONE); - add(btnCenter, "cell 0 0"); - btnCenter.addActionListener(new ActionTimingEntities()); + setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 1 0"); + add(btnTeleport, "cell 0 0"); btnTeleport.addActionListener(new ActionTimingEntities()); btnPull = new JButtonAccess("Pull", AccessLevel.PRIVILEGED); - add(btnPull, "cell 2 0"); + add(btnPull, "cell 1 0"); btnPull.addActionListener(new ActionTimingEntities()); btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); @@ -64,7 +59,6 @@ public class PanelTimingEntities extends JPanelMsgHandler implements ITabPanel{ public JButton getBtnRun() {return btnRun;} public JButton getBtnPull() {return btnPull;} public JButton getBtnTeleport() {return btnTeleport;} - public JButton getBtnCenter() {return btnCenter;} public JLabel getLblSummary() {return lblSummary;} @Override 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 8d10ff6..f97a888 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 @@ -23,7 +23,6 @@ import javax.swing.JLabel; import javax.swing.table.DefaultTableModel; public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnCenter; private JButtonAccess btnTeleport; private JButtonAccess btnReset; private JButtonAccess btnRun; @@ -33,19 +32,15 @@ public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel{ * Create the panel. */ public PanelTimingTileEnts() { - setLayout(new MigLayout("", "[][][][grow][]", "[][grow][]")); - - btnCenter = new JButtonAccess("Center Map", AccessLevel.NONE); - add(btnCenter, "cell 0 0"); - btnCenter.addActionListener(new ActionTimingTileEnts()); + setLayout(new MigLayout("", "[][][grow][]", "[][grow][]")); btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 1 0"); + add(btnTeleport, "cell 0 0"); btnTeleport.addActionListener(new ActionTimingTileEnts()); btnReset = new JButtonAccess("Reset Highlight", AccessLevel.PRIVILEGED); btnReset.setEnabled(false); - add(btnReset, "cell 2 0"); + add(btnReset, "cell 1 0"); btnReset.addActionListener(new ActionTimingTileEnts()); btnRun = new JButtonAccess("Run Opis", AccessLevel.PRIVILEGED); @@ -65,7 +60,6 @@ public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel{ add(lblSummary, "cell 0 2 5 1,alignx center"); } - public JButton getBtnCenter() {return btnCenter;} public JButton getBtnTeleport(){return btnTeleport;} public JButton getBtnReset() {return btnReset;} public JButton getBtnRun() {return btnRun;} 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 79bfb1b..952d686 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 @@ -18,7 +18,6 @@ import javax.swing.JScrollPane; import javax.swing.table.DefaultTableModel; public class PanelPlayers extends JPanelMsgHandler implements ITabPanel{ - private JButtonAccess btnCenter; private JButtonAccess btnTeleport; private JButtonAccess btnPull; @@ -26,27 +25,23 @@ public class PanelPlayers extends JPanelMsgHandler implements ITabPanel{ * Create the panel. */ public PanelPlayers() { - setLayout(new MigLayout("", "[][][][][][grow]", "[][grow]")); - - btnCenter = new JButtonAccess("Center Map", AccessLevel.NONE); - add(btnCenter, "cell 0 0"); - btnCenter.addActionListener(new ActionPlayers()); + setLayout(new MigLayout("", "[][][][][grow]", "[][grow]")); btnTeleport = new JButtonAccess("Teleport", AccessLevel.PRIVILEGED); - add(btnTeleport, "cell 1 0"); + add(btnTeleport, "cell 0 0"); btnTeleport.addActionListener(new ActionPlayers()); btnPull = new JButtonAccess("Pull", AccessLevel.PRIVILEGED); - add(btnPull, "cell 2 0"); + add(btnPull, "cell 1 0"); btnPull.addActionListener(new ActionPlayers()); JButton btnKill = new JButton("Kill"); btnKill.setEnabled(false); - add(btnKill, "cell 3 0"); + add(btnKill, "cell 2 0"); JButton btnMorph = new JButton("Morph"); btnMorph.setEnabled(false); - add(btnMorph, "cell 4 0"); + add(btnMorph, "cell 3 0"); JScrollPane scrollPane = new JScrollPane(); add(scrollPane, "cell 0 1 6 1,grow"); @@ -58,7 +53,6 @@ public class PanelPlayers extends JPanelMsgHandler implements ITabPanel{ scrollPane.setViewportView(table); } - public JButton getBtnCenter() {return btnCenter;} public JButton getBtnTeleport() {return btnTeleport;} public JButton getBtnPull() {return btnPull;}