Applied Eclipse formatting.

This commit is contained in:
FrozenCow 2011-02-05 02:25:18 +01:00
parent e7aff6ee79
commit a89ef6ac75
25 changed files with 1763 additions and 1708 deletions

View file

@ -2,115 +2,110 @@ package org.dynmap;
import java.util.HashMap; import java.util.HashMap;
public class Cache<K, V> public class Cache<K, V> {
{ private final int size;
private final int size; private int len;
private int len;
private CacheNode head; private CacheNode head;
private CacheNode tail; private CacheNode tail;
private class CacheNode private class CacheNode {
{ public CacheNode prev;
public CacheNode prev; public CacheNode next;
public CacheNode next; public K key;
public K key; public V value;
public V value;
public CacheNode(K key, V value) public CacheNode(K key, V value) {
{ this.key = key;
this.key = key; this.value = value;
this.value = value; prev = null;
prev = null; next = null;
next = null; }
}
public void unlink() public void unlink() {
{ if (prev == null) {
if(prev == null) { head = next;
head = next; } else {
} else { prev.next = next;
prev.next = next; }
}
if(next == null) { if (next == null) {
tail = prev; tail = prev;
} else { } else {
next.prev = prev; next.prev = prev;
} }
prev = null; prev = null;
next = null; next = null;
len --; len--;
} }
public void append() public void append() {
{ if (tail == null) {
if(tail == null) { head = this;
head = this; tail = this;
tail = this; } else {
} else { tail.next = this;
tail.next = this; prev = tail;
prev = tail; tail = this;
tail = this; }
}
len ++; len++;
} }
} }
private HashMap<K, CacheNode> map; private HashMap<K, CacheNode> map;
public Cache(int size) public Cache(int size) {
{ this.size = size;
this.size = size; len = 0;
len = 0;
head = null; head = null;
tail = null; tail = null;
map = new HashMap<K, CacheNode>(); map = new HashMap<K, CacheNode>();
} }
/* returns value for key, if key exists in the cache /*
* otherwise null */ * returns value for key, if key exists in the cache otherwise null
public V get(K key) */
{ public V get(K key) {
CacheNode n = map.get(key); CacheNode n = map.get(key);
if(n == null) if (n == null)
return null; return null;
return n.value; return n.value;
} }
/* puts a new key-value pair in the cache /*
* if the key existed already, the value is updated, and the old value is returned * puts a new key-value pair in the cache if the key existed already, the
* if the key didn't exist, it is added; the oldest value (now pushed out of the * value is updated, and the old value is returned if the key didn't exist,
* cache) may be returned, or null if the cache isn't yet full */ * it is added; the oldest value (now pushed out of the cache) may be
public V put(K key, V value) * returned, or null if the cache isn't yet full
{ */
CacheNode n = map.get(key); public V put(K key, V value) {
if(n == null) { CacheNode n = map.get(key);
V ret = null; if (n == null) {
V ret = null;
if(len >= size) { if (len >= size) {
CacheNode first = head; CacheNode first = head;
first.unlink(); first.unlink();
map.remove(first.key); map.remove(first.key);
ret = first.value; ret = first.value;
} }
CacheNode add = new CacheNode(key, value); CacheNode add = new CacheNode(key, value);
add.append(); add.append();
map.put(key, add); map.put(key, add);
return ret; return ret;
} else { } else {
n.unlink(); n.unlink();
V old = n.value; V old = n.value;
n.value = value; n.value = value;
n.append(); n.append();
return old; return old;
} }
} }
} }

View file

@ -6,65 +6,58 @@ import java.util.LinkedList;
import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerChatEvent;
public class ChatQueue { public class ChatQueue {
public class ChatMessage
{
public long time;
public String playerName;
public String message;
public ChatMessage(PlayerChatEvent event)
{
time = System.currentTimeMillis();
playerName = event.getPlayer().getName();
message = event.getMessage();
}
}
/* a list of recent chat message */
private LinkedList<ChatMessage> messageQueue;
/* remember up to this old chat messages (ms) */
private static final int maxChatAge = 120000;
public ChatQueue() {
messageQueue = new LinkedList<ChatMessage>();
}
/* put a chat message in the queue */
public void pushChatMessage(PlayerChatEvent event)
{
synchronized(MapManager.lock) {
messageQueue.add(new ChatMessage(event));
}
}
public ChatMessage[] getChatMessages(long cutoff) {
ArrayList<ChatMessage> queue = new ArrayList<ChatMessage>(); public class ChatMessage {
ArrayList<ChatMessage> updateList = new ArrayList<ChatMessage>(); public long time;
queue.addAll(messageQueue); public String playerName;
public String message;
long now = System.currentTimeMillis();
long deadline = now - maxChatAge; public ChatMessage(PlayerChatEvent event) {
time = System.currentTimeMillis();
synchronized(MapManager.lock) { playerName = event.getPlayer().getName();
message = event.getMessage();
for (ChatMessage message : queue) }
{ }
if (message.time < deadline)
{ /* a list of recent chat message */
messageQueue.remove(message); private LinkedList<ChatMessage> messageQueue;
}
else if (message.time >= cutoff) /* remember up to this old chat messages (ms) */
{ private static final int maxChatAge = 120000;
updateList.add(message);
} public ChatQueue() {
} messageQueue = new LinkedList<ChatMessage>();
} }
ChatMessage[] messages = new ChatMessage[updateList.size()];
updateList.toArray(messages); /* put a chat message in the queue */
return messages; public void pushChatMessage(PlayerChatEvent event) {
} synchronized (MapManager.lock) {
messageQueue.add(new ChatMessage(event));
}
}
public ChatMessage[] getChatMessages(long cutoff) {
ArrayList<ChatMessage> queue = new ArrayList<ChatMessage>();
ArrayList<ChatMessage> updateList = new ArrayList<ChatMessage>();
queue.addAll(messageQueue);
long now = System.currentTimeMillis();
long deadline = now - maxChatAge;
synchronized (MapManager.lock) {
for (ChatMessage message : queue) {
if (message.time < deadline) {
messageQueue.remove(message);
} else if (message.time >= cutoff) {
updateList.add(message);
}
}
}
ChatMessage[] messages = new ChatMessage[updateList.size()];
updateList.toArray(messages);
return messages;
}
} }

View file

@ -7,22 +7,22 @@ import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
public class DynmapBlockListener extends BlockListener { public class DynmapBlockListener extends BlockListener {
private MapManager mgr; private MapManager mgr;
public DynmapBlockListener(MapManager mgr) {
this.mgr = mgr;
}
@Override public DynmapBlockListener(MapManager mgr) {
public void onBlockPlace(BlockPlaceEvent event) { this.mgr = mgr;
Block blockPlaced = event.getBlockPlaced(); }
mgr.touch(blockPlaced.getX(), blockPlaced.getY(), blockPlaced.getZ());
}
public void onBlockDamage(BlockDamageEvent event) { @Override
if (event.getDamageLevel() == BlockDamageLevel.BROKEN) { public void onBlockPlace(BlockPlaceEvent event) {
Block blockBroken = event.getBlock(); Block blockPlaced = event.getBlockPlaced();
mgr.touch(blockBroken.getX(), blockBroken.getY(), blockBroken.getZ()); mgr.touch(blockPlaced.getX(), blockPlaced.getY(), blockPlaced.getZ());
} }
}
public void onBlockDamage(BlockDamageEvent event) {
if (event.getDamageLevel() == BlockDamageLevel.BROKEN) {
Block blockBroken = event.getBlock();
mgr.touch(blockBroken.getX(), blockBroken.getY(), blockBroken.getZ());
}
}
} }

View file

@ -1,9 +1,10 @@
package org.dynmap; package org.dynmap;
public class DynmapChunk { public class DynmapChunk {
public int x,y; public int x, y;
public DynmapChunk(int x, int y) {
this.x = x; public DynmapChunk(int x, int y) {
this.y = y; this.x = x;
} this.y = y;
}
} }

View file

@ -5,53 +5,59 @@ import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerListener;
public class DynmapPlayerListener extends PlayerListener { public class DynmapPlayerListener extends PlayerListener {
private MapManager mgr; private MapManager mgr;
private PlayerList playerList; private PlayerList playerList;
public DynmapPlayerListener(MapManager mgr, PlayerList playerList) { public DynmapPlayerListener(MapManager mgr, PlayerList playerList) {
this.mgr = mgr; this.mgr = mgr;
this.playerList = playerList; this.playerList = playerList;
} }
@Override @Override
public void onPlayerCommand(PlayerChatEvent event) { public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" "); String[] split = event.getMessage().split(" ");
if (split[0].equalsIgnoreCase("/dynmap")) { if (split[0].equalsIgnoreCase("/dynmap")) {
if (split.length > 1) { if (split.length > 1) {
if (split[1].equals("render")) { if (split[1].equals("render")) {
Player player = event.getPlayer(); Player player = event.getPlayer();
mgr.touch(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); mgr.touch(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
event.setCancelled(true); event.setCancelled(true);
} else if (split[1].equals("hide")) { } else if (split[1].equals("hide")) {
if (split.length == 2) { if (split.length == 2) {
playerList.hide(event.getPlayer().getName()); playerList.hide(event.getPlayer().getName());
} else for (int i=2;i<split.length;i++) } else {
playerList.hide(split[i]); for (int i = 2; i < split.length; i++) {
event.setCancelled(true); playerList.hide(split[i]);
} else if (split[1].equals("show")) { }
if (split.length == 2) { }
playerList.show(event.getPlayer().getName()); event.setCancelled(true);
} else for (int i=2;i<split.length;i++) } else if (split[1].equals("show")) {
playerList.show(split[i]); if (split.length == 2) {
event.setCancelled(true); playerList.show(event.getPlayer().getName());
} else if (split[1].equals("fullrender")) { } else {
Player player = event.getPlayer(); for (int i = 2; i < split.length; i++) {
mgr.renderFullWorld(player.getLocation()); playerList.show(split[i]);
} else if (split[1].equals("fullrenderasync")) { }
Player player = event.getPlayer(); }
mgr.renderFullWorldAsync(player.getLocation()); event.setCancelled(true);
} } else if (split[1].equals("fullrender")) {
} Player player = event.getPlayer();
mgr.renderFullWorld(player.getLocation());
} else if (split[1].equals("fullrenderasync")) {
Player player = event.getPlayer();
mgr.renderFullWorldAsync(player.getLocation());
}
}
} }
} }
/** /**
* Called when a player sends a chat message * Called when a player sends a chat message
* *
* @param event Relevant event details * @param event
* Relevant event details
*/ */
public void onPlayerChat(PlayerChatEvent event) public void onPlayerChat(PlayerChatEvent event) {
{ mgr.addChatEvent(event);
mgr.addChatEvent(event);
} }
} }

View file

@ -16,69 +16,69 @@ import org.dynmap.web.WebServer;
public class DynmapPlugin extends JavaPlugin { public class DynmapPlugin extends JavaPlugin {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
private WebServer webServer = null; private WebServer webServer = null;
private MapManager mapManager = null; private MapManager mapManager = null;
private PlayerList playerList; private PlayerList playerList;
private BukkitPlayerDebugger debugger = new BukkitPlayerDebugger(this);
public static File dataRoot;
public DynmapPlugin(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
super(pluginLoader, instance, desc, folder, plugin, cLoader);
dataRoot = folder;
}
public World getWorld() { private BukkitPlayerDebugger debugger = new BukkitPlayerDebugger(this);
return getServer().getWorlds()[0];
}
public MapManager getMapManager() {
return mapManager;
}
public WebServer getWebServer() {
return webServer;
}
public void onEnable() { public static File dataRoot;
Configuration configuration = new Configuration(new File(this.getDataFolder(), "configuration.txt"));
configuration.load();
debugger.enable();
playerList = new PlayerList(getServer());
playerList.load();
mapManager = new MapManager(getWorld(), debugger, configuration);
mapManager.startManager();
try { public DynmapPlugin(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
webServer = new WebServer(mapManager, getWorld(), playerList, debugger, configuration); super(pluginLoader, instance, desc, folder, plugin, cLoader);
} catch(IOException e) { dataRoot = folder;
log.info("position failed to start WebServer (IOException)"); }
}
registerEvents();
}
public void onDisable() { public World getWorld() {
mapManager.stopManager(); return getServer().getWorlds()[0];
}
if(webServer != null) { public MapManager getMapManager() {
webServer.shutdown(); return mapManager;
webServer = null; }
}
debugger.disable();
}
public void registerEvents() { public WebServer getWebServer() {
BlockListener blockListener = new DynmapBlockListener(mapManager); return webServer;
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this); }
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal, this);
public void onEnable() {
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new DynmapPlayerListener(mapManager, playerList), Priority.Normal, this); Configuration configuration = new Configuration(new File(this.getDataFolder(), "configuration.txt"));
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_CHAT, new DynmapPlayerListener(mapManager, playerList), Priority.Normal, this); configuration.load();
}
debugger.enable();
playerList = new PlayerList(getServer());
playerList.load();
mapManager = new MapManager(getWorld(), debugger, configuration);
mapManager.startManager();
try {
webServer = new WebServer(mapManager, getWorld(), playerList, debugger, configuration);
} catch (IOException e) {
log.info("position failed to start WebServer (IOException)");
}
registerEvents();
}
public void onDisable() {
mapManager.stopManager();
if (webServer != null) {
webServer.shutdown();
webServer = null;
}
debugger.disable();
}
public void registerEvents() {
BlockListener blockListener = new DynmapBlockListener(mapManager);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new DynmapPlayerListener(mapManager, playerList), Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_CHAT, new DynmapPlayerListener(mapManager, playerList), Priority.Normal, this);
}
} }

