tcr/java/src/game/Game.java

2819 lines
97 KiB
Java
Raw Normal View History

2025-03-11 00:23:54 +01:00
package game;
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.IDN;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import javax.imageio.ImageIO;
import game.BaseVar.VarFunction;
import game.BoolVar.BoolFunction;
import game.EnumVar.EnumFunction;
import game.FloatVar.FloatFunction;
import game.IntVar.IntFunction;
import game.Variable.IntType;
import game.audio.AudioInterface;
import game.audio.SoundManager;
import game.audio.Volume;
import game.biome.Biome;
import game.block.Block;
import game.collect.Lists;
import game.collect.Maps;
import game.color.Colorizer;
import game.color.TextColor;
import game.entity.Entity;
import game.entity.animal.EntityHorse;
import game.entity.npc.Energy;
import game.entity.npc.EntityNPC;
import game.entity.types.EntityLiving;
import game.future.Futures;
import game.future.ListenableFuture;
import game.future.ListenableFutureTask;
import game.gui.GuiCheat;
import game.gui.GuiContainer;
import game.gui.GuiGameOver;
import game.gui.GuiInventory;
import game.init.BlockRegistry;
import game.init.Config;
import game.init.EntityRegistry;
import game.init.ItemRegistry;
import game.init.Registry;
import game.init.SoundEvent;
import game.inventory.InventoryPlayer;
import game.item.Item;
import game.item.ItemBlock;
import game.item.ItemControl;
import game.item.ItemStack;
import game.material.Material;
import game.model.ModelManager;
import game.network.IThreadListener;
import game.network.NetConnection;
import game.network.NetHandler.ThreadQuickExitException;
import game.network.NetHandlerLoginClient;
import game.network.NetHandlerPlayClient;
import game.network.PlayerController;
import game.packet.CPacketAction;
import game.packet.CPacketAction.Action;
import game.packet.CPacketCheat;
import game.packet.CPacketMessage;
import game.packet.HPacketHandshake;
import game.packet.LPacketPasswordResponse;
import game.potion.Potion;
import game.potion.PotionEffect;
import game.potion.PotionHelper;
import game.properties.IProperty;
import game.renderer.BlockRenderer;
import game.renderer.EntityRenderer;
import game.renderer.GlState;
import game.renderer.ItemRenderer;
import game.renderer.RenderGlobal;
import game.renderer.chunk.RenderChunk;
import game.renderer.entity.RenderItem;
import game.renderer.entity.RenderManager;
import game.renderer.particle.EffectRenderer;
import game.renderer.texture.EntityTexManager;
import game.renderer.texture.TextureManager;
import game.renderer.texture.TextureMap;
import game.rng.Random;
import game.world.BlockPos;
import game.world.Chunk;
import game.world.Converter;
import game.world.Facing;
import game.world.HitPosition;
import game.world.HitPosition.ObjectType;
import game.world.LightType;
import game.world.Region;
import game.world.State;
import game.world.World;
import game.world.WorldClient;
import game.world.WorldServer;
/*
Een net ganz funktionierndes Programm ...
Absolute Mindestanforderungen:
Prozessor : Intel Core i3 530 oder AMD Phenom 2 X2 545
Grafikkarte : NVIDIA GeForce GTS 450 oder AMD Radeon HD 7730
Arbeitsspeicher : Etwa 512 MB ~ 1 GB, 2 - 4 GB empfohlen
Mainboard : Was gerade passt (auch mit Hammer)
Kühler : Ne Klimaanlage oder ordentlich Pusten
Festplatte : Richtet sich nach der Geduld des Nutzers
Netzteil : Atomkraftwerk oder stabiler Energiekern
Gehäuse : Pappkarton, Bierkasten oder auch gar keins
Tastatur : Hlb fktonrnd odr bsr
Maus : Aus Plastik oder mit extra Quietsch-Effekt
Monitor : Olle Röhre oder gebrochener Flachbild (Mindestens 1280x800)
Stuhl : Interessiert niemanden (sonst siehe Gehäuse)
[[oder einfach einen Toaster mit nem LCD und Maus]]
*/
public class Game implements IThreadListener {
public static class SyncFunction implements IntFunction {
public void apply(IntVar cv, int value) {
Game.getGame().sync(value);
}
}
public static class TickFunction implements FloatFunction {
public void apply(FloatVar cv, float value) {
Game.getGame().tick_target(value);
}
}
public static class ConFunction implements IntFunction {
public void apply(IntVar cv, int value) {
Game.getGame().resize(value);
}
}
public static class DistanceFunction implements IntFunction {
public void apply(IntVar cv, int value) {
if(Game.getGame().renderGlobal != null)
Game.getGame().renderGlobal.setDisplayListEntitiesDirty();
Game.getGame().distance(value);
}
}
public static final int LOG_BUFFER = 32768;
private final Queue<FutureTask<?>> tasks = new ArrayDeque<FutureTask<?>>();
private final Map<Integer, Long> bars = Maps.newTreeMap();
private final Thread clThread = Thread.currentThread();
private final Map<String, CVar> cvars = Maps.newTreeMap();
private final List<Message> log = Lists.newArrayList();
private final File config = new File(System.getProperty("config.file", "game.cfg"));
private boolean primary;
private boolean secondary;
private boolean tertiary;
private boolean quarternary;
public boolean jump;
public boolean sneak;
public boolean debugCamEnable;
public boolean debugWorld;
public boolean zooming;
public boolean sprint;
public boolean renderOutlines;
public boolean setGamma;
public boolean nickChanged;
public boolean xrayActive;
public boolean tileOverlay;
public boolean itemCheat;
public boolean dayCycle = true;
private int leftClickCounter;
private int rightClickTimer;
private int chunkLoadTimer;
public int thirdPersonView;
public int timeFactor = 1;
public int chunksUpdated;
private long lastTicked = 0L;
private long debugUpdateTime = System.currentTimeMillis();
private long tickStart;
private float deltaX;
private float deltaY;
public float moveStrafe;
public float moveForward;
public float zoomLevel;
public float gravity = 1.0f;
private TextureManager textureManager;
private RenderManager renderManager;
private RenderItem renderItem;
private ItemRenderer itemRenderer;
public RenderGlobal renderGlobal;
public EffectRenderer effectRenderer;
public EntityRenderer entityRenderer;
private TextureMap textureMap;
private ModelManager modelManager;
private BlockRenderer blockRenderer;
public Gui open;
private SoundManager soundManager;
private NetConnection connection;
private Entity viewEntity;
private Entity pointedEntity;
private BufferedImage skin;
private Object popupTarget;
public PlayerController controller;
public WorldClient theWorld;
public EntityNPC thePlayer;
public HitPosition pointed;
@Variable(name = "chunk_view_distance", category = CVarCategory.WORLD, min = 2, max = 128, callback = DistanceFunction.class, display = "Sichtweite", unit = "Chunks")
public int renderDistance = 8;
@Variable(name = "chunk_build_time", category = CVarCategory.WORLD, min = 1, max = 100, display = "Max. Zeit für Chunk-Bau pro Frame", unit = "ms")
public int maxBuildTime = 8;
@Variable(name = "gl_fov", category = CVarCategory.RENDER, min = 1.0f, max = 179.0f, display = "Sichtfeld (FOV)", unit = "°", precision = 1)
public float fov = 70.0f;
@Variable(name = "gl_wireframe", category = CVarCategory.RENDER)
public boolean wireframe = false;
@Variable(name = "con_timestamps", category = CVarCategory.CONSOLE, display = "Zeiten")
public boolean conTimestamps = false;
@Variable(name = "con_loglevel", category = CVarCategory.CONSOLE, display = "Ausgabe")
public LogLevel level = LogLevel.INFO;
@Variable(name = "win_sync", category = CVarCategory.WINDOW, min = -1, max = 16384, callback = SyncFunction.class)
public int sync = 0;
public int width;
public int height;
public int mouse_x;
public int mouse_y;
@Variable(name = "win_width", category = CVarCategory.WINDOW, min = 1, max = 65536)
public int xsize = 1280;
@Variable(name = "win_height", category = CVarCategory.WINDOW, min = 1, max = 65536)
public int ysize = 800;
@Variable(name = "win_pos_x", category = CVarCategory.WINDOW, min = -65536, max = 65536)
public int saved_xpos = 0x80000000;
@Variable(name = "win_pos_y", category = CVarCategory.WINDOW, min = -65536, max = 65536)
public int saved_ypos = 0x80000000;
public int fb_x;
public int fb_y;
@Variable(name = "phy_sensitivity", category = CVarCategory.PHYSICS, min = 0.01f, max = 10.0f, display = "Mausempfindlichkeit", precision = 2, unit = "%")
public float sensitivity = 1.0f;
public boolean fullscreen;
public long syncLimit;
public boolean mouseFirst;
public boolean nograb = System.getProperty("mouse.nograb") != null;
public DisplayMode vidMode;
@Variable(name = "gui_dclick_delay", category = CVarCategory.GUI, min = 150, max = 750, display = "Doppelklick bei", unit = "ms")
public int dclickDelay = 250;
@Variable(name = "con_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ConFunction.class, display = "Nachrichten im Overlay")
public int hudSize = 32;
@Variable(name = "con_fadeout", category = CVarCategory.CONSOLE, min = 100, max = 60000, display = "Dauer bis zum Ausblenden", unit = "ms")
public int hudFadeout = 5000;
@Variable(name = "con_overlay", category = CVarCategory.CONSOLE, display = "Konsolen-Overlay")
public boolean hudOverlay = true;
@Variable(name = "con_position", category = CVarCategory.CONSOLE, display = "Position")
public ConsolePos hudPos = ConsolePos.BOTTOM;
@Variable(name = "con_opacity", category = CVarCategory.CONSOLE, min = 0x00, max = 0xff, display = "Deckkraft Hintergrund")
public int hudOpacity = 0x40;
public boolean syncLimited;
public boolean vsync;
public boolean screenshot;
public boolean saving;
public boolean drawFps;
public boolean drawDebug;
@Variable(name = "gl_vsync_flush", category = CVarCategory.RENDER, display = "Puffer vor Synch. leeren")
public boolean glFlush = false;
@Variable(name = "con_autoclose", category = CVarCategory.CONSOLE, display = "Schließen")
public boolean conAutoclose = true;
public boolean interrupted;
public List<DisplayMode> vid_modes = Lists.newArrayList();
public List<Message> messages = Lists.newArrayList();
@Variable(name = "gui_theme", category = CVarCategory.STYLE)
public Style style = Style.DEFAULT;
public List<Style> themes;
@Variable(name = "gui_scroll_lines", category = CVarCategory.GUI, min = 1, max = 10, display = "Scrollbreite", unit = "Zeilen#")
public int scrollLines = 3;
@Variable(name = "tic_target", category = CVarCategory.PHYSICS, min = 1.0f, max = 1200.0f, callback = TickFunction.class)
public float tpsTarget = 20.0f;
@Variable(name = "tic_timeout", category = CVarCategory.PHYSICS, min = 1, max = 60000)
public int tickTimeout = 2000;
@Variable(name = "srv_port", category = CVarCategory.WORLD, min = 0, max = 65535)
public int port = 26666;
public int bind = -1;
@Variable(name = "snd_device_type", category = CVarCategory.SOUND, display = "Tonausgabe")
public boolean soundEnabled = true;
@Variable(name = "snd_buffer_size", category = CVarCategory.SOUND, min = 0, max = 1048576, display = "Puffergröße")
public int soundBufferSize = 2048;
@Variable(name = "snd_frame_size", category = CVarCategory.SOUND, min = 2, max = 8192, display = "PCM-Intervall")
public int soundFrameSize = 32;
private Server server;
private AudioInterface audio;
private long start;
private boolean cfgDirty;
private String buffer = "";
private boolean crashed;
private static final Game INSTANCE = new Game();
private final Bind[] keyBindsHotbar = new Bind[] {
Bind.SELECT1, Bind.SELECT2, Bind.SELECT3, Bind.SELECT4, Bind.SELECT5, Bind.SELECT6, Bind.SELECT7, Bind.SELECT8, Bind.SELECT9
};
2025-03-11 00:48:54 +01:00
2025-03-11 00:23:54 +01:00
private Game() {
}
public static Game getGame() {
return INSTANCE;
}
public void connect(String address, int port, String user, String pass, String access) {
Log.JNI.info("Verbinde zu " + address + ":" + port);
NetConnection connection = null;
try
{
connection = NetConnection.createNetworkManagerAndConnect(InetAddress.getByName(IDN.toASCII(address)), port);
connection.setNetHandler(new NetHandlerLoginClient(connection, this));
connection.sendPacket(new HPacketHandshake(Config.PROTOCOL));
connection.sendPacket(new LPacketPasswordResponse(user, access, pass));
}
catch (UnknownHostException u)
{
Log.JNI.error(u, "Konnte nicht zu Server verbinden");
this.disconnected("Unbekannter Hostname: " + address);
return;
}
catch (Exception e)
{
Log.JNI.error(e, "Konnte nicht zu Server verbinden");
this.disconnected(e.toString());
return;
}
this.connection = connection;
}
public void connectToIntegrated(Server server, String user) {
this.debugWorld = server.getFolder() == null;
this.displayGuiScreen(null);
SocketAddress socket = server.setLocalEndpoint();
NetConnection connection = NetConnection.provideLocalClient(socket);
connection.setNetHandler(new NetHandlerLoginClient(connection, this));
connection.sendPacket(new HPacketHandshake(Config.PROTOCOL));
connection.sendPacket(new LPacketPasswordResponse(user, "", ""));
this.connection = connection;
}
public void unloadWorld() {
NetHandlerPlayClient netHandler = this.getNetHandler();
if(netHandler != null)
netHandler.cleanup();
this.debugWorld = false;
this.viewEntity = null;
this.connection = null;
this.theWorld = null;
this.thePlayer = null;
this.soundManager.stopSounds();
}
public void refreshResources()
{
this.textureManager.onReload();
Colorizer.reload();
this.modelManager.onReload();
this.renderItem.onReload();
this.blockRenderer.onReload();
this.renderGlobal.onReload();
EntityTexManager.loadNpcTextures();
this.renderGlobal.loadRenderers();
}
public void init()
{
this.textureManager = new TextureManager();
this.textureManager.onReload();
this.soundManager = new SoundManager(this);
Colorizer.reload();
GlState.enableTexture2D();
GlState.shadeModel(7425);
GlState.clearDepth(1.0D);
GlState.enableDepth();
GlState.depthFunc(515);
GlState.enableAlpha();
GlState.alphaFunc(516, 0.1F);
GlState.cullFace(1029);
GlState.enableCull();
WCF.glMatrixMode(5889);
WCF.glLoadIdentity();
WCF.glMatrixMode(5888);
this.textureMap = new TextureMap();
this.textureManager.loadTexture(TextureMap.locationBlocksTexture, this.textureMap);
this.textureManager.bindTexture(TextureMap.locationBlocksTexture);
WCF.glTexParameteri(WCF.GL_TEXTURE_MIN_FILTER, WCF.GL_NEAREST);
WCF.glTexParameteri(WCF.GL_TEXTURE_MAG_FILTER, WCF.GL_NEAREST);
this.modelManager = new ModelManager(this.textureMap);
this.modelManager.onReload();
this.renderItem = new RenderItem(this.textureManager, this.modelManager);
this.renderManager = new RenderManager(this.textureManager, this.renderItem);
this.itemRenderer = new ItemRenderer(this);
this.renderItem.onReload();
this.entityRenderer = new EntityRenderer(this);
this.blockRenderer = new BlockRenderer(this.modelManager, this);
this.blockRenderer.onReload();
this.renderGlobal = new RenderGlobal(this);
this.renderGlobal.onReload();
EntityTexManager.loadNpcTextures();
this.effectRenderer = new EffectRenderer(this.theWorld, this.textureManager);
new File("skins").mkdirs();
}
public void start()
{
this.tickStart = System.nanoTime();
synchronized (this.tasks)
{
while (!this.tasks.isEmpty())
{
FutureTask<?> task = this.tasks.poll();
try {
task.run();
task.get();
}
catch(ExecutionException e1) {
if(!(e1.getCause() instanceof ThreadQuickExitException))
Log.JNI.error(e1, "Fehler beim Ausführen von Render-Task " + task);
}
catch(InterruptedException e2) {
Log.JNI.error(e2, "Fehler beim Ausführen von Render-Task " + task);
}
}
}
}
public void inputGui() {
if (this.open != null)
{
if(Bind.THROW.isPressed())
this.open.dropItem();
for(int z = 0; z < this.keyBindsHotbar.length; z++) {
if(this.keyBindsHotbar[z].isPressed())
this.open.useHotbar(z);
}
this.primary = this.secondary = this.tertiary = this.quarternary = false;
this.zooming = false;
}
2025-03-11 01:10:34 +01:00
else
2025-03-11 00:23:54 +01:00
{
if (Bind.PERSPECTIVE.isPressed())
{
++this.thirdPersonView;
if (this.thirdPersonView > 2)
{
this.thirdPersonView = 0;
}
if (this.debugCamEnable && this.thirdPersonView == 2)
{
this.thirdPersonView = 0;
}
this.renderGlobal.setDisplayListEntitiesDirty();
}
boolean hadZoom = this.zooming;
this.zooming = Bind.ZOOM.isDown();
if(this.zooming && !hadZoom) {
this.zoomLevel = 2.0f;
}
// this.overlay = this.keyBindPlayerList.isKeyDown();
for (int l = 0; l < 9; ++l)
{
if (this.keyBindsHotbar[l].isPressed())
{
// if(!this.showDebugProfilerChart) {
this.thePlayer.inventory.currentItem = l;
// }
}
}
// if (SKC.isBindPressed(SKC.KEY_INVENTORY))
// {
// }
if (Bind.THROW.isPressed())
{
this.thePlayer.dropOneItem(this.ctrl());
}
this.primary |= Bind.PRIMARY.isPressed();
this.secondary |= Bind.SECONDARY.isPressed();
this.tertiary |= Bind.TERTIARY.isPressed();
this.quarternary |= Bind.QUARTERNARY.isPressed();
}
}
public void tick() {
if (this.rightClickTimer > 0)
{
--this.rightClickTimer;
}
// this.ingameGui.updateTick();
this.entityRenderer.getMouseOver(1.0F);
if (/* !this.paused && */ this.theWorld != null)
{
this.controller.updateController();
}
this.textureMap.updateAnimations();
if (this.open != null)
{
this.open.updateScreen();
}
if (this.open == null && this.thePlayer != null)
{
if (this.thePlayer.getHealth() <= 0)
{
this.displayGuiScreen(null);
}
}
if (this.open != null)
{
this.leftClickCounter = 10000;
}
else if (this.leftClickCounter > 0)
{
--this.leftClickCounter;
}
if (this.open == null && this.thePlayer != null) {
if (this.thePlayer.isUsingItem())
{
if (!Bind.SECONDARY.isDown())
{
this.controller.onStoppedUsingItem(this.thePlayer);
}
}
else
{
if (this.primary)
{
this.primary();
}
if (this.secondary)
{
this.secondary();
}
if (this.tertiary)
{
this.tertiary();
}
if (this.quarternary)
{
this.quarternary();
}
}
if (Bind.SECONDARY.isDown() && this.rightClickTimer == 0 && !this.thePlayer.isUsingItem())
{
this.secondary();
}
this.sendClickBlockToController(this.open == null && Bind.PRIMARY.isDown());
}
this.primary = this.secondary = this.tertiary = this.quarternary = false;
if (this.theWorld != null)
{
if (this.thePlayer != null)
{
++this.chunkLoadTimer;
if (this.chunkLoadTimer == 30)
{
this.chunkLoadTimer = 0;
this.theWorld.ensureAreaLoaded(this.thePlayer);
}
}
this.entityRenderer.updateRenderer();
this.renderGlobal.updateClouds();
this.theWorld.decrLightning();
this.theWorld.updateEntities();
}
this.soundManager.update();
if (this.theWorld != null)
{
this.theWorld.tick();
if (/* !this.paused && */ this.theWorld != null)
{
this.theWorld.displayTick(ExtMath.floord(this.thePlayer.posX), ExtMath.floord(this.thePlayer.posY), ExtMath.floord(this.thePlayer.posZ));
}
this.effectRenderer.updateEffects();
}
else if (this.connection != null)
{
this.connection.processReceivedPackets();
}
}
public void render() {
GlState.tryBlendFuncSeparate(WCF.GL_SRC_ALPHA, WCF.GL_ONE_MINUS_SRC_ALPHA, WCF.GL_SRC_ALPHA, WCF.GL_ONE_MINUS_SRC_ALPHA);
GlState.enableDepth();
GlState.clearColor(0.0f, 0.0f, 0.0f, 1.0f);
WCF.glClear(WCF.GL_COLOR_BUFFER_BIT | WCF.GL_DEPTH_BUFFER_BIT);
if(this.wireframe) {
WCF.glLineWidth(1.0f);
WCF.glPolygonMode(true); // GL_FRONT_AND_BACK, GL_LINE
}
if(this.open == null) {
if(this.thePlayer != null)
this.thePlayer.setAngles(this.deltaX, this.deltaY);
this.deltaX = this.deltaY = 0.0f;
}
if(this.thePlayer != null)
this.soundManager.setListener(this.thePlayer, (float)Timing.tick_fraction);
if(this.thePlayer != null && this.thePlayer.isEntityInsideOpaqueBlock())
this.thirdPersonView = 0;
WCF.glPushMatrix();
WCF.glClear(16640);
GlState.enableTexture2D();
if(this.theWorld != null)
this.entityRenderer.renderWorld((float)Timing.tick_fraction, System.nanoTime() - this.tickStart);
WCF.glPopMatrix();
GlState.disableTexture2D();
GlState.disableCull();
GlState.enableBlend();
if(this.wireframe)
WCF.glPolygonMode(false); // GL_FRONT_AND_BACK, GL_FILL
}
private static int stats(int x, int y, String name, int value, int max, int color) {
int w = (int)(246.0f * (float)value / (float)max);
Drawing.drawTextboxRight(name, x + 250, y, 0x3f000000);
Drawing.drawTextbox(String.format(TextColor.GREEN + "%d " + TextColor.GRAY + "/ " + TextColor.NEON + "%d", value, max), x, y, 0x3f000000);
// Drawing.drawRectColor(x, y + 20, 250, 10, 0xff000000);
Drawing.drawRect2GradBorder(x, y + 20, 250, 10, 0xff000000, 0xff202020, 0xffcfcfcf, 0xff9f9f9f, 0xff9f9f9f, 0xff6f6f6f);
Drawing.drawGradient(x + 2 + 246 - w, y + 20 + 2, w, 6, color | 0xff000000, Drawing.mixColor(color | 0xff000000, 0xff000000));
return y + 40;
}
private static int bar(int x, int y, String name, float fill, int color) {
Drawing.drawTextbox(name, x, y, 0x3f000000);
// Drawing.drawRectColor(x, y + 20, 250, 10, 0xff000000);
// Drawing.drawRectColor(x, y + 20, (int)(250.0f * fill), 10, color | 0xff000000);
Drawing.drawRect2GradBorder(x, y + 20, 250, 10, 0xff000000, 0xff202020, 0xffcfcfcf, 0xff9f9f9f, 0xff9f9f9f, 0xff6f6f6f);
Drawing.drawGradient(x + 2, y + 20 + 2, (int)(246.0f * fill), 6, color | 0xff000000, Drawing.mixColor(color | 0xff000000, 0xff000000));
return y + 40;
}
public void renderHud() {
this.setupOverlay();
if(this.theWorld != null && this.open == null && this.thirdPersonView == 0) {
Drawing.drawRectColor(this.fb_x / 2 - 1, this.fb_y / 2 - 16, 2, 32,
this.pointed != null && this.pointed.type != ObjectType.MISS ? 0xffffffff : 0xffcfcfcf);
Drawing.drawRectColor(this.fb_x / 2 - 16, this.fb_y / 2 - 1, 32, 2,
this.pointed != null && this.pointed.type != ObjectType.MISS ? 0xffffffff : 0xffcfcfcf);
}
if(this.theWorld != null && this.open == null) {
int selected = // this.getRenderViewEntity() != null && this.getRenderViewEntity().isPlayer() ? 9 : 0,
this.getRenderViewEntity() != null && this.getRenderViewEntity().isPlayer() ?
((EntityNPC)this.getRenderViewEntity()).inventory.currentItem : -1;
for(int n = 0; n < 9; n++) {
int x = this.fb_x / 2 - 180 + n * 40 + 4;
int y = this.fb_y - 40;
// Drawing.drawRect2Border(x - 1, y - 1, 36, 36, 0xff6f6f6f, selected == n ? 0xffffffff : 0xffafafaf);
Drawing.drawRect2GradBorder(x - 1, y - 1, 36, 36, 0xff6f6f6f, selected == n ? 0xffffffff : 0xff000000, 0xffafafaf, 0xff7f7f7f, 0xff7f7f7f, 0xff4f4f4f);
}
ItemStack itemstack = this.thePlayer != null ? this.thePlayer.inventory.getCurrentItem() : null;
String current = itemstack != null ? itemstack.getItem().getHotbarText(this.thePlayer, itemstack) : "";
if(!current.isEmpty())
Drawing.drawTextUpward(current, this.fb_x / 2, this.fb_y - 80, 0xffffffff);
}
if(this.theWorld != null && !(this.open instanceof GuiConsole)) {
int x = this.fb_x / 2;
int y = 0;
Iterator<Entry<Integer, Long>> iter = this.bars.entrySet().iterator();
long now = System.currentTimeMillis();
while(iter.hasNext()) {
Entry<Integer, Long> status = iter.next();
Entity ent;
if(this.thePlayer != null && now - status.getValue() < 10000L && (ent = this.thePlayer.worldObj.getEntityByID(status.getKey())) instanceof EntityLiving) {
EntityLiving entity = (EntityLiving)ent;
String s = entity.getName() + TextColor.GRAY + " [" +
EntityLiving.getHealthColor(entity.getHealth(), entity.getMaxHealth()) +
entity.getHealth() + TextColor.GRAY + " / " + EntityLiving.getMaxHpColor(entity.getMaxHealth()) +
entity.getMaxHealth() + TextColor.GRAY + "]";
Drawing.drawTextboxCentered(s, x, y, 0x3f000000);
Drawing.drawRectColor(x - 200, y + 20, 400, 10, 0xff000000);
Drawing.drawRectColor(x - 200, y + 20, (int)(400.0f * ((float)entity.getHealth() / (float)entity.getMaxHealth())), 10, 0xff000000 | entity.getColor());
y += 40;
}
else {
iter.remove();
}
}
if(this.thePlayer != null && (!this.drawDebug || this.open != null)) {
x = 40;
y = 40;
for(PotionEffect effect : this.thePlayer.getEffects()) {
Potion potion = Potion.POTION_TYPES[effect.getPotionID()];
int color = potion.getLiquidColor();
String name = (potion.isBadEffect() ? TextColor.ORANGE : TextColor.ACID) + potion.getDisplay() + PotionHelper.getPotionPotency(effect.getAmplifier());
String desc = TextColor.NEON + Potion.getDurationString(effect);
// Drawing.drawRectColor(x, y, 250, Font.DEFAULT.yglyph + 2, color | 0xff000000);
Drawing.drawGradient2GradBorder(x, y, 250, Font.YGLYPH + 4, color | 0xff000000, Drawing.mixColor(color | 0xff000000, 0xff000000), 0xff202020, 0xffcfcfcf, 0xff9f9f9f, 0xff9f9f9f, 0xff6f6f6f);
Drawing.drawText(name, x + 2 + 2, y + 2, 0xffffffff);
Drawing.drawTextRight(desc, x + 250 - 2, y + 2, 0xffffffff);
y += 24;
}
}
if(this.getRenderViewEntity() instanceof EntityLiving) {
EntityLiving entity = (EntityLiving)this.getRenderViewEntity();
int absorb = entity.getAbsorptionAmount();
int armor = entity.getTotalArmorValue();
int stats = 1 + (absorb > 0 ? 1 : 0) + (armor > 0 ? 1 : 0) + (entity.vehicle instanceof EntityLiving ? 1 : 0)
+ (entity instanceof EntityNPC && ((EntityNPC)entity).canUseMagic() ? 1 : 0);
for(Energy energy : Energy.values()) {
if(entity.getEnergy(energy) > 0)
stats += 1;
}
x = this.fb_x - 40 - 250;
y = this.fb_y - 40 - stats * 40;
int hp = entity.getHealth();
int max = entity.getMaxHealth();
y = stats(x, y, TextColor.RED + "Schaden", hp, max, 0xff0000);
if(absorb > 0)
y = stats(x, y, TextColor.YELLOW + "Schadenspuffer", absorb, 1024, 0xffff00);
if(armor > 0)
y = stats(x, y, TextColor.GRAY + "Rüstung", armor, 1024, 0x707070);
if(entity.vehicle instanceof EntityLiving) {
EntityLiving living = (EntityLiving)entity.vehicle;
int vh = living.getHealth();
int vhMax = living.getMaxHealth();
y = stats(x, y, living.getDisplayName() /* + " (Reittier)" */, vh, vhMax, 0xff6060);
}
if(entity instanceof EntityNPC && ((EntityNPC)entity).canUseMagic()) {
int mana = entity.getManaPoints();
int maxm = entity.getMaxMana();
y = stats(x, y, TextColor.CYAN + "Mana", mana, maxm, 0x0000ff);
}
for(int z = 0; z < Energy.values().length; z++) {
Energy type = Energy.values()[z];
int energy = entity.getEnergy(type);
if(energy > 0) {
int emax = entity.getEnergyCap(type);
y = stats(x, y, TextColor.LGRAY + type.display, energy, emax, entity.hasEnergyEffect(type) ? type.effect : type.color);
}
}
}
if(this.thePlayer != null) {
x = 40;
y = this.fb_y - 40 - (this.thePlayer.isRidingHorse() && this.thePlayer.getHorseJumpPower() != 0.0f ? 2 : 1) * 40;
if(this.thePlayer.isRidingHorse() && this.thePlayer.getHorseJumpPower() != 0.0f) // {
y = bar(x, y, String.format(TextColor.NEON + "Sprungkraft: " + TextColor.CYAN + "%d %%", (int)(this.thePlayer.getHorseJumpPower() * 100.0f)),
this.thePlayer.getHorseJumpPower(), 0x4040ff);
// }
// else {
y = bar(x, y, String.format(TextColor.ACID + "EXP: " + TextColor.GREEN + "Level %d, %d/%d", this.thePlayer.experienceLevel, (int)((float)this.thePlayer.xpBarCap() * this.thePlayer.experience), this.thePlayer.xpBarCap()), this.thePlayer.experience, 0x40ff40);
// }
}
// SKC.pointed(this.pointed != null && this.pointed.type != ObjectType.MISS);
// SKC.crosshair(this.thirdPersonView == 0);
}
// gdr.shader = 0;
// glUseProgram(0);
// glBindVertexArray(0);
// glActiveTexture(GL_TEXTURE0);
// GlState.setActiveTexture(WCF.GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, 0);
GlState.bindTexture(0);
// jsys.tooltip[0] = 0;
// this.tooltip = null;
// GlState.resetTextures();
GlState.setActiveTexture(WCF.GL_TEXTURE0);
GlState.enableTexture2D();
// GlState.disableDepth();
if(this.open == null && this.getRenderViewEntity() != null && this.getRenderViewEntity().isPlayer()) {
EntityNPC player = (EntityNPC)this.getRenderViewEntity();
GlState.enableRescaleNormal();
GlState.enableBlend();
GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
// GlState.tryBlendFuncSeparate(770, 771, 1, 0);
ItemRenderer.enableGUIStandardItemLighting();
// this.getTextureManager().bindTexture("textures/gui/inventory.png");
WCF.glPushMatrix();
WCF.glTranslatef(this.fb_x / 2 - 180 + 4 + 1, this.fb_y - 40 + 1, 0.0f);
WCF.glScalef(2.0f, 2.0f, 2.0f);
for(int index = 0; index < 9; ++index) {
int xPos = index * 20;
// int yPos = this.fb_y - 40;
ItemStack itemstack = player.inventory.mainInventory[index];
if(itemstack != null) {
GlState.enableDepth();
this.renderItem.renderItemAndEffectIntoGUI(itemstack, xPos, 0);
// this.renderItem.renderItemOverlayIntoGUI(itemstack, xPos, 0, null);
}
}
WCF.glPopMatrix();
ItemRenderer.disableStandardItemLighting();
GlState.disableRescaleNormal();
GlState.disableBlend();
}
GlState.disableTexture2D();
GlState.disableCull();
GlState.enableBlend();
// SKC.gui();
// java_callv(gui, (sys.console->mouse_x - jsys.container_x) / 2, (sys.console->mouse_y - jsys.container_y) / 2);
// java_check_exc();
GlState.disableDepth();
// SKC.foreground();
if(this.open == null && this.getRenderViewEntity() != null && this.getRenderViewEntity().isPlayer()) {
EntityNPC player = (EntityNPC)this.getRenderViewEntity();
for(int index = 0; index < 9; ++index) {
ItemStack itemstack = player.inventory.mainInventory[index];
if(itemstack != null) {
GuiContainer.renderItemOverlay(itemstack,
this.fb_x / 2 - 180 + 4 + 1 + index * 40, this.fb_y - 40 + 1, null);
}
}
}
if(this.open != null)
this.open.render();
if(this.hudOverlay && !(this.open instanceof GuiConsole))
this.drawOverlay();
if(this.drawFps) { // && !(this.open instanceof GuiConsole)
if(this.drawDebug && this.open == null) {
this.renderStats();
}
else {
String str = String.format("%s%.2f", framecode(), Timing.framerate);
Drawing.txt_draw(0, 0,
0, 0,
this.fb_x, this.fb_y,
0xffffffff, str);
}
}
GlState.enableBlend();
}
public void renderStats() {
int offset = 5;
int x1 = this.fb_x - 320;
int y1 = 0;
int y2 = this.fb_y;
// int pos = 0;
String str = this.getldebug();
// if(jstr)
// str = (*jsys.env)->GetStringUTFChars(jsys.env, jstr, NULL);
// elem->r_dirty = 1;
// if(!value)
// return;
offset += str != null ? 18 : 0;
String draw = String.format(
"OpenGL: %s\n" +
"Renderer: %s (%s)\n" +
"Bildrate: %s%.2f" + TextColor.RESET + " %s [%s" + TextColor.RESET + "], %.3f ms, W %d x %d%s\n" +
"Tickrate: %s%.2f" + TextColor.RESET + " %s [" + TextColor.GREEN + "%.1f" + TextColor.RESET + "], %.3f ms, E %d ms" +
"%s%s"
,
WCF.glGetString(WCF.GL_VERSION), // WCF.glGetString(WCF.GL_SHADING_LANGUAGE_VERSION),
WCF.glGetString(WCF.GL_RENDERER), WCF.glGetString(WCF.GL_VENDOR),
this.framecode(), Timing.framerate < 1.0f ? 1.0f / Timing.framerate : Timing.framerate, Timing.framerate < 1.0f ? "SPF" : "FPS",
this.vsync ? TextColor.DGRAY + "VSYNC" : (this.syncLimited ? TextColor.GREEN + "" + this.syncLimit : TextColor.RED + "UNL"),
(float)PerfSection.getTotal(false) / 1000.0f, this.fb_x, this.fb_y,
this.fullscreen ? " @ " + (this.vidMode == null ? "?" : this.vidMode.refresh) + " Hz" : "",
this.tpscode(), Timing.tickrate < 1.0f ? 1.0f / Timing.tickrate : Timing.tickrate,
Timing.tickrate < 1.0f ? "SPT" : "TPS", (float)Timing.tickTarget / 1000.0f,
(float)Timing.tick_time / 1000.0f, this.tickTimeout,
str != null ? "\n" : "", str != null ? str : ""
);
// if(str)
// (*jsys.env)->ReleaseStringUTFChars(jsys.env, jstr, str);
// gui_render_text(elem, 0, 0, sys.style.text_label, sys.work_buf);
Drawing.txt_draw(0, 0,
0, 0,
this.fb_x, this.fb_y,
0xffffffff, draw);
str = this.getRight(false);
// str = jstr ? (*jsys.env)->GetStringUTFChars(jsys.env, jstr, NULL) : NULL;
// offset = 10 + (str ? 10 : 0);
StringBuilder sb = new StringBuilder();
for(PerfSection perf : PerfSection.values()) {
if(sb.length() > 0)
sb.append('\n');
sb.append(perf.getName());
}
Drawing.txt_draw(x1 + 0, y1, x1 + 0, y1, x1 + 120, y2,
this.style.text_label, sb.toString());
// pos = 0;
sb.setLength(0);
for(PerfSection perf : PerfSection.values()) {
if(sb.length() > 0)
sb.append('\n');
sb.append(String.format("%.3f ms", (float)perf.getLast() / 1000.0f));
}
Drawing.txt_draw(x1 + 120, y1, x1 + 120, y1, x1 + 240, y2,
this.style.text_label, sb.toString());
// pos = 0;
sb.setLength(0);
long total = PerfSection.getTotal(true);
for(PerfSection perf : PerfSection.values()) {
if(sb.length() > 0)
sb.append('\n');
sb.append(String.format("%.2f %%", ((float)perf.getLast() / (float)total) * 100.0f));
}
Drawing.txt_draw(x1 + 240, y1, x1 + 240, y1, x1 + 320, y2,
this.style.text_label, sb.toString());
if(str != null) {
y1 = Font.YGLYPH * 10;
Drawing.txt_draw(x1, y1, x1, y1, x1 + 320, y1 + Font.YGLYPH * 12,
this.style.text_label, str);
// (*jsys.env)->ReleaseStringUTFChars(jsys.env, jstr, str);
}
}
public void finish() {
if(this.screenshot) {
this.screenshot = false;
screenshot();
}
if(this.isDirty())
this.save();
Thread.yield();
while(System.currentTimeMillis() >= this.debugUpdateTime + 1000L) {
this.chunksUpdated = RenderChunk.renderChunksUpdated;
RenderChunk.renderChunksUpdated = 0;
this.debugUpdateTime += 1000L;
}
}
// public void action(int btn) {
// if(this.open != null) {
// this.soundManager.playSound(new PositionedSound(SoundEvent.CLICK, 1.0F));
// this.open.actionPerformed(btn);
// }
// }
public void scroll(int dir) {
// if(this.open != null) // {
// return;
// if(this.open instanceof GuiCheat)
// ((GuiCheat)this.open).scroll(dir);
// }
if(this.zooming)
this.zoomLevel = ExtMath.clampf(this.zoomLevel + (dir < 0 ? -0.25f : 0.25f), 2.0f, 16.0f);
else if(this.thePlayer != null)
this.thePlayer.inventory.changeCurrentItem(dir);
}
// public void resize(int width, int height)
// {
// this.fb_x = width;
// this.fb_y = height;
// // if(this.open != null)
// // this.open.initialize(this, this.fb_x, this.fb_y);
// }
// public void distance(int distance)
// {
// this.renderDistance = distance;
// this.updateViewDistance();
// }
// public void buildTime(int time)
// {
// this.maxBuildTime = time;
// }
public void moveCamera(float x, float y) {
this.deltaX += x;
this.deltaY += y;
}
// public void closeScreen() {
// if(this.open != null) {
// if(this.thePlayer != null)
// this.thePlayer.setScreenClosed();
// this.displayGuiScreen(null);
// }
// }
public void displayGuiScreen(Gui gui)
{
if(this.thePlayer != null)
this.thePlayer.setScreenClosed();
if (this.open != null)
{
this.open.onGuiClosed();
}
// if(this.thePlayer != null && this.thePlayer.getHealth() <= 0 && this.open instanceof GuiGameOver)
// this.thePlayer.respawnPlayer();
// if (guiScreenIn == null && this.theWorld == null)
// {
// guiScreenIn = new GuiMainMenu();
// }
// else
if (gui == null && this.theWorld != null && this.thePlayer.getHealth() <= 0)
{
gui = GuiGameOver.INSTANCE;
}
else if(gui == null && this.open instanceof GuiInventory && this.itemCheat) {
gui = new GuiCheat();
}
this.open = gui;
if (gui != null)
{
this.menu(true);
// if(this.open != null) {
// this.open.init();
// }
// else {
// }
gui.init();
// if(gui instanceof GuiEmpty)
// SKC.setGuiMenu();
// else
// SKC.setGuiAny();
WCF.setTitle(String.format("%s - %s", Config.VERSION, gui.getTitle()));
}
else
{
this.menu(false);
this.leftClickCounter = 10000;
Bind.disableMouse();
WCF.setTitle(String.format("%s - %s%s", Config.VERSION, "Welt / Render", this.nograb ? "" : " (Maus gefangen)"));
// SKC.setGuiNone();
}
}
private void sendClickBlockToController(boolean leftClick)
{
if (!leftClick)
{
this.leftClickCounter = 0;
this.controller.resetInteraction();
}
if (this.leftClickCounter <= 0 && !this.thePlayer.isUsingItem())
{
if (leftClick && this.pointed != null && this.pointed.type == HitPosition.ObjectType.BLOCK)
{
BlockPos blockpos = this.pointed.block;
if (this.theWorld.getState(blockpos).getBlock().getMaterial() != Material.air && this.controller.onPlayerDamageBlock(blockpos, this.pointed.side))
{
this.effectRenderer.addBlockHitEffects(blockpos, this.pointed.side);
this.thePlayer.swingItem();
}
}
else
{
this.controller.resetBlockRemoving();
}
}
}
private void primary()
{
if (this.leftClickCounter <= 0)
{
if (this.pointed == null)
{
this.thePlayer.swingItem();
Log.JNI.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!");
this.leftClickCounter = 10;
}
else
{
ItemStack itemstack = this.thePlayer.inventory.getCurrentItem();
if ((this.pointed.type != ObjectType.BLOCK || this.theWorld.getState(this.pointed.block).getBlock().getMaterial() == Material.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.thePlayer, this.theWorld, ItemControl.PRIMARY, null))
{
this.thePlayer.swingItem();
this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.PRIMARY.ordinal()));
this.leftClickCounter = 10;
return;
}
switch (this.pointed.type)
{
case ENTITY:
this.thePlayer.swingItem();
this.controller.attackEntity(this.thePlayer, this.pointed.entity);
break;
case BLOCK:
this.thePlayer.swingItem();
BlockPos blockpos = this.pointed.block;
if (this.theWorld.getState(blockpos).getBlock().getMaterial() != Material.air)
{
this.controller.clickBlock(blockpos, this.pointed.side);
break;
}
this.leftClickCounter = 10;
break;
case MISS:
default:
this.thePlayer.swingItem();
this.leftClickCounter = 10;
}
}
}
}
private void secondary()
{
if (!this.controller.getIsHittingBlock())
{
this.rightClickTimer = 4;
boolean flag = true;
ItemStack itemstack = this.thePlayer.inventory.getCurrentItem();
// if (itemstack != null && itemstack.getItem() == Items.camera)
// {
// this.makeScreenshot();
// }
if (this.pointed == null)
{
Log.JNI.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!");
}
else
{
if ((this.pointed.type != ObjectType.BLOCK || this.theWorld.getState(this.pointed.block).getBlock().getMaterial() == Material.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.thePlayer, this.theWorld, ItemControl.SECONDARY, null))
{
this.thePlayer.swingItem();
this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.SECONDARY.ordinal()));
return;
}
switch (this.pointed.type)
{
case ENTITY:
// if (this.controller.isPlayerRightClickingOnEntity(this.thePlayer, this.pointed.entityHit, this.pointed))
// {
// flag = false;
// }
// else
if (this.controller.interactWithEntitySendPacket(this.thePlayer, this.pointed.entity))
{
flag = false;
}
break;
case BLOCK:
BlockPos blockpos = this.pointed.block;
if (this.theWorld.getState(blockpos).getBlock().getMaterial() != Material.air)
{
int i = itemstack != null ? itemstack.stackSize : 0;
if (this.controller.onPlayerRightClick(this.thePlayer, this.theWorld, itemstack, blockpos, this.pointed.side, this.pointed.vec))
{
flag = false;
this.thePlayer.swingItem();
}
if (itemstack == null)
{
return;
}
if (itemstack.stackSize == 0)
{
this.thePlayer.inventory.mainInventory[this.thePlayer.inventory.currentItem] = null;
}
else if (itemstack.stackSize != i) // || this.controller.isCreative())
{
this.entityRenderer.itemRenderer.resetEquippedProgress();
}
}
}
}
if (flag)
{
ItemStack itemstack1 = this.thePlayer.inventory.getCurrentItem();
if (itemstack1 != null && this.controller.sendUseItem(this.thePlayer, this.theWorld, itemstack1))
{
this.entityRenderer.itemRenderer.resetEquippedProgress2();
}
}
}
}
private void tertiary()
{
if (this.pointed != null)
{
if(this.thePlayer.getHeldItem() != null && this.thePlayer.getHeldItem().getItem().onAction(this.thePlayer.getHeldItem(), this.thePlayer, this.theWorld, ItemControl.TERTIARY, null)) {
this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.TERTIARY.ordinal()));
return;
}
// boolean flag = this.thePlayer.creative;
int meta = 0;
boolean flag1 = false;
// TileEntity tileentity = null;
Item item = null;
// NBTTagCompound tag = null;
if (this.pointed.type == HitPosition.ObjectType.BLOCK)
{
BlockPos blockpos = this.pointed.block;
Block block = this.theWorld.getState(blockpos).getBlock();
if (block.getMaterial() == Material.air)
{
return;
}
item = block.getItem(this.theWorld, blockpos);
if (item == null)
{
return;
}
Block block1 = item instanceof ItemBlock && !block.isPickStrict() ? item.getBlock() : block;
meta = block1.getDamageValue(this.theWorld, blockpos);
flag1 = item.getHasSubtypes();
}
else
{
if (this.pointed.type != HitPosition.ObjectType.ENTITY || this.pointed.entity == null || !this.itemCheat)
{
return;
}
item = this.pointed.entity.getItem();
if(item == null)
return;
}
InventoryPlayer inventoryplayer = this.thePlayer.inventory;
inventoryplayer.setCurrentItem(item, meta, flag1);
if(this.itemCheat) {
this.thePlayer.sendQueue.addToSendQueue(new CPacketCheat(new ItemStack(item, 1, meta), inventoryplayer.currentItem, this.ctrl()));
}
}
}
private void quarternary()
{
if (this.pointed != null)
{
if(this.thePlayer.getHeldItem() != null && this.thePlayer.getHeldItem().getItem().onAction(this.thePlayer.getHeldItem(), this.thePlayer, this.theWorld, ItemControl.QUARTERNARY, null)) {
this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.QUARTERNARY.ordinal()));
return;
}
}
}
// private void printDebugMessage(String text) {
// this.printDebugMessage(text, null);
// }
//
// private void printDebugMessage(String text, String desc) {
// SKC.notify(text, desc);
// this.soundManager.playSound(new PositionedSound(SoundEvent.CLICK));
// }
public void loadWorld(WorldClient world, int type)
{
this.viewEntity = null;
this.connection = null;
this.soundManager.stopSounds();
this.theWorld = world;
if (this.renderGlobal != null)
{
this.renderGlobal.setWorldAndLoadRenderers(world);
}
if (this.effectRenderer != null)
{
this.effectRenderer.clearEffects(world);
}
if (this.thePlayer == null)
{
this.thePlayer = this.controller.createPlayerEntity(world, type);
this.thePlayer.rotYaw = -180.0F;
}
this.thePlayer.preparePlayerToSpawn();
world.spawnEntityInWorld(this.thePlayer);
this.viewEntity = this.thePlayer;
System.gc();
// SKC.loaded(true);
}
public void setDimensionAndSpawnPlayer(int dimension, int type)
{
this.theWorld.removeAllEntities();
int i = 0;
if (this.thePlayer != null)
{
i = this.thePlayer.getId();
this.theWorld.removeEntity(this.thePlayer);
}
this.viewEntity = null;
EntityNPC entityplayersp = this.thePlayer;
this.thePlayer = this.controller.createPlayerEntity(this.theWorld, type);
this.thePlayer.getDataWatcher().updateWatchedObjectsFromList(entityplayersp.getDataWatcher().getAllWatched());
this.viewEntity = this.thePlayer;
this.thePlayer.preparePlayerToSpawn();
this.theWorld.spawnEntityInWorld(this.thePlayer);
this.thePlayer.rotYaw = -180.0F;
this.thePlayer.setId(i);
// if (this.open instanceof GuiGameOver)
// {
this.displayGuiScreen(null);
// }
}
public NetHandlerPlayClient getNetHandler()
{
return this.thePlayer != null ? this.thePlayer.sendQueue : null;
}
// public void setSkin(BufferedImage skin, String id, ModelType model, boolean slim)
// {
// this.skinSet = id == null ? "" : id;
// this.skinSlim = slim;
// if(this.getNetHandler() != null) {
// this.getNetHandler().addToSendQueue(new CPacketSkin(skin, model));
// }
// else {
// this.confirmSkin(true);
// }
// }
// public void confirmSkin(boolean changed) {
// if(changed && this.skinSet != null) {
// this.skinId = this.skinSet;
// if(this.thePlayer != null)
// this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_MODELPARTS,
// (this.thePlayer.getModelParts() & ~ModelPart.ARMS_SLIM.getMask()) |
// (this.skinSlim ? ModelPart.ARMS_SLIM.getMask() : 0)));
// }
// else if(changed) {
// this.skinId = "";
// }
// this.skinSet = null;
// this.skinSlim = false;
// }
public TextureManager getTextureManager()
{
return this.textureManager;
}
public TextureMap getTextureMapBlocks()
{
return this.textureMap;
}
public SoundManager getSoundManager()
{
return this.soundManager;
}
public void performAction(Action action) {
if(this.thePlayer != null)
this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(action));
}
public void setBossStatus(EntityLiving entity) {
if(this.bars.size() < 5 || this.bars.containsKey(entity.getId()))
this.bars.put(entity.getId(), System.currentTimeMillis());
}
public Entity getRenderViewEntity()
{
return this.viewEntity;
}
public Entity getPointedEntity()
{
return this.pointedEntity;
}
public void setPointedEntity(Entity entity)
{
this.pointedEntity = entity;
}
public void setRenderViewEntity(Entity viewingEntity)
{
this.viewEntity = viewingEntity;
}
private <V> ListenableFuture<V> addScheduledTask(Callable<V> callableToSchedule)
{
if (!this.isMainThread())
{
ListenableFutureTask<V> listenablefuturetask = ListenableFutureTask.<V>create(callableToSchedule);
synchronized (this.tasks)
{
this.tasks.add(listenablefuturetask);
return listenablefuturetask;
}
}
else
{
try
{
return Futures.<V>immediateFuture(callableToSchedule.call());
}
catch (Exception exception)
{
return Futures.immediateFailedFuture(exception);
}
}
}
public ListenableFuture<Object> schedule(Runnable runnableToSchedule)
{
return this.<Object>addScheduledTask(Executors.callable(runnableToSchedule));
}
public boolean isMainThread()
{
return Thread.currentThread() == this.clThread;
}
public BlockRenderer getBlockRendererDispatcher()
{
return this.blockRenderer;
}
public RenderManager getRenderManager()
{
return this.renderManager;
}
public RenderItem getRenderItem()
{
return this.renderItem;
}
public ItemRenderer getItemRenderer()
{
return this.itemRenderer;
}
public void setTicked() {
this.lastTicked = System.currentTimeMillis();
}
public void updatePlayerMoveState()
{
this.moveStrafe = 0.0F;
this.moveForward = 0.0F;
if (this.open == null && Bind.FORWARD.isDown())
{
++this.moveForward;
}
if (this.open == null && Bind.BACKWARD.isDown())
{
--this.moveForward;
}
if (this.open == null && Bind.LEFT.isDown())
{
++this.moveStrafe;
}
if (this.open == null && Bind.RIGHT.isDown())
{
--this.moveStrafe;
}
this.jump = this.open == null && Bind.UP.isDown();
this.sneak = this.open == null && Bind.DOWN.isDown();
this.sprint = this.open == null && Bind.FAST.isDown();
if (this.sneak)
{
this.moveStrafe = (float)((double)this.moveStrafe * 0.3D);
this.moveForward = (float)((double)this.moveForward * 0.3D);
}
}
public String getLeft(Server server) {
long maxMem = Runtime.getRuntime().maxMemory();
long totalMem = Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
long usedMem = totalMem - freeMem;
String mem = String.format("JVM-Speicher: %d%% %d/%dMB", usedMem * 100L / maxMem, usedMem / 1024L / 1024L, maxMem / 1024L / 1024L)
+ "\n" +
String.format("JVM-Reserviert: %d%% %dMB", totalMem * 100L / maxMem, totalMem / 1024L / 1024L);
if(this.theWorld == null) {
return mem;
}
BlockPos blockpos = new BlockPos(this.viewEntity.posX, this.viewEntity.getEntityBoundingBox().minY,
this.viewEntity.posZ);
Entity entity = this.viewEntity;
Facing facing = entity.getHorizontalFacing();
String dirStr = "Ungültig";
switch(facing) {
case NORTH:
dirStr = "Norden (Nach negativer Z)";
break;
case SOUTH:
dirStr = "Süden (Nach positiver Z)";
break;
case WEST:
dirStr = "Westen (Nach negativer X)";
break;
case EAST:
dirStr = "Osten (Nach positiver X)";
break;
}
Biome biome = null;
String bline;
String lline;
if(this.theWorld.isBlockLoaded(blockpos)) {
Chunk chunk = this.theWorld.getChunk(blockpos);
biome = chunk.getBiome(blockpos, null);
bline = "Biom: " + biome.display + " (" + biome.id + ")" + /* (this.debugHideInfo ? "" : */ (", D: " +
TextColor.stripCodes(this.theWorld.dimension.getFormattedName(false)) +
" (" + this.theWorld.dimension.getDimensionId() + ")");
lline = "Licht: " + chunk.getLightSub(blockpos, 0) + " (" + chunk.getLight(LightType.SKY, blockpos) + " Himmel, "
+ chunk.getLight(LightType.BLOCK, blockpos) + " Blöcke, " + String.format(
"%.1f", this.theWorld.getSunBrightness(1.0f) * 15.0f) + " Welt), A: "
+ String.format("%.3f", this.theWorld.getCelestialAngle(1.0f));
}
else {
bline = "Biom: <?>, D: " +
TextColor.stripCodes(this.theWorld.dimension.getFormattedName(false)) +
" (" + this.theWorld.dimension.getDimensionId() + ")";
lline = "Licht: " + String.format(
"%.1f", this.theWorld.getSunBrightness(1.0f) * 15.0f) + " Welt, A: "
+ String.format("%.3f", this.theWorld.getCelestialAngle(1.0f));
}
float temp = this.theWorld.getTempOffset() + (biome != null ? biome.getFloatTemperature(blockpos) : 0.0f);
long ticked = System.currentTimeMillis() - this.lastTicked;
return
mem + "\n" +
// (this.debugWorld ? "Debug-Welt" :
// (this.isServer() ? "ES: " + this.server.getFolderName() :
// "MS: " + (
// this.connected != null ? this.connected : "[???]"))),
this.renderGlobal.getDebugInfoRenders() + "\n" +
this.renderGlobal.getDebugInfoEntities() + "\n" +
"Partikel: " + this.effectRenderer.getStatistics() + ". O: " + this.theWorld.getDebugLoadedEntities() + "\n" +
this.theWorld.getInfo() + "\n" +
// "",
String.format("XYZ: %.3f / %.3f / %.3f", this.viewEntity.posX,
this.viewEntity.getEntityBoundingBox().minY, this.viewEntity.posZ) + "\n" +
String.format("Block: %d %d %d, R: '%s/%s'", blockpos.getX(), blockpos.getY(), blockpos.getZ(),
Region.getRegionFolder(blockpos.getX() >> 4, blockpos.getZ() >> 4),
Region.getRegionName(blockpos.getX() >> 4, blockpos.getZ() >> 4)) + "\n" +
String.format("Chunk: %d %d %d + %d %d %d, FOV: %.1f °%s", blockpos.getX() >> 4, blockpos.getY() >> 4, blockpos.getZ() >> 4,
blockpos.getX() & 15, blockpos.getY() & 15, blockpos.getZ() & 15, this.zooming ?
(this.fov / this.zoomLevel) : this.fov, this.zooming ?
String.format(" (Zoom x%.1f)", this.zoomLevel) : "") + "\n" +
String.format("Richtung: %s (%.1f / %.1f)", dirStr,
ExtMath.wrapf(entity.rotYaw), ExtMath.wrapf(entity.rotPitch)) + "\n" +
bline + "\n" +
lline + "\n" +
String.format("Zeit: %d T, R %d / %d T, U %d / %d T",
this.theWorld.getDayTime(),
this.theWorld.getDayTime() % this.theWorld.dimension.getRotationalPeriod(),
this.theWorld.dimension.getRotationalPeriod(),
this.theWorld.getDayTime() % this.theWorld.dimension.getOrbitalPeriod(),
this.theWorld.dimension.getOrbitalPeriod()
) + "\n" +
String.format("Laub: %s%s, T: %.2f K / %.2f °C, %s (R %.1f, %.1f)",
!this.theWorld.dimension.getType().days ? "*" : "",
this.theWorld.getLeavesGen(blockpos).getDisplayName(),
temp, World.ABSOLUTE_ZERO + temp,
this.theWorld.getWeather().getDisplay(), this.theWorld.getRainStrength(),
this.theWorld.getDarkness()
) + "\n" +
String.format("Zeitfaktor: %dx, Schwerkraft: %.2f m/s²",
this.timeFactor, this.theWorld.gravity * 10.0
) + "\n" +
String.format("Letzte Zeitsynch.: + %d.%d s",
ticked / 1000L, (ticked / 100L) % 10L
) + "\n" +
(server != null ?
String.format("Server: %.3f T/s (%.1fx), Z: %.1f T/s, D: %.3f ms", server.getTpsRate(),
server.getTpsRate() / 20.0f,
server.getTpsTarget(), server.getAverageTps()) : "Server: <remote>") + "\n" +
(server != null ? "Geladen: " + server.getWorlds().size() + " Welten, " + WorldServer.getLoadedInfo(server) :
"Geladen: <?>")
// WorldServer world = this.server.getWorld(this.theWorld.dimension.getDimensionId());
// if(world != null)
// list.add("Seed: " + world.getSeed());
;
}
public String getRight(boolean showPlayerInfo) {
if(this.theWorld == null) {
return null;
}
if(!showPlayerInfo && this.pointed != null && this.pointed.type == HitPosition.ObjectType.BLOCK
&& this.pointed.block != null) {
BlockPos pos = this.pointed.block;
State block = this.theWorld.getState(pos);
if(!this.debugWorld) {
block = block.getBlock().getActualState(block, this.theWorld, pos);
}
StringBuilder str = new StringBuilder(
"Schaue auf: " + BlockRegistry.REGISTRY.getNameForObject(block.getBlock()) + " [" + BlockRegistry.getIdFromBlock(block.getBlock()) +
":" + block.getBlock().getMetaFromState(block) + "]" + "\n" +
String.format("Position: %d %d %d", pos.getX(), pos.getY(), pos.getZ())
);
// int off = 2;
for(Entry<IProperty, Comparable> entry : block.getProperties().entrySet()) {
str.append("\n" + entry.getKey().getName() + ": " + entry.getValue().toString());
}
return str.toString(); // new String[] {
// list.add("");
// list.add();
// };
}
else if((this.pointed != null && this.pointed.type == HitPosition.ObjectType.ENTITY
&& this.pointed.entity != null) || showPlayerInfo) {
Entity entity = showPlayerInfo ? this.thePlayer : this.pointed.entity;
ItemStack held = entity instanceof EntityLiving && ((EntityLiving)entity).getHeldItem() != null ? ((EntityLiving)entity).getHeldItem() : null;
return
// list.add("");
"Schaue auf: " + (entity.isPlayer() ? "Player/" : "") + EntityRegistry.getEntityString(entity) + // " [" + (entity.isPlayer() ? "player" :
/* (EntityRegistry.getEntityID(entity) + "/" + EntityRegistry.getObjectID(entity))) + "]" */ " (" + entity.getId() + ")"
+ "\n" +
String.format("Position: %.3f %.3f %.3f", entity.posX, entity.posY, entity.posZ) + "\n" +
// list.add("Name: '" + entity.getName() + "'");
"Geladen: " + entity.ticksExisted + "t" + (entity instanceof EntityLiving ? (", Alter: " + ((EntityLiving)entity).getGrowingAge()) + "t" : "") + "\n" +
String.format("Größe: %.2fx%.2f, A: %.2f", entity.width, entity.height, entity.getEyeHeight()) + "\n" +
// if(!this.debugHideInfo) {
String.format("Bewegung: %.3f %.3f %.3f", entity.motionX, entity.motionY, entity.motionZ) + "\n" +
String.format("Drehung: %.1f %.1f, K: %.1f", entity.rotYaw, entity.rotPitch, entity.getRotationYawHead()) + "\n" +
// }
(entity instanceof EntityLiving
? String.format("Leben: %d/%d, A: %d", ((EntityLiving)entity).getHealth(), ((EntityLiving)entity).getMaxHealth(),
((EntityLiving)entity).getAbsorptionAmount()) : "Leben: n/a") + "\n" +
"Schaden: " + entity.hurtResistance + "t" + (showPlayerInfo ? String.format(", Fallh.: %.3f", entity.fallDistance) : "") + "\n" + // + ", Luft: " + entity.getAir());
(entity instanceof EntityLiving ?
(((EntityLiving)entity).deathTime != 0 ? "Tod: " + ((EntityLiving)entity).deathTime + "t, " : "") + "Rüstung: " + ((EntityLiving)entity).getTotalArmorValue() + ", Pfeile: " + ((EntityLiving)entity).getArrowCountInEntity()
: "Rüstung: n/a, Pfeile: n/a") + "\n" +
// ItemStack held = ((EntityLiving)entity).getHeldItem();
(held != null ?
"Gegens.: " + ItemRegistry.REGISTRY.getNameForObject(held.getItem()) + " x" + held.stackSize + " (" + held.getMetadata() + ")" : "Gegens.: n/a") + "\n" +
"Eigens.: " + (entity.dead ? "D" : " ") + (entity.noClip ? "N" : " ") + (entity.onGround ? "G" : " ")
+ (entity.canBeCollidedWith() ? "C" : " ") + (entity.canBePushed() ? "P" : " ")
+ (entity.isBurning() ? "B" : " ") // + (entity.isInvisible() ? "I" : " ") // + (entity.isSilent() ? "S" : " ")
+ (entity.isWet() ? "W" : " ") + (entity.canAttackWithItem() ? "A" : " ")
+ (entity.passenger != null ? "H" : " ") + (entity.vehicle != null ? "R" : " ") + (entity instanceof EntityLiving ?
("+" /* + (((EntityLivingBase)entity).isEntityUndead() ? "U" : " ") */ // + (((EntityLivingBase)entity).isChild() ? "C" : " ")
+ (((EntityLiving)entity).doesEntityNotTriggerPressurePlate() ? "P" : " ")) : "") + "\n" +
// list.add("UUID: " + entity.getUniqueID().toString());
(entity.hasCustomName() ? "Name: '" + TextColor.stripCodes(entity.getCustomNameTag()) + "'" : "Name: n/a")
;
}
return null;
}
public boolean shift() {
return Bind.isWindowActive() && (Keysym.LEFT_SHIFT.read() || Keysym.RIGHT_SHIFT.read());
}
public boolean ctrl() {
return Bind.isWindowActive() && (Keysym.LEFT_CONTROL.read() || Keysym.RIGHT_CONTROL.read());
}
private void fbsize(int x, int y) {
WCF.glViewport(0, 0, x, y);
fb_x = x;
fb_y = y;
if(this.open != null)
this.displayGuiScreen(this.open);
if(!fullscreen) {
xsize = x;
ysize = y;
}
}
private void pos(int x, int y) {
if(!fullscreen) {
saved_xpos = x;
saved_ypos = y;
}
}
private void mouse(int x, int y) {
if(!mouseFirst && open == null)
this.moveCamera((float)(x - mouse_x) * sensitivity, (float)(mouse_y - y) * sensitivity);
mouse_x = x;
mouse_y = y;
mouseFirst = false;
if(open != null && Bind.isInputEnabled() && Button.isMouseDown() /* && !(win->mouse & 0xfc) */ && !ctrl()) {
// if(mouse_clickx < 0 || mouse_clicky < 0) {
// return;
// }
// SKC.drag(mouse_x, mouse_y);
open.drag(mouse_x, mouse_y);
}
}
private void scroll(int x, int y) {
x *= -1;
if(open != null && Bind.isInputEnabled()) {
// if(y != 0)
// this.scroll(ExtMath.clampi(y, -1, 1));
open.scroll(x, y, mouse_x, mouse_y, ctrl(), shift());
}
else if(open != null) {
if((x != 0) || (y != 0))
Bind.setBind((x < 0) ? Wheel.SCROLL_LEFT : ((x > 0) ? Wheel.SCROLL_RIGHT : ((y < 0) ? Wheel.SCROLL_DOWN : Wheel.SCROLL_UP)), false);
}
else if(Bind.isInputEnabled()) {
if(y != 0)
this.scroll(ExtMath.clampi(y, -1, 1));
}
else {
if(x < 0)
Wheel.SCROLL_LEFT.setUsed();
else if(x > 0)
Wheel.SCROLL_RIGHT.setUsed();
if(y < 0)
Wheel.SCROLL_DOWN.setUsed();
else if(y > 0)
Wheel.SCROLL_UP.setUsed();
}
}
private void button(Button btn, boolean press) {
// if(btn < 0 || btn >= 8) {
// return;
// }
// byte press = act == KEY_PRESS;
boolean prev = btn.isDown();
if(open != null && prev != press && Bind.isInputEnabled() && !Button.isMouseDown()) {
// SKC.press(btn, mouse_x, mouse_y);
open.mouse(btn, mouse_x, mouse_y, ctrl(), shift());
}
else if(open != null && press) {
Bind.setBind(btn, false);
}
btn.setDown(press);
if(open != null && prev != press && Bind.isInputEnabled() && !Button.isMouseDown()) {
// SKC.release(btn, mouse_x, mouse_y);
open.mouserel(btn, mouse_x, mouse_y);
}
}
private void key(Keysym key, KeyEvent act) {
if(open != null && (act != KeyEvent.RELEASE) && Bind.isInputEnabled()) {
open.key(key, ctrl(), shift());
}
else if(open != null && (act != KeyEvent.REPEAT)) {
Bind.setBind(key, act == KeyEvent.RELEASE);
}
}
private void character(char code) {
if(open != null && Bind.isInputEnabled()) {
open.character(code);
}
}
private void focus(boolean focus) {
Bind.setWindowActive(focus);
if(open != null)
open.mouse(Button.MOUSE_LEFT, -1, -1, false, false);
// open.restyle();
}
private void redraw() {
if(this.open != null)
this.displayGuiScreen(this.open);
}
private void closed() {
interrupted = true;
}
public void poll() {
for(WindowEvent event : WCF.poll()) {
switch(event.action) {
case BUTTON:
if(event.param1 >= 0 && event.param1 < Button.values().length)
button(Button.values()[event.param1], event.param2 != 0);
break;
case CHARACTER:
if(event.param1 >= (int)Log.CHR_SPC && event.param1 <= (int)Character.MAX_VALUE)
character((char)event.param1);
break;
case CLOSED:
closed();
break;
case CURSOR:
mouse(event.param1, event.param2);
break;
case FOCUS:
focus(event.param1 != 0);
break;
case KEY:
if(event.param1 > 0 && event.param1 <= Keysym.values().length)
key(Keysym.values()[event.param1 - 1], KeyEvent.values()[event.param2 % KeyEvent.values().length]);
break;
case POSITION:
pos(event.param1, event.param2);
break;
case REDRAW:
redraw();
break;
case RESIZE:
fbsize(event.param1, event.param2);
break;
case SCROLL:
if(event.param1 != 0 || event.param2 != 0)
scroll(event.param1, event.param2);
break;
}
}
}
public void menu(boolean menu) {
WCF.grabCursor(!menu && !nograb);
mouseFirst = true;
}
public void full(boolean full) {
if(full != fullscreen && (!full || vidMode != null)) {
if(full) {
WCF.setFullscreen(vidMode.width, vidMode.height, vidMode.refresh);
}
else {
WCF.setWindowed(saved_xpos, saved_ypos, xsize, ysize);
}
WCF.setVSync(vsync);
fullscreen = full;
}
}
public void sync(int sync) {
vsync = sync == 0;
syncLimited = sync > 0;
if(sync > 0) {
syncLimit = sync;
}
else {
DisplayMode mode = WCF.getDisplayMode();
syncLimit = mode != null ? mode.refresh : 60;
}
WCF.setVSync(vsync);
}
public void setupOverlay() {
GlState.disableDepth();
GlState.tryBlendFuncSeparate(WCF.GL_SRC_ALPHA, WCF.GL_ONE_MINUS_SRC_ALPHA, WCF.GL_ONE, WCF.GL_ONE_MINUS_SRC_ALPHA);
GlState.setActiveTexture(WCF.GL_TEXTURE0);
GlState.color(1.0f, 1.0f, 1.0f, 1.0f);
WCF.glClear(256);
WCF.glMatrixMode(5889);
WCF.glLoadIdentity();
WCF.glOrtho(0.0D, (double)this.fb_x, (double)this.fb_y, 0.0D, 1000.0D, 3000.0D);
WCF.glMatrixMode(5888);
WCF.glLoadIdentity();
WCF.glTranslatef(0.0F, 0.0F, -2000.0F);
}
public void run() {
start = WCF.getTime();
Log.SYSTEM.info("Java " + System.getProperty("java.version"));
Log.SYSTEM.info(Config.VERSION);
if(!WCF.createWindow(Config.VERSION, System.getProperty("opengl.debug") != null))
System.exit(1);
Log.SYSTEM.info("OpenGL %s", WCF.glGetString(WCF.GL_VERSION));
Log.SYSTEM.info("GL_VENDOR: %s", WCF.glGetString(WCF.GL_VENDOR));
Log.SYSTEM.info("GL_RENDERER: %s", WCF.glGetString(WCF.GL_RENDERER));
Log.SYSTEM.info("Starte ...");
this.init();
System.gc();
System.gc();
Font.load();
GlState.enableBlend();
GlState.blendFunc(WCF.GL_SRC_ALPHA, WCF.GL_ONE_MINUS_SRC_ALPHA);
this.initConsole();
this.vidMode = WCF.getDisplayMode();
WCF.initWindow(this.saved_xpos, this.saved_ypos, this.xsize, this.ysize);
WCF.setIcon(genTriwave(64, 64, 0x00000000, 0xffff0000, 0xff00ff00, 0xff0000ff, 0xff7f00ff, 0xff000000), 64, 64);
this.sync(this.sync);
this.startSound(true);
this.getVar("tic_target").setDefault();
this.displayGuiScreen(GuiMenu.INSTANCE);
while(!this.interrupted) {
PerfSection.swap();
PerfSection.TIMING.enter();
Timing.tmr_current = rtime();
Timing.tmr_delta = Timing.tmr_current - Timing.tmr_last;
Timing.tmr_last = Timing.tmr_current;
Timing.fdelta = ((float)Timing.tmr_delta) / 1000000.0f;
if((Timing.tmr_current - Timing.tmr_update) >= 1000000L) {
Timing.framerate = ((float)Timing.tmr_frames) * 1000000.0f / ((float)(long)(Timing.tmr_current - Timing.tmr_update));
Timing.tmr_frames = 0L;
Timing.tmr_update = Timing.tmr_current;
}
this.start();
PerfSection.INPUT.enter();
Bind.updateBinds();
this.input();
Bind.enableInput();
GlState.setActiveTexture(WCF.GL_TEXTURE0);
GlState.bindTexture(0);
this.inputGui();
if(this.open != null)
this.open.update();
PerfSection.TICK.enter();
this.doTicks();
PerfSection.UPDATE.enter();
PerfSection.RENDER.enter();
this.render();
PerfSection.GUI.enter();
this.renderHud();
PerfSection.REST.enter();
this.finish();
PerfSection.SWAP.enter();
if(this.glFlush)
WCF.glFlush();
WCF.swapBuffers();
PerfSection.EVENTS.enter();
Log.flushLog();
this.poll();
PerfSection.WAIT.enter();
while(this.syncLimited && (rtime() - Timing.tmr_current) < (1000000L / this.syncLimit)) {
;
}
Timing.tmr_frames += 1L;
}
Log.SYSTEM.info("Beende ...");
unload();
this.getSoundManager().unload();
Region.killIO();
this.renderGlobal.stopChunkBuilders();
if(audio.end())
Log.SOUND.info("Audiogerät geschlossen");
Log.flushLog();
this.save();
Font.unload();
WCF.destroyWindow();
Log.SYSTEM.info("Beendet.");
}
// public void complete(String[] comp) {
//
// }
public void infolist(String[] list, int[] data) {
}
public void disconnected(String msg) {
Log.SYSTEM.info("Getrennt: %s", msg);
this.unload();
this.displayGuiScreen(new GuiInfo("Von Server getrennt", TextColor.RED + "Verbindung zum Server wurde getrennt\n\n" + TextColor.RESET + msg));
}
private void input() {
if(Bind.QUIT.isPressed()) {
this.interrupted = true;
}
if(Bind.SYNC.isPressed()) {
this.getVar("win_sync").parse("" + (this.vsync ? this.syncLimit : (this.syncLimited ? -1 : 0)));
this.setDirty();
}
if(!this.saving && Bind.SCREENSHOT.isPressed()) {
this.screenshot = true;
}
if(Bind.isWindowActive()) {
if(Bind.FULLSCREEN.isPressed()) {
this.full(!this.fullscreen);
}
if(!(this.open instanceof GuiConsole) && Bind.COMMAND.isPressed()) {
this.displayGuiScreen(GuiConsole.INSTANCE);
}
// if(this.theWorld != null && this.open == null && Bind.COMMAND.isPressed()) {
// this.displayGuiScreen(GuiChat.INSTANCE);
// }
if(this.theWorld != null && Bind.MENU.isPressed()) {
if(this.open != null)
this.displayGuiScreen(null);
else
this.displayGuiScreen(GuiMenu.INSTANCE);
}
else if(this.theWorld == null && !(this.open instanceof GuiMenu) && Bind.MENU.isPressed()) {
this.displayGuiScreen(GuiMenu.INSTANCE);
}
if(this.theWorld != null && Bind.INVENTORY.isPressed()) {
if(this.open instanceof GuiContainer) {
this.displayGuiScreen(null);
}
else if(this.open == null) {
if(this.thePlayer.isRiding() && this.thePlayer.vehicle instanceof EntityHorse)
this.thePlayer.sendHorseInventory();
else
this.displayGuiScreen(this.itemCheat ? new GuiCheat() : new GuiInventory(this.thePlayer));
}
}
if(Bind.SHOW.isPressed()) {
if(this.drawDebug) {
this.drawDebug = this.drawFps = false;
}
else {
this.drawDebug = this.drawFps;
this.drawFps = true;
}
}
}
if(Bind.isWindowActive() && this.open == null) {
if(Bind.NOCLIP.isPressed()) {
this.performAction(Action.NOCLIP);
}
if(Bind.GOD.isPressed()) {
this.performAction(Action.GOD);
}
if(Bind.SPEED.isPressed()) {
this.performAction(Action.SPEED);
}
if(Bind.CHEAT.isPressed()) {
Log.CONSOLE.user("Cheat-Menü: %s", (this.itemCheat ^= true) ? "an" : "aus");
}
if(Bind.REPAIR.isPressed()) {
this.performAction(Action.REPAIR);
}
if(Bind.LIGHT.isPressed()) {
Log.CONSOLE.user("Maximale Helligkeit: %s", (this.setGamma ^= true) ? "an" : "aus");
}
}
}
private void screenshot() {
if(this.saving)
return;
this.saving = true;
final int stride = ((this.fb_x * 3) & 3) != 0 ? 4 + ((this.fb_x * 3) & ~3) : (this.fb_x * 3);
final ByteBuffer data = ByteBuffer.allocateDirect(stride * this.fb_y).order(ByteOrder.nativeOrder());
WCF.glReadPixels(this.fb_x, this.fb_y, data);
new Thread(new Runnable() {
public void run() {
byte[] pixels = new byte[stride * Game.this.fb_y];
data.get(pixels);
byte[] conv = new byte[Game.this.fb_x * Game.this.fb_y * 3];
for(int l = 0; l < Game.this.fb_y; l++) {
System.arraycopy(pixels, l * stride, conv, (Game.this.fb_y - 1 - l) * Game.this.fb_x * 3, Game.this.fb_x * 3);
}
BufferedImage image = new BufferedImage(Game.this.fb_x, Game.this.fb_y, BufferedImage.TYPE_INT_ARGB);
int[] img = new int[Game.this.fb_x * Game.this.fb_y];
for(int z = 0; z < img.length; z++) {
img[z] = (int)(conv[(z * 3) + 2] & 0xff) | ((int)(conv[(z * 3) + 1] & 0xff) << 8) | ((int)(conv[(z * 3) + 0] & 0xff) << 16) | 0xff000000;
}
image.setRGB(0, 0, Game.this.fb_x, Game.this.fb_y, img, 0, Game.this.fb_x);
File dir = new File("screenshots");
dir.mkdirs();
int n = 0;
File file;
Date date = new Date();
do {
file = new File(dir, "screen_" + new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss").format(date) + (n != 0 ? "_" + n : "") + ".png");
n++;
}
while(file.exists());
final File saved = file;
try {
ImageIO.write(image, "png", file);
}
catch(IOException e) {
Game.this.schedule(new Runnable() {
public void run() {
Game.this.saving = false;
Log.IO.error(e, "Konnte Textur '" + saved + "' nicht speichern");
}
});
return;
}
Game.this.schedule(new Runnable() {
public void run() {
Game.this.saving = false;
Log.SYSTEM.user("Bildschirmfoto als '%s' gespeichert", saved.getName());
}
});
}
}, "Screenshot writer").start();
}
public TextColor framecode() {
return (Timing.framerate >= 59.0f) ? TextColor.GREEN : ((Timing.framerate >= 29.0f) ? TextColor.YELLOW : ((Timing.framerate >= 14.0f) ? TextColor.ORANGE : TextColor.RED));
}
public TextColor tpscode() {
return (Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) - 1.0f)) ? TextColor.GREEN : ((Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) / 2.0f - 1.0f)) ? TextColor.YELLOW :
((Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) / 4.0f - 1.0f)) ? TextColor.ORANGE : TextColor.RED));
}
private void doTicks() {
Timing.tick_stime = rtime();
if((Timing.tick_stime - Timing.tick_update) >= 1000000L) {
Timing.tickrate = ((float)Timing.tick_done) * 1000000.0f / ((float)(long)(Timing.tick_stime - Timing.tick_update));
Timing.tick_done = 0;
Timing.tick_update = Timing.tick_stime;
}
Timing.tick_torun += (((long)Timing.tickTarget) * Timing.tmr_delta) / 1000L;
Timing.tickFrame = 0;
Timing.tick_torun = Timing.tick_torun > 2000000L ? 1000000L : Timing.tick_torun;
while(Timing.tick_torun >= 1000000L) {
this.tick();
Timing.tick_done += 1L;
Timing.tickFrame += 1;
Timing.tick_total += 1L;
Timing.tick_torun -= 1000000L;
if((Timing.tick_ftime = (rtime() - Timing.tick_stime)) >= (((long)this.tickTimeout) * 1000L)) {
Log.TICK.warn("Ticks benötigten %d ms dieses Frame (maximal %d ms), überspringe %d Ticks", Timing.tick_ftime / 1000L, this.tickTimeout, Timing.tick_torun / 1000000L);
Timing.tick_torun = 0L;
break;
}
}
Timing.tick_fraction = ((double)Timing.tick_torun) / 1000000.0;
Timing.tick_ttime += Timing.tick_ftime;
Timing.tick_time = Timing.tickFrame != 0 ? (Timing.tick_ftime / (long)Timing.tickFrame) : 0L;
}
public void tick_target(float tps) {
Timing.tickTarget = (int)(tps * 1000.0f);
Timing.tick_torun = 0L;
Timing.tick_done = 0L;
Timing.tick_update = rtime();
}
public boolean isRemote() {
return this.theWorld != null && server == null;
}
public void unload() {
if(this.theWorld != null) {
if(server == null && this.getNetHandler() != null)
this.getNetHandler().getNetworkManager().closeChannel("Quitting");
this.unloadWorld();
if(server != null)
server.shutdown();
}
while(server != null && !server.isStopped()) {
try {
Thread.sleep(10L);
}
catch(InterruptedException e) {
}
}
server = null;
}
public void startServer(File dir, String user) {
server = new Server(dir);
server.start();
while(server != null && !server.isStarted()) {
try {
Thread.sleep(10L);
}
catch(InterruptedException e) {
}
}
if(server != null) {
server.setVar("viewDistance", "" + this.renderDistance);
this.connectToIntegrated(server, user);
}
}
private void startSound(boolean load) {
if(load)
SoundEvent.loadSounds();
audio = new AudioInterface(this.soundFrameSize, this.soundBufferSize, !this.soundEnabled);
boolean started = audio.start();
Log.flushLog();
if(started)
Log.SOUND.info("Audiogerät geöffnet");
else if(this.soundEnabled)
Log.SOUND.info("Audiogerät konnte nicht geöffnet werden");
for(Volume volume : Volume.values()) {
volume.apply();
}
}
public void restartSound(boolean load) {
Log.CONSOLE.user("Lade Sound-System neu");
this.soundManager.unload();
if(audio.end())
Log.SOUND.info("Audiogerät geschlossen");
this.startSound(load);
Log.CONSOLE.user("Das Sound-System wurde neu geladen");
}
public AudioInterface getAudioInterface() {
return audio;
}
public long rtime() {
return WCF.getTime() - start;
}
public double ftime() {
return ((double)rtime()) / 1000000.0;
}
public void jvmgc() {
Log.CONSOLE.user("Führe JVM GC aus");
long mem = Runtime.getRuntime().freeMemory();
System.gc();
System.gc();
mem = Runtime.getRuntime().freeMemory() - mem;
mem = mem < 0L ? 0L : mem;
Log.CONSOLE.user("JVM GC ausgeführt: %d MB freigegeben", (int)(mem / 1024L / 1024L));
}
public void hitboxes() {
this.getRenderManager().setDebugBoundingBox(!this.getRenderManager().isDebugBoundingBox());
Log.CONSOLE.user("Objekt-Grenzen: %s", this.getRenderManager().isDebugBoundingBox() ? "an" : "aus");
}
public void debugcam() {
Log.CONSOLE.user("Debug-Kamera 3. Person: %s", (this.debugCamEnable ^= true) ? "an" : "aus");
}
public void xray() {
this.xrayActive ^= true;
this.renderGlobal.loadRenderers();
Log.CONSOLE.user("Röntgenblick: %s", this.xrayActive ? "an" : "aus");
}
public void outlines() {
Log.CONSOLE.user("Objekt-Umrahmung: %s", (this.renderOutlines ^= true) ? "an" : "aus");
}
public void tileview() {
Log.CONSOLE.user("Block-Objekte anzeigen: %s", (this.tileOverlay ^= true) ? "an" : "aus");
}
public void rebuild() {
Log.CONSOLE.user("Kompiliere alle Chunks neu");
this.renderGlobal.loadRenderers();
Log.CONSOLE.user("Alle Chunks wurden neu kompiliert");
}
public void refreshtex() {
Log.CONSOLE.user("Lade Texturen neu");
this.refreshResources();
Log.CONSOLE.user("Texturen wurden neu geladen");
}
public void warp() {
if(server != null) {
server.schedule(new Runnable() {
public void run() {
server.setTpsTarget(server.getTpsTarget() < 10000.0f ? 10000.0f : 20.0f);
}
});
}
}
public void magnet() {
this.performAction(Action.MAGNET);
}
public void heal() {
this.performAction(Action.HEAL);
}
public void perfs() {
this.performAction(Action.PERF);
}
public void convert(File folder, String user) {
Converter.convertMapFormat(folder, user);
}
public void bind(int port) {
if(server != null)
server.bind(port);
}
public String getldebug() {
return this.getLeft(server);
}
public void crash() {
throw new RuntimeException("Manuell herbeigerufener Debugging-Absturz");
}
public void distance(int distance) {
if(server != null)
server.setVar("viewDistance", "" + distance);
}
public static void main(String[] args) {
WCF.init();
Locale.setDefault(Locale.ROOT);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable e) {
System.err.println("Fehler in Thread '" + thread.getName() + "'");
e.printStackTrace(System.err);
if(INSTANCE.crashed)
System.exit(1);
if(e instanceof OutOfMemoryError) {
System.gc();
System.gc();
}
if(!thread.getName().startsWith("Thread-") || e instanceof OutOfMemoryError) {
System.err.println("Beende!");
INSTANCE.crashed = true;
if(System.getProperty("crash.nodump") == null) {
PrintStream ps = null;
File report = null;
try {
Date date = new Date();
File file = new File("crash-" + new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(date) + ".txt");
FileOutputStream out = new FileOutputStream(file);
ps = new PrintStream(out);
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] info = bean.dumpAllThreads(true, true);
StringBuilder sb = new StringBuilder();
Error error = new Error();
for(ThreadInfo threadinfo : info) {
if(threadinfo.getThreadId() == thread.getId())
error.setStackTrace(threadinfo.getStackTrace());
sb.append(threadinfo);
}
ps.println("************************************************ " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date) + " ************************************************");
ps.println();
ps.println("\"Wie haste das denn nu wieder geschafft, Bursche?\"");
ps.println("Unerwarteter Fehler in Thread '" + thread.getName() + "':");
e.printStackTrace(ps);
ps.println();
ps.println("---------------------------------------------- Thread-Dump (" + info.length + " Threads) ---------------------------------------------");
ps.println();
ps.print(sb.toString());
ps.println("*********************************************************************************************************************");
report = file;
}
catch(Throwable t) {
System.err.println("Konnte Absturzbericht nicht speichern:");
t.printStackTrace(System.err);
}
finally {
if(ps != null)
ps.close();
}
if(report != null) {
System.err.println("Absturzbericht gespeichert unter " + report.getPath());
try {
Desktop.getDesktop().browse(report.toURI());
}
catch(Throwable e1) {
System.err.println("Konnte " + report + " nicht öffnen: " + e1);
}
}
}
System.exit(1);
}
}
});
ImageIO.setUseCache(false);
Thread timer = new Thread("Timer Hack Thread") {
public void run() {
while(true) {
try {
Thread.sleep(2147483647L);
}
catch(InterruptedException e) {
;
}
}
}
};
timer.setDaemon(true);
timer.start();
System.setProperty("java.net.preferIPv4Stack", "true");
Registry.register();
// game = new Game();
Runtime.getRuntime().addShutdownHook(new Thread("Game Shutdown Thread") {
public void run() {
if(!INSTANCE.crashed && INSTANCE.server != null) {
try {
INSTANCE.server.stopServer();
}
catch(Throwable e) {
e.printStackTrace();
}
}
}
});
Thread.currentThread().setName("Render thread");
INSTANCE.run();
}
private static float tri(float x, float p, float a) {
return ((4.0f * a) / p) * ExtMath.absf(((x - p / 4.0f) % p) - p / 2.0f) - a;
}
private static void memcpy(byte[] dest, int doff, byte[] src, int soff, int len) {
System.arraycopy(src, soff, dest, doff, len);
}
private static byte[] genTriwave(int w, int h, int color1, int color2, int color3, int color4, int color5, int color6) {
byte[] data = new byte[w * h * 4];
byte[] color = new byte[24];
color1 = (color1 << 8) | (color1 >> 24);
color2 = (color2 << 8) | (color2 >> 24);
color3 = (color3 << 8) | (color3 >> 24);
color4 = (color4 << 8) | (color4 >> 24);
color5 = (color5 << 8) | (color5 >> 24);
color6 = (color6 << 8) | (color6 >> 24);
for(int z = 0; z < 4; z++) {
color[z] = (byte)((color1 >> ((3 - z) * 8)) & 0xff);
color[z+4] = (byte)((color2 >> ((3 - z) * 8)) & 0xff);
color[z+8] = (byte)((color3 >> ((3 - z) * 8)) & 0xff);
color[z+12] = (byte)((color4 >> ((3 - z) * 8)) & 0xff);
color[z+16] = (byte)((color5 >> ((3 - z) * 8)) & 0xff);
color[z+20] = (byte)((color6 >> ((3 - z) * 8)) & 0xff);
}
for(int y = 0; y < h; y++) {
int offs = ((y / 2 == h / 16) || (y / 2 == (h / 2 - h / 16) - 1)) ? 16 : (((y / 2 == h / 16 + 1) || (y / 2 == (h / 2 - h / 16) - 2)) ? 20 : 0);
for(int x = 0; x < w; x++) {
memcpy(data, (y*w+x) << 2, color, offs, 4);
}
}
for(int x = 0; x < w; x++) {
int y = ((x < w / 8) || (x >= w - w / 8)) ? (h / 2) : (h / 2 + (int)tri((float)(w / 4 + x), (float)((w * 3) / 4), (float)(((h * 3) / 4) / 2)));
// sys_assert(y - 8 >= 0 && y + 7 < h)
memcpy(data, ((y-8)*w+x) << 2, color, 0, 4);
memcpy(data, ((y-7)*w+x) << 2, color, 0, 4);
memcpy(data, ((y-6)*w+x) << 2, color, 0, 4);
memcpy(data, ((y-5)*w+x) << 2, color, 4, 4);
memcpy(data, ((y-4)*w+x) << 2, color, 4, 4);
memcpy(data, ((y-3)*w+x) << 2, color, 0, 4);
memcpy(data, ((y-2)*w+x) << 2, color, 0, 4);
memcpy(data, ((y-1)*w+x) << 2, color, 8, 4);
memcpy(data, ((y+0)*w+x) << 2, color, 8, 4);
memcpy(data, ((y+1)*w+x) << 2, color, 0, 4);
memcpy(data, ((y+2)*w+x) << 2, color, 0, 4);
memcpy(data, ((y+3)*w+x) << 2, color, 12, 4);
memcpy(data, ((y+4)*w+x) << 2, color, 12, 4);
memcpy(data, ((y+5)*w+x) << 2, color, 0, 4);
memcpy(data, ((y+6)*w+x) << 2, color, 0, 4);
memcpy(data, ((y+7)*w+x) << 2, color, 0, 4);
}
return data;
}
// plr_play("/home/sen/Musik/midi50k/Video_Games/ff/ff2cecil.mid", 0);
public static void meltdown() {
Random rand = new Random();
Log.SYSTEM.error("CORE_MELTDOWN: Nuclear processor core meltdown imminent\n\n" +
" ************************ CAUTION ************************\n" +
" KCTL: Processor core #%02d has reached a critical\n" +
" temperature, system explosion is imminent! \n" +
" According to the general core density \n" +
" calculation routine defined by the SKC \n" +
" (Hard) Warfare Testing Facility (SKC-WTF) \n" +
" your processor will cause a detonation with \n" +
" a radius of (roughly) %d.%d kilometers. \n" +
" In addition, it will release appoximately \n" +
" %d megajoules of ionizing radiation. \n" +
" You have an estimate time of %d minutes and \n" +
" %d seconds left to clear the detonation area. \n" +
" ************************ CAUTION ************************\n"
, rand.range(1, 64), rand.range(1, 9), rand.range(0, 9), rand.range(10000, 39999), rand.range(3, 9), rand.range(2, 59));
}
public <T extends CVar> T getVar(String name) {
return (T)cvars.get(name);
}
public void setDirty() {
cfgDirty = true;
}
public boolean isDirty() {
return cfgDirty;
}
public String getBuffer() {
return buffer;
}
private void regVar(CVar cv) {
if(cvars.containsKey(cv.getCVarName()))
throw new IllegalArgumentException("Variable " + cv.getCVarName() + " existiert bereits!");
cvars.put(cv.getCVarName(), cv);
}
private void regVars(Class clazz, Object object) {
for(Field field : clazz.getDeclaredFields()) {
if(field.isAnnotationPresent(Variable.class)) {
if(Modifier.isStatic(field.getModifiers()) != (object == null))
continue;
if(Modifier.isFinal(field.getModifiers()))
throw new IllegalArgumentException("Feld für Variable " + field + " muss änderbar sein!");
Variable value = field.getAnnotation(Variable.class);
if(value.name().isEmpty())
throw new IllegalArgumentException("Variablenname von " + field + " kann nicht leer sein!");
CVar cv;
VarFunction func = null;
if(value.callback() != VarFunction.class) {
try {
func = value.callback().getConstructor().newInstance();
}
catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
if(field.getType() == int.class)
cv = value.type() != IntType.INT ? new ColorVar(value.name(), value.display(), field, object, value.category(), value.type() == IntType.ALPHA, (IntFunction)func) :
new IntVar(value.name(), value.display(), field, object, value.category(), (int)value.min(), (int)value.max(), (IntFunction)func, value.unit(), value.precision());
else if(field.getType() == float.class)
cv = new FloatVar(value.name(), value.display(), field, object, value.category(), value.min(), value.max(), (FloatFunction)func, value.unit(), value.precision());
else if(field.getType() == boolean.class)
cv = new BoolVar(value.name(), value.display(), field, object, value.category(), (BoolFunction)func);
else if(field.getType().isEnum())
cv = new EnumVar(value.name(), value.display(), field, object, value.category(), (EnumFunction)func);
else
throw new IllegalArgumentException(value.name() + ": Unbekannter Variablen-Typ - " + field.getType());
regVar(cv);
}
}
}
private void regVars(Object object) {
regVars(object.getClass(), object);
}
private void regVars(Class clazz) {
regVars(clazz, null);
}
public void initConsole() {
reset();
for(Bind bind : Bind.values()) {
regVar(bind);
}
for(Volume volume : Volume.values()) {
regVar(volume);
}
regVars(this);
regVars(Style.CUSTOM);
if(!config.exists())
return;
String data;
try {
data = FileUtils.read(config);
}
catch(IOException e) {
Log.CONSOLE.error(e, "Konnte Konfigurationsdatei nicht laden");
return;
}
if(data == null)
return;
for(String line : data.split("\n")) { // new String(data, CharsetUtil.UTF_8).split("\n")
if(line.startsWith("#"))
continue;
String[] tok = line.split("=", 2);
if(tok.length != 2)
continue;
CVar cv = getVar(tok[0]);
if(cv == null) {
Log.CONSOLE.error("CVAR '%s' existiert nicht", tok[0]);
continue;
}
if(cv.parse(tok[1])) {
Log.CONSOLE.trace("%s = %s", cv.getCVarName(), cv.format());
}
else {
Log.CONSOLE.error("Kann CVAR '%s' nicht auf '%s' setzen", cv.getCVarName(), tok[1]);
}
}
}
public void save() {
cfgDirty = false;
StringBuilder sb = new StringBuilder();
for(CVar cv : cvars.values()) {
if(sb.length() > 0)
sb.append('\n');
sb.append(cv.getCVarName() + "=" + cv.format());
}
try {
FileUtils.write(config, sb.toString());
}
catch(IOException e) {
Log.CONSOLE.error(e, "Konnte Konfigurationsdatei nicht speichern");
}
}
private void printVar(CVar cv) {
String values = cv.getValues();
Log.CONSOLE.user("%s " + TextColor.NEON + "%s " + TextColor.DGRAY + "[%s" + TextColor.DGRAY + "]" + TextColor.GRAY + " = " + TextColor.WHITE + "%s " + TextColor.DGRAY +
"[" + TextColor.GRAY + "D " + TextColor.CRIMSON + "%s" + TextColor.DGRAY + "]%s", cv.getType(), cv.getCVarName(), cv.getCategory(), cv.format(), cv.getDefault(),
values != null ? " [" + TextColor.LGRAY + values + TextColor.DGRAY + "]" : "");
}
public void exec(String line) {
if(line.equals("#")) {
for(CVar cv : cvars.values()) {
printVar(cv);
}
Log.CONSOLE.user(TextColor.GREEN + "CVARs insgesamt registriert: %d", cvars.size());
// this.command(line);
// return;
}
else if(line.startsWith("#")) {
String tok = line.substring(1);
int space = tok.indexOf(' ');
CVar cv = getVar(space >= 0 ? tok.substring(0, space) : tok);
if(cv != null) {
if(space < 0 || space >= tok.trim().length()) {
Log.CONSOLE.user("%s = %s", cv.getCVarName(), cv.format());
return;
}
String value = tok.substring(space + 1).trim();
if(cv.parse(value)) {
cfgDirty = true;
Log.CONSOLE.user("%s -> %s", cv.getCVarName(), cv.format());
}
else {
Log.CONSOLE.error("Kann CVAR '%s' nicht auf '%s' setzen", cv.getCVarName(), value);
}
return;
}
}
if(this.thePlayer != null && this.getNetHandler() != null)
this.getNetHandler().addToSendQueue(new CPacketMessage(CPacketMessage.Type.CHAT, line));
// Log.CONSOLE.user("%s", line);
// this.command(line);
}
public void reset() {
buffer = TextColor.NEON + "*** " + Config.VERSION + " ***";
log.clear();
}
public void resize(int size) {
while(log.size() > this.hudSize) {
log.remove(log.size() - 1);
}
}
public void log(String prefixed, String line) {
String msg = this.conTimestamps ? prefixed : line;
if((buffer.length() + msg.length() + 1) > LOG_BUFFER) {
int offset = (msg.length() + 1) > 1024 ? (msg.length() + 1) : 1024;
int nl = buffer.indexOf('\n', offset);
buffer = nl >= 0 ? buffer.substring(nl + 1) : "";
}
buffer = buffer + "\n" + msg;
if(this.open instanceof GuiConsole) {
((GuiConsole)this.open).setLog(buffer);
}
if(this.hudSize > 0) {
Message lmsg = new Message(line, Timing.tmr_current);
while(log.size() >= this.hudSize) {
log.remove(log.size() - 1);
}
log.add(0, lmsg);
}
}
public void drawOverlay() {
if(this.hudSize > 0) {
long fade = 1000L * (long)this.hudFadeout;
int y = this.hudPos == ConsolePos.BOTTOM ? this.fb_y - Font.YGLYPH : 0;
for(Iterator<Message> iter = log.iterator(); iter.hasNext();) {
Message msg = iter.next();
if((Timing.tmr_current - msg.time) <= fade) {
Drawing.txt_draw(0, y, 0, y, this.fb_x, this.fb_y,
(this.hudOpacity << 24) | 0xffffff, msg.message);
y += this.hudPos == ConsolePos.BOTTOM ? -(Font.YGLYPH) : Font.YGLYPH;
}
else {
iter.remove();
}
}
}
else {
log.clear();
}
}
public void showDirDialog(final String title, final String def, final FileCallback callback) {
new Thread(new Runnable() {
public void run() {
String output;
try {
Process proc = Runtime.getRuntime().exec(new String[] {"zenity", "--file-selection", "--directory", "--title", title, "--filename", def + File.separator +
"__THISFILEDOESNOTEXIST__"});
BufferedReader buf = new BufferedReader(new InputStreamReader(new BufferedInputStream(proc.getInputStream())));
proc.waitFor();
output = buf.readLine();
try {
buf.close();
}
catch(Throwable e) {
}
}
catch(Throwable e) {
return;
}
if(output != null) {
File file = new File(output);
if(file.isDirectory()) {
Game.this.schedule(new Runnable() {
public void run() {
callback.selected(file);
}
});
}
}
}
}, "Zenity listener").start();
}
}