More commands added to server, new logging

This commit is contained in:
Anuken
2018-01-28 14:18:21 -05:00
parent adfa66a73b
commit 205c4e723a
26 changed files with 308 additions and 178 deletions

View File

@@ -22,7 +22,7 @@ allprojects {
appName = "Mindustry" appName = "Mindustry"
gdxVersion = '1.9.8' gdxVersion = '1.9.8'
aiVersion = '1.8.1' aiVersion = '1.8.1'
uCoreVersion = 'fe0b063' uCoreVersion = '79f8108'
} }
repositories { repositories {

View File

@@ -95,6 +95,7 @@ text.enemies={0} Enemies
text.enemies.single={0} Enemy text.enemies.single={0} Enemy
text.loadimage=Load Image text.loadimage=Load Image
text.saveimage=Save Image text.saveimage=Save Image
text.oregen=Ore Generation
text.editor.badsize=[orange]Invalid image dimensions![]\nValid map dimensions: {0} text.editor.badsize=[orange]Invalid image dimensions![]\nValid map dimensions: {0}
text.editor.errorimageload=Error loading image file:\n[orange]{0} text.editor.errorimageload=Error loading image file:\n[orange]{0}
text.editor.errorimagesave=Error saving image file:\n[orange]{0} text.editor.errorimagesave=Error saving image file:\n[orange]{0}

View File

@@ -3,8 +3,8 @@ package io.anuke.mindustry;
import io.anuke.mindustry.core.*; import io.anuke.mindustry.core.*;
import io.anuke.mindustry.io.BlockLoader; import io.anuke.mindustry.io.BlockLoader;
import io.anuke.mindustry.io.BundleLoader; import io.anuke.mindustry.io.BundleLoader;
import io.anuke.ucore.core.Inputs;
import io.anuke.ucore.modules.ModuleCore; import io.anuke.ucore.modules.ModuleCore;
import io.anuke.ucore.util.Log;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -12,6 +12,7 @@ public class Mindustry extends ModuleCore {
@Override @Override
public void init(){ public void init(){
Log.setUseColors(false);
BundleLoader.load(); BundleLoader.load();
BlockLoader.load(); BlockLoader.load();
@@ -24,11 +25,4 @@ public class Mindustry extends ModuleCore {
module(netClient = new NetClient()); module(netClient = new NetClient());
module(netCommon = new NetCommon()); module(netCommon = new NetCommon());
} }
//hack
@Override
public void render() {
super.render();
Inputs.update();
}
} }

View File

@@ -7,9 +7,9 @@ import com.badlogic.gdx.math.Vector2;
import io.anuke.mindustry.entities.enemies.Enemy; import io.anuke.mindustry.entities.enemies.Enemy;
import io.anuke.mindustry.game.SpawnPoint; import io.anuke.mindustry.game.SpawnPoint;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.util.Angles; import io.anuke.ucore.util.Angles;
import io.anuke.ucore.util.Log;
import io.anuke.ucore.util.Mathf; import io.anuke.ucore.util.Mathf;
import io.anuke.ucore.util.Tmp; import io.anuke.ucore.util.Tmp;
@@ -109,7 +109,7 @@ public class Pathfind{
/**Re-calculate paths for all enemies. Runs when a path changes while moving.*/ /**Re-calculate paths for all enemies. Runs when a path changes while moving.*/
private void remakePath(){ private void remakePath(){
for(int i = 0; i < enemyGroup.amount(); i ++){ for(int i = 0; i < enemyGroup.size(); i ++){
Enemy enemy = enemyGroup.all().get(i); Enemy enemy = enemyGroup.all().get(i);
enemy.node = -1; enemy.node = -1;
} }
@@ -160,7 +160,7 @@ public class Pathfind{
point.finder.searchNodePath(point.start, world.getCore(), state.difficulty.heuristic, point.path); point.finder.searchNodePath(point.start, world.getCore(), state.difficulty.heuristic, point.path);
point.path.clear(); point.path.clear();
} }
UCore.log("Time elapsed: " + Timers.elapsed() + "ms\nAverage MS per path: " + Timers.elapsed()/amount); Log.info("Time elapsed: {0}ms\nAverage MS per path: {1}", Timers.elapsed(), Timers.elapsed()/amount);
} }
/**Reset and clear the paths.*/ /**Reset and clear the paths.*/

View File

@@ -2,7 +2,6 @@ package io.anuke.mindustry.core;
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.utils.IntSet; import com.badlogic.gdx.utils.IntSet;
import com.badlogic.gdx.utils.TimeUtils; import com.badlogic.gdx.utils.TimeUtils;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
@@ -20,8 +19,8 @@ import io.anuke.mindustry.net.NetworkIO;
import io.anuke.mindustry.net.Packets.*; import io.anuke.mindustry.net.Packets.*;
import io.anuke.mindustry.resource.Upgrade; import io.anuke.mindustry.resource.Upgrade;
import io.anuke.mindustry.resource.Weapon; import io.anuke.mindustry.resource.Weapon;
import io.anuke.mindustry.world.Map;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Effects; import io.anuke.ucore.core.Effects;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.entities.BaseBulletType; import io.anuke.ucore.entities.BaseBulletType;
@@ -29,6 +28,7 @@ import io.anuke.ucore.entities.Entities;
import io.anuke.ucore.entities.Entity; import io.anuke.ucore.entities.Entity;
import io.anuke.ucore.entities.EntityGroup; import io.anuke.ucore.entities.EntityGroup;
import io.anuke.ucore.modules.Module; import io.anuke.ucore.modules.Module;
import io.anuke.ucore.util.Log;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
@@ -91,7 +91,7 @@ public class NetClient extends Module {
}); });
Net.handleClient(WorldData.class, data -> { Net.handleClient(WorldData.class, data -> {
UCore.log("Recieved world data: " + data.stream.available() + " bytes."); Log.info("Recieved world data: {0} bytes.", data.stream.available());
NetworkIO.loadWorld(data.stream); NetworkIO.loadWorld(data.stream);
player.set(world.getSpawnX(), world.getSpawnY()); player.set(world.getSpawnX(), world.getSpawnY());
@@ -101,12 +101,12 @@ public class NetClient extends Module {
}); });
Net.handleClient(CustomMapPacket.class, packet -> { Net.handleClient(CustomMapPacket.class, packet -> {
UCore.log("Recieved custom map: " + packet.stream.available() + " bytes."); Log.info("Recieved custom map: {0} bytes.", packet.stream.available());
//custom map is always sent before world data //custom map is always sent before world data
Pixmap pixmap = NetworkIO.loadMap(packet.stream); Map map = NetworkIO.loadMap(packet.stream);
world.maps().setNetworkMap(pixmap); world.maps().setNetworkMap(map);
MapAckPacket ack = new MapAckPacket(); MapAckPacket ack = new MapAckPacket();
Net.send(ack, SendMode.tcp); Net.send(ack, SendMode.tcp);
@@ -128,7 +128,7 @@ public class NetClient extends Module {
if (entity == null || id == player.id) { if (entity == null || id == player.id) {
if (id != player.id) { if (id != player.id) {
UCore.log("Requesting entity " + id, "group " + group.getType()); Log.info("Requesting entity {0}, group {1}.", id, group.getType().toString().replace("class io.anuke.mindustry.entities.", ""));
EntityRequestPacket req = new EntityRequestPacket(); EntityRequestPacket req = new EntityRequestPacket();
req.id = id; req.id = id;
Net.send(req, SendMode.udp); Net.send(req, SendMode.udp);
@@ -228,7 +228,7 @@ public class NetClient extends Module {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (Exception e) { } catch (Exception e) {
UCore.error(e); Log.err(e);
//do nothing else... //do nothing else...
//TODO fix //TODO fix
} }

View File

@@ -30,14 +30,20 @@ public class NetCommon extends Module {
}); });
Net.handle(PlacePacket.class, (packet) -> { Net.handle(PlacePacket.class, (packet) -> {
control.input().placeBlockInternal(packet.x, packet.y, Block.getByID(packet.block), packet.rotation, true, false); if(headless)
world.placeBlock(packet.x, packet.y, Block.getByID(packet.block), packet.rotation);
else
control.input().placeBlockInternal(packet.x, packet.y, Block.getByID(packet.block), packet.rotation, true, false);
Recipe recipe = Recipes.getByResult(Block.getByID(packet.block)); Recipe recipe = Recipes.getByResult(Block.getByID(packet.block));
if (recipe != null) state.inventory.removeItems(recipe.requirements); if (recipe != null) state.inventory.removeItems(recipe.requirements);
}); });
Net.handle(BreakPacket.class, (packet) -> { Net.handle(BreakPacket.class, (packet) -> {
control.input().breakBlockInternal(packet.x, packet.y, false); if(headless)
world.removeBlock(world.tile(packet.x, packet.y));
else
control.input().breakBlockInternal(packet.x, packet.y, false);
}); });
Net.handle(ChatPacket.class, (packet) -> { Net.handle(ChatPacket.class, (packet) -> {

View File

@@ -16,12 +16,12 @@ import io.anuke.mindustry.resource.Upgrade;
import io.anuke.mindustry.resource.UpgradeRecipes; import io.anuke.mindustry.resource.UpgradeRecipes;
import io.anuke.mindustry.resource.Weapon; import io.anuke.mindustry.resource.Weapon;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.entities.Entities; import io.anuke.ucore.entities.Entities;
import io.anuke.ucore.entities.EntityGroup; import io.anuke.ucore.entities.EntityGroup;
import io.anuke.ucore.modules.Module; import io.anuke.ucore.modules.Module;
import io.anuke.ucore.util.Bundles; import io.anuke.ucore.util.Bundles;
import io.anuke.ucore.util.Log;
import io.anuke.ucore.util.Mathf; import io.anuke.ucore.util.Mathf;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -41,7 +41,7 @@ public class NetServer extends Module{
public NetServer(){ public NetServer(){
Net.handleServer(Connect.class, (id, connect) -> UCore.log("Connection found: " + connect.addressTCP)); Net.handleServer(Connect.class, (id, connect) -> {});
Net.handleServer(ConnectPacket.class, (id, packet) -> { Net.handleServer(ConnectPacket.class, (id, packet) -> {
@@ -50,7 +50,7 @@ public class NetServer extends Module{
return; return;
} }
UCore.log("Sending world data to client (ID=" + id + ")"); Log.info("Sending world data to client (ID = {0})", id);
Player player = new Player(); Player player = new Player();
player.clientid = id; player.clientid = id;
@@ -63,12 +63,12 @@ public class NetServer extends Module{
if(world.getMap().custom){ if(world.getMap().custom){
ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
NetworkIO.writeMap(world.getMap().pixmap, stream); NetworkIO.writeMap(world.getMap(), stream);
CustomMapPacket data = new CustomMapPacket(); CustomMapPacket data = new CustomMapPacket();
data.stream = new ByteArrayInputStream(stream.toByteArray()); data.stream = new ByteArrayInputStream(stream.toByteArray());
Net.sendStream(id, data); Net.sendStream(id, data);
UCore.log("Sending custom map: Packed " + stream.size() + " uncompressed bytes of MAP data."); Log.info("Sending custom map: Packed {0}uncompressed bytes of MAP data.", stream.size());
}else{ }else{
//hack-- simulate the map ack packet recieved to send the world data to the client. //hack-- simulate the map ack packet recieved to send the world data to the client.
Net.handleServerReceived(id, new MapAckPacket()); Net.handleServerReceived(id, new MapAckPacket());
@@ -86,7 +86,7 @@ public class NetServer extends Module{
data.stream = new ByteArrayInputStream(stream.toByteArray()); data.stream = new ByteArrayInputStream(stream.toByteArray());
Net.sendStream(id, data); Net.sendStream(id, data);
UCore.log("Packed " + stream.size() + " uncompressed bytes of WORLD data."); Log.info("Packed {0} uncompressed bytes of WORLD data.", stream.size());
}); });
Net.handleServer(ConnectConfirmPacket.class, (id, packet) -> { Net.handleServer(ConnectConfirmPacket.class, (id, packet) -> {
@@ -183,7 +183,6 @@ public class NetServer extends Module{
p.android = player.isAndroid; p.android = player.isAndroid;
Net.sendTo(dest, p, SendMode.tcp); Net.sendTo(dest, p, SendMode.tcp);
log("Replying to entity request (" + id + "): player, " + id);
} else if (enemyGroup.getByID(id) != null) { } else if (enemyGroup.getByID(id) != null) {
Enemy enemy = enemyGroup.getByID(id); Enemy enemy = enemyGroup.getByID(id);
EnemySpawnPacket e = new EnemySpawnPacket(); EnemySpawnPacket e = new EnemySpawnPacket();
@@ -195,9 +194,8 @@ public class NetServer extends Module{
e.type = enemy.type.id; e.type = enemy.type.id;
e.health = (short) enemy.health; e.health = (short) enemy.health;
Net.sendTo(dest, e, SendMode.tcp); Net.sendTo(dest, e, SendMode.tcp);
log("Replying to entity request(" + id + "): enemy, " + id);
} else { } else {
Gdx.app.error("Mindustry", "Entity request target not found!"); Log.err("Entity request target not found!");
} }
}); });
@@ -229,12 +227,12 @@ public class NetServer extends Module{
if(Timers.get("serverSync", serverSyncTime)){ if(Timers.get("serverSync", serverSyncTime)){
//scan through all groups with syncable entities //scan through all groups with syncable entities
for(EntityGroup<?> group : Entities.getAllGroups()) { for(EntityGroup<?> group : Entities.getAllGroups()) {
if(group.amount() == 0 || !(group.all().first() instanceof SyncEntity)) continue; if(group.size() == 0 || !(group.all().first() instanceof SyncEntity)) continue;
//get write size for one entity (adding 4, as you need to write the ID as well) //get write size for one entity (adding 4, as you need to write the ID as well)
int writesize = SyncEntity.getWriteSize((Class<? extends SyncEntity>)group.getType()) + 4; int writesize = SyncEntity.getWriteSize((Class<? extends SyncEntity>)group.getType()) + 4;
//amount of entities //amount of entities
int amount = group.amount(); int amount = group.size();
//maximum amount of entities per packet //maximum amount of entities per packet
int maxsize = 64; int maxsize = 64;
@@ -362,7 +360,6 @@ public class NetServer extends Module{
} }
packet.stream = new ByteArrayInputStream(bs.toByteArray()); packet.stream = new ByteArrayInputStream(bs.toByteArray());
//UCore.log("Sent block update stream to " + client + " / " + packet.stream.available());
Net.sendStream(client, packet); Net.sendStream(client, packet);
} }

View File

@@ -253,7 +253,7 @@ public class Renderer extends RendererModule{
} }
void drawShield(){ void drawShield(){
if(shieldGroup.amount() == 0 && shieldDraws.size == 0) return; if(shieldGroup.size() == 0 && shieldDraws.size == 0) return;
Graphics.surface(renderer.shieldSurface, false); Graphics.surface(renderer.shieldSurface, false);
Draw.color(Color.ROYAL); Draw.color(Color.ROYAL);

View File

@@ -1,25 +1,32 @@
package io.anuke.mindustry.core; package io.anuke.mindustry.core;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Gdx;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Player;
import io.anuke.mindustry.game.Difficulty;
import io.anuke.mindustry.game.GameMode;
import io.anuke.mindustry.io.SaveIO;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.net.Packets.ChatPacket; import io.anuke.mindustry.net.Packets.ChatPacket;
import io.anuke.mindustry.world.Map; import io.anuke.mindustry.world.Map;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Effects; import io.anuke.ucore.core.Effects;
import io.anuke.ucore.core.Sounds; import io.anuke.ucore.core.Sounds;
import io.anuke.ucore.modules.Module; import io.anuke.ucore.modules.Module;
import io.anuke.ucore.util.ColorCodes;
import io.anuke.ucore.util.CommandHandler; import io.anuke.ucore.util.CommandHandler;
import io.anuke.ucore.util.CommandHandler.Command; import io.anuke.ucore.util.CommandHandler.Command;
import io.anuke.ucore.util.CommandHandler.Response; import io.anuke.ucore.util.CommandHandler.Response;
import io.anuke.ucore.util.CommandHandler.ResponseType; import io.anuke.ucore.util.CommandHandler.ResponseType;
import io.anuke.ucore.util.Log;
import io.anuke.ucore.util.Strings;
import java.io.IOException; import java.io.IOException;
import java.util.Scanner; import java.util.Scanner;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
import static io.anuke.ucore.util.ColorCodes.*; import static io.anuke.ucore.util.Log.*;
;
public class ServerControl extends Module { public class ServerControl extends Module {
private final CommandHandler handler = new CommandHandler(""); private final CommandHandler handler = new CommandHandler("");
@@ -29,11 +36,21 @@ public class ServerControl extends Module {
Effects.setEffectProvider((a, b, c, d, e) -> {}); Effects.setEffectProvider((a, b, c, d, e) -> {});
Sounds.setHeadless(true); Sounds.setHeadless(true);
//override default handling //override default handling of chat packets
Net.handle(ChatPacket.class, (packet) -> { Net.handle(ChatPacket.class, (packet) -> {
info("&y" + (packet.name == null ? "" : packet.name) + ": &lb{0}", packet.text); info("&y" + (packet.name == null ? "" : packet.name) + ": &lb{0}", packet.text);
}); });
//don't do anything at all for GDX logging
Gdx.app.setApplicationLogger(new ApplicationLogger() {
@Override public void log(String tag, String message) { }
@Override public void log(String tag, String message, Throwable exception) { }
@Override public void error(String tag, String message) { }
@Override public void error(String tag, String message, Throwable exception) { }
@Override public void debug(String tag, String message) { }
@Override public void debug(String tag, String message, Throwable exception) { }
});
registerCommands(); registerCommands();
Thread thread = new Thread(this::readCommands, "Server Controls"); Thread thread = new Thread(this::readCommands, "Server Controls");
thread.setDaemon(true); thread.setDaemon(true);
@@ -61,9 +78,10 @@ public class ServerControl extends Module {
state.set(State.menu); state.set(State.menu);
}); });
handler.register("host", "<mapname>", "Open the server with a specific map.", arg -> { handler.register("host", "<mapname> <mode>", "Open the server with a specific map.", arg -> {
if(state.is(State.playing)){ if(state.is(State.playing)){
err("Already hosting. Type 'stop' to stop hosting first."); err("Already hosting. Type 'stop' to stop hosting first.");
return;
} }
String search = arg[0]; String search = arg[0];
@@ -78,24 +96,102 @@ public class ServerControl extends Module {
return; return;
} }
GameMode mode = null;
try{
mode = GameMode.valueOf(arg[1]);
}catch (IllegalArgumentException e){
err("No gamemode '{0}' found.", arg[1]);
return;
}
info("Loading map..."); info("Loading map...");
state.mode = mode;
logic.reset(); logic.reset();
world.loadMap(result); world.loadMap(result);
state.set(State.playing); state.set(State.playing);
info("Map loaded."); info("Map loaded.");
try { host();
Net.host(port); });
info("Server opened.");
}catch (IOException e){ handler.register("status", "", "Display server status.", arg -> {
UCore.error(e); if(state.is(State.menu)){
info("&lyStatus: &rserver closed");
}else{
info("&lyStatus: &lcPlaying on map &fi{0}&fb &lb/&lc Wave {1} &lb/&lcDifficulty {2}", Strings.capitalize(world.getMap().name), state.wave, state.difficulty.name());
if(playerGroup.size() > 0) {
info("&lyPlayers: {0}", playerGroup.size());
for (Player p : playerGroup.all()) {
print(" &y" + p.name);
}
}else{
info("&lyNo players connected.");
}
} }
}); });
handler.register("say", "<message>", "Send a message to all players.", arg -> {
if(!state.is(State.playing)) {
err("Not hosting. Host a game first.");
return;
}
netCommon.sendMessage("[pink][[Server]:[] " + arg[0]);
info("&ly[Server]: &lb{0}", arg[0]);
}).mergeArgs();
handler.register("difficulty", "<difficulty>", "Set game difficulty.", arg -> {
try{
Difficulty diff = Difficulty.valueOf(arg[0]);
state.difficulty = diff;
info("Difficulty set to '{0}'.", arg[0]);
}catch (IllegalArgumentException e){
err("No difficulty with name '{0}' found.", arg[0]);
}
});
handler.register("load", "<slot>", "Load a save from a slot.", arg -> {
if(state.is(State.playing)){
err("Already hosting. Type 'stop' to stop hosting first.");
return;
}else if(!Strings.canParseInt(arg[0])){
err("Invalid save slot '{0}'.", arg[0]);
return;
}
int slot = Strings.parseInt(arg[0]);
if(!SaveIO.isSaveValid(slot)){
err("No save data found for slot.");
return;
}
SaveIO.loadFromSlot(slot);
info("Save loaded.");
host();
state.set(State.playing);
});
handler.register("save", "<slot>", "Save game state to a slot.", arg -> {
if(!state.is(State.playing)){
err("Not hosting. Host a game first.");
return;
}else if(!Strings.canParseInt(arg[0])){
err("Invalid save slot '{0}'.", arg[0]);
return;
}
int slot = Strings.parseInt(arg[0]);
SaveIO.saveToSlot(slot);
info("Saved to slot {0}.", slot);
});
} }
private void readCommands(){ private void readCommands(){
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);
System.out.print(LIGHT_BLUE + "> " + RESET);
while(true){ while(true){
String line = scan.nextLine(); String line = scan.nextLine();
@@ -107,32 +203,16 @@ public class ServerControl extends Module {
} else if (response.type == ResponseType.invalidArguments) { } else if (response.type == ResponseType.invalidArguments) {
err("Invalid command arguments. Usage: " + response.command.text + " " + response.command.params); err("Invalid command arguments. Usage: " + response.command.text + " " + response.command.params);
} }
System.out.print(LIGHT_BLUE + "> " + RESET);
}); });
} }
} }
private void print(String text, Object... args){ private void host(){
System.out.println(format(text, args) + RESET); try {
} Net.host(port);
}catch (IOException e){
private void info(String text, Object... args){ Log.err(e);
print(LIGHT_GREEN + BOLD + format(text, args)); state.set(State.menu);
}
private void err(String text, Object... args){
print(LIGHT_RED + BOLD + format(text, args));
}
private String format(String text, Object... args){
for(int i = 0; i < args.length; i ++){
text = text.replace("{" + i + "}", args[i].toString());
} }
for(String color : ColorCodes.getColorCodes()){
text = text.replace("&" + color, ColorCodes.getColorText(color));
}
return text;
} }
} }

View File

@@ -4,7 +4,7 @@ import com.badlogic.gdx.utils.IntMap;
import com.badlogic.gdx.utils.ObjectIntMap; import com.badlogic.gdx.utils.ObjectIntMap;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.blocks.*; import io.anuke.mindustry.world.blocks.*;
import io.anuke.ucore.UCore; import io.anuke.ucore.util.Log;
public class BlockLoader { public class BlockLoader {
static final ObjectIntMap<String> defaultMap = map( static final ObjectIntMap<String> defaultMap = map(
@@ -123,7 +123,7 @@ public class BlockLoader {
blockmap.put(defaultMap.get(string, -1), block); blockmap.put(defaultMap.get(string, -1), block);
} }
UCore.log("Total blocks loaded: " + Block.getAllBlocks().size); Log.info("Total blocks loaded: {0}", Block.getAllBlocks().size);
} }
public static Block getByOldID(int id){ public static Block getByOldID(int id){

View File

@@ -3,12 +3,14 @@ package io.anuke.mindustry.io;
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.I18NBundle; import com.badlogic.gdx.utils.I18NBundle;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Core; import io.anuke.ucore.core.Core;
import io.anuke.ucore.core.Settings; import io.anuke.ucore.core.Settings;
import io.anuke.ucore.util.Log;
import java.util.Locale; import java.util.Locale;
import static io.anuke.mindustry.Vars.headless;
public class BundleLoader { public class BundleLoader {
private static boolean externalBundle = false; private static boolean externalBundle = false;
@@ -18,7 +20,6 @@ public class BundleLoader {
loadBundle(); loadBundle();
} }
private static Locale getLocale(){ private static Locale getLocale(){
String loc = Settings.getString("locale"); String loc = Settings.getString("locale");
if(loc.equals("default")){ if(loc.equals("default")){
@@ -46,7 +47,7 @@ public class BundleLoader {
Locale locale = Locale.ENGLISH; Locale locale = Locale.ENGLISH;
Core.bundle = I18NBundle.createBundle(handle, locale); Core.bundle = I18NBundle.createBundle(handle, locale);
}catch (Exception e){ }catch (Exception e){
UCore.error(e); Log.err(e);
Platform.instance.showError("Failed to find bundle!\nMake sure you have bundle.properties in the same directory\nas the jar file.\n\nIf the problem persists, try running it through the command prompt:\n" + Platform.instance.showError("Failed to find bundle!\nMake sure you have bundle.properties in the same directory\nas the jar file.\n\nIf the problem persists, try running it through the command prompt:\n" +
"Hold left-shift, then right click and select 'open command prompt here'.\nThen, type in 'java -jar mindustry.jar' without quotes."); "Hold left-shift, then right click and select 'open command prompt here'.\nThen, type in 'java -jar mindustry.jar' without quotes.");
Gdx.app.exit(); Gdx.app.exit();
@@ -55,7 +56,7 @@ public class BundleLoader {
FileHandle handle = Gdx.files.internal("bundles/bundle"); FileHandle handle = Gdx.files.internal("bundles/bundle");
Locale locale = getLocale(); Locale locale = getLocale();
UCore.log("Got locale: " + locale); if(!headless) Log.info("Got locale: {0}", locale);
Core.bundle = I18NBundle.createBundle(handle, locale); Core.bundle = I18NBundle.createBundle(handle, locale);
} }
} }

View File

@@ -9,9 +9,9 @@ import com.badlogic.gdx.utils.*;
import com.badlogic.gdx.utils.Json.Serializer; import com.badlogic.gdx.utils.Json.Serializer;
import com.badlogic.gdx.utils.JsonWriter.OutputType; import com.badlogic.gdx.utils.JsonWriter.OutputType;
import io.anuke.mindustry.world.Map; import io.anuke.mindustry.world.Map;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Settings; import io.anuke.ucore.core.Settings;
import io.anuke.ucore.graphics.Pixmaps; import io.anuke.ucore.graphics.Pixmaps;
import io.anuke.ucore.util.Log;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -32,17 +32,13 @@ public class Maps implements Disposable{
return maps.values(); return maps.values();
} }
public void setNetworkMap(Pixmap pixmap){ public void setNetworkMap(Map map){
if(networkMap != null){ if(networkMap != null){
networkMap.pixmap.dispose(); networkMap.pixmap.dispose();
networkMap = null; networkMap = null;
} }
networkMap = new Map();
networkMap.custom = true; networkMap = map;
networkMap.pixmap = pixmap;
networkMap.visible = false;
networkMap.name = "network map";
networkMap.id = -1;
} }
public Map getMap(int id){ public Map getMap(int id){
@@ -155,7 +151,7 @@ public class Maps implements Disposable{
} }
return true; return true;
}catch(Exception e){ }catch(Exception e){
if(!android) UCore.error(e); if(!android) Log.err(e);
Gdx.app.error("Mindustry-Maps", "Failed loading map file: " + file); Gdx.app.error("Mindustry-Maps", "Failed loading map file: " + file);
return false; return false;
} }

View File

@@ -66,26 +66,31 @@ public class Save15 extends SaveFileVersion {
int playerhealth = stream.readInt(); int playerhealth = stream.readInt();
player.x = playerx; if(!headless) {
player.y = playery; player.x = playerx;
player.health = playerhealth; player.y = playery;
state.mode = GameMode.values()[mode]; player.health = playerhealth;
Core.camera.position.set(playerx, playery, 0); state.mode = GameMode.values()[mode];
Core.camera.position.set(playerx, playery, 0);
//weapons //weapons
control.upgrades().getWeapons().clear(); control.upgrades().getWeapons().clear();
control.upgrades().getWeapons().add(Weapon.blaster); control.upgrades().getWeapons().add(Weapon.blaster);
player.weaponLeft = player.weaponRight = Weapon.blaster; player.weaponLeft = player.weaponRight = Weapon.blaster;
int weapons = stream.readByte(); int weapons = stream.readByte();
for(int i = 0; i < weapons; i ++){ for (int i = 0; i < weapons; i++) {
control.upgrades().addWeapon((Weapon) Upgrade.getByID(stream.readByte())); control.upgrades().addWeapon((Weapon) Upgrade.getByID(stream.readByte()));
}
ui.hudfrag.updateWeapons();
}else{
byte b = stream.readByte();
for(int i = 0; i < b; i ++) stream.readByte();
} }
ui.hudfrag.updateWeapons();
//inventory //inventory
int totalItems = stream.readByte(); int totalItems = stream.readByte();
@@ -98,7 +103,7 @@ public class Save15 extends SaveFileVersion {
state.inventory.getItems()[item.id] = amount; state.inventory.getItems()[item.id] = amount;
} }
ui.hudfrag.updateItems(); if(!headless) ui.hudfrag.updateItems();
//enemies //enemies
@@ -134,7 +139,7 @@ public class Save15 extends SaveFileVersion {
state.wave = wave; state.wave = wave;
state.wavetime = wavetime; state.wavetime = wavetime;
if(!android) if(!android && !headless)
player.add(); player.add();
//map //map
@@ -142,7 +147,7 @@ public class Save15 extends SaveFileVersion {
int seed = stream.readInt(); int seed = stream.readInt();
world.loadMap(world.maps().getMap(mapid), seed); world.loadMap(world.maps().getMap(mapid), seed);
renderer.clearTiles(); if(!headless) renderer.clearTiles();
for(Enemy enemy : enemiesToUpdate){ for(Enemy enemy : enemiesToUpdate){
enemy.node = -2; enemy.node = -2;
@@ -225,16 +230,23 @@ public class Save15 extends SaveFileVersion {
stream.writeShort(block.id); stream.writeShort(block.id);
} }
stream.writeFloat(player.x); //player x/y if(!headless) {
stream.writeFloat(player.y); stream.writeFloat(player.x); //player x/y
stream.writeFloat(player.y);
stream.writeInt(player.health); //player health stream.writeInt(player.health); //player health
stream.writeByte(control.upgrades().getWeapons().size - 1); //amount of weapons stream.writeByte(control.upgrades().getWeapons().size - 1); //amount of weapons
//start at 1, because the first weapon is always the starter - ignore that //start at 1, because the first weapon is always the starter - ignore that
for(int i = 1; i < control.upgrades().getWeapons().size; i ++){ for (int i = 1; i < control.upgrades().getWeapons().size; i++) {
stream.writeByte(control.upgrades().getWeapons().get(i).id); //weapon ordinal stream.writeByte(control.upgrades().getWeapons().get(i).id); //weapon ordinal
}
}else{
stream.writeFloat(0);
stream.writeFloat(0);
stream.writeInt(0);
stream.writeByte(0);
} }
//--INVENTORY-- //--INVENTORY--

View File

@@ -12,7 +12,6 @@ import io.anuke.mindustry.world.ColorMapper.BlockPair;
import io.anuke.mindustry.world.Map; import io.anuke.mindustry.world.Map;
import io.anuke.mindustry.world.blocks.Blocks; import io.anuke.mindustry.world.blocks.Blocks;
import io.anuke.mindustry.world.blocks.SpecialBlocks; import io.anuke.mindustry.world.blocks.SpecialBlocks;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Core; import io.anuke.ucore.core.Core;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.graphics.Draw; import io.anuke.ucore.graphics.Draw;
@@ -24,6 +23,7 @@ import io.anuke.ucore.scene.builders.table;
import io.anuke.ucore.scene.ui.*; import io.anuke.ucore.scene.ui.*;
import io.anuke.ucore.scene.ui.layout.Table; import io.anuke.ucore.scene.ui.layout.Table;
import io.anuke.ucore.util.Bundles; import io.anuke.ucore.util.Bundles;
import io.anuke.ucore.util.Log;
import io.anuke.ucore.util.Strings; import io.anuke.ucore.util.Strings;
import java.util.Arrays; import java.util.Arrays;
@@ -63,7 +63,7 @@ public class MapEditorDialog extends Dialog{
} }
}catch (Exception e){ }catch (Exception e){
ui.showError(Bundles.format("text.editor.errorimageload", Strings.parseException(e, false))); ui.showError(Bundles.format("text.editor.errorimageload", Strings.parseException(e, false)));
UCore.error(e); Log.err(e);
} }
ui.loadfrag.hide(); ui.loadfrag.hide();
}); });
@@ -80,7 +80,7 @@ public class MapEditorDialog extends Dialog{
Pixmaps.write(editor.pixmap(), result); Pixmaps.write(editor.pixmap(), result);
}catch (Exception e){ }catch (Exception e){
ui.showError(Bundles.format("text.editor.errorimagesave", Strings.parseException(e, false))); ui.showError(Bundles.format("text.editor.errorimagesave", Strings.parseException(e, false)));
if(!android) UCore.error(e); if(!android) Log.err(e);
} }
ui.loadfrag.hide(); ui.loadfrag.hide();
}); });
@@ -96,6 +96,7 @@ public class MapEditorDialog extends Dialog{
copy.id = -1; copy.id = -1;
copy.pixmap = Pixmaps.copy(map.pixmap); copy.pixmap = Pixmaps.copy(map.pixmap);
copy.texture = new Texture(copy.pixmap); copy.texture = new Texture(copy.pixmap);
copy.oreGen = map.oreGen;
editor.beginEdit(copy); editor.beginEdit(copy);
ui.loadfrag.hide(); ui.loadfrag.hide();
view.clearStack(); view.clearStack();
@@ -277,8 +278,16 @@ public class MapEditorDialog extends Dialog{
new label(() -> Bundles.format("text.editor.brushsize", MapEditor.brushSizes[(int)slider.getValue()])).left(); new label(() -> Bundles.format("text.editor.brushsize", MapEditor.brushSizes[(int)slider.getValue()])).left();
row(); row();
add(slider).growX().padTop(4f); add(slider).growX().padTop(4f);
}}.growX().end(); }}.growX().padBottom(-6).end();
row();
new table("button"){{
get().addCheck("$text.oregen", b -> {
editor.getMap().oreGen = b;
}).update(c -> c.setChecked(editor.getMap().oreGen)).padTop(3).padBottom(3);
}}.growX().padBottom(-6).end();
row(); row();
addBlockSelection(get()); addBlockSelection(get());
@@ -362,7 +371,7 @@ public class MapEditorDialog extends Dialog{
Table extra = new Table("button"); Table extra = new Table("button");
extra.labelWrap(() -> editor.getDrawBlock().formalName).width(180f).center(); extra.labelWrap(() -> editor.getDrawBlock().formalName).width(180f).center();
table.add(extra).growX(); table.add(extra).padBottom(-6).growX();
table.row(); table.row();
table.add(pane).growY().fillX(); table.add(pane).growY().fillX();
} }

