Added server-to-client configuration and maptype-configuration: enables serverside configuration of maps and updaterate.

This commit is contained in:
FrozenCow 2011-02-01 14:17:08 +01:00
parent e47b4dc49f
commit 1beb4fa466
10 changed files with 573 additions and 150 deletions

19
configuration.txt Normal file → Executable file
View File

@ -15,10 +15,23 @@ webserver-bindaddress: 0.0.0.0
# The TCP-port the webserver will listen on. # The TCP-port the webserver will listen on.
webserver-port: 8123 webserver-port: 8123
maps:
- class: org.dynmap.kzedmap.KzedMap
renderers:
- class: org.dynmap.kzedmap.DefaultTileRenderer
prefix: t
- class: org.dynmap.kzedmap.CaveTileRenderer
prefix: ct
web: web:
# Interval the browser should poll for updates. # Interval the browser should poll for updates.
updaterate: 2000 updaterate: 2000
showchatballoon: true
defaultmap: defaultmap
shownmaps: shownmaps:
defaultmap: DefaultMapType - type: KzedMapType
cavemap: CaveMapType name: defaultmap
prefix: t
- type: KzedMapType
name: cavemap
prefix: ct

View File

@ -1,6 +1,12 @@
package org.dynmap; package org.dynmap;
import java.io.File; import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Location; import org.bukkit.Location;
@ -15,7 +21,7 @@ public class MapManager extends Thread {
private World world; private World world;
private Debugger debugger; private Debugger debugger;
private MapType map; private MapType[] maps;
public StaleQueue staleQueue; public StaleQueue staleQueue;
public ChatQueue chatQueue; public ChatQueue chatQueue;
public PlayerList playerList; public PlayerList playerList;
@ -67,7 +73,29 @@ public class MapManager extends Thread {
if (!tileDirectory.isDirectory()) if (!tileDirectory.isDirectory())
tileDirectory.mkdirs(); tileDirectory.mkdirs();
map = new KzedMap(this, world, debugger, configuration); maps = loadMapTypes(configuration);
}
private MapType[] loadMapTypes(ConfigurationNode configuration) {
List<?> configuredMaps = (List<?>)configuration.getProperty("maps");
ArrayList<MapType> mapTypes = new ArrayList<MapType>();
for(Object configuredMapObj : configuredMaps) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> configuredMap = (Map<String, Object>)configuredMapObj;
String typeName = (String)configuredMap.get("class");
log.info("Loading map '" + typeName.toString() + "'...");
Class<?> mapTypeClass = Class.forName(typeName);
Constructor<?> constructor = mapTypeClass.getConstructor(MapManager.class, World.class, Debugger.class, Map.class);
MapType mapType = (MapType)constructor.newInstance(this, world, debugger, configuredMap);
mapTypes.add(mapType);
} catch (Exception e) {
debugger.error("Error loading map", e);
}
}
MapType[] result = new MapType[mapTypes.size()];
mapTypes.toArray(result);
return result;
} }
/* initialize and start map manager */ /* initialize and start map manager */
@ -142,7 +170,9 @@ public class MapManager extends Thread {
} }
public void touch(int x, int y, int z) { public void touch(int x, int y, int z) {
map.touch(new Location(world, x, y, z)); for (int i = 0; i < maps.length; i++) {
maps[i].touch(new Location(world, x, y, z));
}
} }
public void invalidateTile(MapTile tile) { public void invalidateTile(MapTile tile) {

View File

@ -1,6 +1,7 @@
package org.dynmap.kzedmap; package org.dynmap.kzedmap;
import java.awt.Color; import java.awt.Color;
import java.util.Map;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.util.config.ConfigurationNode; import org.bukkit.util.config.ConfigurationNode;
@ -8,8 +9,8 @@ import org.dynmap.debug.Debugger;
public class CaveTileRenderer extends DefaultTileRenderer { public class CaveTileRenderer extends DefaultTileRenderer {
public CaveTileRenderer(String name, Debugger debugger, ConfigurationNode configuration) { public CaveTileRenderer(Debugger debugger, Map<String, Object> configuration) {
super(name, debugger, configuration); super(debugger, configuration);
} }
@Override @Override

View File

@ -5,11 +5,11 @@ import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster; import java.awt.image.WritableRaster;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.util.config.ConfigurationNode;
import org.dynmap.debug.Debugger; import org.dynmap.debug.Debugger;
public class DefaultTileRenderer implements MapTileRenderer { public class DefaultTileRenderer implements MapTileRenderer {
@ -20,9 +20,9 @@ public class DefaultTileRenderer implements MapTileRenderer {
return name; return name;
} }
public DefaultTileRenderer(String name, Debugger debugger, ConfigurationNode configuration) { public DefaultTileRenderer(Debugger debugger, Map<String, Object> configuration) {
this.name = name;
this.debugger = debugger; this.debugger = debugger;
name = (String)configuration.get("prefix");
} }
public void render(KzedMapTile tile, String path) { public void render(KzedMapTile tile, String path) {

View File

@ -4,18 +4,24 @@ import java.awt.Color;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner; import java.util.Scanner;
import java.util.logging.Logger;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.util.config.ConfigurationNode;
import org.dynmap.MapType;
import org.dynmap.MapManager; import org.dynmap.MapManager;
import org.dynmap.MapTile; import org.dynmap.MapTile;
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");
/* dimensions of a map tile */ /* dimensions of a map tile */
public static final int tileWidth = 128; public static final int tileWidth = 128;
public static final int tileHeight = 128; public static final int tileHeight = 128;
@ -34,18 +40,38 @@ public class KzedMap extends MapType {
MapTileRenderer[] renderers; MapTileRenderer[] renderers;
ZoomedTileRenderer zoomrenderer; ZoomedTileRenderer zoomrenderer;
public KzedMap(MapManager manager, World world, Debugger debugger, ConfigurationNode configuration) { public KzedMap(MapManager manager, World world, Debugger debugger, Map<String, Object> configuration) {
super(manager, world, debugger); super(manager, world, debugger);
if (colors == null) { if (colors == null) {
colors = loadColorSet("colors.txt"); colors = loadColorSet("colors.txt");
} }
renderers = new MapTileRenderer[] {
new DefaultTileRenderer("t", debugger, configuration), renderers = loadRenderers(configuration);
new CaveTileRenderer("ct", debugger, configuration),
};
zoomrenderer = new ZoomedTileRenderer(debugger, 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 @Override
public void touch(Location l) { public void touch(Location l) {
int x = l.getBlockX(); int x = l.getBlockX();

View File

@ -5,6 +5,7 @@ import java.awt.RenderingHints;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
@ -14,7 +15,7 @@ import org.dynmap.debug.Debugger;
public class ZoomedTileRenderer { public class ZoomedTileRenderer {
protected Debugger debugger; protected Debugger debugger;
public ZoomedTileRenderer(Debugger debugger, ConfigurationNode configuration) { public ZoomedTileRenderer(Debugger debugger, Map<String, Object> configuration) {
this.debugger = debugger; this.debugger = debugger;
} }

View File

@ -2,15 +2,6 @@ var config = {
tileUrl: 'tiles/', tileUrl: 'tiles/',
updateUrl: 'up/', // For Apache and lighttpd updateUrl: 'up/', // For Apache and lighttpd
// updateUrl: 'up.aspx?path=', // For IIS // updateUrl: 'up.aspx?path=', // For IIS
updateRate: 2000, // Seconds the map should poll for updates. (Seconds) * 1000. The default is 2000 (every 2 seconds).
showPortraitsOnMap: true,
showPortraitsInPlayerList: true,
showPlayerNameOnMap: false,
defaultMap: 'defaultmap',
maps: {
'defaultmap': new DefaultMapType(),
'cavemap': new CaveMapType()
},
tileWidth: 128, tileWidth: 128,
tileHeight: 128 tileHeight: 128
}; };

84
web/jquery.json.js Normal file
View File

@ -0,0 +1,84 @@
if(!this.JSON){this.JSON={};}(function(){function f(n){return n<10?'0'+n:n;}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value});};}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');};}}());
jQuery.parseJSON = function(str) {
return JSON.parse(str);
};
jQuery.stringifyJSON = function(obj) {
return JSON.stringify(obj);
};
function fixedAjax(obj) {
var mysuccess = obj.success;
obj.success = function(data, status, request) {
if (request.status == 200) {
if (mysuccess) mysuccess(data, status, request);
} else {
obj.error(request, request.status, null);
}
};
$.ajax(obj);
}
jQuery.deleteJSON = function(url, success, error) {
fixedAjax({
type: 'DELETE',
dataType: 'text',
url: url,
success: function(data, status, request) {
if (success) success(request);
},
error: function(request, status, errorThrown) {
if (error) error(request.status, request.statusText, request);
}
});
};
jQuery.postJSON = function(obj, url, success, error) {
fixedAjax({
type: 'POST',
contentType: 'application/json',
dataType: 'text',
url: url,
data: $.stringifyJSON(obj),
success: function(data, status, request) {
if (success) success(data ? $.parseJSON(data) : null, request);
},
error: function(request, status, errorThrown) {
if (error) error(request.status, request.statusText, request);
}
});
};
jQuery.putJSON = function(obj, url, success, error) {
fixedAjax({
type: 'PUT',
contentType: 'application/json',
dataType: 'text',
url: url,
data: $.stringifyJSON(obj),
success: function(data, status, request) {
if (success) success(request);
},
error: function(request, status, errorThrown) {
if (error) error(request.status, request.statusText, request);
}
});
};
jQuery.getJSON = function(url, success, error) {
fixedAjax({
type: 'GET',
dataType: 'text',
url: url,
beforeSend: function(request) {
request.setRequestHeader('Accept', 'application/json');
},
success: function(data, status, request) {
if (success) success(data ? $.parseJSON(data) : null, request);
},
error: function(request, status, errorThrown) {
if (error) error(request.status, request.statusText, request);
}
});
};

View File

@ -1,130 +1,392 @@
function KzedProjection() {} package org.dynmap.kzedmap;
KzedProjection.prototype = {
fromLatLngToPoint: function(latLng) {
var x = (latLng.lng() * config.tileWidth)|0;
var y = (latLng.lat() * config.tileHeight)|0;
return new google.maps.Point(x, y); import java.awt.Color;
}, import java.io.File;
fromPointToLatLng: function(point) { import java.io.FileInputStream;
var lng = point.x / config.tileWidth; import java.io.InputStream;
var lat = point.y / config.tileHeight; import java.lang.reflect.Constructor;
return new google.maps.LatLng(lat, lng); import java.util.ArrayList;
}, import java.util.HashMap;
fromWorldToLatLng: function(x, y, z) import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.World;
import org.dynmap.MapManager;
import org.dynmap.MapTile;
import org.dynmap.MapType;
import org.dynmap.debug.Debugger;
public class KzedMap extends MapType {
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 void touch(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);
invalidateTile(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) invalidateTile(tx - tileWidth, ty);
if(redge) invalidateTile(tx + tileWidth, ty);
if(tedge) invalidateTile(tx, ty - tileHeight);
if(bedge) invalidateTile(tx, ty + tileHeight);
if(ledge && tedge) invalidateTile(tx - tileWidth, ty - tileHeight);
if(ledge && bedge) invalidateTile(tx - tileWidth, ty + tileHeight);
if(redge && tedge) invalidateTile(tx + tileWidth, ty - tileHeight);
if(redge && bedge) invalidateTile(tx + tileWidth, ty + tileHeight);
}
public void invalidateTile(int px, int py) {
for(MapTileRenderer renderer : renderers) {
invalidateTile(new KzedMapTile(this, renderer, px, py));
}
}
@Override
public void render(MapTile tile) {
if (tile instanceof KzedZoomedMapTile) {
zoomrenderer.render((KzedZoomedMapTile)tile, getMapManager().tileDirectory.getAbsolutePath());
} else if (tile instanceof KzedMapTile) {
((KzedMapTile)tile).renderer.render((KzedMapTile)tile, getMapManager().tileDirectory.getAbsolutePath());
}
}
/* tile X for position x */
static int tilex(int x)
{ {
var dx = +x; if(x < 0)
var dy = +y - 127; return x - (tileWidth + (x % tileWidth));
var dz = +z; else
var px = dx + dz; return x - (x % tileWidth);
var py = dx - dz - dy;
var lng = -px / config.tileWidth / 2 + 0.5;
var lat = py / config.tileHeight / 2;
return new google.maps.LatLng(lat, lng);
} }
};
function KzedMapType() {} /* tile Y for position y */
KzedMapType.prototype = $.extend(new DynMapType(), { static int tiley(int y)
constructor: KzedMapType, {
projection: new KzedProjection(), if(y < 0)
tileSize: new google.maps.Size(128, 128), return y - (tileHeight + (y % tileHeight));
minZoom: 0, else
maxZoom: 3, return y - (y % tileHeight);
prefix: null, }
getTile: function(coord, zoom, doc) {
var tileDebugText = null;
var tileSize = 128;
var tileName;
var imgSize;
var offset = {x: 0, y: 0};
var debugred; /* zoomed-out tile X for tile position x */
var debugblue; static int ztilex(int x)
{
if(x < 0)
return x + x % zTileWidth;
else
return x - (x % zTileWidth);
}
if (zoom == 0) { /* zoomed-out tile Y for tile position y */
// Most zoomed out tiles. static int ztiley(int y)
{
if(y < 0)
return y + y % zTileHeight;
//return y - (zTileHeight + (y % zTileHeight));
else
return y - (y % zTileHeight);
}
tileSize = 128; /*
imgSize = tileSize; // regenerate the entire map, starting at position
tileName = 'z' + this.prefix + '_' + (-coord.x * tileSize*2) + '_' + (coord.y * tileSize*2); public void regenerate(int x, int y, int z)
{
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);
MapTile first = getTileByPosition(tx, ty);
Vector<MapTile> open = new Vector<MapTile>();
open.add(first);
while(open.size() > 0) {
MapTile t = open.remove(open.size() - 1);
if(t.stale) continue;
int h = world.getHighestBlockYAt(t.mx, t.mz);
log.info("walking: " + t.mx + ", " + t.mz + ", h = " + h);
if(h < 1)
continue;
pushStaleTile(t);
open.add(getTileByPosition(t.px + tileWidth, t.py));
open.add(getTileByPosition(t.px - tileWidth, t.py));
open.add(getTileByPosition(t.px, t.py + tileHeight));
open.add(getTileByPosition(t.px, t.py - tileHeight));
}
}
// regenerate all zoom tiles, starting at position
public void regenerateZoom(int x, int y, int z)
{
int dx = x - anchorx;
int dy = y - anchory;
int dz = z - anchorz;
int px = dx + dz;
int py = dx - dz - dy;
int fzpx = ztilex(tilex(px));
int fzpy = ztiley(tiley(py));
class Pair implements Comparator {
public int x;
public int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
public int hashCode()
{
return (x << 16) ^ y;
}
public boolean equals(Object o)
{
Pair p = (Pair) o;
return x == p.x && y == p.y;
}
public int compare(Object o1, Object o2)
{
Pair p1 = (Pair) o1;
Pair p2 = (Pair) o2;
if(p1.x < p1.x) return -1;
if(p1.x > p1.x) return 1;
if(p1.y < p1.y) return -1;
if(p1.y > p1.y) return 1;
return 0;
}
}
HashSet<Pair> visited = new HashSet<Pair>();
Vector<Pair> open = new Vector<Pair>();
Pair fp = new Pair(fzpx, fzpy);
open.add(fp);
visited.add(fp);
while(open.size() > 0) {
Pair p = open.remove(open.size() - 1);
int zpx = p.x;
int zpy = p.y;
log.info("Regenerating zoom tile " + zpx + "," + zpy);
int g = regenZoomTile(zpx, zpy);
if(g > 0) {
Pair[] np = new Pair[4];
np[0] = new Pair(zpx-zTileWidth, zpy);
np[1] = new Pair(zpx+zTileWidth, zpy);
np[2] = new Pair(zpx, zpy-zTileHeight);
np[3] = new Pair(zpx, zpy+zTileHeight);
for(int i=0; i<4; i++) {
if(!visited.contains(np[i])) {
visited.add(np[i]);
open.add(np[i]);
}
}
}
}
}
// regenerate zoom-out tile
// returns number of valid subtiles
public int regenZoomTile(int zpx, int zpy)
{
int px1 = zpx + tileWidth;
int py1 = zpy;
int px2 = zpx;
int py2 = py1 + tileHeight;
MapTile t1 = getTileByPosition(px1, py1);
MapTile t2 = getTileByPosition(px2, py1);
MapTile t3 = getTileByPosition(px1, py2);
MapTile t4 = getTileByPosition(px2, py2);
BufferedImage im1 = t1.loadTile(this);
BufferedImage im2 = t2.loadTile(this);
BufferedImage im3 = t3.loadTile(this);
BufferedImage im4 = t4.loadTile(this);
BufferedImage zIm = new BufferedImage(MapManager.tileWidth, MapManager.tileHeight, BufferedImage.TYPE_INT_RGB);
WritableRaster zr = zIm.getRaster();
Graphics2D g2 = zIm.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
int scw = tileWidth / 2;
int sch = tileHeight / 2;
int good = 0;
if(im1 != null) {
g2.drawImage(im1, 0, 0, scw, sch, null);
good ++;
}
if(im2 != null) {
g2.drawImage(im2, scw, 0, scw, sch, null);
good ++;
}
if(im3 != null) {
g2.drawImage(im3, 0, sch, scw, sch, null);
good ++;
}
if(im4 != null) {
g2.drawImage(im4, scw, sch, scw, sch, null);
good ++;
}
if(good == 0) {
return 0;
}
String zPath = t1.getZoomPath(this);
// save zoom-out tile
try {
File file = new File(zPath);
ImageIO.write(zIm, "png", file);
log.info("regenZoomTile saved zoom-out tile at " + zPath);
} catch(IOException e) {
log.log(Level.SEVERE, "Failed to save zoom-out tile: " + zPath, e);
} catch(java.lang.NullPointerException e) {
log.log(Level.SEVERE, "Failed to save zoom-out tile (NullPointerException): " + zPath, e);
}
return good;
}
*/
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 { } else {
// Other zoom levels. getDebugger().debug("Loading colors from jar...");
tileSize = 128; stream = KzedMap.class.getResourceAsStream("/colors.txt");
// Helper functions.
var floor = Math.floor;
var div = function(x,y){return floor(x/y);}
var mod = function(x,y){return ((x%y)+y)%y;};
// Split the image up in ... segments (1*1 for zoom 1, 2*2 for zoom 2, 4*4 for zoom 3, etc).
var segments = Math.pow(2,zoom-1);
imgSize = segments*tileSize;
// Calculate the location relative to the world of this segment.
var mapcoord = {x: div(coord.x,segments)*tileSize, y: div(coord.y,segments)*tileSize};
// Calculate the location relative to the image of this segment.
offset = {x: mod(coord.x,segments)*-tileSize, y: mod(coord.y,segments)*-tileSize};
// The next couple of lines are somewhat of a hack, but makes it faster to render zoomed in tiles:
tileSize = imgSize;
if (offset.x == 0 && offset.y == 0) {
tileName = this.prefix + '_' + (-mapcoord.x) + '_' + mapcoord.y;
} }
offset = {x: 0, y: 0};
// The next line is not: Scanner scanner = new Scanner(stream);
//tileName = this.prefix + '_' + (-mapcoord.x) + '_' + mapcoord.y; int nc = 0;
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("#") || line.equals("")) {
continue;
} }
var img;
var tile = $('<div/>') String[] split = line.split("\t");
.addClass('tile') if (split.length < 17) {
.css({ continue;
overflow: 'hidden',
width: tileSize + 'px',
height: tileSize + 'px'
});
if (tileDebugText) {
$('<span/>')
.text(tileDebugText)
.css({
position: 'absolute',
color: 'red'
})
.appendTo(tile);
} }
if (tileName) {
img = $('<img/>') Integer id = new Integer(split[0]);
.attr('src', this.dynmap.getTileUrl(tileName))
.error(function() { img.hide(); }) Color[] c = new Color[4];
.css({
width: imgSize + 'px', /* store colors by raycast sequence number */
height: imgSize + 'px', c[0] = new Color(Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4]));
borderStyle: 'none', c[3] = new Color(Integer.parseInt(split[5]), Integer.parseInt(split[6]), Integer.parseInt(split[7]), Integer.parseInt(split[8]));
marginLeft: offset.x + 'px', c[1] = new Color(Integer.parseInt(split[9]), Integer.parseInt(split[10]), Integer.parseInt(split[11]), Integer.parseInt(split[12]));
marginTop: offset.y + 'px' c[2] = new Color(Integer.parseInt(split[13]), Integer.parseInt(split[14]), Integer.parseInt(split[15]), Integer.parseInt(split[16]));
})
.appendTo(tile); colors.put(id, c);
this.dynmap.registerTile(this, tileName, img); nc += 1;
} else {
this.dynmap.unregisterTile(this, tileName);
} }
return tile.get(0); scanner.close();
} catch(Exception e) {
getDebugger().error("Could not load colors", e);
return null;
} }
}); return colors;
}
}
function DefaultMapType(){}
DefaultMapType.prototype = $.extend(new KzedMapType(), {
prefix: 't'
});
function CaveMapType(){}
CaveMapType.prototype = $.extend(new KzedMapType(), {
prefix: 'ct'
});

View File

@ -68,8 +68,12 @@ MinecraftClock.prototype = {
}; };
function DynMap(options) { function DynMap(options) {
this.options = options; var self = this;
this.initialize(); self.options = options;
$.getJSON(self.options.updateUrl + 'configuration', function(configuration) {
self.configure(configuration);
self.initialize();
})
} }
DynMap.prototype = { DynMap.prototype = {
registeredTiles: new Array(), registeredTiles: new Array(),
@ -78,6 +82,17 @@ DynMap.prototype = {
chatPopups: new Array(), chatPopups: new Array(),
lasttimestamp: '0', lasttimestamp: '0',
followingPlayer: '', followingPlayer: '',
configure: function(configuration) {
var self = this;
$.extend(this.options, configuration);
if (!self.options.maps) self.options.maps = {};
$.each(self.options.shownmaps, function(index, mapentry) {
var mapconstructor = eval(mapentry.type);
var mapname = mapentry.name;
var mapconfiguration = mapentry;
self.options.maps[mapname] = new mapconstructor(mapconfiguration);
});
},
initialize: function() { initialize: function() {
var me = this; var me = this;
@ -136,7 +151,7 @@ DynMap.prototype = {
name: 'map', name: 'map',
id: 'maptypebutton_' + name id: 'maptypebutton_' + name
}) })
.attr('checked', me.options.defaultMap == name ? 'checked' : null) .attr('checked', me.options.defaultmap == name ? 'checked' : null)
) )
.append($('<label/>') .append($('<label/>')
.attr('for', 'maptypebutton_' + name) .attr('for', 'maptypebutton_' + name)
@ -150,7 +165,7 @@ DynMap.prototype = {
.data('maptype', mapType) .data('maptype', mapType)
.appendTo(maplist); .appendTo(maplist);
}); });
map.setMapTypeId(me.options.defaultMap); map.setMapTypeId(me.options.defaultmap);
// The Player List // The Player List
var playerlist = me.playerlist = $('<div/>') var playerlist = me.playerlist = $('<div/>')