View file

@ -1,6 +1,6 @@
package org.dynmap; package org.dynmap;
public class MapLocation { public class MapLocation {
public float x; public float x;
public float y; public float y;
} }

View file

@ -15,274 +15,274 @@ import org.bukkit.util.config.ConfigurationNode;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public class MapManager extends Thread { public class MapManager extends Thread {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
private World world; private World world;
private Debugger debugger; private Debugger debugger;
private MapType[] maps; private MapType[] maps;
public StaleQueue staleQueue; public StaleQueue staleQueue;
public ChatQueue chatQueue; public ChatQueue chatQueue;
public PlayerList playerList; public PlayerList playerList;
/* lock for our data structures */ /* lock for our data structures */
public static final Object lock = new Object(); public static final Object lock = new Object();
/* whether the worker thread should be running now */ /* whether the worker thread should be running now */
private boolean running = false; private boolean running = false;
/* path to image tile directory */ /* path to image tile directory */
public File tileDirectory; public File tileDirectory;
/* web files location */ /* web files location */
public File webDirectory; public File webDirectory;
/* bind web server to ip-address */ /* bind web server to ip-address */
public String bindaddress = "0.0.0.0"; public String bindaddress = "0.0.0.0";
/* port to run web server on */ /* port to run web server on */
public int serverport = 8123; public int serverport = 8123;
/* time to pause between rendering tiles (ms) */ /* time to pause between rendering tiles (ms) */
public int renderWait = 500; public int renderWait = 500;
public boolean loadChunks = true; public boolean loadChunks = true;
public void debug(String msg) { public void debug(String msg) {
debugger.debug(msg); debugger.debug(msg);
} }
private static File combinePaths(File parent, String path) { private static File combinePaths(File parent, String path) {
return combinePaths(parent, new File(path)); return combinePaths(parent, new File(path));
} }
private static File combinePaths(File parent, File path) { private static File combinePaths(File parent, File path) {
if(path.isAbsolute()) if (path.isAbsolute())
return path; return path;
return new File(parent, path.getPath()); return new File(parent, path.getPath());
} }
public MapManager(World world, Debugger debugger, ConfigurationNode configuration) { public MapManager(World world, Debugger debugger, ConfigurationNode configuration) {
this.world = world; this.world = world;
this.debugger = debugger; this.debugger = debugger;
this.staleQueue = new StaleQueue(); this.staleQueue = new StaleQueue();
this.chatQueue = new ChatQueue(); this.chatQueue = new ChatQueue();
tileDirectory = combinePaths(DynmapPlugin.dataRoot, configuration.getString("tilespath", "web/tiles")); tileDirectory = combinePaths(DynmapPlugin.dataRoot, configuration.getString("tilespath", "web/tiles"));
webDirectory = combinePaths(DynmapPlugin.dataRoot, configuration.getString("webpath", "web")); webDirectory = combinePaths(DynmapPlugin.dataRoot, configuration.getString("webpath", "web"));
renderWait = (int) (configuration.getDouble("renderinterval", 0.5) * 1000); renderWait = (int) (configuration.getDouble("renderinterval", 0.5) * 1000);
loadChunks = configuration.getBoolean("loadchunks", true); loadChunks = configuration.getBoolean("loadchunks", true);
if(!tileDirectory.isDirectory()) if (!tileDirectory.isDirectory())
tileDirectory.mkdirs(); tileDirectory.mkdirs();
maps = loadMapTypes(configuration); maps = loadMapTypes(configuration);
} }
void renderFullWorldAsync(Location l) { void renderFullWorldAsync(Location l) {
fullmapTiles.clear(); fullmapTiles.clear();
fullmapTilesRendered.clear(); fullmapTilesRendered.clear();
debugger.debug("Full render starting..."); debugger.debug("Full render starting...");
for(MapType map : maps) { for (MapType map : maps) {
for(MapTile tile : map.getTiles(l)) { for (MapTile tile : map.getTiles(l)) {
fullmapTiles.add(tile); fullmapTiles.add(tile);
invalidateTile(tile); invalidateTile(tile);
} }
} }
debugger.debug("Full render finished."); debugger.debug("Full render finished.");
} }
void renderFullWorld(Location l) { void renderFullWorld(Location l) {
debugger.debug("Full render starting..."); debugger.debug("Full render starting...");
for(MapType map : maps) { for (MapType map : maps) {
HashSet<MapTile> found = new HashSet<MapTile>(); HashSet<MapTile> found = new HashSet<MapTile>();
LinkedList<MapTile> renderQueue = new LinkedList<MapTile>(); LinkedList<MapTile> renderQueue = new LinkedList<MapTile>();
for(MapTile tile : map.getTiles(l)) { for (MapTile tile : map.getTiles(l)) {
if(!(found.contains(tile) || map.isRendered(tile))) { if (!(found.contains(tile) || map.isRendered(tile))) {
found.add(tile); found.add(tile);
renderQueue.add(tile); renderQueue.add(tile);
} }
} }
while(!renderQueue.isEmpty()) { while (!renderQueue.isEmpty()) {
MapTile tile = renderQueue.pollFirst(); MapTile tile = renderQueue.pollFirst();
loadRequiredChunks(tile); loadRequiredChunks(tile);
debugger.debug("renderQueue: " + renderQueue.size() + "/" + found.size()); debugger.debug("renderQueue: " + renderQueue.size() + "/" + found.size());
if(map.render(tile)) { if (map.render(tile)) {
found.remove(tile); found.remove(tile);
staleQueue.onTileUpdated(tile); staleQueue.onTileUpdated(tile);
for(MapTile adjTile : map.getAdjecentTiles(tile)) { for (MapTile adjTile : map.getAdjecentTiles(tile)) {
if(!(found.contains(adjTile) || map.isRendered(adjTile))) { if (!(found.contains(adjTile) || map.isRendered(adjTile))) {
found.add(adjTile); found.add(adjTile);
renderQueue.add(adjTile); renderQueue.add(adjTile);
} }
} }
} }
found.remove(tile); found.remove(tile);
System.gc(); System.gc();
} }
} }
debugger.debug("Full render finished."); debugger.debug("Full render finished.");
} }
public HashSet<MapTile> fullmapTiles = new HashSet<MapTile>(); public HashSet<MapTile> fullmapTiles = new HashSet<MapTile>();
public boolean fullmapRenderStarting = false; public boolean fullmapRenderStarting = false;
public HashSet<MapTile> fullmapTilesRendered = new HashSet<MapTile>(); public HashSet<MapTile> fullmapTilesRendered = new HashSet<MapTile>();
void handleFullMapRender(MapTile tile) { void handleFullMapRender(MapTile tile) {
if(!fullmapTiles.contains(tile)) { if (!fullmapTiles.contains(tile)) {
debugger.debug("Non fullmap-render tile: " + tile); debugger.debug("Non fullmap-render tile: " + tile);
return; return;
} }
fullmapTilesRendered.add(tile); fullmapTilesRendered.add(tile);
MapType map = tile.getMap(); MapType map = tile.getMap();
MapTile[] adjecenttiles = map.getAdjecentTiles(tile); MapTile[] adjecenttiles = map.getAdjecentTiles(tile);
for(int i = 0; i < adjecenttiles.length; i++) { for (int i = 0; i < adjecenttiles.length; i++) {
MapTile adjecentTile = adjecenttiles[i]; MapTile adjecentTile = adjecenttiles[i];
if(!fullmapTiles.contains(adjecentTile)) { if (!fullmapTiles.contains(adjecentTile)) {
fullmapTiles.add(adjecentTile); fullmapTiles.add(adjecentTile);
staleQueue.pushStaleTile(adjecentTile); staleQueue.pushStaleTile(adjecentTile);
} }
} }
debugger.debug("Queue size: " + staleQueue.size() + "+" + fullmapTilesRendered.size() + "/" + fullmapTiles.size()); debugger.debug("Queue size: " + staleQueue.size() + "+" + fullmapTilesRendered.size() + "/" + fullmapTiles.size());
} }
private boolean hasEnoughMemory() { private boolean hasEnoughMemory() {
return Runtime.getRuntime().freeMemory() >= 100 * 1024 * 1024; return Runtime.getRuntime().freeMemory() >= 100 * 1024 * 1024;
} }
private void waitForMemory() { private void waitForMemory() {
if(!hasEnoughMemory()) { if (!hasEnoughMemory()) {
debugger.debug("Waiting for memory..."); debugger.debug("Waiting for memory...");
// Wait until there is at least 50mb of free memory. // Wait until there is at least 50mb of free memory.
do { do {
System.gc(); System.gc();
try { try {
Thread.sleep(500); Thread.sleep(500);
} catch(InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} while(!hasEnoughMemory()); } while (!hasEnoughMemory());
debugger.debug(Runtime.getRuntime().freeMemory() / (1024 * 1024) + "MB of memory free, will continue..."); debugger.debug(Runtime.getRuntime().freeMemory() / (1024 * 1024) + "MB of memory free, will continue...");
} }
} }
private void loadRequiredChunks(MapTile tile) { private void loadRequiredChunks(MapTile tile) {
if(!loadChunks) if (!loadChunks)
return; return;
waitForMemory(); waitForMemory();
// Actually load the chunks. // Actually load the chunks.
for(DynmapChunk chunk : tile.getMap().getRequiredChunks(tile)) { for (DynmapChunk chunk : tile.getMap().getRequiredChunks(tile)) {
if(!world.isChunkLoaded(chunk.x, chunk.y)) if (!world.isChunkLoaded(chunk.x, chunk.y))
world.loadChunk(chunk.x, chunk.y); world.loadChunk(chunk.x, chunk.y);
} }
} }
private MapType[] loadMapTypes(ConfigurationNode configuration) { private MapType[] loadMapTypes(ConfigurationNode configuration) {
List<?> configuredMaps = (List<?>) configuration.getProperty("maps"); List<?> configuredMaps = (List<?>) configuration.getProperty("maps");
ArrayList<MapType> mapTypes = new ArrayList<MapType>(); ArrayList<MapType> mapTypes = new ArrayList<MapType>();
for(Object configuredMapObj : configuredMaps) { for (Object configuredMapObj : configuredMaps) {
try { try {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> configuredMap = (Map<String, Object>) configuredMapObj; Map<String, Object> configuredMap = (Map<String, Object>) configuredMapObj;
String typeName = (String) configuredMap.get("class"); String typeName = (String) configuredMap.get("class");
log.info("Loading map '" + typeName.toString() + "'..."); log.info("Loading map '" + typeName.toString() + "'...");
Class<?> mapTypeClass = Class.forName(typeName); Class<?> mapTypeClass = Class.forName(typeName);
Constructor<?> constructor = mapTypeClass.getConstructor(MapManager.class, World.class, Debugger.class, Map.class); Constructor<?> constructor = mapTypeClass.getConstructor(MapManager.class, World.class, Debugger.class, Map.class);
MapType mapType = (MapType) constructor.newInstance(this, world, debugger, configuredMap); MapType mapType = (MapType) constructor.newInstance(this, world, debugger, configuredMap);
mapTypes.add(mapType); mapTypes.add(mapType);
} catch(Exception e) { } catch (Exception e) {
debugger.error("Error loading map", e); debugger.error("Error loading map", e);
} }
} }
MapType[] result = new MapType[mapTypes.size()]; MapType[] result = new MapType[mapTypes.size()];
mapTypes.toArray(result); mapTypes.toArray(result);
return result; return result;
} }
/* initialize and start map manager */ /* initialize and start map manager */
public void startManager() { public void startManager() {
synchronized(lock) { synchronized (lock) {
running = true; running = true;
this.start(); this.start();
try { try {
this.setPriority(MIN_PRIORITY); this.setPriority(MIN_PRIORITY);
log.info("Set minimum priority for worker thread"); log.info("Set minimum priority for worker thread");
} catch(SecurityException e) { } catch (SecurityException e) {
log.info("Failed to set minimum priority for worker thread!"); log.info("Failed to set minimum priority for worker thread!");
} }
} }
} }
/* stop map manager */ /* stop map manager */
public void stopManager() { public void stopManager() {
synchronized(lock) { synchronized (lock) {
if(!running) if (!running)
return; return;
log.info("Stopping map renderer..."); log.info("Stopping map renderer...");
running = false; running = false;
try { try {
this.join(); this.join();
} catch(InterruptedException e) { } catch (InterruptedException e) {
log.info("Waiting for map renderer to stop is interrupted"); log.info("Waiting for map renderer to stop is interrupted");
} }
} }
} }
/* the worker/renderer thread */ /* the worker/renderer thread */
public void run() { public void run() {
try { try {
log.info("Map renderer has started."); log.info("Map renderer has started.");
while(running) { while (running) {
MapTile t = staleQueue.popStaleTile(); MapTile t = staleQueue.popStaleTile();
if(t != null) { if (t != null) {
loadRequiredChunks(t); loadRequiredChunks(t);
debugger.debug("Rendering tile " + t + "..."); debugger.debug("Rendering tile " + t + "...");
boolean isNonEmptyTile = t.getMap().render(t); boolean isNonEmptyTile = t.getMap().render(t);
staleQueue.onTileUpdated(t); staleQueue.onTileUpdated(t);
if(isNonEmptyTile) if (isNonEmptyTile)
handleFullMapRender(t); handleFullMapRender(t);
try { try {
Thread.sleep(renderWait); Thread.sleep(renderWait);
} catch(InterruptedException e) { } catch (InterruptedException e) {
} }
} else { } else {
try { try {
Thread.sleep(500); Thread.sleep(500);
} catch(InterruptedException e) { } catch (InterruptedException e) {
} }
} }
} }
log.info("Map renderer has stopped."); log.info("Map renderer has stopped.");
} catch(Exception ex) { } catch (Exception ex) {
debugger.error("Exception on rendering-thread: " + ex.toString()); debugger.error("Exception on rendering-thread: " + ex.toString());
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public void touch(int x, int y, int z) { public void touch(int x, int y, int z) {
for(int i = 0; i < maps.length; i++) { for (int i = 0; i < maps.length; i++) {
MapTile[] tiles = maps[i].getTiles(new Location(world, x, y, z)); MapTile[] tiles = maps[i].getTiles(new Location(world, x, y, z));
for(int j = 0; j < tiles.length; j++) { for (int j = 0; j < tiles.length; j++) {
invalidateTile(tiles[j]); invalidateTile(tiles[j]);
} }
} }
} }
public void invalidateTile(MapTile tile) { public void invalidateTile(MapTile tile) {
debugger.debug("Invalidating tile " + tile.getName()); debugger.debug("Invalidating tile " + tile.getName());
staleQueue.pushStaleTile(tile); staleQueue.pushStaleTile(tile);
} }
public void addChatEvent(PlayerChatEvent event) { public void addChatEvent(PlayerChatEvent event) {
chatQueue.pushChatMessage(event); chatQueue.pushChatMessage(event);
} }
} }

View file

@ -1,14 +1,15 @@
package org.dynmap; package org.dynmap;
public abstract class MapTile { public abstract class MapTile {
private MapType map; private MapType map;
public MapType getMap() {
return map; public MapType getMap() {
} return map;
}
public abstract String getName();
public abstract String getName();
public MapTile(MapType map) {
this.map = map; public MapTile(MapType map) {
} this.map = map;
}
} }

View file

@ -5,30 +5,37 @@ import org.bukkit.World;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public abstract class MapType { public abstract class MapType {
private MapManager manager; private MapManager manager;
public MapManager getMapManager() {
return manager; public MapManager getMapManager() {
} return manager;
}
private World world;
public World getWorld() { private World world;
return world;
} public World getWorld() {
return world;
private Debugger debugger; }
public Debugger getDebugger() {
return debugger; private Debugger debugger;
}
public Debugger getDebugger() {
public MapType(MapManager manager, World world, Debugger debugger) { return debugger;
this.manager = manager; }
this.world = world;
this.debugger = debugger; public MapType(MapManager manager, World world, Debugger debugger) {
} this.manager = manager;
this.world = world;
public abstract MapTile[] getTiles(Location l); this.debugger = debugger;
public abstract MapTile[] getAdjecentTiles(MapTile tile); }
public abstract DynmapChunk[] getRequiredChunks(MapTile tile);
public abstract boolean render(MapTile tile); public abstract MapTile[] getTiles(Location l);
public abstract boolean isRendered(MapTile tile);
public abstract MapTile[] getAdjecentTiles(MapTile tile);
public abstract DynmapChunk[] getRequiredChunks(MapTile tile);
public abstract boolean render(MapTile tile);
public abstract boolean isRendered(MapTile tile);
} }

View file

@ -14,68 +14,71 @@ import org.bukkit.Server;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class PlayerList { public class PlayerList {
private Server server; private Server server;
private HashSet<String> hiddenPlayerNames = new HashSet<String>(); private HashSet<String> hiddenPlayerNames = new HashSet<String>();
private File hiddenPlayersFile = new File(DynmapPlugin.dataRoot, "hiddenplayers.txt"); private File hiddenPlayersFile = new File(DynmapPlugin.dataRoot, "hiddenplayers.txt");
public PlayerList(Server server) { public PlayerList(Server server) {
this.server = server; this.server = server;
} }
public void save() { public void save() {
OutputStream stream; OutputStream stream;
try { try {
stream = new FileOutputStream(hiddenPlayersFile); stream = new FileOutputStream(hiddenPlayersFile);
OutputStreamWriter writer = new OutputStreamWriter(stream); OutputStreamWriter writer = new OutputStreamWriter(stream);
for(String player : hiddenPlayerNames) { for (String player : hiddenPlayerNames) {
writer.write(player); writer.write(player);
writer.write("\n"); writer.write("\n");
} }
writer.close(); writer.close();
stream.close(); stream.close();
} catch(IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void load() { public void load() {
try { try {
Scanner scanner = new Scanner(hiddenPlayersFile); Scanner scanner = new Scanner(hiddenPlayersFile);
while(scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String line = scanner.nextLine(); String line = scanner.nextLine();
hiddenPlayerNames.add(line); hiddenPlayerNames.add(line);
} }
scanner.close(); scanner.close();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
return; return;
} }
} }
public void hide(String playerName) { public void hide(String playerName) {
hiddenPlayerNames.add(playerName); hiddenPlayerNames.add(playerName);
save(); save();
} }
public void show(String playerName) { public void show(String playerName) {
hiddenPlayerNames.remove(playerName); hiddenPlayerNames.remove(playerName);
save(); save();
} }
public void setVisible(String playerName, boolean visible) { public void setVisible(String playerName, boolean visible) {
if (visible) show(playerName); else hide(playerName); if (visible)
} show(playerName);
else
public Player[] getVisiblePlayers() { hide(playerName);
ArrayList<Player> visiblePlayers = new ArrayList<Player>(); }
Player[] onlinePlayers = server.getOnlinePlayers();
for(int i=0;i<onlinePlayers.length;i++){ public Player[] getVisiblePlayers() {
Player p = onlinePlayers[i]; ArrayList<Player> visiblePlayers = new ArrayList<Player>();
if (!hiddenPlayerNames.contains(p.getName())) { Player[] onlinePlayers = server.getOnlinePlayers();
visiblePlayers.add(p); for (int i = 0; i < onlinePlayers.length; i++) {
} Player p = onlinePlayers[i];
} if (!hiddenPlayerNames.contains(p.getName())) {
Player[] result = new Player[visiblePlayers.size()]; visiblePlayers.add(p);
visiblePlayers.toArray(result); }
return result; }
} Player[] result = new Player[visiblePlayers.size()];
visiblePlayers.toArray(result);
return result;
}
} }

View file

@ -9,92 +9,95 @@ import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
public class StaleQueue { public class StaleQueue {
/* a list of MapTiles to be updated */ /* a list of MapTiles to be updated */
private LinkedList<MapTile> staleTilesQueue; private LinkedList<MapTile> staleTilesQueue;
private Set<MapTile> staleTiles; private Set<MapTile> staleTiles;
/* this list stores the tile updates */ /* this list stores the tile updates */
public LinkedList<TileUpdate> tileUpdates = null; public LinkedList<TileUpdate> tileUpdates = null;
/* remember up to this old tile updates (ms) */ /* remember up to this old tile updates (ms) */
private static final int maxTileAge = 60000; private static final int maxTileAge = 60000;
public StaleQueue() { public StaleQueue() {
staleTilesQueue = new LinkedList<MapTile>(); staleTilesQueue = new LinkedList<MapTile>();
staleTiles = new HashSet<MapTile>(); staleTiles = new HashSet<MapTile>();
tileUpdates = new LinkedList<TileUpdate>(); tileUpdates = new LinkedList<TileUpdate>();
} }
public int size() { public int size() {
return staleTilesQueue.size(); return staleTilesQueue.size();
} }
/* put a MapTile that needs to be regenerated on the list of stale tiles */ /* put a MapTile that needs to be regenerated on the list of stale tiles */
public boolean pushStaleTile(MapTile m) public boolean pushStaleTile(MapTile m) {
{ synchronized (MapManager.lock) {
synchronized(MapManager.lock) { if (staleTiles.add(m)) {
if(staleTiles.add(m)) { staleTilesQueue.addLast(m);
staleTilesQueue.addLast(m); return true;
return true; }
} return false;
return false; }
} }
}
/*
/* get next MapTile that needs to be regenerated, or null * get next MapTile that needs to be regenerated, or null the mapTile is
* the mapTile is removed from the list of stale tiles! */ * removed from the list of stale tiles!
public MapTile popStaleTile() */
{ public MapTile popStaleTile() {
synchronized(MapManager.lock) { synchronized (MapManager.lock) {
try { try {
MapTile t = staleTilesQueue.removeFirst(); MapTile t = staleTilesQueue.removeFirst();
if(!staleTiles.remove(t)) { if (!staleTiles.remove(t)) {
// This should never happen. // This should never happen.
} }
return t; return t;
} catch(NoSuchElementException e) { } catch (NoSuchElementException e) {
return null; return null;
} }
} }
} }
public void onTileUpdated(MapTile t) { public void onTileUpdated(MapTile t) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
long deadline = now - maxTileAge; long deadline = now - maxTileAge;
synchronized(MapManager.lock) { synchronized (MapManager.lock) {
ListIterator<TileUpdate> it = tileUpdates.listIterator(0); ListIterator<TileUpdate> it = tileUpdates.listIterator(0);
while(it.hasNext()) { while (it.hasNext()) {
TileUpdate tu = it.next(); TileUpdate tu = it.next();
if(tu.at < deadline || tu.tile == t) if (tu.at < deadline || tu.tile == t)
it.remove(); it.remove();
} }
tileUpdates.addLast(new TileUpdate(now, t)); tileUpdates.addLast(new TileUpdate(now, t));
} }
} }
private ArrayList<TileUpdate> tmpupdates = new ArrayList<TileUpdate>(); private ArrayList<TileUpdate> tmpupdates = new ArrayList<TileUpdate>();
public TileUpdate[] getTileUpdates(long cutoff) {
long now = System.currentTimeMillis(); public TileUpdate[] getTileUpdates(long cutoff) {
long deadline = now - maxTileAge; long now = System.currentTimeMillis();
TileUpdate[] updates; long deadline = now - maxTileAge;
synchronized(MapManager.lock) { TileUpdate[] updates;
tmpupdates.clear(); synchronized (MapManager.lock) {
Iterator<TileUpdate> it = tileUpdates.descendingIterator(); tmpupdates.clear();
while(it.hasNext()) { Iterator<TileUpdate> it = tileUpdates.descendingIterator();
TileUpdate tu = it.next(); while (it.hasNext()) {
if(tu.at >= cutoff) { // Tile is new. TileUpdate tu = it.next();
tmpupdates.add(tu); if (tu.at >= cutoff) { // Tile is new.
} else if(tu.at < deadline) { // Tile is too old, removing this one (will eventually decrease). tmpupdates.add(tu);
it.remove(); } else if (tu.at < deadline) { // Tile is too old, removing this
break; // one (will eventually
} else { // Tile is old, but not old enough for removal. // decrease).
break; it.remove();
} break;
} } else { // Tile is old, but not old enough for removal.
updates = new TileUpdate[tmpupdates.size()]; break;
tmpupdates.toArray(updates); }
} }
return updates; updates = new TileUpdate[tmpupdates.size()];
} tmpupdates.toArray(updates);
}
return updates;
}
} }

View file

@ -3,12 +3,11 @@ package org.dynmap;
/* this class stores a tile update */ /* this class stores a tile update */
public class TileUpdate { public class TileUpdate {
public long at; public long at;
public MapTile tile; public MapTile tile;
public TileUpdate(long at, MapTile tile) public TileUpdate(long at, MapTile tile) {
{ this.at = at;
this.at = at; this.tile = tile;
this.tile = tile; }
}
} }

View file

@ -15,85 +15,86 @@ import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
public class BukkitPlayerDebugger implements Debugger { public class BukkitPlayerDebugger implements Debugger {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
private boolean isLogging = false; private boolean isLogging = false;
private JavaPlugin plugin; private JavaPlugin plugin;
private HashSet<Player> debugees = new HashSet<Player>(); private HashSet<Player> debugees = new HashSet<Player>();
private String debugCommand; private String debugCommand;
private String undebugCommand; private String undebugCommand;
private String prepend; private String prepend;
public BukkitPlayerDebugger(JavaPlugin plugin) { public BukkitPlayerDebugger(JavaPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
PluginDescriptionFile pdfFile = plugin.getDescription(); PluginDescriptionFile pdfFile = plugin.getDescription();
debugCommand = "/debug_" + pdfFile.getName(); debugCommand = "/debug_" + pdfFile.getName();
undebugCommand = "/undebug_" + pdfFile.getName(); undebugCommand = "/undebug_" + pdfFile.getName();
prepend = pdfFile.getName() + ": "; prepend = pdfFile.getName() + ": ";
} }
public synchronized void enable() { public synchronized void enable() {
plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new CommandListener(), Priority.Normal, plugin); plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new CommandListener(), Priority.Normal, plugin);
plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, new CommandListener(), Priority.Normal, plugin); plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, new CommandListener(), Priority.Normal, plugin);
} }
public synchronized void disable() { public synchronized void disable() {
clearDebugees(); clearDebugees();
} }
public synchronized void addDebugee(Player p) { public synchronized void addDebugee(Player p) {
debugees.add(p); debugees.add(p);
} }
public synchronized void removeDebugee(Player p) { public synchronized void removeDebugee(Player p) {
debugees.remove(p); debugees.remove(p);
} }
public synchronized void clearDebugees() { public synchronized void clearDebugees() {
debugees.clear(); debugees.clear();
} }
public synchronized void sendToDebuggees(String message) { public synchronized void sendToDebuggees(String message) {
for (Player p : debugees) { for (Player p : debugees) {
p.sendMessage(prepend + message); p.sendMessage(prepend + message);
} }
} }
public synchronized void debug(String message) { public synchronized void debug(String message) {
sendToDebuggees(message); sendToDebuggees(message);
if (isLogging) log.info(prepend + message); if (isLogging)
} log.info(prepend + message);
}
public synchronized void error(String message) {
sendToDebuggees(prepend + ChatColor.RED + message); public synchronized void error(String message) {
log.log(Level.SEVERE, prepend + message); sendToDebuggees(prepend + ChatColor.RED + message);
} log.log(Level.SEVERE, prepend + message);
}
public synchronized void error(String message, Throwable thrown) {
sendToDebuggees(prepend + ChatColor.RED + message); public synchronized void error(String message, Throwable thrown) {
sendToDebuggees(thrown.toString()); sendToDebuggees(prepend + ChatColor.RED + message);
log.log(Level.SEVERE, prepend + message); sendToDebuggees(thrown.toString());
} log.log(Level.SEVERE, prepend + message);
}
protected class CommandListener extends PlayerListener {
@Override protected class CommandListener extends PlayerListener {
public void onPlayerCommand(PlayerChatEvent event) { @Override
String[] split = event.getMessage().split(" "); public void onPlayerCommand(PlayerChatEvent event) {
Player player = event.getPlayer(); String[] split = event.getMessage().split(" ");
if (split[0].equalsIgnoreCase(debugCommand)) { Player player = event.getPlayer();
addDebugee(player); if (split[0].equalsIgnoreCase(debugCommand)) {
event.setCancelled(true); addDebugee(player);
} else if (split[0].equalsIgnoreCase(undebugCommand)) { event.setCancelled(true);
removeDebugee(player); } else if (split[0].equalsIgnoreCase(undebugCommand)) {
event.setCancelled(true); removeDebugee(player);
} event.setCancelled(true);
} }
}
@Override
public void onPlayerQuit(PlayerEvent event) { @Override
removeDebugee(event.getPlayer()); public void onPlayerQuit(PlayerEvent event) {
} removeDebugee(event.getPlayer());
} }
}
} }

View file

@ -1,7 +1,9 @@
package org.dynmap.debug; package org.dynmap.debug;
public interface Debugger { public interface Debugger {
void debug(String message); void debug(String message);
void error(String message);
void error(String message, Throwable thrown); void error(String message);
void error(String message, Throwable thrown);
} }

View file

@ -1,14 +1,15 @@
package org.dynmap.debug; package org.dynmap.debug;
public class NullDebugger implements Debugger { public class NullDebugger implements Debugger {
public static final NullDebugger instance = new NullDebugger(); public static final NullDebugger instance = new NullDebugger();
public void debug(String message) {
}
public void error(String message) { public void debug(String message) {
} }
public void error(String message, Throwable thrown) { public void error(String message) {
} }
public void error(String message, Throwable thrown) {
}
} }

View file

@ -7,89 +7,88 @@ import org.dynmap.debug.Debugger;
public class CaveTileRenderer extends DefaultTileRenderer { public class CaveTileRenderer extends DefaultTileRenderer {
public CaveTileRenderer(Debugger debugger, Map<String, Object> configuration) { public CaveTileRenderer(Debugger debugger, Map<String, Object> configuration) {
super(debugger, configuration); super(debugger, configuration);
} }
@Override @Override
protected Color scan(World world, int x, int y, int z, int seq) protected Color scan(World world, int x, int y, int z, int seq) {
{ boolean air = true;
boolean air = true;
for(;;) { for (;;) {
if(y < 0) if (y < 0)
return translucent; return translucent;
int id = world.getBlockTypeIdAt(x, y, z); int id = world.getBlockTypeIdAt(x, y, z);
switch(seq) { switch (seq) {
case 0: case 0:
x--; x--;
break; break;
case 1: case 1:
y--; y--;
break; break;
case 2: case 2:
z++; z++;
break; break;
case 3: case 3:
y--; y--;
break; break;
} }
seq = (seq + 1) & 3; seq = (seq + 1) & 3;
switch(id) { switch (id) {
case 20: case 20:
case 18: case 18:
case 17: case 17:
case 78: case 78:
case 79: case 79:
id = 0; id = 0;
break; break;
default: default:
} }
if(id != 0) { if (id != 0) {
air = false; air = false;
continue; continue;
} }
if(id == 0 && !air) { if (id == 0 && !air) {
int cr, cg, cb; int cr, cg, cb;
int mult = 256; int mult = 256;
if(y < 64) { if (y < 64) {
cr = 0; cr = 0;
cg = 64 + y * 3; cg = 64 + y * 3;
cb = 255 - y * 4; cb = 255 - y * 4;
} else { } else {
cr = (y-64) * 4; cr = (y - 64) * 4;
cg = 255; cg = 255;
cb = 0; cb = 0;
} }
switch(seq) { switch (seq) {
case 0: case 0:
mult = 224; mult = 224;
break; break;
case 1: case 1:
mult = 256; mult = 256;
break; break;
case 2: case 2:
mult = 192; mult = 192;
break; break;
case 3: case 3:
mult = 160; mult = 160;
break; break;
} }
cr = cr * mult / 256; cr = cr * mult / 256;
cg = cg * mult / 256; cg = cg * mult / 256;
cb = cb * mult / 256; cb = cb * mult / 256;
return new Color(cr, cg, cb); return new Color(cr, cg, cb);
} }
} }
} }
} }

View file

@ -13,152 +13,164 @@ import org.bukkit.World;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public class DefaultTileRenderer implements MapTileRenderer { public class DefaultTileRenderer implements MapTileRenderer {
protected static Color translucent = new Color(0, 0, 0, 0); protected static Color translucent = new Color(0, 0, 0, 0);
private String name; private String name;
protected Debugger debugger; protected Debugger debugger;
public String getName() { public String getName() {
return name; return name;
} }
public DefaultTileRenderer(Debugger debugger, Map<String, Object> configuration) { public DefaultTileRenderer(Debugger debugger, Map<String, Object> configuration) {
this.debugger = debugger; this.debugger = debugger;
name = (String) configuration.get("prefix"); name = (String) configuration.get("prefix");
} }
public boolean render(KzedMapTile tile, String path) { public boolean render(KzedMapTile tile, String path) {
World world = tile.getMap().getWorld(); World world = tile.getMap().getWorld();
BufferedImage im = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB); BufferedImage im = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB);
WritableRaster r = im.getRaster(); WritableRaster r = im.getRaster();
boolean isempty = true; boolean isempty = true;
int ix = tile.mx; int ix = tile.mx;
int iy = tile.my; int iy = tile.my;
int iz = tile.mz; int iz = tile.mz;
int jx, jz; int jx, jz;
int x, y; int x, y;
/* draw the map */ /* draw the map */
for (y = 0; y < KzedMap.tileHeight;) { for (y = 0; y < KzedMap.tileHeight;) {
jx = ix; jx = ix;
jz = iz; jz = iz;
for (x = KzedMap.tileWidth - 1; x >= 0; x -= 2) { for (x = KzedMap.tileWidth - 1; x >= 0; x -= 2) {
Color c1 = scan(world, jx, iy, jz, 0); Color c1 = scan(world, jx, iy, jz, 0);
Color c2 = scan(world, jx, iy, jz, 2); Color c2 = scan(world, jx, iy, jz, 2);
isempty = isempty && c1 == translucent && c2 == translucent; isempty = isempty && c1 == translucent && c2 == translucent;
r.setPixel(x, y, new int[] { c1.getRed(), c1.getGreen(), c1.getBlue() }); r.setPixel(x, y, new int[] {
r.setPixel(x - 1, y, new int[] { c2.getRed(), c2.getGreen(), c2.getBlue() }); c1.getRed(),
c1.getGreen(),
c1.getBlue() });
r.setPixel(x - 1, y, new int[] {
c2.getRed(),
c2.getGreen(),
c2.getBlue() });
jx++; jx++;
jz++; jz++;
} }
y++; y++;
jx = ix; jx = ix;
jz = iz - 1; jz = iz - 1;
for (x = KzedMap.tileWidth - 1; x >= 0; x -= 2) { for (x = KzedMap.tileWidth - 1; x >= 0; x -= 2) {
Color c1 = scan(world, jx, iy, jz, 2); Color c1 = scan(world, jx, iy, jz, 2);
jx++; jx++;
jz++; jz++;
Color c2 = scan(world, jx, iy, jz, 0); Color c2 = scan(world, jx, iy, jz, 0);
isempty = isempty && c1 == translucent && c2 == translucent; isempty = isempty && c1 == translucent && c2 == translucent;
r.setPixel(x, y, new int[] { c1.getRed(), c1.getGreen(), c1.getBlue() }); r.setPixel(x, y, new int[] {
r.setPixel(x - 1, y, new int[] { c2.getRed(), c2.getGreen(), c2.getBlue() }); c1.getRed(),
} c1.getGreen(),
c1.getBlue() });
r.setPixel(x - 1, y, new int[] {
c2.getRed(),
c2.getGreen(),
c2.getBlue() });
}
y++; y++;
ix++; ix++;
iz--; iz--;
} }
/* save the generated tile */ /* save the generated tile */
saveTile(tile, im, path); saveTile(tile, im, path);
((KzedMap) tile.getMap()).invalidateTile(new KzedZoomedMapTile((KzedMap)tile.getMap(), im, tile)); ((KzedMap) tile.getMap()).invalidateTile(new KzedZoomedMapTile((KzedMap) tile.getMap(), im, tile));
return !isempty; return !isempty;
} }
protected Color scan(World world, int x, int y, int z, int seq) { protected Color scan(World world, int x, int y, int z, int seq) {
for (;;) { for (;;) {
if (y < 0) if (y < 0)
return translucent; return translucent;
int id = world.getBlockTypeIdAt(x, y, z); int id = world.getBlockTypeIdAt(x, y, z);
switch (seq) { switch (seq) {
case 0: case 0:
x--; x--;
break; break;
case 1: case 1:
y--; y--;
break; break;
case 2: case 2:
z++; z++;
break; break;
case 3: case 3:
y--; y--;
break; break;
} }
seq = (seq + 1) & 3; seq = (seq + 1) & 3;
if (id != 0) { if (id != 0) {
Color[] colors = KzedMap.colors.get(id); Color[] colors = KzedMap.colors.get(id);
if (colors != null) { if (colors != null) {
Color c = colors[seq]; Color c = colors[seq];
if (c.getAlpha() > 0) { if (c.getAlpha() > 0) {
/* we found something that isn't transparent! */ /* we found something that isn't transparent! */
if (c.getAlpha() == 255) { if (c.getAlpha() == 255) {
/* it's opaque - the ray ends here */ /* it's opaque - the ray ends here */
return c; return c;
} }
/* this block is transparent, so recurse */ /* this block is transparent, so recurse */
Color bg = scan(world, x, y, z, seq); Color bg = scan(world, x, y, z, seq);
int cr = c.getRed(); int cr = c.getRed();
int cg = c.getGreen(); int cg = c.getGreen();
int cb = c.getBlue(); int cb = c.getBlue();
int ca = c.getAlpha(); int ca = c.getAlpha();
cr *= ca; cr *= ca;
cg *= ca; cg *= ca;
cb *= ca; cb *= ca;
int na = 255 - ca; int na = 255 - ca;
return new Color((bg.getRed() * na + cr) >> 8, (bg.getGreen() * na + cg) >> 8, (bg.getBlue() * na + cb) >> 8); return new Color((bg.getRed() * na + cr) >> 8, (bg.getGreen() * na + cg) >> 8, (bg.getBlue() * na + cb) >> 8);
} }
} }
} }
} }
} }
/* save rendered tile, update zoom-out tile */ /* save rendered tile, update zoom-out tile */
public void saveTile(KzedMapTile tile, BufferedImage im, String path) { public void saveTile(KzedMapTile tile, BufferedImage im, String path) {
String tilePath = getPath(tile, path); String tilePath = getPath(tile, path);
debugger.debug("saving tile " + tilePath); debugger.debug("saving tile " + tilePath);
/* save image */ /* save image */
try { try {
File file = new File(tilePath); File file = new File(tilePath);
ImageIO.write(im, "png", file); ImageIO.write(im, "png", file);
} catch (IOException e) { } catch (IOException e) {
debugger.error("Failed to save tile: " + tilePath, e); debugger.error("Failed to save tile: " + tilePath, e);
} catch (java.lang.NullPointerException e) { } catch (java.lang.NullPointerException e) {
debugger.error("Failed to save tile (NullPointerException): " + tilePath, e); debugger.error("Failed to save tile (NullPointerException): " + tilePath, e);
} }
} }
public static String getPath(KzedMapTile tile, String outputPath) { public static String getPath(KzedMapTile tile, String outputPath) {
return new File(new File(outputPath), tile.getName() + ".png").getPath(); return new File(new File(outputPath), tile.getName() + ".png").getPath();
} }
} }

View file

@ -20,249 +20,258 @@ import org.dynmap.MapType;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public class KzedMap extends MapType { public class KzedMap extends MapType {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
/* dimensions of a map tile */
public static final int tileWidth = 128;
public static final int tileHeight = 128;
/* (logical!) dimensions of a zoomed out map tile
* must be twice the size of the normal tile */
public static final int zTileWidth = 256;
public static final int zTileHeight = 256;
/* map x, y, z for projection origin */
public static final int anchorx = 0;
public static final int anchory = 127;
public static final int anchorz = 0;
public static java.util.Map<Integer, Color[]> colors;
MapTileRenderer[] renderers;
ZoomedTileRenderer zoomrenderer;
public KzedMap(MapManager manager, World world, Debugger debugger, Map<String, Object> configuration) {
super(manager, world, debugger);
if (colors == null) {
colors = loadColorSet("colors.txt");
}
renderers = loadRenderers(configuration);
zoomrenderer = new ZoomedTileRenderer(debugger, configuration);
}
private MapTileRenderer[] loadRenderers(Map<String, Object> configuration) {
List<?> configuredRenderers = (List<?>) configuration.get("renderers");
ArrayList<MapTileRenderer> renderers = new ArrayList<MapTileRenderer>();
for (Object configuredRendererObj : configuredRenderers) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> configuredRenderer = (Map<String, Object>) configuredRendererObj;
String typeName = (String) configuredRenderer.get("class");
log.info("Loading renderer '" + typeName.toString() + "'...");
Class<?> mapTypeClass = Class.forName(typeName);
Constructor<?> constructor = mapTypeClass.getConstructor(Debugger.class, Map.class);
MapTileRenderer mapTileRenderer = (MapTileRenderer) constructor.newInstance(getDebugger(), configuredRenderer);
renderers.add(mapTileRenderer);
} catch (Exception e) {
getDebugger().error("Error loading renderer", e);
}
}
MapTileRenderer[] result = new MapTileRenderer[renderers.size()];
renderers.toArray(result);
return result;
}
@Override
public MapTile[] getTiles(Location l) {
int x = l.getBlockX();
int y = l.getBlockY();
int z = l.getBlockZ();
int dx = x - anchorx;
int dy = y - anchory;
int dz = z - anchorz;
int px = dx + dz;
int py = dx - dz - dy;
int tx = tilex(px);
int ty = tiley(py);
ArrayList<MapTile> tiles = new ArrayList<MapTile>();
addTile(tiles, tx, ty);
boolean ledge = tilex(px - 4) != tx;
boolean tedge = tiley(py - 4) != ty;
boolean redge = tilex(px + 4) != tx;
boolean bedge = tiley(py + 4) != ty;
if (ledge) addTile(tiles, tx - tileWidth, ty);
if (redge) addTile(tiles, tx + tileWidth, ty);
if (tedge) addTile(tiles, tx, ty - tileHeight);
if (bedge) addTile(tiles, tx, ty + tileHeight);
if (ledge && tedge) addTile(tiles, tx - tileWidth, ty - tileHeight);
if (ledge && bedge) addTile(tiles, tx - tileWidth, ty + tileHeight);
if (redge && tedge) addTile(tiles, tx + tileWidth, ty - tileHeight);
if (redge && bedge) addTile(tiles, tx + tileWidth, ty + tileHeight);
MapTile[] result = new MapTile[tiles.size()];
tiles.toArray(result);
return result;
}
@Override
public MapTile[] getAdjecentTiles(MapTile tile) {
if (tile instanceof KzedMapTile) {
KzedMapTile t = (KzedMapTile) tile;
MapTileRenderer renderer = t.renderer;
return new MapTile[] {
new KzedMapTile(this, renderer, t.px - tileWidth, t.py),
new KzedMapTile(this, renderer, t.px + tileWidth, t.py),
new KzedMapTile(this, renderer, t.px, t.py - tileHeight),
new KzedMapTile(this, renderer, t.px, t.py + tileHeight)
};
}
return new MapTile[0];
}
public void addTile(ArrayList<MapTile> tiles, int px, int py) {
for (int i = 0; i < renderers.length; i++) {
tiles.add(new KzedMapTile(this, renderers[i], px, py));
}
}
public void invalidateTile(MapTile tile) {
getMapManager().invalidateTile(tile);
}
@Override
public DynmapChunk[] getRequiredChunks(MapTile tile) {
if (tile instanceof KzedMapTile) {
KzedMapTile t = (KzedMapTile) tile;
int x1 = t.mx - KzedMap.tileHeight / 2;
int x2 = t.mx + KzedMap.tileWidth / 2 + KzedMap.tileHeight / 2;
int z1 = t.mz - KzedMap.tileHeight / 2;
int z2 = t.mz + KzedMap.tileWidth / 2 + KzedMap.tileHeight / 2;
int x, z;
ArrayList<DynmapChunk> chunks = new ArrayList<DynmapChunk>();
for (x = x1; x < x2; x += 16) {
for (z = z1; z < z2; z += 16) {
DynmapChunk chunk = new DynmapChunk(x / 16, z / 16);
chunks.add(chunk);
}
}
DynmapChunk[] result = new DynmapChunk[chunks.size()];
chunks.toArray(result);
return result;
} else {
return new DynmapChunk[0];
}
}
@Override
public boolean render(MapTile tile) {
if (tile instanceof KzedZoomedMapTile) {
zoomrenderer.render((KzedZoomedMapTile) tile, getMapManager().tileDirectory.getAbsolutePath());
return true;
} else if (tile instanceof KzedMapTile) {
return ((KzedMapTile) tile).renderer.render((KzedMapTile) tile, getMapManager().tileDirectory.getAbsolutePath());
}
return false;
}
@Override
public boolean isRendered(MapTile tile) {
if (tile instanceof KzedMapTile) {
File tileFile = new File(DefaultTileRenderer.getPath((KzedMapTile) tile, getMapManager().tileDirectory.getAbsolutePath()));
return tileFile.exists();
}
return false;
}
/* tile X for position x */
static int tilex(int x) {
if (x < 0)
return x - (tileWidth + (x % tileWidth));
else
return x - (x % tileWidth);
}
/* tile Y for position y */
static int tiley(int y) {
if (y < 0)
return y - (tileHeight + (y % tileHeight));
else
return y - (y % tileHeight);
}
/* zoomed-out tile X for tile position x */
static int ztilex(int x) {
if (x < 0)
return x + x % zTileWidth;
else
return x - (x % zTileWidth);
}
/* zoomed-out tile Y for tile position y */
static int ztiley(int y) {
if (y < 0)
return y + y % zTileHeight;
//return y - (zTileHeight + (y % zTileHeight));
else
return y - (y % zTileHeight);
}
public java.util.Map<Integer, Color[]> loadColorSet(String colorsetpath) { /* dimensions of a map tile */
java.util.Map<Integer, Color[]> colors = new HashMap<Integer, Color[]>(); public static final int tileWidth = 128;
public static final int tileHeight = 128;
InputStream stream;
/*
try { * (logical!) dimensions of a zoomed out map tile must be twice the size of
/* load colorset */ * the normal tile
File cfile = new File(colorsetpath); */
if (cfile.isFile()) { public static final int zTileWidth = 256;
getDebugger().debug("Loading colors from '" + colorsetpath + "'..."); public static final int zTileHeight = 256;
stream = new FileInputStream(cfile);
} else { /* map x, y, z for projection origin */
getDebugger().debug("Loading colors from jar..."); public static final int anchorx = 0;
stream = KzedMap.class.getResourceAsStream("/colors.txt"); public static final int anchory = 127;
} public static final int anchorz = 0;
Scanner scanner = new Scanner(stream); public static java.util.Map<Integer, Color[]> colors;
int nc = 0; MapTileRenderer[] renderers;
while (scanner.hasNextLine()) { ZoomedTileRenderer zoomrenderer;
String line = scanner.nextLine();
if (line.startsWith("#") || line.equals("")) { public KzedMap(MapManager manager, World world, Debugger debugger, Map<String, Object> configuration) {
continue; super(manager, world, debugger);
} if (colors == null) {
colors = loadColorSet("colors.txt");
String[] split = line.split("\t"); }
if (split.length < 17) {
continue; renderers = loadRenderers(configuration);
} zoomrenderer = new ZoomedTileRenderer(debugger, configuration);
}
Integer id = new Integer(split[0]);
private MapTileRenderer[] loadRenderers(Map<String, Object> configuration) {
Color[] c = new Color[4]; List<?> configuredRenderers = (List<?>) configuration.get("renderers");
ArrayList<MapTileRenderer> renderers = new ArrayList<MapTileRenderer>();
/* store colors by raycast sequence number */ for (Object configuredRendererObj : configuredRenderers) {
c[0] = new Color(Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4])); try {
c[3] = new Color(Integer.parseInt(split[5]), Integer.parseInt(split[6]), Integer.parseInt(split[7]), Integer.parseInt(split[8])); @SuppressWarnings("unchecked")
c[1] = new Color(Integer.parseInt(split[9]), Integer.parseInt(split[10]), Integer.parseInt(split[11]), Integer.parseInt(split[12])); Map<String, Object> configuredRenderer = (Map<String, Object>) configuredRendererObj;
c[2] = new Color(Integer.parseInt(split[13]), Integer.parseInt(split[14]), Integer.parseInt(split[15]), Integer.parseInt(split[16])); String typeName = (String) configuredRenderer.get("class");
log.info("Loading renderer '" + typeName.toString() + "'...");
colors.put(id, c); Class<?> mapTypeClass = Class.forName(typeName);
nc += 1; Constructor<?> constructor = mapTypeClass.getConstructor(Debugger.class, Map.class);
} MapTileRenderer mapTileRenderer = (MapTileRenderer) constructor.newInstance(getDebugger(), configuredRenderer);
scanner.close(); renderers.add(mapTileRenderer);
} catch (Exception e) { } catch (Exception e) {
getDebugger().error("Could not load colors", e); getDebugger().error("Error loading renderer", e);
return null; }
} }
return colors; MapTileRenderer[] result = new MapTileRenderer[renderers.size()];
} renderers.toArray(result);
return result;
}
@Override
public MapTile[] getTiles(Location l) {
int x = l.getBlockX();
int y = l.getBlockY();
int z = l.getBlockZ();
int dx = x - anchorx;
int dy = y - anchory;
int dz = z - anchorz;
int px = dx + dz;
int py = dx - dz - dy;
int tx = tilex(px);
int ty = tiley(py);
ArrayList<MapTile> tiles = new ArrayList<MapTile>();
addTile(tiles, tx, ty);
boolean ledge = tilex(px - 4) != tx;
boolean tedge = tiley(py - 4) != ty;
boolean redge = tilex(px + 4) != tx;
boolean bedge = tiley(py + 4) != ty;
if (ledge)
addTile(tiles, tx - tileWidth, ty);
if (redge)
addTile(tiles, tx + tileWidth, ty);
if (tedge)
addTile(tiles, tx, ty - tileHeight);
if (bedge)
addTile(tiles, tx, ty + tileHeight);
if (ledge && tedge)
addTile(tiles, tx - tileWidth, ty - tileHeight);
if (ledge && bedge)
addTile(tiles, tx - tileWidth, ty + tileHeight);
if (redge && tedge)
addTile(tiles, tx + tileWidth, ty - tileHeight);
if (redge && bedge)
addTile(tiles, tx + tileWidth, ty + tileHeight);
MapTile[] result = new MapTile[tiles.size()];
tiles.toArray(result);
return result;
}
@Override
public MapTile[] getAdjecentTiles(MapTile tile) {
if (tile instanceof KzedMapTile) {
KzedMapTile t = (KzedMapTile) tile;
MapTileRenderer renderer = t.renderer;
return new MapTile[] {
new KzedMapTile(this, renderer, t.px - tileWidth, t.py),
new KzedMapTile(this, renderer, t.px + tileWidth, t.py),
new KzedMapTile(this, renderer, t.px, t.py - tileHeight),
new KzedMapTile(this, renderer, t.px, t.py + tileHeight) };
}
return new MapTile[0];
}
public void addTile(ArrayList<MapTile> tiles, int px, int py) {
for (int i = 0; i < renderers.length; i++) {
tiles.add(new KzedMapTile(this, renderers[i], px, py));
}
}
public void invalidateTile(MapTile tile) {
getMapManager().invalidateTile(tile);
}
@Override
public DynmapChunk[] getRequiredChunks(MapTile tile) {
if (tile instanceof KzedMapTile) {
KzedMapTile t = (KzedMapTile) tile;
int x1 = t.mx - KzedMap.tileHeight / 2;
int x2 = t.mx + KzedMap.tileWidth / 2 + KzedMap.tileHeight / 2;
int z1 = t.mz - KzedMap.tileHeight / 2;
int z2 = t.mz + KzedMap.tileWidth / 2 + KzedMap.tileHeight / 2;
int x, z;
ArrayList<DynmapChunk> chunks = new ArrayList<DynmapChunk>();
for (x = x1; x < x2; x += 16) {
for (z = z1; z < z2; z += 16) {
DynmapChunk chunk = new DynmapChunk(x / 16, z / 16);
chunks.add(chunk);
}
}
DynmapChunk[] result = new DynmapChunk[chunks.size()];
chunks.toArray(result);
return result;
} else {
return new DynmapChunk[0];
}
}
@Override
public boolean render(MapTile tile) {
if (tile instanceof KzedZoomedMapTile) {
zoomrenderer.render((KzedZoomedMapTile) tile, getMapManager().tileDirectory.getAbsolutePath());
return true;
} else if (tile instanceof KzedMapTile) {
return ((KzedMapTile) tile).renderer.render((KzedMapTile) tile, getMapManager().tileDirectory.getAbsolutePath());
}
return false;
}
@Override
public boolean isRendered(MapTile tile) {
if (tile instanceof KzedMapTile) {
File tileFile = new File(DefaultTileRenderer.getPath((KzedMapTile) tile, getMapManager().tileDirectory.getAbsolutePath()));
return tileFile.exists();
}
return false;
}
/* tile X for position x */
static int tilex(int x) {
if (x < 0)
return x - (tileWidth + (x % tileWidth));
else
return x - (x % tileWidth);
}
/* tile Y for position y */
static int tiley(int y) {
if (y < 0)
return y - (tileHeight + (y % tileHeight));
else
return y - (y % tileHeight);
}
/* zoomed-out tile X for tile position x */
static int ztilex(int x) {
if (x < 0)
return x + x % zTileWidth;
else
return x - (x % zTileWidth);
}
/* zoomed-out tile Y for tile position y */
static int ztiley(int y) {
if (y < 0)
return y + y % zTileHeight;
// return y - (zTileHeight + (y % zTileHeight));
else
return y - (y % zTileHeight);
}
public java.util.Map<Integer, Color[]> loadColorSet(String colorsetpath) {
java.util.Map<Integer, Color[]> colors = new HashMap<Integer, Color[]>();
InputStream stream;
try {
/* load colorset */
File cfile = new File(colorsetpath);
if (cfile.isFile()) {
getDebugger().debug("Loading colors from '" + colorsetpath + "'...");
stream = new FileInputStream(cfile);
} else {
getDebugger().debug("Loading colors from jar...");
stream = KzedMap.class.getResourceAsStream("/colors.txt");
}
Scanner scanner = new Scanner(stream);
int nc = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("#") || line.equals("")) {
continue;
}
String[] split = line.split("\t");
if (split.length < 17) {
continue;
}
Integer id = new Integer(split[0]);
Color[] c = new Color[4];
/* store colors by raycast sequence number */
c[0] = new Color(Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4]));
c[3] = new Color(Integer.parseInt(split[5]), Integer.parseInt(split[6]), Integer.parseInt(split[7]), Integer.parseInt(split[8]));
c[1] = new Color(Integer.parseInt(split[9]), Integer.parseInt(split[10]), Integer.parseInt(split[11]), Integer.parseInt(split[12]));
c[2] = new Color(Integer.parseInt(split[13]), Integer.parseInt(split[14]), Integer.parseInt(split[15]), Integer.parseInt(split[16]));
colors.put(id, c);
nc += 1;
}
scanner.close();
} catch (Exception e) {
getDebugger().error("Could not load colors", e);
return null;
}
return colors;
}
} }