View File

@@ -4,14 +4,15 @@ import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.IntMap; import com.badlogic.gdx.utils.IntMap;
import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.reflect.ClassReflection;
import io.anuke.mindustry.net.Packet.ImportantPacket; import io.anuke.mindustry.net.Packet.ImportantPacket;
import io.anuke.mindustry.net.Packets.KickReason; import io.anuke.mindustry.net.Packets.KickReason;
import io.anuke.mindustry.net.Streamable.StreamBegin; import io.anuke.mindustry.net.Streamable.StreamBegin;
import io.anuke.mindustry.net.Streamable.StreamBuilder; import io.anuke.mindustry.net.Streamable.StreamBuilder;
import io.anuke.mindustry.net.Streamable.StreamChunk; import io.anuke.mindustry.net.Streamable.StreamChunk;
import io.anuke.ucore.UCore;
import io.anuke.ucore.function.BiConsumer; import io.anuke.ucore.function.BiConsumer;
import io.anuke.ucore.function.Consumer; import io.anuke.ucore.function.Consumer;
import io.anuke.ucore.util.Log;
import java.io.IOException; import java.io.IOException;
@@ -37,7 +38,7 @@ public class Net{
if(!headless){ if(!headless){
ui.showError(text); ui.showError(text);
}else{ }else{
UCore.log(text); Log.err(text);
} }
} }
@@ -92,9 +93,9 @@ public class Net{
/**Send an object to all connected clients, or to the server if this is a client.*/ /**Send an object to all connected clients, or to the server if this is a client.*/
public static void send(Object object, SendMode mode){ public static void send(Object object, SendMode mode){
if(server){ if(server){
serverProvider.send(object, mode); if(serverProvider != null) serverProvider.send(object, mode);
}else { }else {
clientProvider.send(object, mode); if(clientProvider != null) clientProvider.send(object, mode);
} }
} }
@@ -160,7 +161,7 @@ public class Net{
if(clientListeners.get(object.getClass()) != null) clientListeners.get(object.getClass()).accept(object); if(clientListeners.get(object.getClass()) != null) clientListeners.get(object.getClass()).accept(object);
if(listeners.get(object.getClass()) != null) listeners.get(object.getClass()).accept(object); if(listeners.get(object.getClass()) != null) listeners.get(object.getClass()).accept(object);
}else{ }else{
UCore.log("Recieved " + object, "but ignoring data, as client is not loaded."); Log.info("Recieved {0}, but ignoring data, as client is not loaded.", ClassReflection.getSimpleName(object.getClass()));
} }
}else{ }else{
Gdx.app.error("Mindustry::Net", "Unhandled packet type: '" + object.getClass() + "'!"); Gdx.app.error("Mindustry::Net", "Unhandled packet type: '" + object.getClass() + "'!");

View File

@@ -7,10 +7,7 @@ import com.badlogic.gdx.utils.TimeUtils;
import io.anuke.mindustry.game.GameMode; import io.anuke.mindustry.game.GameMode;
import io.anuke.mindustry.resource.Upgrade; import io.anuke.mindustry.resource.Upgrade;
import io.anuke.mindustry.resource.Weapon; import io.anuke.mindustry.resource.Weapon;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.ColorMapper;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.WorldGenerator;
import io.anuke.mindustry.world.blocks.Blocks; import io.anuke.mindustry.world.blocks.Blocks;
import io.anuke.mindustry.world.blocks.types.BlockPart; import io.anuke.mindustry.world.blocks.types.BlockPart;
import io.anuke.mindustry.world.blocks.types.Rock; import io.anuke.mindustry.world.blocks.types.Rock;
@@ -23,8 +20,10 @@ import static io.anuke.mindustry.Vars.*;
public class NetworkIO { public class NetworkIO {
public static void writeMap(Pixmap map, OutputStream os){ public static void writeMap(Map map, OutputStream os){
try(DataOutputStream stream = new DataOutputStream(os)){ try(DataOutputStream stream = new DataOutputStream(os)){
stream.writeBoolean(map.oreGen);
stream.writeShort(map.getWidth()); stream.writeShort(map.getWidth());
stream.writeShort(map.getHeight()); stream.writeShort(map.getHeight());
@@ -33,7 +32,7 @@ public class NetworkIO {
int pos = 0; int pos = 0;
while(pos < cap){ while(pos < cap){
int color = map.getPixel(pos % width, pos / width); int color = map.pixmap.getPixel(pos % width, pos / width);
byte id = ColorMapper.getColorID(color); byte id = ColorMapper.getColorID(color);
int length = 1; int length = 1;
@@ -44,7 +43,7 @@ public class NetworkIO {
pos ++; pos ++;
int next = map.getPixel(pos % width, pos / width); int next = map.pixmap.getPixel(pos % width, pos / width);
if(next != color){ if(next != color){
pos --; pos --;
break; break;
@@ -64,8 +63,10 @@ public class NetworkIO {
} }
} }
public static Pixmap loadMap(InputStream is){ public static Map loadMap(InputStream is){
try(DataInputStream stream = new DataInputStream(is)){ try(DataInputStream stream = new DataInputStream(is)){
boolean ores = stream.readBoolean();
short width = stream.readShort(); short width = stream.readShort();
short height = stream.readShort(); short height = stream.readShort();
Pixmap pixmap = new Pixmap(width, height, Format.RGBA8888); Pixmap pixmap = new Pixmap(width, height, Format.RGBA8888);
@@ -83,8 +84,15 @@ public class NetworkIO {
} }
} }
Map map = new Map();
map.oreGen = ores;
map.custom = true;
map.pixmap = pixmap;
map.visible = false;
map.name = "network map";
map.id = -1;
return pixmap; return map;
}catch (IOException e){ }catch (IOException e){
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@@ -5,7 +5,6 @@ import io.anuke.mindustry.Vars;
import io.anuke.mindustry.io.Platform; import io.anuke.mindustry.io.Platform;
import io.anuke.mindustry.net.Host; import io.anuke.mindustry.net.Host;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Settings; import io.anuke.ucore.core.Settings;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.scene.style.Drawable; import io.anuke.ucore.scene.style.Drawable;
@@ -14,6 +13,7 @@ import io.anuke.ucore.scene.ui.ScrollPane;
import io.anuke.ucore.scene.ui.TextButton; import io.anuke.ucore.scene.ui.TextButton;
import io.anuke.ucore.scene.ui.layout.Table; import io.anuke.ucore.scene.ui.layout.Table;
import io.anuke.ucore.util.Bundles; import io.anuke.ucore.util.Bundles;
import io.anuke.ucore.util.Log;
import io.anuke.ucore.util.Strings; import io.anuke.ucore.util.Strings;
import static io.anuke.mindustry.Vars.ui; import static io.anuke.mindustry.Vars.ui;
@@ -238,7 +238,7 @@ public class JoinDialog extends FloatingDialog {
ui.showError(Bundles.format("text.connectfail", error)); ui.showError(Bundles.format("text.connectfail", error));
ui.loadfrag.hide(); ui.loadfrag.hide();
UCore.error(e); Log.err(e);
} }
}); });
} }

View File

@@ -1,16 +1,17 @@
package io.anuke.mindustry.ui.dialogs; package io.anuke.mindustry.ui.dialogs;
import static io.anuke.mindustry.Vars.*;
import io.anuke.mindustry.io.Platform; import io.anuke.mindustry.io.Platform;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Settings; import io.anuke.ucore.core.Settings;
import io.anuke.ucore.scene.ui.ButtonGroup; import io.anuke.ucore.scene.ui.ButtonGroup;
import io.anuke.ucore.scene.ui.ScrollPane; import io.anuke.ucore.scene.ui.ScrollPane;
import io.anuke.ucore.scene.ui.TextButton; import io.anuke.ucore.scene.ui.TextButton;
import io.anuke.ucore.scene.ui.layout.Table; import io.anuke.ucore.scene.ui.layout.Table;
import io.anuke.ucore.util.Log;
import java.util.Locale; import java.util.Locale;
import static io.anuke.mindustry.Vars.ui;
public class LanguageDialog extends FloatingDialog{ public class LanguageDialog extends FloatingDialog{
private Locale[] locales = {Locale.ENGLISH, new Locale("fr", "FR"), private Locale[] locales = {Locale.ENGLISH, new Locale("fr", "FR"),
new Locale("es", "LA"), new Locale("pt", "BR"), new Locale("ko"), new Locale("in", "ID")}; new Locale("es", "LA"), new Locale("pt", "BR"), new Locale("ko"), new Locale("in", "ID")};
@@ -36,7 +37,7 @@ public class LanguageDialog extends FloatingDialog{
if(ui.getLocale().equals(loc)) return; if(ui.getLocale().equals(loc)) return;
Settings.putString("locale", loc.toString()); Settings.putString("locale", loc.toString());
Settings.save(); Settings.save();
UCore.log("Setting locale: " + loc.toString()); Log.info("Setting locale: {0}", loc.toString());
ui.showInfo("$text.language.restart"); ui.showInfo("$text.language.restart");
}); });
langs.add(button).group(group).update(t -> { langs.add(button).group(group).update(t -> {

View File

@@ -4,13 +4,13 @@ import com.badlogic.gdx.utils.Array;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.io.SaveIO; import io.anuke.mindustry.io.SaveIO;
import io.anuke.mindustry.io.Saves.SaveSlot; import io.anuke.mindustry.io.Saves.SaveSlot;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Core; import io.anuke.ucore.core.Core;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.scene.ui.ScrollPane; import io.anuke.ucore.scene.ui.ScrollPane;
import io.anuke.ucore.scene.ui.TextButton; import io.anuke.ucore.scene.ui.TextButton;
import io.anuke.ucore.scene.ui.layout.Table; import io.anuke.ucore.scene.ui.layout.Table;
import io.anuke.ucore.util.Bundles; import io.anuke.ucore.util.Bundles;
import io.anuke.ucore.util.Log;
import io.anuke.ucore.util.Strings; import io.anuke.ucore.util.Strings;
import java.io.IOException; import java.io.IOException;
@@ -163,7 +163,7 @@ public class LoadDialog extends FloatingDialog{
state.set(State.playing); state.set(State.playing);
ui.paused.hide(); ui.paused.hide();
}catch(Exception e){ }catch(Exception e){
UCore.error(e); Log.err(e);
ui.paused.hide(); ui.paused.hide();
state.set(State.menu); state.set(State.menu);
logic.reset(); logic.reset();

View File

@@ -156,9 +156,9 @@ public class HudFragment implements Fragment{
row(); row();
new label(() -> "[blue]requests: " + renderer.getBlocks().getRequests()).left(); new label(() -> "[blue]requests: " + renderer.getBlocks().getRequests()).left();
row(); row();
new label(() -> "[purple]tiles: " + tileGroup.amount()).left(); new label(() -> "[purple]tiles: " + tileGroup.size()).left();
row(); row();
new label(() -> "[purple]enemies: " + enemyGroup.amount()).left(); new label(() -> "[purple]enemies: " + enemyGroup.size()).left();
row(); row();
new label(() -> "[orange]noclip: " + noclip).left(); new label(() -> "[orange]noclip: " + noclip).left();
row(); row();
@@ -178,7 +178,7 @@ public class HudFragment implements Fragment{
if(debugNet) { if(debugNet) {
new table() {{ new table() {{
new label(() -> "players: " + playerGroup.amount()); new label(() -> "players: " + playerGroup.size());
row(); row();
new label(() -> "" + playerGroup.all()); new label(() -> "" + playerGroup.all());
}}.end(); }}.end();

View File

@@ -26,8 +26,8 @@ public class PlayerListFragment implements Fragment{
new table(){{ new table(){{
new table("pane"){{ new table("pane"){{
margin(14f); margin(14f);
new label(() -> Bundles.format(playerGroup.amount() == 1 ? "text.players.single" : new label(() -> Bundles.format(playerGroup.size() == 1 ? "text.players.single" :
"text.players", playerGroup.amount())); "text.players", playerGroup.size()));
row(); row();
content.marginRight(13f).marginLeft(13f); content.marginRight(13f).marginLeft(13f);
ScrollPane pane = new ScrollPane(content, "clear"); ScrollPane pane = new ScrollPane(content, "clear");
@@ -51,9 +51,9 @@ public class PlayerListFragment implements Fragment{
if(!(Net.active() && !state.is(State.menu))){ if(!(Net.active() && !state.is(State.menu))){
visible = false; visible = false;
} }
if(playerGroup.amount() != last){ if(playerGroup.size() != last){
rebuild(); rebuild();
last = playerGroup.amount(); last = playerGroup.size();
} }
}); });

View File

@@ -3,8 +3,8 @@ package io.anuke.mindustry.world.blocks.types.distribution;
import io.anuke.mindustry.resource.Item; import io.anuke.mindustry.resource.Item;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.ucore.UCore;
import io.anuke.ucore.core.Timers; import io.anuke.ucore.core.Timers;
import io.anuke.ucore.util.Log;
public class TunnelConveyor extends Block{ public class TunnelConveyor extends Block{
protected int maxdist = 3; protected int maxdist = 3;
@@ -32,10 +32,11 @@ public class TunnelConveyor extends Block{
Timers.run(25, () -> { Timers.run(25, () -> {
if(to.block() != before) return; if(to.block() != before) return;
//TODO fix
try { try {
to.block().handleItem(item, to, tunnel); to.block().handleItem(item, to, tunnel);
}catch (NullPointerException e){ }catch (NullPointerException e){
UCore.error(e); Log.err(e);
} }
}); });
} }

View File

@@ -12,8 +12,8 @@ import io.anuke.mindustry.net.Packet;
import io.anuke.mindustry.net.Packets.Connect; import io.anuke.mindustry.net.Packets.Connect;
import io.anuke.mindustry.net.Packets.Disconnect; import io.anuke.mindustry.net.Packets.Disconnect;
import io.anuke.mindustry.net.Registrator; import io.anuke.mindustry.net.Registrator;
import io.anuke.ucore.UCore;
import io.anuke.ucore.function.Consumer; import io.anuke.ucore.function.Consumer;
import io.anuke.ucore.util.Log;
import org.java_websocket.client.WebSocketClient; import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455; import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshake;
@@ -32,7 +32,7 @@ public class JavaWebsocketClient implements ClientProvider {
public void connect(String ip, int port) throws IOException { public void connect(String ip, int port) throws IOException {
try { try {
URI i = new URI("ws://" + ip + ":" + Vars.webPort); URI i = new URI("ws://" + ip + ":" + Vars.webPort);
UCore.log("Connecting: " + i); Log.info("Connecting: {0}", i);
socket = new WebSocketClient(i, new Draft_6455(), null, 5000) { socket = new WebSocketClient(i, new Draft_6455(), null, 5000) {
Thread thread; Thread thread;
@@ -47,14 +47,13 @@ public class JavaWebsocketClient implements ClientProvider {
@Override @Override
public void onOpen(ServerHandshake handshakedata) { public void onOpen(ServerHandshake handshakedata) {
UCore.log("Connected!"); Log.info("Connected!");
Connect connect = new Connect(); Connect connect = new Connect();
Net.handleClientReceived(connect); Net.handleClientReceived(connect);
} }
@Override @Override
public void onMessage(String message) { public void onMessage(String message) {
if(debug) UCore.log("Got message: " + message);
try { try {
byte[] bytes = Base64Coder.decode(message); byte[] bytes = Base64Coder.decode(message);
ByteBuffer buffer = ByteBuffer.wrap(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes);
@@ -63,7 +62,6 @@ public class JavaWebsocketClient implements ClientProvider {
//this is a framework message... do nothing yet? //this is a framework message... do nothing yet?
} else { } else {
Class<?> type = Registrator.getByID(id); Class<?> type = Registrator.getByID(id);
if(debug) UCore.log("Got class ID: " + type);
Packet packet = (Packet) ClassReflection.newInstance(type); Packet packet = (Packet) ClassReflection.newInstance(type);
packet.read(buffer); packet.read(buffer);
Net.handleClientReceived(packet); Net.handleClientReceived(packet);
@@ -76,7 +74,6 @@ public class JavaWebsocketClient implements ClientProvider {
@Override @Override
public void onClose(int code, String reason, boolean remote) { public void onClose(int code, String reason, boolean remote) {
if(debug) UCore.log("Closed.");
Disconnect disconnect = new Disconnect(); Disconnect disconnect = new Disconnect();
Net.handleClientReceived(disconnect); Net.handleClientReceived(disconnect);
} }
@@ -105,7 +102,6 @@ public class JavaWebsocketClient implements ClientProvider {
byte[] out = new byte[pos]; byte[] out = new byte[pos];
buffer.get(out); buffer.get(out);
String string = new String(Base64Coder.encode(out)); String string = new String(Base64Coder.encode(out));
if(debug) UCore.log("Sending string: " + string);
socket.send(string); socket.send(string);
} }

View File

@@ -12,17 +12,19 @@ import io.anuke.mindustry.net.Net.ClientProvider;
import io.anuke.mindustry.net.Net.SendMode; import io.anuke.mindustry.net.Net.SendMode;
import io.anuke.mindustry.net.Packets.Connect; import io.anuke.mindustry.net.Packets.Connect;
import io.anuke.mindustry.net.Packets.Disconnect; import io.anuke.mindustry.net.Packets.Disconnect;
import io.anuke.ucore.UCore;
import io.anuke.ucore.function.Consumer; import io.anuke.ucore.function.Consumer;
import io.anuke.ucore.util.Log;
import java.io.IOException; import java.io.IOException;
import java.net.DatagramPacket; import java.net.DatagramPacket;
import java.net.DatagramSocket; import java.net.DatagramSocket;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.util.List; import java.util.List;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.netClient;
import static io.anuke.mindustry.Vars.port;
public class KryoClient implements ClientProvider{ public class KryoClient implements ClientProvider{
Client client; Client client;
@@ -41,7 +43,7 @@ public class KryoClient implements ClientProvider{
ByteBuffer buffer = ByteBuffer.wrap(datagramPacket.getData()); ByteBuffer buffer = ByteBuffer.wrap(datagramPacket.getData());
Host address = KryoRegistrator.readServerData(datagramPacket.getAddress(), buffer); Host address = KryoRegistrator.readServerData(datagramPacket.getAddress(), buffer);
addresses.put(datagramPacket.getAddress(), address); addresses.put(datagramPacket.getAddress(), address);
UCore.log("Host data found: " + buffer.capacity() + " bytes."); Log.info("Host data found: {0} bytes.", buffer.capacity());
} }
@Override @Override
@@ -106,7 +108,7 @@ public class KryoClient implements ClientProvider{
try{ try{
client.run(); client.run();
}catch (Exception e){ }catch (Exception e){
handleException(e); if(!(e instanceof ClosedSelectorException)) handleException(e);
} }
}, "Kryonet Client"); }, "Kryonet Client");
updateThread.setDaemon(true); updateThread.setDaemon(true);

View File

@@ -1,29 +1,57 @@
package io.anuke.kryonet; package io.anuke.kryonet;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.minlog.Log;
import com.esotericsoftware.minlog.Log.Logger;
import io.anuke.mindustry.Vars; import io.anuke.mindustry.Vars;
import io.anuke.mindustry.net.Host; import io.anuke.mindustry.net.Host;
import io.anuke.mindustry.net.Net; import io.anuke.ucore.util.ColorCodes;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import static io.anuke.mindustry.Vars.headless;
import static io.anuke.mindustry.Vars.playerGroup;
public class KryoRegistrator { public class KryoRegistrator {
public static boolean fakeLag = false; public static boolean fakeLag = false;
public static final int fakeLagAmount = 500; public static final int fakeLagAmount = 500;
public static void register(Kryo kryo){ static{
//TODO register stuff? Log.setLogger(new Logger(){
//Log.set(Log.LEVEL_DEBUG); public void log (int level, String category, String message, Throwable ex) {
StringBuilder builder = new StringBuilder(256);
if(headless)
builder.append(ColorCodes.BLUE);
builder.append("Net: ");
builder.append(message);
if (ex != null) {
StringWriter writer = new StringWriter(256);
ex.printStackTrace(new PrintWriter(writer));
builder.append('\n');
builder.append(writer.toString().trim());
}
if(headless)
builder.append(ColorCodes.RESET);
io.anuke.ucore.util.Log.info("&b" + builder.toString());
}
});
} }
public static ByteBuffer writeServerData(){ public static ByteBuffer writeServerData(){
String host = Vars.headless ? "Server" : Vars.player.name; String host = headless ? "Server" : Vars.player.name;
ByteBuffer buffer = ByteBuffer.allocate(1 + host.getBytes().length + 4); ByteBuffer buffer = ByteBuffer.allocate(1 + host.getBytes().length + 4);
buffer.put((byte)host.getBytes().length); buffer.put((byte)host.getBytes().length);
buffer.put(host.getBytes()); buffer.put(host.getBytes());
buffer.putInt(Net.getConnections().size + 1); buffer.putInt(playerGroup.size());
return buffer; return buffer;
} }

View File

@@ -23,6 +23,7 @@ import io.anuke.mindustry.net.Streamable;
import io.anuke.mindustry.net.Streamable.StreamBegin; import io.anuke.mindustry.net.Streamable.StreamBegin;
import io.anuke.mindustry.net.Streamable.StreamChunk; import io.anuke.mindustry.net.Streamable.StreamChunk;
import io.anuke.ucore.UCore; import io.anuke.ucore.UCore;
import io.anuke.ucore.util.Log;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ClientHandshake;
@@ -32,7 +33,7 @@ import java.io.IOException;
import java.net.BindException; import java.net.BindException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Arrays; import java.nio.channels.ClosedSelectorException;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
public class KryoServer implements ServerProvider { public class KryoServer implements ServerProvider {
@@ -50,7 +51,7 @@ public class KryoServer implements ServerProvider {
server = new Server(4096*2, 2048, connection -> new ByteSerializer()); //TODO tweak server = new Server(4096*2, 2048, connection -> new ByteSerializer()); //TODO tweak
server.setDiscoveryHandler((datagramChannel, fromAddress) -> { server.setDiscoveryHandler((datagramChannel, fromAddress) -> {
ByteBuffer buffer = KryoRegistrator.writeServerData(); ByteBuffer buffer = KryoRegistrator.writeServerData();
UCore.log("Replying to discover request with buffer of size " + buffer.capacity()); Log.info("Replying to discover request with buffer of size {0}.", buffer.capacity());
buffer.position(0); buffer.position(0);
datagramChannel.send(buffer, fromAddress); datagramChannel.send(buffer, fromAddress);
return true; return true;
@@ -67,7 +68,6 @@ public class KryoServer implements ServerProvider {
c.addressTCP = connection.getRemoteAddressTCP().toString(); c.addressTCP = connection.getRemoteAddressTCP().toString();
connections.add(kn); connections.add(kn);
UCore.log("Adding connection #" + kn.id + " to list.");
Gdx.app.postRunnable(() -> Net.handleServerReceived(kn.id, c)); Gdx.app.postRunnable(() -> Net.handleServerReceived(kn.id, c));
} }
@@ -136,7 +136,7 @@ public class KryoServer implements ServerProvider {
try{ try{
server.run(); server.run();
}catch (Exception e){ }catch (Exception e){
handleException(e); if(!(e instanceof ClosedSelectorException)) handleException(e);
} }
}, "Kryonet Server"); }, "Kryonet Server");
thread.setDaemon(true); thread.setDaemon(true);
@@ -152,7 +152,7 @@ public class KryoServer implements ServerProvider {
Thread thread = new Thread(() ->{ Thread thread = new Thread(() ->{
try { try {
server.close(); server.close();
UCore.log("Killing web server..."); Log.info("Killing web server...");
try { try {
if (webServer != null) webServer.stop(1); //please die, right now if (webServer != null) webServer.stop(1); //please die, right now
}catch(Exception e){ }catch(Exception e){
@@ -164,7 +164,7 @@ public class KryoServer implements ServerProvider {
worker.interrupt(); worker.interrupt();
} }
} }
UCore.log("Killed web server."); Log.info("Killed web server.");
}catch (Exception e){ }catch (Exception e){
Gdx.app.postRunnable(() -> {throw new RuntimeException(e);}); Gdx.app.postRunnable(() -> {throw new RuntimeException(e);});
} }
@@ -260,7 +260,7 @@ public class KryoServer implements ServerProvider {
} }
try { try {
UCore.log("Disposing web server..."); Log.info("Disposing web server...");
if(webServer != null) webServer.stop(1); if(webServer != null) webServer.stop(1);
//kill them all //kill them all
@@ -269,7 +269,7 @@ public class KryoServer implements ServerProvider {
thread.interrupt(); thread.interrupt();
} }
} }
UCore.log("Killed web server."); Log.info("Killed web server.");
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); e.printStackTrace();
} }
@@ -334,14 +334,14 @@ public class KryoServer implements ServerProvider {
try { try {
synchronized (buffer) { synchronized (buffer) {
buffer.position(0); buffer.position(0);
if(debug) UCore.log("Sending object with ID " + Registrator.getID(object.getClass())); if(debug) Log.info("Sending object with ID {0}", Registrator.getID(object.getClass()));
serializer.write(buffer, object); serializer.write(buffer, object);
int pos = buffer.position(); int pos = buffer.position();
buffer.position(0); buffer.position(0);
byte[] out = new byte[pos]; byte[] out = new byte[pos];
buffer.get(out); buffer.get(out);
String string = new String(Base64Coder.encode(out)); String string = new String(Base64Coder.encode(out));
if(debug) UCore.log("Sending string: " + string); if(debug) Log.info("Sending string: {0}", string);
socket.send(string); socket.send(string);
} }
}catch (WebsocketNotConnectedException e){ }catch (WebsocketNotConnectedException e){
@@ -360,7 +360,7 @@ public class KryoServer implements ServerProvider {
} }
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); e.printStackTrace();
UCore.log("Disconnecting invalid client!"); Log.info("Disconnecting invalid client!");
connection.close(); connection.close();
} }
} }
@@ -387,7 +387,7 @@ public class KryoServer implements ServerProvider {
public void onOpen(WebSocket conn, ClientHandshake handshake) { public void onOpen(WebSocket conn, ClientHandshake handshake) {
Connect connect = new Connect(); Connect connect = new Connect();
connect.addressTCP = conn.getRemoteSocketAddress().toString(); connect.addressTCP = conn.getRemoteSocketAddress().toString();
UCore.log("Websocket connection recieved: " + connect.addressTCP); Log.info("Websocket connection recieved: {0}", connect.addressTCP);
KryoConnection kn = new KryoConnection(lastconnection ++, connect.addressTCP, conn); KryoConnection kn = new KryoConnection(lastconnection ++, connect.addressTCP, conn);
connections.add(kn); connections.add(kn);
} }
@@ -412,23 +412,20 @@ public class KryoServer implements ServerProvider {
conn.send("---" + connections.size() + "|" + Vars.player.name); conn.send("---" + connections.size() + "|" + Vars.player.name);
connections.remove(k); connections.remove(k);
}else { }else {
if (debug) UCore.log("Got message: " + message);
byte[] out = Base64Coder.decode(message); byte[] out = Base64Coder.decode(message);
if (debug) UCore.log("Decoded: " + Arrays.toString(out));
ByteBuffer buffer = ByteBuffer.wrap(out); ByteBuffer buffer = ByteBuffer.wrap(out);
Object o = serializer.read(buffer); Object o = serializer.read(buffer);
Net.handleServerReceived(k.id, o); Net.handleServerReceived(k.id, o);
} }
}catch (Exception e){ }catch (Exception e){
UCore.log("Error reading message!"); Log.err(e);
e.printStackTrace();
} }
} }
@Override @Override
public void onError(WebSocket conn, Exception ex) { public void onError(WebSocket conn, Exception ex) {
UCore.log("WS error:"); Log.info("WS error:");
ex.printStackTrace(); ex.printStackTrace();
if(ex instanceof BindException){ if(ex instanceof BindException){
Net.closeServer(); Net.closeServer();
@@ -441,7 +438,7 @@ public class KryoServer implements ServerProvider {
@Override @Override
public void onStart() { public void onStart() {
UCore.log("Web server started."); Log.info("Web server started.");
} }
} }