View file

@ -4,54 +4,54 @@ import java.util.logging.Logger;
import org.dynmap.MapTile; import org.dynmap.MapTile;
public class KzedMapTile extends MapTile { public class KzedMapTile extends MapTile {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
public KzedMap map; public KzedMap map;
public MapTileRenderer renderer; public MapTileRenderer renderer;
/* projection position */ /* projection position */
public int px, py; public int px, py;
/* minecraft space origin */ /* minecraft space origin */
public int mx, my, mz; public int mx, my, mz;
/* create new MapTile */ /* create new MapTile */
public KzedMapTile(KzedMap map, MapTileRenderer renderer, int px, int py) { public KzedMapTile(KzedMap map, MapTileRenderer renderer, int px, int py) {
super(map); super(map);
this.map = map; this.map = map;
this.renderer = renderer; this.renderer = renderer;
this.px = px; this.px = px;
this.py = py; this.py = py;
mx = KzedMap.anchorx + px / 2 + py / 2; mx = KzedMap.anchorx + px / 2 + py / 2;
my = KzedMap.anchory; my = KzedMap.anchory;
mz = KzedMap.anchorz + px / 2 - py / 2; mz = KzedMap.anchorz + px / 2 - py / 2;
} }
@Override @Override
public String getName() { public String getName() {
return renderer.getName() + "_" + px + "_" + py; return renderer.getName() + "_" + px + "_" + py;
} }
public int hashCode() { public int hashCode() {
return getName().hashCode(); return getName().hashCode();
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof KzedMapTile) { if (obj instanceof KzedMapTile) {
return equals((KzedMapTile) obj); return equals((KzedMapTile) obj);
} }
return super.equals(obj); return super.equals(obj);
} }
public boolean equals(KzedMapTile o) { public boolean equals(KzedMapTile o) {
return o.getName().equals(getName()); return o.getName().equals(getName());
} }
/* return a simple string representation... */ /* return a simple string representation... */
public String toString() { public String toString() {
return getName(); return getName();
} }
} }

View file

@ -4,53 +4,53 @@ import java.awt.image.BufferedImage;
import org.dynmap.MapTile; import org.dynmap.MapTile;
public class KzedZoomedMapTile extends MapTile { public class KzedZoomedMapTile extends MapTile {
@Override @Override
public String getName() { public String getName() {
return "z" + originalTile.renderer.getName() + "_" + getTileX() + "_" + getTileY(); return "z" + originalTile.renderer.getName() + "_" + getTileX() + "_" + getTileY();
} }
public BufferedImage unzoomedImage; public BufferedImage unzoomedImage;
public KzedMapTile originalTile; public KzedMapTile originalTile;
public KzedZoomedMapTile(KzedMap map, BufferedImage unzoomedImage, KzedMapTile original) { public KzedZoomedMapTile(KzedMap map, BufferedImage unzoomedImage, KzedMapTile original) {
super(map); super(map);
this.unzoomedImage = unzoomedImage; this.unzoomedImage = unzoomedImage;
this.originalTile = original; this.originalTile = original;
} }
public int getTileX() { public int getTileX() {
return ztilex(originalTile.px + KzedMap.tileWidth); return ztilex(originalTile.px + KzedMap.tileWidth);
} }
public int getTileY() { public int getTileY() {
return ztiley(originalTile.py); return ztiley(originalTile.py);
} }
private static int ztilex(int x) { private static int ztilex(int x) {
if (x < 0) if (x < 0)
return x + (x % (KzedMap.tileWidth * 2)); return x + (x % (KzedMap.tileWidth * 2));
else else
return x - (x % (KzedMap.tileWidth * 2)); return x - (x % (KzedMap.tileWidth * 2));
} }
/* zoomed-out tile Y for tile position y */ /* zoomed-out tile Y for tile position y */
private static int ztiley(int y) { private static int ztiley(int y) {
if (y < 0) if (y < 0)
return y + (y % (KzedMap.tileHeight * 2)); return y + (y % (KzedMap.tileHeight * 2));
else else
return y - (y % (KzedMap.tileHeight * 2)); return y - (y % (KzedMap.tileHeight * 2));
} }
@Override @Override
public int hashCode() { public int hashCode() {
return getName().hashCode(); return getName().hashCode();
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof KzedZoomedMapTile) { if (obj instanceof KzedZoomedMapTile) {
return ((KzedZoomedMapTile) obj).originalTile.equals(originalTile); return ((KzedZoomedMapTile) obj).originalTile.equals(originalTile);
} }
return super.equals(obj); return super.equals(obj);
} }
} }

View file

@ -1,7 +1,7 @@
package org.dynmap.kzedmap; package org.dynmap.kzedmap;
public interface MapTileRenderer { public interface MapTileRenderer {
String getName(); String getName();
boolean render(KzedMapTile tile, String path);
boolean render(KzedMapTile tile, String path);
} }

View file

@ -10,66 +10,68 @@ import javax.imageio.ImageIO;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public class ZoomedTileRenderer { public class ZoomedTileRenderer {
protected Debugger debugger; protected Debugger debugger;
public ZoomedTileRenderer(Debugger debugger, Map<String, Object> configuration) {
this.debugger = debugger;
}
public void render(KzedZoomedMapTile zt, String outputPath) {
KzedMapTile t = zt.originalTile;
String zoomPath = new File(new File(outputPath), zt.getName() + ".png").getPath();
render(t.px, t.py, zt.getTileX(), zt.getTileY(), zt.unzoomedImage, zoomPath);
}
public void render(int px, int py, int zpx, int zpy, BufferedImage image, String zoomPath) {
BufferedImage zIm = null;
debugger.debug("Trying to load zoom-out tile: " + zoomPath);
try {
File file = new File(zoomPath);
zIm = ImageIO.read(file);
} catch(IOException e) {
}
if(zIm == null) { public ZoomedTileRenderer(Debugger debugger, Map<String, Object> configuration) {
/* create new one */ this.debugger = debugger;
zIm = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB); }
debugger.debug("New zoom-out tile created " + zoomPath);
} else {
debugger.debug("Loaded zoom-out tile from " + zoomPath);
}
/* update zoom-out tile */ public void render(KzedZoomedMapTile zt, String outputPath) {
KzedMapTile t = zt.originalTile;
String zoomPath = new File(new File(outputPath), zt.getName() + ".png").getPath();
render(t.px, t.py, zt.getTileX(), zt.getTileY(), zt.unzoomedImage, zoomPath);
}
/* scaled size */ public void render(int px, int py, int zpx, int zpy, BufferedImage image, String zoomPath) {
int scw = KzedMap.tileWidth / 2; BufferedImage zIm = null;
int sch = KzedMap.tileHeight / 2; debugger.debug("Trying to load zoom-out tile: " + zoomPath);
try {
File file = new File(zoomPath);
zIm = ImageIO.read(file);
} catch (IOException e) {
}
/* origin in zoomed-out tile */ if (zIm == null) {
int ox = 0; /* create new one */
int oy = 0; zIm = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB);
debugger.debug("New zoom-out tile created " + zoomPath);
} else {
debugger.debug("Loaded zoom-out tile from " + zoomPath);
}
if(zpx != px) ox = scw; /* update zoom-out tile */
if(zpy != py) oy = sch;
/* blit scaled rendered tile onto zoom-out tile */ /* scaled size */
//WritableRaster zr = zIm.getRaster(); int scw = KzedMap.tileWidth / 2;
Graphics2D g2 = zIm.createGraphics(); int sch = KzedMap.tileHeight / 2;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, ox, oy, scw, sch, null);
image.flush(); /* origin in zoomed-out tile */
int ox = 0;
/* save zoom-out tile */ int oy = 0;
try {
File file = new File(zoomPath); if (zpx != px)
ImageIO.write(zIm, "png", file); ox = scw;
debugger.debug("Saved zoom-out tile at " + zoomPath); if (zpy != py)
} catch(IOException e) { oy = sch;
debugger.error("Failed to save zoom-out tile: " + zoomPath, e);
} catch(java.lang.NullPointerException e) { /* blit scaled rendered tile onto zoom-out tile */
debugger.error("Failed to save zoom-out tile (NullPointerException): " + zoomPath, e); // WritableRaster zr = zIm.getRaster();
} Graphics2D g2 = zIm.createGraphics();
zIm.flush(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
} g2.drawImage(image, ox, oy, scw, sch, null);
image.flush();
/* save zoom-out tile */
try {
File file = new File(zoomPath);
ImageIO.write(zIm, "png", file);
debugger.debug("Saved zoom-out tile at " + zoomPath);
} catch (IOException e) {
debugger.error("Failed to save zoom-out tile: " + zoomPath, e);
} catch (java.lang.NullPointerException e) {
debugger.error("Failed to save zoom-out tile (NullPointerException): " + zoomPath, e);
}
zIm.flush();
}
} }

View file

@ -14,65 +14,63 @@ import org.dynmap.debug.Debugger;
public class WebServer extends Thread { public class WebServer extends Thread {
public static final String VERSION = "Huncraft"; public static final String VERSION = "Huncraft";
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
private Debugger debugger; private Debugger debugger;
private ServerSocket sock = null;
private boolean running = false;
private MapManager mgr; private ServerSocket sock = null;
private World world; private boolean running = false;
private PlayerList playerList;
private ConfigurationNode configuration;
public WebServer(MapManager mgr, World world, PlayerList playerList, Debugger debugger, ConfigurationNode configuration) throws IOException private MapManager mgr;
{ private World world;
this.mgr = mgr; private PlayerList playerList;
this.world = world; private ConfigurationNode configuration;
this.playerList = playerList;
this.configuration = configuration;
this.debugger = debugger;
String bindAddress = configuration.getString("webserver-bindaddress", "0.0.0.0");
int port = configuration.getInt("webserver-port", 8123);
sock = new ServerSocket(port, 5, bindAddress.equals("0.0.0.0") ? null : InetAddress.getByName(bindAddress));
running = true;
start();
log.info("Dynmap WebServer started on " + bindAddress + ":" + port);
}
public void run() public WebServer(MapManager mgr, World world, PlayerList playerList, Debugger debugger, ConfigurationNode configuration) throws IOException {
{ this.mgr = mgr;
try { this.world = world;
while (running) { this.playerList = playerList;
try { this.configuration = configuration;
Socket socket = sock.accept(); this.debugger = debugger;
WebServerRequest requestThread = new WebServerRequest(socket, mgr, world, playerList, configuration, debugger);
requestThread.start();
}
catch (IOException e) {
log.info("map WebServer.run() stops with IOException");
break;
}
}
log.info("map WebServer run() exiting");
} catch (Exception ex) {
debugger.error("Exception on WebServer-thread: " + ex.toString());
}
}
public void shutdown() String bindAddress = configuration.getString("webserver-bindaddress", "0.0.0.0");
{ int port = configuration.getInt("webserver-port", 8123);
try {
if(sock != null) { sock = new ServerSocket(port, 5, bindAddress.equals("0.0.0.0")
sock.close(); ? null
} : InetAddress.getByName(bindAddress));
} catch(IOException e) { running = true;
log.info("map stop() got IOException while closing socket"); start();
} log.info("Dynmap WebServer started on " + bindAddress + ":" + port);
running = false; }
}
public void run() {
try {
while (running) {
try {
Socket socket = sock.accept();
WebServerRequest requestThread = new WebServerRequest(socket, mgr, world, playerList, configuration, debugger);
requestThread.start();
} catch (IOException e) {
log.info("map WebServer.run() stops with IOException");
break;
}
}
log.info("map WebServer run() exiting");
} catch (Exception ex) {
debugger.error("Exception on WebServer-thread: " + ex.toString());
}
}
public void shutdown() {
try {
if (sock != null) {
sock.close();
}
} catch (IOException e) {
log.info("map stop() got IOException while closing socket");
}
running = false;
}
} }

View file

@ -25,263 +25,286 @@ import org.dynmap.TileUpdate;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public class WebServerRequest extends Thread { public class WebServerRequest extends Thread {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
private Debugger debugger; private Debugger debugger;
private Socket socket; private Socket socket;
private MapManager mgr; private MapManager mgr;
private World world; private World world;
private PlayerList playerList; private PlayerList playerList;
private ConfigurationNode configuration; private ConfigurationNode configuration;
public WebServerRequest(Socket socket, MapManager mgr, World world, PlayerList playerList, ConfigurationNode configuration, Debugger debugger) public WebServerRequest(Socket socket, MapManager mgr, World world, PlayerList playerList, ConfigurationNode configuration, Debugger debugger) {
{ this.debugger = debugger;
this.debugger = debugger; this.socket = socket;
this.socket = socket; this.mgr = mgr;
this.mgr = mgr; this.world = world;
this.world = world; this.playerList = playerList;
this.playerList = playerList; this.configuration = configuration;
this.configuration = configuration; }
}
private static void writeHttpHeader(BufferedOutputStream out, int statusCode, String statusText) throws IOException {
out.write("HTTP/1.0 ".getBytes());
out.write(Integer.toString(statusCode).getBytes());
out.write((" " + statusText + "\r\n").getBytes());
}
private static void writeHeaderField(BufferedOutputStream out, String name, String value) throws IOException {
out.write(name.getBytes());
out.write((int)':');
out.write((int)' ');
out.write(value.getBytes());
out.write(13);
out.write(10);
}
private static void writeEndOfHeaders(BufferedOutputStream out) throws IOException {
out.write(13);
out.write(10);
}
public void run() private static void writeHttpHeader(BufferedOutputStream out, int statusCode, String statusText) throws IOException {
{ out.write("HTTP/1.0 ".getBytes());
BufferedReader in = null; out.write(Integer.toString(statusCode).getBytes());
BufferedOutputStream out = null; out.write((" " + statusText + "\r\n").getBytes());
try { }
socket.setSoTimeout(30000);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedOutputStream(socket.getOutputStream());
String request = in.readLine(); private static void writeHeaderField(BufferedOutputStream out, String name, String value) throws IOException {
if (request == null || !request.startsWith("GET ") || !(request.endsWith(" HTTP/1.0") || request.endsWith("HTTP/1.1"))) { out.write(name.getBytes());
// Invalid request type (no "GET") out.write((int) ':');
writeHttpHeader(out, 500, "Invalid Method."); out.write((int) ' ');
writeEndOfHeaders(out); out.write(value.getBytes());
return; out.write(13);
} out.write(10);
}
String path = request.substring(4, request.length() - 9); private static void writeEndOfHeaders(BufferedOutputStream out) throws IOException {
debugger.debug("request: " + path); out.write(13);
if (path.equals("/up/configuration")) { out.write(10);
handleConfiguration(out); }
} else if (path.startsWith("/up/")) {
handleUp(out, path.substring(3));
} else if (path.startsWith("/tiles/")) {
handleMapToDirectory(out, path.substring(6), mgr.tileDirectory);
} else if (path.startsWith("/")) {
handleMapToDirectory(out, path, mgr.webDirectory);
}
out.flush();
out.close();
}
catch (IOException e) {
if (out != null) { try { out.close(); } catch (Exception anye) { } }
if (in != null) { try { in.close(); } catch (Exception anye) { } }
}
catch(Exception ex) {
if (out != null) { try { out.close(); } catch (Exception anye) { } }
if (in != null) { try { in.close(); } catch (Exception anye) { } }
debugger.error("Exception on WebRequest-thread: " + ex.toString());
}
}
public String stringifyJson(Object o) {
if (o == null) {
return "null";
} else if (o instanceof Boolean) {
return ((Boolean)o) ? "true" : "false";
} else if (o instanceof String) {
return "\"" + o + "\"";
} else if (o instanceof Integer || o instanceof Long || o instanceof Float || o instanceof Double) {
return o.toString();
} else if (o instanceof LinkedHashMap<?, ?>) {
@SuppressWarnings("unchecked")
LinkedHashMap<String, Object> m = (LinkedHashMap<String, Object>)o;
StringBuilder sb = new StringBuilder();
sb.append("{");
boolean first = true;
for (String key : m.keySet()) {
if (first) first = false;
else sb.append(",");
sb.append(stringifyJson(key));
sb.append(": ");
sb.append(stringifyJson(m.get(key)));
}
sb.append("}");
return sb.toString();
} else if (o instanceof ArrayList<?>) {
@SuppressWarnings("unchecked")
ArrayList<Object> l = (ArrayList<Object>)o;
StringBuilder sb = new StringBuilder();
int count = 0;
for(int i=0;i<l.size();i++) {
sb.append(count++ == 0 ? "[" : ",");
sb.append(stringifyJson(l.get(i)));
}
sb.append("]");
return sb.toString();
} else {
return "undefined";
}
}
public void handleConfiguration(BufferedOutputStream out) throws IOException {
String s = stringifyJson(configuration.getProperty("web"));
byte[] bytes = s.getBytes();
String dateStr = new Date().toString();
writeHttpHeader(out, 200, "OK");
writeHeaderField(out, "Date", dateStr);
writeHeaderField(out, "Content-Type", "text/plain");
writeHeaderField(out, "Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
writeHeaderField(out, "Last-modified", dateStr);
writeHeaderField(out, "Content-Length", Integer.toString(bytes.length));
writeEndOfHeaders(out);
out.write(bytes);
}
public void handleUp(BufferedOutputStream out, String path) throws IOException {
int current = (int) (System.currentTimeMillis() / 1000);
long cutoff = 0;
if(path.charAt(0) == '/') { public void run() {
try { BufferedReader in = null;
cutoff = ((long) Integer.parseInt(path.substring(1))) * 1000; BufferedOutputStream out = null;
} catch(NumberFormatException e) { try {
} socket.setSoTimeout(30000);
} in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedOutputStream(socket.getOutputStream());
StringBuilder sb = new StringBuilder(); String request = in.readLine();
long relativeTime = world.getTime() % 24000; if (request == null || !request.startsWith("GET ") || !(request.endsWith(" HTTP/1.0") || request.endsWith("HTTP/1.1"))) {
sb.append(current + " " + relativeTime + "\n"); // Invalid request type (no "GET")
writeHttpHeader(out, 500, "Invalid Method.");
writeEndOfHeaders(out);
return;
}
Player[] players = playerList.getVisiblePlayers(); String path = request.substring(4, request.length() - 9);
for(Player player : players) { debugger.debug("request: " + path);
sb.append("player " + player.getName() + " " + player.getLocation().getX() + " " + player.getLocation().getY() + " " + player.getLocation().getZ() + "\n"); if (path.equals("/up/configuration")) {
} handleConfiguration(out);
} else if (path.startsWith("/up/")) {
TileUpdate[] tileUpdates = mgr.staleQueue.getTileUpdates(cutoff); handleUp(out, path.substring(3));
for(TileUpdate tu : tileUpdates) { } else if (path.startsWith("/tiles/")) {
sb.append("tile " + tu.tile.getName() + "\n"); handleMapToDirectory(out, path.substring(6), mgr.tileDirectory);
} } else if (path.startsWith("/")) {
handleMapToDirectory(out, path, mgr.webDirectory);
ChatQueue.ChatMessage[] messages = mgr.chatQueue.getChatMessages(cutoff); }
for(ChatQueue.ChatMessage cu : messages) { out.flush();
sb.append("chat " + cu.playerName + " " + cu.message + "\n"); out.close();
} } catch (IOException e) {
if (out != null) {
try {
out.close();
} catch (Exception anye) {
}
}
if (in != null) {
try {
in.close();
} catch (Exception anye) {
}
}
} catch (Exception ex) {
if (out != null) {
try {
out.close();
} catch (Exception anye) {
}
}
if (in != null) {
try {
in.close();
} catch (Exception anye) {
}
}
debugger.error("Exception on WebRequest-thread: " + ex.toString());
}
}
debugger.debug("Sending " + players.length + " players, " + tileUpdates.length + " tile-updates, and " + messages.length + " chats. "+ path + ";" + cutoff); public String stringifyJson(Object o) {
if (o == null) {
byte[] bytes = sb.toString().getBytes(); return "null";
} else if (o instanceof Boolean) {
String dateStr = new Date().toString(); return ((Boolean) o) ? "true" : "false";
writeHttpHeader(out, 200, "OK"); } else if (o instanceof String) {
writeHeaderField(out, "Date", dateStr); return "\"" + o + "\"";
writeHeaderField(out, "Content-Type", "text/plain"); } else if (o instanceof Integer || o instanceof Long || o instanceof Float || o instanceof Double) {
writeHeaderField(out, "Expires", "Thu, 01 Dec 1994 16:00:00 GMT"); return o.toString();
writeHeaderField(out, "Last-modified", dateStr); } else if (o instanceof LinkedHashMap<?, ?>) {
writeHeaderField(out, "Content-Length", Integer.toString(bytes.length)); @SuppressWarnings("unchecked")
writeEndOfHeaders(out); LinkedHashMap<String, Object> m = (LinkedHashMap<String, Object>) o;
out.write(bytes); StringBuilder sb = new StringBuilder();
} sb.append("{");
boolean first = true;
private byte[] readBuffer = new byte[40960]; for (String key : m.keySet()) {
if (first)
public void writeFile(BufferedOutputStream out, String path, InputStream fileInput) throws IOException { first = false;
int dotindex = path.lastIndexOf('.'); else
String extension = null; sb.append(",");
if (dotindex > 0) extension = path.substring(dotindex);
sb.append(stringifyJson(key));
writeHttpHeader(out, 200, "OK"); sb.append(": ");
writeHeaderField(out, "Content-Type", getMimeTypeFromExtension(extension)); sb.append(stringifyJson(m.get(key)));
writeHeaderField(out, "Connection", "close"); }
writeEndOfHeaders(out); sb.append("}");
try { return sb.toString();
int readBytes; } else if (o instanceof ArrayList<?>) {
while((readBytes = fileInput.read(readBuffer)) > 0) { @SuppressWarnings("unchecked")
out.write(readBuffer, 0, readBytes); ArrayList<Object> l = (ArrayList<Object>) o;
} StringBuilder sb = new StringBuilder();
} catch(IOException e) { int count = 0;
fileInput.close(); for (int i = 0; i < l.size(); i++) {
throw e; sb.append(count++ == 0 ? "[" : ",");
} sb.append(stringifyJson(l.get(i)));
fileInput.close(); }
} sb.append("]");
return sb.toString();
public String getFilePath(String path) { } else {
int qmark = path.indexOf('?'); return "undefined";
if (qmark >= 0) path = path.substring(0, qmark); }
path = path.substring(1); }
if (path.startsWith("/") || path.startsWith(".")) public void handleConfiguration(BufferedOutputStream out) throws IOException {
return null;
if (path.length() == 0) path = "index.html"; String s = stringifyJson(configuration.getProperty("web"));
return path;
} byte[] bytes = s.getBytes();
String dateStr = new Date().toString();
public void handleMapToJar(BufferedOutputStream out, String path) throws IOException { writeHttpHeader(out, 200, "OK");
path = getFilePath(path); writeHeaderField(out, "Date", dateStr);
if (path != null) { writeHeaderField(out, "Content-Type", "text/plain");
InputStream s = this.getClass().getResourceAsStream("/web/" + path); writeHeaderField(out, "Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
if (s != null) { writeHeaderField(out, "Last-modified", dateStr);
writeFile(out, path, s); writeHeaderField(out, "Content-Length", Integer.toString(bytes.length));
return; writeEndOfHeaders(out);
} out.write(bytes);
} }
writeHttpHeader(out, 404, "Not found");
writeEndOfHeaders(out); public void handleUp(BufferedOutputStream out, String path) throws IOException {
} int current = (int) (System.currentTimeMillis() / 1000);
long cutoff = 0;
public void handleMapToDirectory(BufferedOutputStream out, String path, File directory) throws IOException {
path = getFilePath(path); if (path.charAt(0) == '/') {
if (path != null) { try {
File tileFile = new File(directory, path); cutoff = ((long) Integer.parseInt(path.substring(1))) * 1000;
} catch (NumberFormatException e) {
if (tileFile.getAbsolutePath().startsWith(directory.getAbsolutePath()) && tileFile.isFile()) { }
FileInputStream s = new FileInputStream(tileFile); }
writeFile(out, path, s);
return; StringBuilder sb = new StringBuilder();
} long relativeTime = world.getTime() % 24000;
} sb.append(current + " " + relativeTime + "\n");
writeHttpHeader(out, 404, "Not found");
writeEndOfHeaders(out); Player[] players = playerList.getVisiblePlayers();
} for (Player player : players) {
sb.append("player " + player.getName() + " " + player.getLocation().getX() + " " + player.getLocation().getY() + " " + player.getLocation().getZ() + "\n");
private static Map<String, String> mimes = new HashMap<String, String>(); }
static {
mimes.put(".html", "text/html"); TileUpdate[] tileUpdates = mgr.staleQueue.getTileUpdates(cutoff);
mimes.put(".htm", "text/html"); for (TileUpdate tu : tileUpdates) {
mimes.put(".js", "text/javascript"); sb.append("tile " + tu.tile.getName() + "\n");
mimes.put(".png", "image/png"); }
mimes.put(".css", "text/css");
mimes.put(".txt", "text/plain"); ChatQueue.ChatMessage[] messages = mgr.chatQueue.getChatMessages(cutoff);
} for (ChatQueue.ChatMessage cu : messages) {
public static String getMimeTypeFromExtension(String extension) { sb.append("chat " + cu.playerName + " " + cu.message + "\n");
String m = mimes.get(extension); }
if (m != null) return m;
return "application/octet-steam"; debugger.debug("Sending " + players.length + " players, " + tileUpdates.length + " tile-updates, and " + messages.length + " chats. " + path + ";" + cutoff);
}
byte[] bytes = sb.toString().getBytes();
String dateStr = new Date().toString();
writeHttpHeader(out, 200, "OK");
writeHeaderField(out, "Date", dateStr);
writeHeaderField(out, "Content-Type", "text/plain");
writeHeaderField(out, "Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
writeHeaderField(out, "Last-modified", dateStr);
writeHeaderField(out, "Content-Length", Integer.toString(bytes.length));
writeEndOfHeaders(out);
out.write(bytes);
}
private byte[] readBuffer = new byte[40960];
public void writeFile(BufferedOutputStream out, String path, InputStream fileInput) throws IOException {
int dotindex = path.lastIndexOf('.');
String extension = null;
if (dotindex > 0)
extension = path.substring(dotindex);
writeHttpHeader(out, 200, "OK");
writeHeaderField(out, "Content-Type", getMimeTypeFromExtension(extension));
writeHeaderField(out, "Connection", "close");
writeEndOfHeaders(out);
try {
int readBytes;
while ((readBytes = fileInput.read(readBuffer)) > 0) {
out.write(readBuffer, 0, readBytes);
}
} catch (IOException e) {
fileInput.close();
throw e;
}
fileInput.close();
}
public String getFilePath(String path) {
int qmark = path.indexOf('?');
if (qmark >= 0)
path = path.substring(0, qmark);
path = path.substring(1);
if (path.startsWith("/") || path.startsWith("."))
return null;
if (path.length() == 0)
path = "index.html";
return path;
}
public void handleMapToJar(BufferedOutputStream out, String path) throws IOException {
path = getFilePath(path);
if (path != null) {
InputStream s = this.getClass().getResourceAsStream("/web/" + path);
if (s != null) {
writeFile(out, path, s);
return;
}
}
writeHttpHeader(out, 404, "Not found");
writeEndOfHeaders(out);
}
public void handleMapToDirectory(BufferedOutputStream out, String path, File directory) throws IOException {
path = getFilePath(path);
if (path != null) {
File tileFile = new File(directory, path);
if (tileFile.getAbsolutePath().startsWith(directory.getAbsolutePath()) && tileFile.isFile()) {
FileInputStream s = new FileInputStream(tileFile);
writeFile(out, path, s);
return;
}
}
writeHttpHeader(out, 404, "Not found");
writeEndOfHeaders(out);
}
private static Map<String, String> mimes = new HashMap<String, String>();
static {
mimes.put(".html", "text/html");
mimes.put(".htm", "text/html");
mimes.put(".js", "text/javascript");
mimes.put(".png", "image/png");
mimes.put(".css", "text/css");
mimes.put(".txt", "text/plain");
}
public static String getMimeTypeFromExtension(String extension) {
String m = mimes.get(extension);
if (m != null)
return m;
return "application/octet-steam";
}
} }