From 483afb30cff03fc647b6e50b3d0a28a77fe55529 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Sat, 27 May 2023 12:31:17 +0200 Subject: [PATCH 01/60] Add lombok and refactor logger --- build.gradle | 4 ++ .../java/com/minecrafttas/tasmod/TASmod.java | 12 +++--- .../com/minecrafttas/tasmod/TASmodClient.java | 8 ++-- .../tasmod/commands/folder/OpenStuff.java | 4 +- .../tasmod/events/OpenGuiEvents.java | 4 +- .../tasmod/handlers/LoadingScreenHandler.java | 6 +-- .../tasmod/ktrng/KillTheRNGHandler.java | 4 +- .../tasmod/networking/PacketSerializer.java | 10 ++--- .../tasmod/playback/PlaybackController.java | 38 +++++++++---------- .../tasmod/playback/PlaybackSerialiser.java | 6 +-- .../playback/server/TASstateServer.java | 2 +- .../client/InputSavestatesHandler.java | 10 ++--- .../client/InputSavestatesPacket.java | 2 +- .../savestates/server/SavestateHandler.java | 2 +- .../chunkloading/SavestatesChunkControl.java | 20 +++++----- .../server/motion/ClientMotionServer.java | 6 +-- .../playerloading/SavestatePlayerLoading.java | 2 +- .../TickrateChangerClient.java | 2 +- .../tasmod/virtual/VirtualInput.java | 4 +- 19 files changed, 75 insertions(+), 71 deletions(-) diff --git a/build.gradle b/build.gradle index 5c41a5a6..dcb5d828 100644 --- a/build.gradle +++ b/build.gradle @@ -42,6 +42,10 @@ configurations { // dependencies dependencies { + // annotation processor + compileOnly 'org.projectlombok:lombok:1.18.28' + annotationProcessor 'org.projectlombok:lombok:1.18.28' + // tasmod dependencies embed group: 'com.dselent', name: 'bigarraylist', version: '1.0' compileOnly group: 'com.minecrafttas', name: 'killtherng', version: '2.0' diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 5447c011..98e58879 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -69,7 +69,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ private static MinecraftServer serverInstance; - public static final Logger logger = LogManager.getLogger("TASmod"); + public static final Logger LOGGER = LogManager.getLogger("TASmod"); public static TASstateServer containerStateServer; @@ -110,10 +110,10 @@ public void onServerInit(MinecraftServer server) { e.printStackTrace(); } - savestateHandler=new SavestateHandler(server, logger); + savestateHandler=new SavestateHandler(server, LOGGER); try { - packetServer = new TASmodNetworkServer(logger); + packetServer = new TASmodNetworkServer(LOGGER); } catch (IOException e) { e.printStackTrace(); } @@ -136,14 +136,14 @@ public static MinecraftServer getServerInstance() { @Override public void onInitialize() { - logger.info("Initializing TASmod"); + LOGGER.info("Initializing TASmod"); EventListener.register(this); - logger.info("Testing connection with KillTheRNG"); + LOGGER.info("Testing connection with KillTheRNG"); ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); EventListener.register(ktrngHandler); - tickratechanger = new TickrateChangerServer(logger); + tickratechanger = new TickrateChangerServer(LOGGER); EventListener.register(tickratechanger); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index ee3e2fb4..52f81046 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -162,17 +162,17 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { Minecraft mc = Minecraft.getMinecraft(); if(mc.isIntegratedServerRunning()) - TASmodClient.packetClient = new TASmodNetworkClient(TASmod.logger); + TASmodClient.packetClient = new TASmodNetworkClient(TASmod.LOGGER); else { String full = mc.getCurrentServerData().serverIP; String[] fullsplit = full.split(":"); if(fullsplit.length == 1) { - TASmodClient.packetClient = new TASmodNetworkClient(TASmod.logger, full, 3111); + TASmodClient.packetClient = new TASmodNetworkClient(TASmod.LOGGER, full, 3111); } else if(fullsplit.length == 2){ String ip = fullsplit[0]; - TASmodClient.packetClient = new TASmodNetworkClient(TASmod.logger, ip, 3111); + TASmodClient.packetClient = new TASmodNetworkClient(TASmod.LOGGER, ip, 3111); } else { - TASmod.logger.error("Something went wrong while connecting. The ip seems to be wrong"); + TASmod.LOGGER.error("Something went wrong while connecting. The ip seems to be wrong"); } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java b/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java index ee84ebf4..16b6e8c8 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java @@ -16,7 +16,7 @@ public static void openTASFolder() { file.mkdir(); Desktop.getDesktop().open(file); } catch (IOException e) { - TASmod.logger.error("Something went wrong while opening ", file.getPath()); + TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); e.printStackTrace(); } } @@ -28,7 +28,7 @@ public static void openSavestates() { file.mkdir(); Desktop.getDesktop().open(file); } catch (IOException e) { - TASmod.logger.error("Something went wrong while opening ", file.getPath()); + TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); e.printStackTrace(); } } diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java index ab07fe34..eb9fd0f2 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java @@ -40,7 +40,7 @@ public static void openGuiIngameMenu(GuiIngameMenu guiIngameMenu) { */ public static void openGuiControls(GuiControls guiControls) { if (TASmodClient.tickratechanger.ticksPerSecond == 0 || TASmodClient.tickratechanger.advanceTick) { - TASmod.logger.info("Pausing game during GuiControls"); + TASmod.LOGGER.info("Pausing game during GuiControls"); TASmodClient.tickratechanger.pauseGame(false); TASstateClient.setOrSend(stateWhenOpened); waszero = true; @@ -54,7 +54,7 @@ public static void openGuiControls(GuiControls guiControls) { */ public static void closeGuiControls(GuiControls guiControls) { if (waszero) { - TASmod.logger.info("Unpausing the game again"); + TASmod.LOGGER.info("Unpausing the game again"); waszero = false; TASmodClient.tickratechanger.pauseGame(true); } diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java index 35ab6609..09234a50 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java @@ -24,7 +24,7 @@ public class LoadingScreenHandler implements EventLaunchIntegratedServer, EventC @Override public void onLaunchIntegratedServer() { - TASmod.logger.debug(LoggerMarkers.Event, "Starting the integrated server"); + TASmod.LOGGER.debug(LoggerMarkers.Event, "Starting the integrated server"); PlaybackController container = TASmodClient.virtual.getContainer(); if(!container.isNothingPlaying() && !container.isPaused()) { container.pause(true); @@ -39,7 +39,7 @@ public void onLaunchIntegratedServer() { public void onRunClientGameLoop(Minecraft mc) { if (loadingScreenDelay > -1) { if (loadingScreenDelay == 0) { - TASmod.logger.debug(LoggerMarkers.Event, "Finished loading screen on the client"); + TASmod.LOGGER.debug(LoggerMarkers.Event, "Finished loading screen on the client"); TASmodClient.tickratechanger.joinServer(); if (!waszero) { if(TASmod.getServerInstance()!=null) { //Check if a server is running and if it's an integrated server @@ -58,7 +58,7 @@ public void onRunClientGameLoop(Minecraft mc) { @Override public void onDoneLoadingWorld() { if(TASmod.getServerInstance()!=null) { //Check if a server is running and if it's an integrated server - TASmod.logger.debug(LoggerMarkers.Event, "Finished loading the world on the client"); + TASmod.LOGGER.debug(LoggerMarkers.Event, "Finished loading the world on the client"); loadingScreenDelay = 1; } } diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index a78a2a27..07c46acf 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -38,7 +38,7 @@ public KillTheRNGHandler(boolean isLoaded) { KillTheRNG.annotations.register(new KTRNGMonitor()); }else { - TASmod.logger.info("KillTheRNG doesn't appear to be loaded"); + TASmod.LOGGER.info("KillTheRNG doesn't appear to be loaded"); } } @@ -130,7 +130,7 @@ public void broadcastStartSeed() { @Environment(EnvType.CLIENT) public void setInitialSeed(long initialSeed) { if(TASmodClient.packetClient != null) { - TASmod.logger.info("Sending initial client seed: {}", initialSeed); + TASmod.LOGGER.info("Sending initial client seed: {}", initialSeed); TASmodClient.packetClient.sendToServer(new KTRNGStartSeedPacket(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD } else { TASmod.ktrngHandler.setGlobalSeedClient(initialSeed); diff --git a/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java b/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java index d901712c..743912b6 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java @@ -35,7 +35,7 @@ public static Packet deserialize(PacketBuffer buf) { } if(packet == null) { - TASmod.logger.warn("Unregistered packet received! Packet Id: " + packetId); + TASmod.LOGGER.warn("Unregistered packet received! Packet Id: " + packetId); return null; } @@ -56,7 +56,7 @@ public static PacketBuffer serialize(Packet packet) { int packetID = REGISTRY.indexOf(packet.getClass()); if(packetID == -1) { - TASmod.logger.warn("Unregistered packet was trying to be serialized! Packet Class: " + packet.getClass().getSimpleName()); + TASmod.LOGGER.warn("Unregistered packet was trying to be serialized! Packet Class: " + packet.getClass().getSimpleName()); return null; } @@ -67,16 +67,16 @@ public static PacketBuffer serialize(Packet packet) { } public static void registerPacket(Class packet) { - TASmod.logger.trace("Registering packet {}", packet.getClass().getSimpleName()); + TASmod.LOGGER.trace("Registering packet {}", packet.getClass().getSimpleName()); if(REGISTRY.contains(packet)) { - TASmod.logger.warn("Trying to register packet which already exists: {}", packet.getClass().getSimpleName()); + TASmod.LOGGER.warn("Trying to register packet which already exists: {}", packet.getClass().getSimpleName()); } REGISTRY.add(packet); } public static void unregisterPacket(Class packet) { if(REGISTRY.contains(packet)) { - TASmod.logger.warn("Trying to unregister packet which doesn't exist in the registry: {}", packet.getClass().getSimpleName()); + TASmod.LOGGER.warn("Trying to unregister packet which doesn't exist in the registry: {}", packet.getClass().getSimpleName()); } REGISTRY.remove(packet); } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 84320e27..54eca09b 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -153,7 +153,7 @@ public String setTASState(TASstate stateIn, boolean verbose) { } else if (state == TASstate.NONE) { // If the container is currently doing nothing switch (stateIn) { case PLAYBACK: - TASmod.logger.debug(LoggerMarkers.Playback, "Starting playback"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Starting playback"); if (Minecraft.getMinecraft().player != null && !startLocation.isEmpty()) { try { tpPlayer(startLocation); @@ -170,7 +170,7 @@ public String setTASState(TASstate stateIn, boolean verbose) { TASmod.ktrngHandler.setInitialSeed(startSeed); return verbose ? TextFormatting.GREEN + "Starting playback" : ""; case RECORDING: - TASmod.logger.debug(LoggerMarkers.Playback, "Starting recording"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Starting recording"); if (Minecraft.getMinecraft().player != null && startLocation.isEmpty()) { startLocation = getStartLocation(Minecraft.getMinecraft().player); } @@ -192,12 +192,12 @@ public String setTASState(TASstate stateIn, boolean verbose) { case RECORDING: return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Recording)"; case PAUSED: - TASmod.logger.debug(LoggerMarkers.Playback, "Pausing a recording"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Pausing a recording"); state = TASstate.PAUSED; tempPause = TASstate.RECORDING; return verbose ? TextFormatting.GREEN + "Pausing a recording" : ""; case NONE: - TASmod.logger.debug(LoggerMarkers.Playback, "Stopping a recording"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Stopping a recording"); TASmodClient.virtual.unpressEverything(); state = TASstate.NONE; return verbose ? TextFormatting.GREEN + "Stopping the recording" : ""; @@ -209,13 +209,13 @@ public String setTASState(TASstate stateIn, boolean verbose) { case RECORDING: return verbose ? TextFormatting.RED + "A playback is currently running. Please stop the playback first before starting a recording" : ""; case PAUSED: - TASmod.logger.debug(LoggerMarkers.Playback, "Pausing a playback"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Pausing a playback"); state = TASstate.PAUSED; tempPause = TASstate.PLAYBACK; TASmodClient.virtual.unpressEverything(); return verbose ? TextFormatting.GREEN + "Pausing a playback" : ""; case NONE: - TASmod.logger.debug(LoggerMarkers.Playback, "Stopping a playback"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Stopping a playback"); Minecraft.getMinecraft().gameSettings.chatLinks = true; TASmodClient.virtual.unpressEverything(); state = TASstate.NONE; @@ -224,19 +224,19 @@ public String setTASState(TASstate stateIn, boolean verbose) { } else if (state == TASstate.PAUSED) { switch (stateIn) { case PLAYBACK: - TASmod.logger.debug(LoggerMarkers.Playback, "Resuming a playback"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Resuming a playback"); state=TASstate.PLAYBACK; tempPause=TASstate.NONE; return verbose ? TextFormatting.GREEN + "Resuming a playback" : ""; case RECORDING: - TASmod.logger.debug(LoggerMarkers.Playback, "Resuming a recording"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Resuming a recording"); state=TASstate.RECORDING; tempPause=TASstate.NONE; return verbose ? TextFormatting.GREEN + "Resuming a recording" : ""; case PAUSED: return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Paused)"; case NONE: - TASmod.logger.debug(LoggerMarkers.Playback, "Aborting pausing"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Aborting pausing"); state=TASstate.NONE; TASstate statey=tempPause; tempPause=TASstate.NONE; @@ -264,7 +264,7 @@ public TASstate togglePause() { * @param pause True, if it should be paused */ public void pause(boolean pause) { - TASmod.logger.trace(LoggerMarkers.Playback, "Pausing {}", pause); + TASmod.LOGGER.trace(LoggerMarkers.Playback, "Pausing {}", pause); if(pause) { if(state!=TASstate.NONE) { setTASState(TASstate.PAUSED, false); @@ -391,7 +391,7 @@ private void recordNextTick() { index++; if(inputs.size()<=index) { if(inputs.size()(directory + File.separator + "temp"); controlBytes.clear(); comments.clear(); @@ -598,7 +598,7 @@ public String getStartLocation() { * @param startLocation The start location of the TAS */ public void setStartLocation(String startLocation) { - TASmod.logger.debug(LoggerMarkers.Playback, "Setting start location"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Setting start location"); this.startLocation = startLocation; } @@ -609,7 +609,7 @@ public void setStartLocation(String startLocation) { * @return The start location from the player */ private String getStartLocation(EntityPlayerSP player) { - TASmod.logger.debug(LoggerMarkers.Playback, "Retrieving player start location"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Retrieving player start location"); String pos = player.posX + "," + player.posY + "," + player.posZ; String pitch = Float.toString(player.rotationPitch); String yaw = Float.toString(player.rotationYaw); @@ -624,7 +624,7 @@ private String getStartLocation(EntityPlayerSP player) { * @throws NumberFormatException If the location can't be parsed */ private void tpPlayer(String startLocation) throws NumberFormatException { - TASmod.logger.debug(LoggerMarkers.Playback, "Teleporting the player to the start location"); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Teleporting the player to the start location"); String[] section = startLocation.split(","); double x = Double.parseDouble(section[0]); double y = Double.parseDouble(section[1]); @@ -703,7 +703,7 @@ public void deserialize(PacketBuffer buf) { * Clears {@link #keyboard} and {@link #mouse} */ public void unpressContainer() { - TASmod.logger.trace(LoggerMarkers.Playback, "Unpressing container"); + TASmod.LOGGER.trace(LoggerMarkers.Playback, "Unpressing container"); keyboard.clear(); mouse.clear(); } @@ -711,7 +711,7 @@ public void unpressContainer() { // ============================================================== public void printCredits() { - TASmod.logger.trace(LoggerMarkers.Playback, "Printing credits"); + TASmod.LOGGER.trace(LoggerMarkers.Playback, "Printing credits"); if (state == TASstate.PLAYBACK&&!creditsPrinted) { creditsPrinted=true; printMessage(title, ChatFormatting.GOLD); @@ -857,7 +857,7 @@ public static TASstate fromIndex(int state) { private TASstate stateWhenOpened; public void setStateWhenOpened(TASstate state) { - TASmod.logger.trace(LoggerMarkers.Playback, "Set state when opened to {}", state); + TASmod.LOGGER.trace(LoggerMarkers.Playback, "Set state when opened to {}", state); stateWhenOpened = state; } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java index 1ef35db8..1d0fe9ee 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java @@ -98,7 +98,7 @@ public void saveToFileV1(File file, PlaybackController container) throws IOExcep * @throws IOException When the input container is empty */ public void saveToFileV1Until(File file, PlaybackController container, int index) throws IOException{ - TASmod.logger.debug(LoggerMarkers.Playback, "Saving playback controller to file {}", file); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Saving playback controller to file {}", file); if (container.size() == 0) { throw new IOException("There are no inputs to save to a file"); } @@ -164,7 +164,7 @@ public void saveToFileV1Until(File file, PlaybackController container, int index } public int getFileVersion(File file) throws IOException { - TASmod.logger.trace(LoggerMarkers.Playback, "Retrieving file version from {}", file); + TASmod.LOGGER.trace(LoggerMarkers.Playback, "Retrieving file version from {}", file); List lines = FileUtils.readLines(file, Charset.defaultCharset()); for (String line : lines) { if (line.contains("Version")) { @@ -182,7 +182,7 @@ public int getFileVersion(File file) throws IOException { } public PlaybackController fromEntireFileV1(File file) throws IOException { - TASmod.logger.debug(LoggerMarkers.Playback, "Loading playback controller to file {}", file); + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Loading playback controller to file {}", file); List lines = FileUtils.readLines(file, StandardCharsets.UTF_8); File monitorFile=new File(file, "../"+file.getName().replace(".mctas", "")+".mon"); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java index 3721a3ae..340fd7dd 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java @@ -69,7 +69,7 @@ public void setServerState(TASstate stateIn) { return; } this.state = stateIn; - TASmod.logger.info(String.format("Set the server state to %s", stateIn.toString())); + TASmod.LOGGER.info(String.format("Set the server state to %s", stateIn.toString())); } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java index b34e066a..923dd528 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java @@ -37,9 +37,9 @@ public class InputSavestatesHandler { * @throws IOException */ public static void savestate(String nameOfSavestate) throws SavestateException, IOException { - TASmod.logger.debug(LoggerMarkers.Savestate, "Saving client savestate {}", nameOfSavestate); + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Saving client savestate {}", nameOfSavestate); if (nameOfSavestate.isEmpty()) { - TASmod.logger.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); + TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); return; } @@ -64,9 +64,9 @@ public static void savestate(String nameOfSavestate) throws SavestateException, * @throws IOException */ public static void loadstate(String nameOfSavestate) throws IOException { - TASmod.logger.debug(LoggerMarkers.Savestate, "Loading client savestate {}", nameOfSavestate); + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Loading client savestate {}", nameOfSavestate); if (nameOfSavestate.isEmpty()) { - TASmod.logger.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); + TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); return; } @@ -82,7 +82,7 @@ public static void loadstate(String nameOfSavestate) throws IOException { TASmodClient.virtual.getContainer().setTASState(TASstate.NONE, false); Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); - TASmod.logger.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); + TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); } } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java index 46ef6fdd..17bd1772 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java @@ -34,7 +34,7 @@ public void handle(PacketSide side, EntityPlayer player) { try { InputSavestatesHandler.savestate(name); } catch (SavestateException e) { - TASmod.logger.error(e.getMessage()); + TASmod.LOGGER.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java index 772148c9..2766ef5a 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java @@ -631,7 +631,7 @@ public int getCurrentIndex() { @Override public void onLoadstateComplete() { - TASmod.logger.trace(LoggerMarkers.Event, "Running loadstate complete event"); + TASmod.LOGGER.trace(LoggerMarkers.Event, "Running loadstate complete event"); PlayerList playerList = TASmod.getServerInstance().getPlayerList(); for (EntityPlayerMP player : playerList.getPlayers()) { NBTTagCompound nbttagcompound = playerList.readPlayerDataFromFile(player); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java index 130f5b06..508949d9 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java @@ -35,7 +35,7 @@ public class SavestatesChunkControl { */ @Environment(EnvType.CLIENT) public static void unloadAllClientChunks() { - TASmod.logger.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); Minecraft mc = Minecraft.getMinecraft(); ChunkProviderClient chunkProvider=mc.world.getChunkProvider(); @@ -50,7 +50,7 @@ public static void unloadAllClientChunks() { * @see MixinChunkProviderServer#unloadAllChunks() */ public static void unloadAllServerChunks(MinecraftServer server) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); //Vanilla WorldServer[] worlds=server.worlds; @@ -74,7 +74,7 @@ public static void disconnectPlayersFromChunkMap(MinecraftServer server) { WorldServer[] worlds=server.worlds; for (WorldServer world : worlds) { for (EntityPlayerMP player : players) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); world.getPlayerChunkMap().removePlayer(player); } } @@ -91,7 +91,7 @@ public static void addPlayersToChunkMap(MinecraftServer server) { //Vanilla WorldServer[] worlds=server.worlds; for (EntityPlayerMP player : players) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); switch (player.dimension) { case -1: worlds[1].getPlayerChunkMap().addPlayer(player); @@ -114,7 +114,7 @@ public static void addPlayersToChunkMap(MinecraftServer server) { * Side: Server */ public static void flushSaveHandler(MinecraftServer server) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Flush the save handler"); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); //Vanilla WorldServer[] worlds=server.worlds; for(WorldServer world : worlds) { @@ -137,7 +137,7 @@ public static void flushSaveHandler(MinecraftServer server) { * Side: Server */ public static void updateSessionLock(MinecraftServer server) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Update the session lock"); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); WorldServer[] worlds=server.worlds; for(WorldServer world : worlds) { ((SaveHandler) world.getSaveHandler()).setSessionLock(); @@ -157,7 +157,7 @@ public static void updateSessionLock(MinecraftServer server) { */ @Environment(EnvType.CLIENT) public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.EntityPlayer player) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Keep player {} in loaded entity list", player.getName()); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Keep player {} in loaded entity list", player.getName()); Minecraft.getMinecraft().world.unloadedEntityList.remove(player); } @@ -177,7 +177,7 @@ public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.Enti */ @Environment(EnvType.CLIENT) public static void addPlayerToClientChunk(EntityPlayer player) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Add player {} to loaded entity list", player.getName()); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to loaded entity list", player.getName()); int i = MathHelper.floor(player.posX / 16.0D); int j = MathHelper.floor(player.posZ / 16.0D); Chunk chunk = Minecraft.getMinecraft().world.getChunkFromChunkCoords(i, j); @@ -196,7 +196,7 @@ public static void addPlayerToClientChunk(EntityPlayer player) { * Side: Server */ public static void addPlayerToServerChunk(EntityPlayerMP player) { - TASmod.logger.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); int i = MathHelper.floor(player.posX / 16.0D); int j = MathHelper.floor(player.posZ / 16.0D); WorldServer world = player.getServerWorld(); @@ -213,7 +213,7 @@ public static void addPlayerToServerChunk(EntityPlayerMP player) { * Updates ticklist entries to the current world time, allowing them to not be stuck in a pressed state #136 */ public static void updateWorldServerTickListEntries() { - TASmod.logger.trace(LoggerMarkers.Savestate, "Update server tick list entries"); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); MinecraftServer server=TASmod.getServerInstance(); for (WorldServer world : server.worlds) { for (NextTickListEntry nextticklistentry : world.pendingTickListEntriesHashSet) { diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java index dbfe299a..49723495 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java @@ -17,7 +17,7 @@ public static Map getMotion() { } public static void requestMotionFromClient() { - TASmod.logger.trace(LoggerMarkers.Savestate, "Request motion from client"); + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); motion.clear(); TASmod.packetServer.sendToAll(new RequestMotionPacket()); @@ -30,11 +30,11 @@ public static void requestMotionFromClient() { e.printStackTrace(); } if(i % 30 == 1) { - TASmod.logger.debug(LoggerMarkers.Savestate, "Resending motion packet"); + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); TASmod.packetServer.sendToAll(new RequestMotionPacket()); } if (i == 1000) { - TASmod.logger.warn(LoggerMarkers.Savestate, "Client motion timed out!"); + TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); break; } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java index 9f8a5821..c64de2bd 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java @@ -101,7 +101,7 @@ public static void reattachEntityToPlayer(NBTTagCompound nbttagcompound, World w if (!playerIn.isRiding()) { - TASmod.logger.warn("Couldn't reattach entity to player"); + TASmod.LOGGER.warn("Couldn't reattach entity to player"); worldserver.removeEntityDangerously(entity1); for (Entity entity2 : entity1.getRecursivePassengers()) diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index f85e1fc9..e72feade 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -176,7 +176,7 @@ public void joinServer() { } private static void log(String msg) { - TASmod.logger.debug(LoggerMarkers.Tickrate, msg); + TASmod.LOGGER.debug(LoggerMarkers.Tickrate, msg); } @Override diff --git a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java index 108fa55c..c32ba999 100644 --- a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java +++ b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java @@ -132,7 +132,7 @@ public VirtualInput(String fileToLoad) { loadInputs(fileToLoad); OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; } catch (IOException e) { - TASmod.logger.error("Cannot load inputs from the start of the TAS: {}", e.getMessage()); + TASmod.LOGGER.error("Cannot load inputs from the start of the TAS: {}", e.getMessage()); } } } @@ -532,7 +532,7 @@ private void preloadInput(PlaybackController container, int index) { // "currentKeyboard" Minecraft.getMinecraft().runTickMouse(); } else { - TASmod.logger.warn("Can't preload inputs, specified inputs are null!"); + TASmod.LOGGER.warn("Can't preload inputs, specified inputs are null!"); } } // ================================Load/Save Inputs===================================== From fc56586f32a7c8a8bbe0f99dd6c6478194191e47 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Sat, 27 May 2023 12:34:16 +0200 Subject: [PATCH 02/60] Implement asynchronous client --- .../java/com/minecrafttas/server/Client.java | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 src/main/java/com/minecrafttas/server/Client.java diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java new file mode 100644 index 00000000..b9c9d160 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -0,0 +1,124 @@ +package com.minecrafttas.server; + +import static com.minecrafttas.tasmod.TASmod.LOGGER; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousSocketChannel; +import java.nio.channels.CompletionHandler; + +import lombok.RequiredArgsConstructor; +import lombok.var; + +@RequiredArgsConstructor +public class Client { + + private final String host; + private final int port; + + private AsynchronousSocketChannel socket; + private ByteBuffer writePacketHeader; + + public static void main(String[] args) throws Exception { + Client c = new Client("127.0.0.1", 5555); + c.connect(); + c.write(ByteBuffer.allocate(4)); + } + + /** + * Try to connect socket + * @throws Exception Unable to connect + */ + public void connect() throws Exception { + if (this.isAlive()) { + LOGGER.warn("Tried to connect alive socket"); + return; + } + + // create connection + LOGGER.info("Connecting tasmod server to {}:{}", this.host, this.port); + this.socket = AsynchronousSocketChannel.open(); + this.socket.connect(new InetSocketAddress(this.host, this.port)).get(); + + // create buffers + this.writePacketHeader = ByteBuffer.allocate(4); + var readPacketHeader = ByteBuffer.allocate(4); + + // create input handler + this.socket.read(readPacketHeader, null, new CompletionHandler() { + + @Override + public void completed(Integer result, Object attachment) { + try { + ByteBuffer data = ByteBuffer.allocate(readPacketHeader.getInt()); + socket.read(data).get(); + + data.position(0); + handle(data); + + socket.read(readPacketHeader, null, this); // read packet header again + } catch (Throwable exc) { + LOGGER.error("Unable to read packet from server {}", exc); + } + } + + @Override + public void failed(Throwable exc, Object attachment) { + LOGGER.error("Unable to read packet from server {}", exc); + } + + }); + + LOGGER.info("Connected to tasmod server"); + } + + /** + * Write packet to server + * @param buf Packet + */ + public void write(ByteBuffer buf) { + this.writePacketHeader.clear(); + this.writePacketHeader.putInt(buf.capacity()); + this.socket.write(this.writePacketHeader, null, new CompletionHandler() { + + @Override + public void completed(Integer result, Object attachment) { + try { + buf.position(0); + socket.write(buf).get(); + } catch (Throwable exc) { + LOGGER.error("Unable to send packet to server {}", exc); + } + } + + @Override + public void failed(Throwable exc, Object attachment) { + LOGGER.error("Unable to send packet to server {}", exc); + } + + }); + } + + private void handle(ByteBuffer buf) { + System.out.println("hello buf, " + buf.getDouble()); + } + + /** + * Try to close socket + * @throws IOException Unable to close + */ + public void close() throws IOException { + if (!this.isAlive()) { + LOGGER.warn("Tried to close dead socket"); + return; + } + + this.socket.close(); + } + + public boolean isAlive() { + return this.socket != null && this.socket.isOpen(); + } + +} From cbdf96e0d00c18e1a63d45b8254045154e720fd0 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Sat, 27 May 2023 13:59:37 +0200 Subject: [PATCH 03/60] Implement server and update client --- .../java/com/minecrafttas/server/Client.java | 132 +++++++++--------- .../java/com/minecrafttas/server/Server.java | 91 ++++++++++++ 2 files changed, 155 insertions(+), 68 deletions(-) create mode 100644 src/main/java/com/minecrafttas/server/Server.java diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index b9c9d160..6a55ba4a 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -7,101 +7,97 @@ import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; +import java.util.concurrent.Future; -import lombok.RequiredArgsConstructor; -import lombok.var; - -@RequiredArgsConstructor public class Client { - private final String host; - private final int port; - private AsynchronousSocketChannel socket; - private ByteBuffer writePacketHeader; - - public static void main(String[] args) throws Exception { - Client c = new Client("127.0.0.1", 5555); - c.connect(); - c.write(ByteBuffer.allocate(4)); - } + private ByteBuffer writeBuffer; + private ByteBuffer readBuffer; + private Future future; /** - * Try to connect socket + * Create and connect socket + * @param host Host + * @param port Port * @throws Exception Unable to connect */ - public void connect() throws Exception { - if (this.isAlive()) { - LOGGER.warn("Tried to connect alive socket"); - return; - } - - // create connection - LOGGER.info("Connecting tasmod server to {}:{}", this.host, this.port); + public Client(String host, int port) throws Exception { + LOGGER.info("Connecting tasmod server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); - this.socket.connect(new InetSocketAddress(this.host, this.port)).get(); - + this.socket.connect(new InetSocketAddress(host, port)).get(); + this.createHandlers(); + LOGGER.info("Connected to tasmod server"); + } + + /** + * Fork existing socket + * @param socket Socket + */ + public Client(AsynchronousSocketChannel socket) { + this.socket = socket; + this.createHandlers(); + } + + /** + * Create read/write buffers and handlers for socket + */ + private void createHandlers() { // create buffers - this.writePacketHeader = ByteBuffer.allocate(4); - var readPacketHeader = ByteBuffer.allocate(4); - + this.writeBuffer = ByteBuffer.allocate(1024*1024); + this.readBuffer = ByteBuffer.allocate(1024*1024); + // create input handler - this.socket.read(readPacketHeader, null, new CompletionHandler() { + this.readBuffer.limit(4); + this.socket.read(this.readBuffer, null, new CompletionHandler() { @Override public void completed(Integer result, Object attachment) { try { - ByteBuffer data = ByteBuffer.allocate(readPacketHeader.getInt()); - socket.read(data).get(); + // read rest of packet + readBuffer.flip(); + int lim = readBuffer.getInt(); + readBuffer.clear().limit(lim); + socket.read(readBuffer).get(); + + // handle packet + readBuffer.position(0); + handle(readBuffer); - data.position(0); - handle(data); - - socket.read(readPacketHeader, null, this); // read packet header again + // read packet header again + readBuffer.clear().limit(4); + socket.read(readBuffer, null, this); } catch (Throwable exc) { - LOGGER.error("Unable to read packet from server {}", exc); + LOGGER.error("Unable to read packet {}", exc); } } @Override public void failed(Throwable exc, Object attachment) { - LOGGER.error("Unable to read packet from server {}", exc); + LOGGER.error("Unable to read packet {}", exc); } - + }); - - LOGGER.info("Connected to tasmod server"); } /** * Write packet to server * @param buf Packet + * @throws Exception Networking exception */ - public void write(ByteBuffer buf) { - this.writePacketHeader.clear(); - this.writePacketHeader.putInt(buf.capacity()); - this.socket.write(this.writePacketHeader, null, new CompletionHandler() { - - @Override - public void completed(Integer result, Object attachment) { - try { - buf.position(0); - socket.write(buf).get(); - } catch (Throwable exc) { - LOGGER.error("Unable to send packet to server {}", exc); - } - } - - @Override - public void failed(Throwable exc, Object attachment) { - LOGGER.error("Unable to send packet to server {}", exc); - } - - }); - } - - private void handle(ByteBuffer buf) { - System.out.println("hello buf, " + buf.getDouble()); + public void write(ByteBuffer buf) throws Exception { + // wait for previous buffer to send + if (this.future != null && !this.future.isDone()) + this.future.get(); + + // prepare buffer + this.writeBuffer.clear(); + this.writeBuffer.putInt(buf.capacity()); + this.writeBuffer.put((ByteBuffer) buf.position(0)); + this.writeBuffer.flip(); + + // send buffer async + this.future = this.socket.write(this.writeBuffer); } /** @@ -109,7 +105,7 @@ private void handle(ByteBuffer buf) { * @throws IOException Unable to close */ public void close() throws IOException { - if (!this.isAlive()) { + if (this.socket == null || !this.socket.isOpen()) { LOGGER.warn("Tried to close dead socket"); return; } @@ -117,8 +113,8 @@ public void close() throws IOException { this.socket.close(); } - public boolean isAlive() { - return this.socket != null && this.socket.isOpen(); + private void handle(ByteBuffer buf) { + System.out.println("hello buf, " + buf.getDouble()); } } diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java new file mode 100644 index 00000000..a8a74d2f --- /dev/null +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -0,0 +1,91 @@ +package com.minecrafttas.server; + +import static com.minecrafttas.tasmod.TASmod.LOGGER; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousServerSocketChannel; +import java.nio.channels.AsynchronousSocketChannel; +import java.nio.channels.CompletionHandler; +import java.util.ArrayList; +import java.util.List; + +import lombok.var; + +public class Server { + + private AsynchronousServerSocketChannel socket; + private List clients; + + public static void main(String[] args) throws Exception { + Server s = new Server(5555); + Client c = new Client("127.0.0.1", 5555); + + // send hello world double to server + var buf = ByteBuffer.allocate(8); + buf.putDouble(420.69); + c.write(buf); + + // send world hello double to client multiple times + for (int i = 0; i < 10; i++) { + buf = ByteBuffer.allocate(8); + buf.putDouble(69.420); + s.writeAll(buf); + } + } + + /** + * Create and bind socket + * @param port Port + * @throws Exception Unable to bind + */ + public Server(int port) throws Exception { + // create connection + LOGGER.info("Creating tasmod server on {}", port); + this.socket = AsynchronousServerSocketChannel.open(); + this.socket.bind(new InetSocketAddress(port)); + + // create connection handler + this.clients = new ArrayList<>(); + this.socket.accept(null, new CompletionHandler() { + + @Override + public void completed(AsynchronousSocketChannel clientSocket, Object attachment) { + clients.add(new Client(clientSocket)); + socket.accept(null, this); + } + + @Override + public void failed(Throwable exc, Object attachment) { + LOGGER.error("Unable to accept client {}", exc); + } + }); + + LOGGER.info("TASmod server created"); + } + + /** + * Write packet to all clients + * @param buf Packet + * @throws Exception Networking exception + */ + public void writeAll(ByteBuffer buf) throws Exception { + for (Client client : this.clients) + client.write(buf); + } + + /** + * Try to close socket + * @throws IOException Unable to close + */ + public void close() throws IOException { + if (this.socket == null || !this.socket.isOpen()) { + LOGGER.warn("Tried to close dead socket"); + return; + } + + this.socket.close(); + } + +} From e0a2f1dda91bebd277bf79f5aa2d9d11a89a51ba Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Wed, 14 Jun 2023 18:15:34 +0200 Subject: [PATCH 04/60] Implement authentication system --- .../java/com/minecrafttas/server/Client.java | 51 +++++++++++++++++-- .../java/com/minecrafttas/server/Server.java | 19 +------ 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 6a55ba4a..759e4176 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -7,14 +7,22 @@ import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.Future; +import java.util.function.Consumer; -public class Client { +import lombok.var; +public class Client { + private AsynchronousSocketChannel socket; private ByteBuffer writeBuffer; private ByteBuffer readBuffer; private Future future; + private Map> handlers = new HashMap<>(); + private UUID id; /** * Create and connect socket @@ -27,6 +35,7 @@ public Client(String host, int port) throws Exception { this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); this.createHandlers(); + this.registerClientsidePacketHandlers(); LOGGER.info("Connected to tasmod server"); } @@ -34,9 +43,10 @@ public Client(String host, int port) throws Exception { * Fork existing socket * @param socket Socket */ - public Client(AsynchronousSocketChannel socket) { + public Client(AsynchronousSocketChannel socket) { this.socket = socket; this.createHandlers(); + this.registerServersidePacketHandlers(); } /** @@ -113,8 +123,41 @@ public void close() throws IOException { this.socket.close(); } - private void handle(ByteBuffer buf) { - System.out.println("hello buf, " + buf.getDouble()); + /** + * Register packet handlers for packets received on the client + */ + private void registerClientsidePacketHandlers() { + } + /** + * Register packet handlers for packets received on the server + */ + private void registerServersidePacketHandlers() { + this.handlers.put(1, buf -> { + this.id = new UUID(buf.getLong(), buf.getLong()); + LOGGER.info("Client authenticated: " + this.id); + }); + } + + /** + * Sends then authentication packet to the server + * @param id Unique ID + * @throws Exception Unable to send packet + */ + public void authenticate(UUID id) throws Exception { + ByteBuffer buf = ByteBuffer.allocate(4+8+8); + buf.putInt(1); + buf.putLong(id.getMostSignificantBits()); + buf.putLong(id.getLeastSignificantBits()); + this.write(buf); + } + + private void handle(ByteBuffer buf) { + var id = buf.getInt(); + this.handlers.getOrDefault(id, _buf -> { + LOGGER.error("Received invalid packet: {}", id); + }).accept(buf); + } + } diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index a8a74d2f..74b12464 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -18,23 +18,6 @@ public class Server { private AsynchronousServerSocketChannel socket; private List clients; - public static void main(String[] args) throws Exception { - Server s = new Server(5555); - Client c = new Client("127.0.0.1", 5555); - - // send hello world double to server - var buf = ByteBuffer.allocate(8); - buf.putDouble(420.69); - c.write(buf); - - // send world hello double to client multiple times - for (int i = 0; i < 10; i++) { - buf = ByteBuffer.allocate(8); - buf.putDouble(69.420); - s.writeAll(buf); - } - } - /** * Create and bind socket * @param port Port @@ -71,7 +54,7 @@ public void failed(Throwable exc, Object attachment) { * @throws Exception Networking exception */ public void writeAll(ByteBuffer buf) throws Exception { - for (Client client : this.clients) + for (var client : this.clients) client.write(buf); } From 56e8f8510df55eb7d53984bd3b0c095a49e3b6ac Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Wed, 14 Jun 2023 18:15:44 +0200 Subject: [PATCH 05/60] Launch server and client on launch --- .../java/com/minecrafttas/tasmod/TASmod.java | 17 ++++++++++++++++- .../com/minecrafttas/tasmod/TASmodClient.java | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 98e58879..608bdfe5 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -10,6 +10,7 @@ import com.minecrafttas.common.events.EventListener; import com.minecrafttas.common.events.EventServer.EventServerInit; import com.minecrafttas.common.events.EventServer.EventServerStop; +import com.minecrafttas.server.Server; import com.minecrafttas.tasmod.commands.clearinputs.ClearInputsPacket; import com.minecrafttas.tasmod.commands.clearinputs.CommandClearInputs; import com.minecrafttas.tasmod.commands.folder.CommandFolder; @@ -83,6 +84,8 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static final TickScheduler tickSchedulerServer = new TickScheduler(); + public static Server server; + @Override public void onServerInit(MinecraftServer server) { serverInstance = server; @@ -125,9 +128,15 @@ public void onServerInit(MinecraftServer server) { } @Override - public void onServerStop(MinecraftServer server) { + public void onServerStop(MinecraftServer mcserver) { serverInstance=null; packetServer.close(); + try { + if (server != null) server.close(); + } catch (IOException e) { + LOGGER.error("Unable to close TASmod server: {}", e); + e.printStackTrace(); + } } public static MinecraftServer getServerInstance() { @@ -193,5 +202,11 @@ public void onInitialize() { PacketSerializer.registerPacket(PlayUntilPacket.class); + try { + server = new Server(5555); + } catch (Exception e) { + LOGGER.error("Unable to launch TASmod server: {}", e); + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 52f81046..606d8660 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import org.lwjgl.input.Keyboard; @@ -15,6 +16,7 @@ import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventClient.EventPlayerLeaveClientSide; import com.minecrafttas.common.events.EventListener; +import com.minecrafttas.server.Client; import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; @@ -71,6 +73,8 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even public static InterpolationHandler interpolation = new InterpolationHandler(); + public static Client client; + public static void createTASDir() { File tasDir=new File(tasdirectory); if(!tasDir.exists()) { @@ -125,6 +129,17 @@ protected boolean isKeyDown(KeyBinding i) { EventListener.register(keybindManager); EventListener.register(interpolation); + + try { + // connect to server and authenticate + client = new Client("127.0.0.1", 5555); + UUID uuid = mc.getSession().getProfile().getId(); + if (uuid == null) // dev environment + uuid = UUID.randomUUID(); + client.authenticate(uuid); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to connect TASmod client: {}", e); + } } @Override From 00f116fb6b47b9eebe7d08dbd7dcd95fb1dfbfe0 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Wed, 14 Jun 2023 18:47:27 +0200 Subject: [PATCH 06/60] Start moving packets to new system this is painful --- .../java/com/minecrafttas/server/Client.java | 36 +++ .../java/com/minecrafttas/server/Server.java | 3 + .../java/com/minecrafttas/tasmod/TASmod.java | 18 -- .../com/minecrafttas/tasmod/TASmodClient.java | 34 +-- .../clearinputs/ClearInputsPacket.java | 3 - .../tasmod/commands/folder/FolderPacket.java | 3 - .../commands/fullplay/FullPlayPacket.java | 2 - .../commands/fullrecord/FullRecordPacket.java | 2 - .../commands/loadtas/LoadTASPacket.java | 3 - .../commands/playuntil/PlayUntilPacket.java | 3 - .../restartandplay/RestartAndPlayPacket.java | 3 - .../commands/savetas/SaveTASPacket.java | 3 - .../tasmod/ktrng/KTRNGSeedPacket.java | 3 - .../tasmod/ktrng/KTRNGStartSeedPacket.java | 3 - .../networking/IdentificationPacket.java | 53 ---- .../tasmod/networking/Packet.java | 36 --- .../tasmod/networking/PacketSerializer.java | 84 ------- .../tasmod/networking/PacketSide.java | 14 -- .../networking/TASmodNetworkClient.java | 145 ----------- .../networking/TASmodNetworkServer.java | 237 ------------------ .../tasmod/playback/PlaybackController.java | 2 - .../server/InitialSyncStatePacket.java | 1 - .../playback/server/SyncStatePacket.java | 2 - .../client/InputSavestatesPacket.java | 2 - .../savestates/server/LoadstatePacket.java | 2 - .../savestates/server/SavestatePacket.java | 2 - .../server/motion/MotionPacket.java | 2 - .../server/motion/RequestMotionPacket.java | 2 - .../SavestatePlayerLoadingPacket.java | 2 - .../AdvanceTickratePacket.java | 3 - .../tickratechanger/ChangeTickratePacket.java | 3 - .../tickratechanger/PauseTickratePacket.java | 37 --- .../TickrateChangerClient.java | 30 ++- .../TickrateChangerServer.java | 49 +++- .../tasmod/ticksync/TickSyncClient.java | 12 +- .../tasmod/ticksync/TickSyncPacket.java | 48 ---- .../tasmod/ticksync/TickSyncServer.java | 10 +- 37 files changed, 131 insertions(+), 766 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/IdentificationPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/Packet.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/PacketSide.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkClient.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkServer.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncPacket.java diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 759e4176..122acf21 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -13,6 +13,12 @@ import java.util.concurrent.Future; import java.util.function.Consumer; +import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; +import com.minecrafttas.tasmod.ticksync.TickSyncClient; +import com.minecrafttas.tasmod.ticksync.TickSyncServer; + import lombok.var; public class Client { @@ -127,17 +133,45 @@ public void close() throws IOException { * Register packet handlers for packets received on the client */ private void registerClientsidePacketHandlers() { + // packet 2: tick client + this.handlers.put(2, buf -> TickSyncClient.onPacket()); + // packet 5: change client tickrate + this.handlers.put(5, buf -> TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())); } /** * Register packet handlers for packets received on the server */ private void registerServersidePacketHandlers() { + // packet 1: authentication packet this.handlers.put(1, buf -> { this.id = new UUID(buf.getLong(), buf.getLong()); LOGGER.info("Client authenticated: " + this.id); }); + + // packet 3: notify server of tick pass + this.handlers.put(3, buf -> TickSyncServer.onPacket(this.id)); + + // packet 4: request tickrate change + this.handlers.put(4, buf -> TASmod.tickratechanger.changeTickrate(buf.getFloat())); + + // packet 6: tickrate zero toggle + this.handlers.put(6, buf -> { + var state = State.fromShort(buf.getShort()); + if (state == State.PAUSE) + TASmod.tickratechanger.pauseGame(true); + else if (state == State.UNPAUSE) + TASmod.tickratechanger.pauseGame(false); + else if (state == State.TOGGLE) + TASmod.tickratechanger.togglePause(); + }); + + // packet 7: request tick advance + this.handlers.put(7, buf -> { + if (TASmod.tickratechanger.ticksPerSecond == 0) + TASmod.tickratechanger.advanceTick(); + }); } /** @@ -146,6 +180,8 @@ private void registerServersidePacketHandlers() { * @throws Exception Unable to send packet */ public void authenticate(UUID id) throws Exception { + this.id = id; + ByteBuffer buf = ByteBuffer.allocate(4+8+8); buf.putInt(1); buf.putLong(id.getMostSignificantBits()); diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 74b12464..32b37c53 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -11,11 +11,14 @@ import java.util.ArrayList; import java.util.List; +import lombok.Getter; import lombok.var; public class Server { private AsynchronousServerSocketChannel socket; + + @Getter private List clients; /** diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 608bdfe5..ccd4b5da 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -32,9 +32,6 @@ import com.minecrafttas.tasmod.ktrng.KTRNGSeedPacket; import com.minecrafttas.tasmod.ktrng.KTRNGStartSeedPacket; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; -import com.minecrafttas.tasmod.networking.IdentificationPacket; -import com.minecrafttas.tasmod.networking.PacketSerializer; -import com.minecrafttas.tasmod.networking.TASmodNetworkServer; import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.server.InitialSyncStatePacket; import com.minecrafttas.tasmod.playback.server.SyncStatePacket; @@ -78,8 +75,6 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static KillTheRNGHandler ktrngHandler; - public static TASmodNetworkServer packetServer; - public static TickrateChangerServer tickratechanger; public static final TickScheduler tickSchedulerServer = new TickScheduler(); @@ -115,12 +110,6 @@ public void onServerInit(MinecraftServer server) { savestateHandler=new SavestateHandler(server, LOGGER); - try { - packetServer = new TASmodNetworkServer(LOGGER); - } catch (IOException e) { - e.printStackTrace(); - } - if(!server.isDedicatedServer()) { TASmod.tickratechanger.ticksPerSecond=0F; TASmod.tickratechanger.tickrateSaved=20F; @@ -130,7 +119,6 @@ public void onServerInit(MinecraftServer server) { @Override public void onServerStop(MinecraftServer mcserver) { serverInstance=null; - packetServer.close(); try { if (server != null) server.close(); } catch (IOException e) { @@ -155,18 +143,12 @@ public void onInitialize() { tickratechanger = new TickrateChangerServer(LOGGER); EventListener.register(tickratechanger); - - PacketSerializer.registerPacket(IdentificationPacket.class); - // Ticksync - PacketSerializer.registerPacket(TickSyncPacket.class); - //Tickratechanger PacketSerializer.registerPacket(ChangeTickratePacket.class); PacketSerializer.registerPacket(PauseTickratePacket.class); PacketSerializer.registerPacket(AdvanceTickratePacket.class); - // Savestates PacketSerializer.registerPacket(SavestatePacket.class); PacketSerializer.registerPacket(LoadstatePacket.class); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 606d8660..e73076e4 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -21,7 +21,6 @@ import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; import com.minecrafttas.tasmod.handlers.LoadingScreenHandler; -import com.minecrafttas.tasmod.networking.TASmodNetworkClient; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.playback.PlaybackSerialiser; import com.minecrafttas.tasmod.playback.server.InitialSyncStatePacket; @@ -57,8 +56,6 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even public static ShieldDownloader shieldDownloader; - public static TASmodNetworkClient packetClient; - public static TickrateChangerClient tickratechanger = new TickrateChangerClient(); public static TickScheduler gameLoopSchedulerClient = new TickScheduler(); @@ -174,38 +171,13 @@ public void onClientInit(Minecraft mc) { @Override public void onPlayerJoinedClientSide(EntityPlayerSP player) { - Minecraft mc = Minecraft.getMinecraft(); - - if(mc.isIntegratedServerRunning()) - TASmodClient.packetClient = new TASmodNetworkClient(TASmod.LOGGER); - else { - String full = mc.getCurrentServerData().serverIP; - String[] fullsplit = full.split(":"); - if(fullsplit.length == 1) { - TASmodClient.packetClient = new TASmodNetworkClient(TASmod.LOGGER, full, 3111); - } else if(fullsplit.length == 2){ - String ip = fullsplit[0]; - TASmodClient.packetClient = new TASmodNetworkClient(TASmod.LOGGER, ip, 3111); - } else { - TASmod.LOGGER.error("Something went wrong while connecting. The ip seems to be wrong"); - } - } - - TASmodClient.packetClient.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); - - + // FIXME: ask how this works + // TASmodClient.packetClient.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); } @Override public void onPlayerLeaveClientSide(EntityPlayerSP player) { - try { - if(TASmodClient.packetClient!=null) { - TASmodClient.packetClient.killClient(); - TASmodClient.packetClient=null; - } - } catch (IOException e) { - e.printStackTrace(); - } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java index f22b5fb6..31979c42 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java @@ -2,9 +2,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java index cb805329..3c9906d9 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java @@ -1,8 +1,5 @@ package com.minecrafttas.tasmod.commands.folder; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java index 86a7ae0e..6800706b 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java @@ -2,8 +2,6 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.OpenGuiEvents; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java index 55c4242e..3d556d65 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java @@ -2,8 +2,6 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.OpenGuiEvents; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java index 09c5059c..4af9941e 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java @@ -6,9 +6,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java index b4bdbe58..48a0408a 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java @@ -1,9 +1,6 @@ package com.minecrafttas.tasmod.commands.playuntil; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java index 044db2cf..7f3811aa 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java @@ -4,9 +4,6 @@ import com.minecrafttas.common.Configuration.ConfigOptions; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java index f2f067db..048cbca8 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java @@ -5,9 +5,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java index c8523c8c..b943d7ed 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java @@ -1,9 +1,6 @@ package com.minecrafttas.tasmod.ktrng; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java index dce516f1..329486b9 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java @@ -2,9 +2,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/networking/IdentificationPacket.java b/src/main/java/com/minecrafttas/tasmod/networking/IdentificationPacket.java deleted file mode 100644 index 3bcb79e5..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/IdentificationPacket.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -import java.util.UUID; - -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.ticksync.TickSyncServer; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * Used to identify the socket. This enables the server to send packets to a specific player - * @author Scribble - */ -public class IdentificationPacket implements Packet { - - private UUID uuid; - - public IdentificationPacket() { - - } - - public IdentificationPacket(UUID uuid) { - this.uuid = uuid; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if (side.isServer()) { - TickSyncServer.onPacket(this.uuid); - } else { - TASmodClient.packetClient.setReady(); - } - } - - @Override - public void serialize(PacketBuffer buf) { - if (uuid != null) { - buf.writeUniqueId(uuid); - } - } - - @Override - public void deserialize(PacketBuffer buf) { - if (buf.capacity() > 0) { - this.uuid = buf.readUniqueId(); - } - } - - public UUID getUuid() { - return uuid; - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/networking/Packet.java b/src/main/java/com/minecrafttas/tasmod/networking/Packet.java deleted file mode 100644 index 776774f3..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/Packet.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * This is a Packet transmittable over the TASmod Custom Server. - * - * IMPLEMENTATION NOTICE: - * There are no clientbound or serverbound packets as they were deemed unnecessary. This means both the server and the client can transmit any packet. - * @author Pancake - */ -public interface Packet { - - /** - * Once a packet is being received it is immediately handled in this method. - * - * IMPLEMENTATION NOTICE: - * This process is non-blocking for the game and executed on the tasmod server thread temporarily blocking it. - */ - void handle(PacketSide side, EntityPlayer player); - - /** - * In order to transfer packets over the network connection they need to be serialized into a stream of bytes. - * @param buf Packet buffer to serialize to - * @return A serializable packet buffer - */ - void serialize(PacketBuffer buf); - - /** - * In order to receive packets over the network connection the other end serializes the packet into a stream of bytes. Therefore this end needs to deserialize the packet - * @param buf A deserializable packet buffer - */ - void deserialize(PacketBuffer buf); - -} diff --git a/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java b/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java deleted file mode 100644 index 743912b6..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/PacketSerializer.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -import java.util.ArrayList; - -import com.minecrafttas.tasmod.TASmod; - -import io.netty.buffer.Unpooled; -import net.minecraft.network.PacketBuffer; - -/** - * This class helps serializing and deserializing packets - * @author Pancake - */ -public class PacketSerializer { - - private static ArrayList> REGISTRY = new ArrayList<>(); - - /** - * Deserialize a TASmod packet from a packet buffer. The packet class is prefixed with an id and read here. - * - * @param buf Serialized byte buffer with id prefix - * @return Deserialized packet - */ - public static Packet deserialize(PacketBuffer buf) { - // Read packet id and deserialize the correct packet - int packetId = buf.readInt(); - - Packet packet=null; - try { - packet = REGISTRY.get(packetId).newInstance(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - - if(packet == null) { - TASmod.LOGGER.warn("Unregistered packet received! Packet Id: " + packetId); - return null; - } - - packet.deserialize(buf); - return packet; - } - - /** - * Serialize a TASmod packet to a packet buffer. The packet class is read and a id prefixed packet buffer is returned - * - * @param packet Non-serialized packet - * @return Serialized packet buffer with id prefix - */ - public static PacketBuffer serialize(Packet packet) { - // Figure out packet class and prefix the correct id - - PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); - int packetID = REGISTRY.indexOf(packet.getClass()); - - if(packetID == -1) { - TASmod.LOGGER.warn("Unregistered packet was trying to be serialized! Packet Class: " + packet.getClass().getSimpleName()); - return null; - } - - buf.writeInt(packetID); - - packet.serialize(buf); - return buf; - } - - public static void registerPacket(Class packet) { - TASmod.LOGGER.trace("Registering packet {}", packet.getClass().getSimpleName()); - if(REGISTRY.contains(packet)) { - TASmod.LOGGER.warn("Trying to register packet which already exists: {}", packet.getClass().getSimpleName()); - } - REGISTRY.add(packet); - } - - public static void unregisterPacket(Class packet) { - if(REGISTRY.contains(packet)) { - TASmod.LOGGER.warn("Trying to unregister packet which doesn't exist in the registry: {}", packet.getClass().getSimpleName()); - } - REGISTRY.remove(packet); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/networking/PacketSide.java b/src/main/java/com/minecrafttas/tasmod/networking/PacketSide.java deleted file mode 100644 index 7b9c0e48..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/PacketSide.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -public enum PacketSide { - CLIENT, - SERVER; - - public boolean isClient() { - return this == CLIENT; - } - - public boolean isServer() { - return this == SERVER; - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkClient.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkClient.java deleted file mode 100644 index 1fff85d7..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkClient.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketException; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.apache.logging.log4j.Logger; - -import com.minecrafttas.tasmod.TASmodClient; - -import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.network.PacketBuffer; - -public class TASmodNetworkClient { - - private Logger logger; - - private Thread clientThread; - - private Socket clientSocket; - - private BlockingQueue packetsToSend = new LinkedBlockingQueue<>(); - - private boolean ready = false; - - public TASmodNetworkClient(Logger logger) { - this(logger, "127.0.0.1", 3111); // Set ip for different server - } - - public TASmodNetworkClient(Logger logger, String serverIP, int port) { - this.logger = logger; - this.logger.info("Trying to connect to {}:{}", serverIP, port); - createClient(serverIP, port); - } - - public void sendToServer(Packet packet) { - if(clientThread == null) - return; - if(!clientThread.isAlive()) - return; - packetsToSend.add(packet); - } - - private void createClient(String serverIp, int port) { - - packetsToSend.add(new IdentificationPacket(Minecraft.getMinecraft().player.getUniqueID())); - - clientThread = new Thread(() -> { - try(Socket cSocket = new Socket()){ - cSocket.connect(new InetSocketAddress(serverIp, port)); - this.clientSocket = cSocket; - - clientSocket.setTcpNoDelay(true); - // Prepare the in and out streams. - DataInputStream inputStream = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); - - createSendThread(); - - // Use the current thread to indefinitly fetch packets - Packet packet; - while (clientSocket.isConnected()) { - // Handle the next packet. If no packet is avilable, the readInt() call will hang until there is one. - int packetSize = inputStream.readInt(); - byte[] packetData = new byte[packetSize]; - inputStream.read(packetData, 0, packetSize); - PacketBuffer packetBuf = new PacketBuffer(Unpooled.wrappedBuffer(packetData)); - // Deserialize and run the packet - packet = PacketSerializer.deserialize(packetBuf); - packet.handle(PacketSide.CLIENT, Minecraft.getMinecraft().player); - logger.trace("Handled a " + packet.getClass().getSimpleName() + " from the socket."); - } - - } catch (EOFException | SocketException | InterruptedIOException exception) { - // The custom TASmod client was closed and the end of stream was reached. The socket was shut down properly. - logger.info("Custom TASmod client was shutdown"); - } catch (Exception exception) { - logger.error("Custom TASmod client was unexpectedly shutdown {}", exception); - exception.printStackTrace(); - TASmodClient.gameLoopSchedulerClient.add(()->{ - throw new RuntimeException("TASmod networking was shut down. The real errors are above"); - }); - } - }); - clientThread.setName("TASmod Network Client Accept"); - clientThread.setDaemon(true); - clientThread.start(); - } - - private void createSendThread() throws IOException { - DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream())); - // Create a new thread that writes packets if available - Thread outputThread = new Thread(() -> { - try { - Packet packet; - while (!clientSocket.isClosed()) { - // Try to poll another packet that wants to be sent - packet = packetsToSend.peek(); - boolean skip = !(packet instanceof IdentificationPacket) && !ready; - if (packet == null || skip) { - Thread.sleep(1); // If nothing has to be done, let the cpu rest by waiting - continue; - } - packetsToSend.poll(); - // A packet was found: Serialize then send it. - byte[] packetData = PacketSerializer.serialize(packet).array(); - outputStream.writeInt(packetData.length); - outputStream.write(packetData); - outputStream.flush(); - logger.trace("Sent a " + packet.getClass().getSimpleName() + " to the socket."); - } - } catch (Exception e) { - e.printStackTrace(); - // This exception is already logged by the thread one layer above - // therefore nothing needs to be done here. - } - }); - outputThread.setDaemon(true); // If daemon is set, the jvm will quit without waiting for this thread to finish - outputThread.setName("TASmod Network Client Send"); - outputThread.start(); - } - - public void killClient() throws IOException { - if(clientThread != null && clientSocket != null) { - clientSocket.close(); - } - } - - public boolean isClosed() { - return clientSocket.isClosed(); - } - - public void setReady() { - ready = true; - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkServer.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkServer.java deleted file mode 100644 index de3daebd..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodNetworkServer.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.apache.logging.log4j.Logger; - -import com.minecrafttas.tasmod.TASmod; - -import io.netty.buffer.Unpooled; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; - -/** - * A custom packet server extending beyond the standard Minecraft network manager - * @author Pancake, Scribble - * - */ -public class TASmodNetworkServer { - - private Logger logger; - - private Thread serverThread; - - private ServerSocket serverSocket; - - private Map connectedPlayers = Collections.synchronizedMap(new HashMap()); - - private Map> queues = Collections.synchronizedMap(new HashMap<>()); - - private int connections = 0; - - public TASmodNetworkServer(Logger logger) throws IOException { - this(logger, 3111); - } - - public TASmodNetworkServer(Logger logger, int port) throws IOException { - this.logger = logger; - createServer(port); - } - - private void createServer(int port) throws IOException { - serverThread = new Thread(() -> { - - try(ServerSocket serverS = new ServerSocket(port)){ - this.serverSocket = serverS; - - while (!this.serverSocket.isClosed()) { - Socket socket = null; - - socket = serverSocket.accept(); - socket.setTcpNoDelay(true); - - final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); - - connections++; - createSendThread(socket, queue); - createAcceptThread(socket, queue); - } - - } catch (EOFException | SocketException | InterruptedIOException exception) { - logger.debug("Custom TASmod server was shutdown"); - } catch (Exception exception) { - logger.error("Custom TASmod server was unexpectedly shutdown {}", exception); - exception.printStackTrace(); - } - - }); - serverThread.setName("TASmod Network Server Main"); - serverThread.setDaemon(true); - serverThread.start(); - } - - private void createSendThread(Socket socket, LinkedBlockingQueue packetQueue) throws IOException, InterruptedException { - Thread sendThread = new Thread(()->{ - DataOutputStream outputStream; - try { - outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); - } catch (IOException e) { - e.printStackTrace(); - return; - } - Packet packet; - while (!socket.isClosed()) { - try { - // Try to poll another packet that wants to be sent - packet = packetQueue.poll(); - if (packet == null) { - Thread.sleep(1); // If nothing has to be done, let the cpu rest by waiting - continue; - } - // A packet was found: Serialize then send it. - byte[] packetData = PacketSerializer.serialize(packet).array(); - outputStream.writeInt(packetData.length); - outputStream.write(packetData); - outputStream.flush(); - logger.trace("Sent a " + packet.getClass().getSimpleName() + " to the socket."); - } catch(Exception e) { - logger.catching(e); - } - } - }); - sendThread.setDaemon(true); - sendThread.setName("TASmod Network Server Send #"+connections); - sendThread.start(); - } - - private void createAcceptThread(Socket socket, LinkedBlockingQueue packetQueue) throws IOException { - Thread acceptThread = new Thread(()->{ - DataInputStream inputStream; - try { - inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream())); - } catch (IOException e2) { - e2.printStackTrace(); - return; - } - Packet packet; - while (!socket.isClosed()) { - // Handle the next packet. If no packet is avilable, the readInt() call will - // hang until there is one. - try { - int packetSize = inputStream.readInt(); - byte[] packetData = new byte[packetSize]; - inputStream.read(packetData, 0, packetSize); - - PacketBuffer packetBuf = new PacketBuffer(Unpooled.wrappedBuffer(packetData)); - // Deserialize and run the packet - packet = PacketSerializer.deserialize(packetBuf); - - if(packet instanceof IdentificationPacket) { - handleIdentificationPacket(packet, socket, packetQueue); - } - - if(connectedPlayers.containsKey(socket)) { - UUID id = connectedPlayers.get(socket); - EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(id); - - packet.handle(PacketSide.SERVER, player); - logger.trace("Handled a " + packet.getClass().getSimpleName() + " from the socket."); - } - }catch (EOFException e){ - logger.info("Client socket was shut down"); - try { - socket.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } catch (Exception e) { - logger.error(e.getMessage()); - e.printStackTrace(); - try { - socket.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - } - UUID id = connectedPlayers.get(socket); - connectedPlayers.remove(socket); - queues.remove(id); - connections--; - }); - acceptThread.setDaemon(true); - acceptThread.setName("TASmod Network Server Accept #"+connections); - acceptThread.start(); - } - - private void handleIdentificationPacket(Packet packet, Socket socket, LinkedBlockingQueue packetQueue) { - if(!connectedPlayers.containsKey(socket)) { - IdentificationPacket idPacket = (IdentificationPacket) packet; - logger.info("Identified player with uuid: {}", idPacket.getUuid()); - connectedPlayers.put(socket, idPacket.getUuid()); - queues.put(idPacket.getUuid(), packetQueue); - sendTo(new IdentificationPacket(), idPacket.getUuid()); - } - } - - public void sendToAll(Packet packet) { - if(serverThread.isAlive()) { - queues.forEach((id, queue) -> queue.add(packet)); - } - } - - public void sendTo(Packet packet, EntityPlayerMP... players) { - if(serverThread.isAlive()) { - queues.forEach((id, queue) -> { - for(EntityPlayerMP player : players) { - if(player.getUniqueID().equals(id)) { - queue.add(packet); - } - } - - }); - } - } - - public void sendTo(Packet packet, UUID... uuids) { - if(serverThread.isAlive()) { - queues.forEach((id, queue) -> { - for(UUID idToSend : uuids) { - if(idToSend.equals(id)) { - queue.add(packet); - } - } - }); - } - } - - public int getConnections() { - return connections; - } - - public void close() { - if(serverSocket==null) - return; - try { - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - connections = 0; - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 54eca09b..9e1a52c5 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -13,8 +13,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import com.minecrafttas.tasmod.playback.server.TASstateClient; import com.minecrafttas.tasmod.util.LoggerMarkers; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java index 7eb69aa1..39559d05 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java @@ -1,7 +1,6 @@ package com.minecrafttas.tasmod.playback.server; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import net.minecraft.entity.player.EntityPlayer; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java index a6994856..eddf53d3 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java @@ -2,8 +2,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.util.TickScheduler.TickTask; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java index 17bd1772..a0daf78b 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java @@ -4,8 +4,6 @@ import java.nio.charset.Charset; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; import net.minecraft.entity.player.EntityPlayer; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java index 188b82e4..2709ed24 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java @@ -1,8 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java index 8d5cb81f..fb5809be 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java @@ -1,8 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java index 4968cd2b..67eec718 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java @@ -1,7 +1,5 @@ package com.minecrafttas.tasmod.savestates.server.motion; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer.Saver; import net.minecraft.entity.player.EntityPlayer; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java index 975db5ae..9b3744aa 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java @@ -1,8 +1,6 @@ package com.minecrafttas.tasmod.savestates.server.motion; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java index e48e5406..4f7f816f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java @@ -1,7 +1,5 @@ package com.minecrafttas.tasmod.savestates.server.playerloading; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java index 168725dd..b9479590 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java @@ -2,9 +2,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java index a5987a41..cbe8d703 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java @@ -2,9 +2,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java index 041f9437..659c1ace 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java @@ -2,9 +2,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; @@ -45,41 +42,7 @@ public State getState() { * @author Scribble * */ - public enum State { - /** - * Set's the game to tickrate 0 - */ - PAUSE((short) 1), - /** - * Set's the game to "tickrate saved" - */ - UNPAUSE((short) 2), - /** - * Toggles between {@link #PAUSE} and {@link #UNPAUSE} - */ - TOGGLE((short) 0); - - private short id; - State(short i) { - id = i; - } - - public short toShort() { - return id; - } - - public static State fromShort(short i) { - switch (i) { - case 1: - return PAUSE; - case 2: - return UNPAUSE; - default: - return TOGGLE; - } - } - } @Override public void handle(PacketSide side, EntityPlayer player) { diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index e72feade..d715394a 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,9 +1,11 @@ package com.minecrafttas.tasmod.tickratechanger; +import java.nio.ByteBuffer; + import com.minecrafttas.common.events.EventClient.EventClientGameLoop; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.ticksync.TickSyncClient; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.client.Minecraft; @@ -91,7 +93,13 @@ public void changeServerTickrate(float tickrate) { if (tickrate < 0) { return; } - TASmodClient.packetClient.sendToServer(new ChangeTickratePacket(tickrate)); + + try { + // packet 4: request tickrate change + TASmodClient.client.write(ByteBuffer.allocate(8).putInt(4).putFloat(tickrate)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to server: {}", e); + } } /** @@ -99,7 +107,12 @@ public void changeServerTickrate(float tickrate) { */ public void togglePause() { if (Minecraft.getMinecraft().world != null) { - TASmodClient.packetClient.sendToServer(new PauseTickratePacket()); + try { + // packet 6: toggle tickrate zero + TASmodClient.client.write(ByteBuffer.allocateDirect(6).putInt(6).putShort(State.TOGGLE.toShort())); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to server: {}", e); + } } else { togglePauseClient(); } @@ -158,7 +171,12 @@ public void advanceTick() { * Sends a {@link AdvanceTickratePacket} to the server to advance the server */ public void advanceServerTick() { - TASmodClient.packetClient.sendToServer(new AdvanceTickratePacket()); + try { + // packet 7: request tick advance + TASmodClient.client.write(ByteBuffer.allocate(4).putInt(7)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to server: {}", e); + } } /** @@ -181,9 +199,7 @@ private static void log(String msg) { @Override public void onRunClientGameLoop(Minecraft mc) { - if (TASmodClient.packetClient != null && TASmodClient.packetClient.isClosed()) { // If the server died, but the client has not left the world - TickSyncClient.shouldTick.set(true); - } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index a6d400df..7911a973 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -1,10 +1,14 @@ package com.minecrafttas.tasmod.tickratechanger; +import java.nio.ByteBuffer; + import org.apache.logging.log4j.Logger; import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.tickratechanger.PauseTickratePacket.State; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.entity.player.EntityPlayerMP; @@ -82,7 +86,13 @@ public void changeClientTickrate(float tickrate) { public void changeClientTickrate(float tickrate, boolean log) { if(log) log("Changing the tickrate "+ tickrate + " to all clients"); - TASmod.packetServer.sendToAll(new ChangeTickratePacket(tickrate)); + + try { + // packet 5: send new tickrate to clients + TASmod.server.writeAll(ByteBuffer.allocate(8).putInt(5).putFloat(tickrate)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } } /** @@ -204,4 +214,41 @@ public void onServerStop(MinecraftServer server) { pauseGame(false); } } + + public static enum State { + /** + * Set's the game to tickrate 0 + */ + PAUSE((short) 1), + /** + * Set's the game to "tickrate saved" + */ + UNPAUSE((short) 2), + /** + * Toggles between {@link #PAUSE} and {@link #UNPAUSE} + */ + TOGGLE((short) 0); + + private short id; + + State(short i) { + id = i; + } + + public short toShort() { + return id; + } + + public static State fromShort(short i) { + switch (i) { + case 1: + return PAUSE; + case 2: + return UNPAUSE; + default: + return TOGGLE; + } + } + } + } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index 184e91a2..5b8a755e 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -1,7 +1,9 @@ package com.minecrafttas.tasmod.ticksync; +import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; +import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import net.minecraft.client.Minecraft; @@ -35,10 +37,16 @@ public static void onPacket() { * @param mc Instance of Minecraft */ public static void clientPostTick(Minecraft mc) { - if (mc.player == null && TASmodClient.packetClient==null) { + if (mc.player == null) { return; } - TASmodClient.packetClient.sendToServer(new TickSyncPacket(mc.player.getGameProfile().getId())); + + try { + // packet 3: notify server of tick pass + TASmodClient.client.write(ByteBuffer.allocate(4).putInt(3)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to server: {}", e); + } } } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncPacket.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncPacket.java deleted file mode 100644 index 27347e51..00000000 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncPacket.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.minecrafttas.tasmod.ticksync; - -import java.util.UUID; - -import com.minecrafttas.tasmod.networking.Packet; -import com.minecrafttas.tasmod.networking.PacketSide; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * Packet for {@linkplain TickSyncServer} - * @author Scribble - * - */ -public class TickSyncPacket implements Packet { - - protected UUID uuid; - - public TickSyncPacket() { - - } - - public TickSyncPacket(UUID id) { - this.uuid = id; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isServer()) { - TickSyncServer.onPacket(this.uuid); - }else { - TickSyncClient.onPacket(); - } - } - - @Override - public void serialize(PacketBuffer buf) { - if(uuid!=null) - buf.writeUniqueId(uuid); - } - - @Override - public void deserialize(PacketBuffer buf) { - uuid = buf.readUniqueId(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index fc5337db..b3f81b3f 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.ticksync; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -37,7 +38,7 @@ public static void onPacket(UUID uuid) { public static boolean shouldTick() { synchronized (synchronizedList) { int acknowledged = synchronizedList.size(); - int totalConnections = TASmod.packetServer.getConnections(); + int totalConnections = TASmod.server.getClients().size(); if(acknowledged >= totalConnections) { return true; }else { @@ -51,7 +52,12 @@ public static boolean shouldTick() { * to all clients making them tick */ public static void serverPostTick() { - TASmod.packetServer.sendToAll(new TickSyncPacket()); + try { + // packet 2: tick clients + TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(2)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } if(synchronizedList.size()>0) synchronizedList.clear(); } From c51f1b6a13c35f4c975352c59e673ce68cc320e0 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Thu, 15 Jun 2023 00:48:25 +0200 Subject: [PATCH 07/60] Continue with packets --- .../java/com/minecrafttas/server/Client.java | 79 ++++++++++++++++++ .../java/com/minecrafttas/server/Server.java | 13 +++ .../java/com/minecrafttas/tasmod/TASmod.java | 15 +--- .../tasmod/ktrng/KillTheRNGHandler.java | 4 +- .../tasmod/mixin/MixinMinecraft.java | 4 +- .../savestates/server/SavestateHandler.java | 37 +++++++-- .../server/motion/ClientMotionServer.java | 16 +++- .../server/motion/MotionPacket.java | 80 ------------------- .../server/motion/RequestMotionPacket.java | 48 ----------- .../AdvanceTickratePacket.java | 45 ----------- .../tickratechanger/ChangeTickratePacket.java | 51 ------------ .../tickratechanger/PauseTickratePacket.java | 79 ------------------ .../TickrateChangerServer.java | 18 +++-- 13 files changed, 153 insertions(+), 336 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 122acf21..b7bc8480 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -15,11 +15,18 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.savestates.client.InputSavestatesHandler; +import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; +import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; +import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; +import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer.Saver; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.ticksync.TickSyncServer; +import lombok.Getter; import lombok.var; +import net.minecraft.client.Minecraft; public class Client { @@ -28,6 +35,8 @@ public class Client { private ByteBuffer readBuffer; private Future future; private Map> handlers = new HashMap<>(); + + @Getter private UUID id; /** @@ -138,6 +147,73 @@ private void registerClientsidePacketHandlers() { // packet 5: change client tickrate this.handlers.put(5, buf -> TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())); + + // packet 8: advance tick on clients + this.handlers.put(8, buf -> TASmodClient.tickratechanger.advanceClientTick()); + + // packet 9: change tickrate on client + this.handlers.put(9, buf -> TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())); + + // packet 10: savestate inputs client + this.handlers.put(10, buf -> { + try { + var nameBytes = new byte[buf.getInt()]; + buf.get(nameBytes); + var name = new String(nameBytes); + InputSavestatesHandler.savestate(name); + } catch (Exception e) { + TASmod.LOGGER.error("Exception occured during input savestate: {}", e); + } + }); + + // packet 11: close GuiSavestateScreen on client + this.handlers.put(11, buf -> + Minecraft.getMinecraft().addScheduledTask(() -> { + var mc = Minecraft.getMinecraft(); + if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) + mc.displayGuiScreen(new GuiSavestateSavingScreen()); + else + mc.displayGuiScreen(null); + }) + ); + + // packet 12: loadstate inputs client + this.handlers.put(12, buf -> { + try { + var nameBytes = new byte[buf.getInt()]; + buf.get(nameBytes); + var name = new String(nameBytes); + InputSavestatesHandler.loadstate(name); + } catch (Exception e) { + TASmod.LOGGER.error("Exception occured during input loadstate: {}", e); + } + }); + + // packet 13: unload chunks on client + this.handlers.put(13, buf -> + Minecraft.getMinecraft().addScheduledTask(() -> + SavestatesChunkControl.unloadAllClientChunks())); + + // packet 14: request client motion + this.handlers.put(14, buf -> { + var player = Minecraft.getMinecraft().player; + if (player != null) { + if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) + Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); + + try { + // packet 15: send client motion to server + TASmodClient.client.write(ByteBuffer.allocate(4 + 8+8+8 + 4+4+4 + 1 + 4).putInt(15) + .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) + .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) + .put((byte) (player.isSprinting() ? 1 : 0)) + .putFloat(player.jumpMovementFactor) + ); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to server: {}", e); + } + } + }); } /** @@ -172,6 +248,9 @@ else if (state == State.TOGGLE) if (TASmod.tickratechanger.ticksPerSecond == 0) TASmod.tickratechanger.advanceTick(); }); + + // packet 15: send client motion to server + this.handlers.put(15, buf -> ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(this.id), new Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1 ? true : false, buf.getFloat()))); } /** diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 32b37c53..58749a81 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -10,6 +10,7 @@ import java.nio.channels.CompletionHandler; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import lombok.Getter; import lombok.var; @@ -73,5 +74,17 @@ public void close() throws IOException { this.socket.close(); } + + /** + * Get client from UUID + * @param uniqueID UUID + */ + public Client getClient(UUID uniqueID) { + for (var client : this.clients) + if (client.getId().equals(uniqueID)) + return client; + + return null; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index ccd4b5da..d0254657 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -45,12 +45,8 @@ import com.minecrafttas.tasmod.savestates.server.motion.MotionPacket; import com.minecrafttas.tasmod.savestates.server.motion.RequestMotionPacket; import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoadingPacket; -import com.minecrafttas.tasmod.tickratechanger.AdvanceTickratePacket; -import com.minecrafttas.tasmod.tickratechanger.ChangeTickratePacket; import com.minecrafttas.tasmod.tickratechanger.CommandTickrate; -import com.minecrafttas.tasmod.tickratechanger.PauseTickratePacket; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; -import com.minecrafttas.tasmod.ticksync.TickSyncPacket; import com.minecrafttas.tasmod.util.TickScheduler; import net.fabricmc.api.ModInitializer; @@ -143,22 +139,13 @@ public void onInitialize() { tickratechanger = new TickrateChangerServer(LOGGER); EventListener.register(tickratechanger); - - //Tickratechanger - PacketSerializer.registerPacket(ChangeTickratePacket.class); - PacketSerializer.registerPacket(PauseTickratePacket.class); - PacketSerializer.registerPacket(AdvanceTickratePacket.class); - // Savestates PacketSerializer.registerPacket(SavestatePacket.class); PacketSerializer.registerPacket(LoadstatePacket.class); PacketSerializer.registerPacket(InputSavestatesPacket.class); PacketSerializer.registerPacket(SavestatePlayerLoadingPacket.class); - - PacketSerializer.registerPacket(RequestMotionPacket.class); - PacketSerializer.registerPacket(MotionPacket.class); - + // KillTheRNG PacketSerializer.registerPacket(KTRNGSeedPacket.class); PacketSerializer.registerPacket(KTRNGStartSeedPacket.class); diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index 07c46acf..506ce0f2 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -99,7 +99,7 @@ public void setGlobalSeedServer(long seedIn) { @Environment(EnvType.CLIENT) public void sendGlobalSeedToServer(long seedIn) { if(isLoaded()) { - if(TASmodClient.packetClient!=null) + if(TASmodClient.client != null) TASmodClient.packetClient.sendToServer(new KTRNGSeedPacket(seedIn)); else setGlobalSeedClient(seedIn); @@ -129,7 +129,7 @@ public void broadcastStartSeed() { @Environment(EnvType.CLIENT) public void setInitialSeed(long initialSeed) { - if(TASmodClient.packetClient != null) { + if(TASmodClient.client != null) { TASmod.LOGGER.info("Sending initial client seed: {}", initialSeed); TASmodClient.packetClient.sendToServer(new KTRNGStartSeedPacket(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD } else { diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java index d51e7a50..566bf0e2 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java @@ -85,9 +85,9 @@ public void redirectRunTick(Minecraft mc) { @Inject(method = "shutdownMinecraftApplet", at = @At("HEAD")) public void inject_shutdownMinecraftApplet(CallbackInfo ci) { try { - if (TASmodClient.packetClient != null) { + if (TASmodClient.client != null) { TASmodClient.tickratechanger.changeTickrate(20); - TASmodClient.packetClient.killClient(); + TASmodClient.client.close(); } } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java index 2766ef5a..3c2c319f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java @@ -3,6 +3,7 @@ import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; @@ -19,7 +20,6 @@ import com.minecrafttas.tasmod.events.EventServer.EventSavestate; import com.minecrafttas.tasmod.mixin.savestates.AccessorAnvilChunkLoader; import com.minecrafttas.tasmod.mixin.savestates.AccessorChunkLoader; -import com.minecrafttas.tasmod.savestates.client.InputSavestatesPacket; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateDeleteException; @@ -31,6 +31,7 @@ import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoading; import com.minecrafttas.tasmod.util.LoggerMarkers; +import lombok.var; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; @@ -182,7 +183,13 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex * Send the name of the world to all players. This will make a savestate of the * recording on the client with that name */ - TASmod.packetServer.sendToAll(new InputSavestatesPacket(true, getSavestateName(indexToSave))); + try { + // packet 10: savestate inputs client + var name = this.getSavestateName(indexToSave).getBytes(); + TASmod.server.writeAll(ByteBuffer.allocate(8 + name.length).putInt(10).putInt(name.length).put(name)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } } // Wait for the chunkloader to save the game @@ -206,8 +213,12 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex // Send a notification that the savestate has been loaded server.getPlayerList().sendMessage(new TextComponentString(TextFormatting.GREEN + "Savestate " + indexToSave + " saved")); - // Close the GuiSavestateScreen on the client - TASmod.packetServer.sendToAll(new SavestatePacket()); + try { + // packet 11: close GuiSavestateScreen + TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(11)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } if (!tickrate0) { TASmod.tickratechanger.pauseGame(false); @@ -308,8 +319,13 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex * InputSavestate) */ if (savestateIndex != 0) { - // Load savestate on the client - TASmod.packetServer.sendToAll(new InputSavestatesPacket(false, getSavestateName(indexToLoad))); + try { + // packet 12: loadstate inputs client + var name = this.getSavestateName(indexToLoad).getBytes(); + TASmod.server.writeAll(ByteBuffer.allocate(8 + name.length).putInt(12).putInt(name.length).put(name)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } } // Disabeling level saving for all worlds in case the auto save kicks in during @@ -318,8 +334,13 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex world.disableLevelSaving = true; } - // Unload chunks on the client - TASmod.packetServer.sendToAll(new LoadstatePacket()); + + try { + // packet 13: unload chunks on client + TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(13)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } // Unload chunks on the server SavestatesChunkControl.disconnectPlayersFromChunkMap(server); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java index 49723495..a6bcf3e6 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.savestates.server.motion; +import java.nio.ByteBuffer; import java.util.Map; import com.google.common.collect.Maps; @@ -19,8 +20,14 @@ public static Map getMotion() { public static void requestMotionFromClient() { TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); motion.clear(); - TASmod.packetServer.sendToAll(new RequestMotionPacket()); + try { + // packet 14: request client motion + TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(14)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } + // TODO: is this still necessary? int i = 1; while (motion.size() != TASmod.getServerInstance().getPlayerList().getCurrentPlayerCount()) { i++; @@ -31,7 +38,12 @@ public static void requestMotionFromClient() { } if(i % 30 == 1) { TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); - TASmod.packetServer.sendToAll(new RequestMotionPacket()); + try { + // packet 14: request client motion + TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(14)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } } if (i == 1000) { TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java deleted file mode 100644 index 67eec718..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/MotionPacket.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server.motion; - -import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer.Saver; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; - -/** - * A packet containing the motion data of the player - * @author Scribble - * - */ -public class MotionPacket implements Packet { - private double x = 0; - private double y = 0; - private double z = 0; - private float rx = 0; - private float ry = 0; - private float rz = 0; - private boolean sprinting; - private float jumpMovementVector = 0.2F; - - public MotionPacket() { - } - - /** - * Sends the players motion data to the server - * @param x - * @param y - * @param z - * @param moveForward - * @param moveVertical - * @param moveStrafe - * @param isSprinting - * @param jumpMovementVector - */ - public MotionPacket(double x, double y, double z, float moveForward, float moveVertical, float moveStrafe, boolean isSprinting, float jumpMovementVector) { - this.x = x; - this.y = y; - this.z = z; - this.rx = moveForward; - this.ry = moveVertical; - this.rz = moveStrafe; - sprinting = isSprinting; - this.jumpMovementVector = jumpMovementVector; - } - - @Override - public void handle(PacketSide side, EntityPlayer playercommon) { - if (side.isServer()) { - EntityPlayerMP player = (EntityPlayerMP) playercommon; - ClientMotionServer.getMotion().put(player, new Saver(x, y, z, rx, ry, rz, sprinting, jumpMovementVector)); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeDouble(x); - buf.writeDouble(y); - buf.writeDouble(z); - buf.writeFloat(rx); - buf.writeFloat(ry); - buf.writeFloat(rz); - buf.writeBoolean(sprinting); - buf.writeFloat(jumpMovementVector); - } - - @Override - public void deserialize(PacketBuffer buf) { - x = buf.readDouble(); - y = buf.readDouble(); - z = buf.readDouble(); - rx = buf.readFloat(); - ry = buf.readFloat(); - rz = buf.readFloat(); - sprinting = buf.readBoolean(); - jumpMovementVector = buf.readFloat(); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java deleted file mode 100644 index 9b3744aa..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/RequestMotionPacket.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server.motion; - -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * Requests the motion from the client - * @author Scribble - * - */ -public class RequestMotionPacket implements Packet { - - /** - * Requests the motion from the client - */ - public RequestMotionPacket() { - } - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if(side.isClient()) { - EntityPlayerSP player = (EntityPlayerSP) playerz; - if (player != null) { - if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) { - Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); - } - TASmodClient.packetClient.sendToServer(new MotionPacket(player.motionX, player.motionY, player.motionZ, player.moveForward, player.moveVertical, player.moveStrafing, player.isSprinting(), player.jumpMovementFactor)); - } - } - - } - - @Override - public void serialize(PacketBuffer buf) { - - } - - @Override - public void deserialize(PacketBuffer buf) { - - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java deleted file mode 100644 index b9479590..00000000 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/AdvanceTickratePacket.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.minecrafttas.tasmod.tickratechanger; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * Advanced game by 1 tick - * - * @author Scribble - * - */ -public class AdvanceTickratePacket implements Packet { - /** - * Advanced game by 1 tick - */ - public AdvanceTickratePacket() { - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if (side.isServer()) { - if (player.canUseCommand(2, "tickrate")) { - if (TASmod.tickratechanger.ticksPerSecond == 0) { - TASmod.tickratechanger.advanceTick(); - } - } - } else { - TASmodClient.tickratechanger.advanceClientTick(); // Using advanceTick() would create an endless loop - } - } - - @Override - public void serialize(PacketBuffer buf) { - - } - - @Override - public void deserialize(PacketBuffer buf) { - - } - - -} diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java deleted file mode 100644 index cbe8d703..00000000 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/ChangeTickratePacket.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.minecrafttas.tasmod.tickratechanger; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * Changes the tickrate on the other side - * - * @author Scribble - * - */ -public class ChangeTickratePacket implements Packet { - - float tickrate; - - public ChangeTickratePacket() { - } - - /** - * Changes the tickrate on the other side - * - * @param tickrate The new tickrate - */ - public ChangeTickratePacket(float tickrate) { - this.tickrate = tickrate; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if (side.isServer()) { - if (player.canUseCommand(2, "tickrate")) { - TASmod.tickratechanger.changeTickrate(tickrate); - } - } else { - TASmodClient.tickratechanger.changeClientTickrate(tickrate); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeFloat(tickrate); - } - - @Override - public void deserialize(PacketBuffer buf) { - tickrate = buf.readFloat(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java deleted file mode 100644 index 659c1ace..00000000 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/PauseTickratePacket.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.minecrafttas.tasmod.tickratechanger; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -/** - * Sets the game to tickrate 0 and back - * - * @author Scribble - * - */ -public class PauseTickratePacket implements Packet { - - private short status; - - /** - * Toggles the tickrate between 0 and tickrate > 0 - */ - public PauseTickratePacket() { - status = 0; - } - - /** - * Changes the state to either PAUSE UNPAUSE or TOGGLED - * - * @param state The state - */ - public PauseTickratePacket(State state) { - this.status = state.toShort(); - } - - public State getState() { - return State.fromShort(status); - } - - - /** - * Can be {@link State#PAUSE}, {@link State#UNPAUSE} or {@link State#TOGGLE} - * - * @author Scribble - * - */ - - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if (side.isServer()) { - if (player.canUseCommand(2, "tickrate")) { - State state = getState(); - if (state == State.PAUSE) - TASmod.tickratechanger.pauseGame(true); - else if (state == State.UNPAUSE) - TASmod.tickratechanger.pauseGame(false); - else if (state == State.TOGGLE) - TASmod.tickratechanger.togglePause(); - } - } else if (side.isClient()) { - State state = getState(); - if (state == State.PAUSE) - TASmodClient.tickratechanger.pauseClientGame(true); - else if (state == State.UNPAUSE) - TASmodClient.tickratechanger.pauseClientGame(false); - else if (state == State.TOGGLE) - TASmodClient.tickratechanger.togglePauseClient(); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeShort(status); - } - - @Override - public void deserialize(PacketBuffer buf) { - status = buf.readShort(); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 7911a973..6a08505d 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -7,8 +7,6 @@ import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.tickratechanger.PauseTickratePacket.State; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.entity.player.EntityPlayerMP; @@ -175,8 +173,13 @@ public void advanceTick() { * Sends a {@link AdvanceTickratePacket} to all clients */ private static void advanceClientTick() { - TASmod.packetServer.sendToAll(new AdvanceTickratePacket()); - } + try { + // packet 8: advance tick on clients + TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(8)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + } + } /** * Advances the server by 1 tick @@ -196,7 +199,12 @@ private void advanceServerTick() { public void onPlayerJoinedServerSide(EntityPlayerMP player) { if(TASmod.getServerInstance().isDedicatedServer()) { log("Sending the current tickrate ("+ticksPerSecond+") to " +player.getName()); - TASmod.packetServer.sendTo(new ChangeTickratePacket(ticksPerSecond), player); + try { + // packet 9: change tickrate on client + TASmod.server.getClient(player.getUniqueID()).write(ByteBuffer.allocate(8).putInt(9).putFloat(ticksPerSecond)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to {}: {}", player.getUniqueID(), e); + } } } From fc261b9957ebb7ad8b43c2ff9bbc996143e52ef5 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Tue, 8 Aug 2023 18:57:27 +0200 Subject: [PATCH 08/60] Mark fields as final and preinitialize buffers --- .../java/com/minecrafttas/server/Client.java | 48 +++++++++---------- .../java/com/minecrafttas/server/Server.java | 15 +++--- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index b7bc8480..3950634d 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -1,18 +1,5 @@ package com.minecrafttas.server; -import static com.minecrafttas.tasmod.TASmod.LOGGER; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousSocketChannel; -import java.nio.channels.CompletionHandler; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.Future; -import java.util.function.Consumer; - import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.savestates.client.InputSavestatesHandler; @@ -23,19 +10,33 @@ import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.ticksync.TickSyncServer; - import lombok.Getter; import lombok.var; import net.minecraft.client.Minecraft; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousSocketChannel; +import java.nio.channels.CompletionHandler; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Future; +import java.util.function.Consumer; + +import static com.minecrafttas.tasmod.TASmod.LOGGER; + public class Client { - - private AsynchronousSocketChannel socket; - private ByteBuffer writeBuffer; - private ByteBuffer readBuffer; + + private static final int BUFFER_SIZE = 1024*1024; + + private final AsynchronousSocketChannel socket; + private final Map> handlers = new HashMap<>(); + private final ByteBuffer writeBuffer = ByteBuffer.allocate(BUFFER_SIZE); + private final ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE); private Future future; - private Map> handlers = new HashMap<>(); - + @Getter private UUID id; @@ -49,6 +50,7 @@ public Client(String host, int port) throws Exception { LOGGER.info("Connecting tasmod server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); + this.createHandlers(); this.registerClientsidePacketHandlers(); LOGGER.info("Connected to tasmod server"); @@ -68,10 +70,6 @@ public Client(AsynchronousSocketChannel socket) { * Create read/write buffers and handlers for socket */ private void createHandlers() { - // create buffers - this.writeBuffer = ByteBuffer.allocate(1024*1024); - this.readBuffer = ByteBuffer.allocate(1024*1024); - // create input handler this.readBuffer.limit(4); this.socket.read(this.readBuffer, null, new CompletionHandler() { @@ -118,7 +116,7 @@ public void write(ByteBuffer buf) throws Exception { // prepare buffer this.writeBuffer.clear(); this.writeBuffer.putInt(buf.capacity()); - this.writeBuffer.put((ByteBuffer) buf.position(0)); + this.writeBuffer.put(buf.position(0)); this.writeBuffer.flip(); // send buffer async diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 58749a81..ead49ca7 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -1,6 +1,7 @@ package com.minecrafttas.server; -import static com.minecrafttas.tasmod.TASmod.LOGGER; +import lombok.Getter; +import lombok.var; import java.io.IOException; import java.net.InetSocketAddress; @@ -12,15 +13,13 @@ import java.util.List; import java.util.UUID; -import lombok.Getter; -import lombok.var; +import static com.minecrafttas.tasmod.TASmod.LOGGER; +@Getter public class Server { - - private AsynchronousServerSocketChannel socket; - - @Getter - private List clients; + + private final AsynchronousServerSocketChannel socket; + private final List clients; /** * Create and bind socket From 475f113c9238b14ce172e8ca803580eb64d01182 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Tue, 8 Aug 2023 18:57:38 +0200 Subject: [PATCH 09/60] Fix loggers --- .../java/com/minecrafttas/server/Client.java | 20 ++++++++----------- .../java/com/minecrafttas/server/Server.java | 2 +- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 3950634d..21a76361 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -91,13 +91,13 @@ public void completed(Integer result, Object attachment) { readBuffer.clear().limit(4); socket.read(readBuffer, null, this); } catch (Throwable exc) { - LOGGER.error("Unable to read packet {}", exc); + LOGGER.error("Unable to read packet!", exc); } } @Override public void failed(Throwable exc, Object attachment) { - LOGGER.error("Unable to read packet {}", exc); + LOGGER.error("Unable to read packet!", exc); } }); @@ -160,7 +160,7 @@ private void registerClientsidePacketHandlers() { var name = new String(nameBytes); InputSavestatesHandler.savestate(name); } catch (Exception e) { - TASmod.LOGGER.error("Exception occured during input savestate: {}", e); + TASmod.LOGGER.error("Exception occured during input savestate:", e); } }); @@ -183,14 +183,12 @@ private void registerClientsidePacketHandlers() { var name = new String(nameBytes); InputSavestatesHandler.loadstate(name); } catch (Exception e) { - TASmod.LOGGER.error("Exception occured during input loadstate: {}", e); + TASmod.LOGGER.error("Exception occured during input loadstate:", e); } }); // packet 13: unload chunks on client - this.handlers.put(13, buf -> - Minecraft.getMinecraft().addScheduledTask(() -> - SavestatesChunkControl.unloadAllClientChunks())); + this.handlers.put(13, buf -> Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)); // packet 14: request client motion this.handlers.put(14, buf -> { @@ -208,7 +206,7 @@ private void registerClientsidePacketHandlers() { .putFloat(player.jumpMovementFactor) ); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server: {}", e); + TASmod.LOGGER.error("Unable to send packet to server:", e); } } }); @@ -248,7 +246,7 @@ else if (state == State.TOGGLE) }); // packet 15: send client motion to server - this.handlers.put(15, buf -> ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(this.id), new Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1 ? true : false, buf.getFloat()))); + this.handlers.put(15, buf -> ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(this.id), new Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1, buf.getFloat()))); } /** @@ -268,9 +266,7 @@ public void authenticate(UUID id) throws Exception { private void handle(ByteBuffer buf) { var id = buf.getInt(); - this.handlers.getOrDefault(id, _buf -> { - LOGGER.error("Received invalid packet: {}", id); - }).accept(buf); + this.handlers.getOrDefault(id, _buf -> LOGGER.error("Received invalid packet: {}", id)).accept(buf); } } diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index ead49ca7..5ba08caf 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -44,7 +44,7 @@ public void completed(AsynchronousSocketChannel clientSocket, Object attachment) @Override public void failed(Throwable exc, Object attachment) { - LOGGER.error("Unable to accept client {}", exc); + LOGGER.error("Unable to accept client!", exc); } }); From bf3a1311d0790b567f09622067d03a1fd47783a8 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Tue, 8 Aug 2023 20:01:14 +0200 Subject: [PATCH 10/60] Don't manually calculate sizes --- .../java/com/minecrafttas/server/Client.java | 26 ++++---- .../com/minecrafttas/server/SecureList.java | 66 +++++++++++++++++++ .../java/com/minecrafttas/server/Server.java | 13 ++-- .../savestates/server/SavestateHandler.java | 50 +++++++------- .../server/motion/ClientMotionServer.java | 18 ++--- .../TickrateChangerClient.java | 18 ++--- .../TickrateChangerServer.java | 21 +++--- .../tasmod/ticksync/TickSyncClient.java | 13 ++-- .../tasmod/ticksync/TickSyncServer.java | 12 ++-- 9 files changed, 159 insertions(+), 78 deletions(-) create mode 100644 src/main/java/com/minecrafttas/server/SecureList.java diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 21a76361..004d15e0 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -25,12 +25,11 @@ import java.util.concurrent.Future; import java.util.function.Consumer; +import static com.minecrafttas.server.SecureList.BUFFER_SIZE; import static com.minecrafttas.tasmod.TASmod.LOGGER; public class Client { - private static final int BUFFER_SIZE = 1024*1024; - private final AsynchronousSocketChannel socket; private final Map> handlers = new HashMap<>(); private final ByteBuffer writeBuffer = ByteBuffer.allocate(BUFFER_SIZE); @@ -105,22 +104,25 @@ public void failed(Throwable exc, Object attachment) { /** * Write packet to server - * @param buf Packet + * @param id Buffer id + * @param buf Buffer * @throws Exception Networking exception */ - public void write(ByteBuffer buf) throws Exception { + public void write(int id, ByteBuffer buf) throws Exception { // wait for previous buffer to send if (this.future != null && !this.future.isDone()) this.future.get(); // prepare buffer + buf.flip(); this.writeBuffer.clear(); - this.writeBuffer.putInt(buf.capacity()); - this.writeBuffer.put(buf.position(0)); + this.writeBuffer.putInt(buf.limit()); + this.writeBuffer.put(buf); this.writeBuffer.flip(); - + // send buffer async this.future = this.socket.write(this.writeBuffer); + SecureList.POOL.unlock(id); } /** @@ -199,7 +201,8 @@ private void registerClientsidePacketHandlers() { try { // packet 15: send client motion to server - TASmodClient.client.write(ByteBuffer.allocate(4 + 8+8+8 + 4+4+4 + 1 + 4).putInt(15) + var bufIndex = SecureList.POOL.available(); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(15) .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) .put((byte) (player.isSprinting() ? 1 : 0)) @@ -257,11 +260,8 @@ else if (state == State.TOGGLE) public void authenticate(UUID id) throws Exception { this.id = id; - ByteBuffer buf = ByteBuffer.allocate(4+8+8); - buf.putInt(1); - buf.putLong(id.getMostSignificantBits()); - buf.putLong(id.getLeastSignificantBits()); - this.write(buf); + var bufIndex = SecureList.POOL.available(); + this.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(1).putLong(id.getMostSignificantBits()).putLong(id.getLeastSignificantBits())); } private void handle(ByteBuffer buf) { diff --git a/src/main/java/com/minecrafttas/server/SecureList.java b/src/main/java/com/minecrafttas/server/SecureList.java new file mode 100644 index 00000000..f02e6af9 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/SecureList.java @@ -0,0 +1,66 @@ +package com.minecrafttas.server; + +import lombok.var; + +import java.nio.ByteBuffer; + +/** + * Thread safe list (probably) for recycling byte buffers without reallocation + * @author Pancake + */ +public class SecureList { + + static final int BUFFER_SIZE = 1000 * 20; // 20 kB + static final int BUFFER_COUNT = 100; // * 100 => 2 MB + + public static SecureList POOL = new SecureList(BUFFER_COUNT, BUFFER_SIZE); + + private final ByteBuffer[] buffers; + private final boolean[] locked; + + /** + * Initialize secure list + * @param length Amount of byte buffers + * @param size Length of each byte buffer + */ + public SecureList(int length, int size) { + this.buffers = new ByteBuffer[length]; + this.locked = new boolean[length]; + + for (int i = 0; i < length; i++) + this.buffers[i] = ByteBuffer.allocate(size); + } + + /** + * Find available byte buffer + * @return Available byte buffer or -1 + */ + public int available() { + for (var i = 0; i < this.locked.length; i++) + if (!this.locked[i]) + return i; + return -1; + } + + /** + * Lock and return byte buffer + * @param i Index to lock + * @return Byte buffer + */ + public ByteBuffer lock(int i) { + if (this.locked[i]) + throw new RuntimeException("Tried to lock already locked buffer"); + + this.locked[i] = true; + return this.buffers[i].clear(); + } + + /** + * Unlocke byte buffer + * @param index Index to unlock + */ + public void unlock(int index) { + this.locked[index] = false; + } + +} diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 5ba08caf..2cadc9c1 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -53,12 +53,17 @@ public void failed(Throwable exc, Object attachment) { /** * Write packet to all clients - * @param buf Packet + * @param id Buffer id + * @param buf Buffer * @throws Exception Networking exception */ - public void writeAll(ByteBuffer buf) throws Exception { - for (var client : this.clients) - client.write(buf); + public void writeAll(int id, ByteBuffer buf) throws Exception { + int limit = buf.position(); + for (var client : this.clients) { + var sid = SecureList.POOL.available(); + client.write(sid, SecureList.POOL.lock(sid).put(buf.position(0).limit(limit))); + } + SecureList.POOL.unlock(id); } /** diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java index 3c2c319f..bc2c74d5 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java @@ -1,19 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.Logger; - +import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; import com.minecrafttas.tasmod.events.EventServer.EventLoadstate; @@ -30,7 +17,6 @@ import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoading; import com.minecrafttas.tasmod.util.LoggerMarkers; - import lombok.var; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -43,6 +29,18 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.storage.AnvilChunkLoader; +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Creates and loads savestates on both client and server without closing the @@ -186,9 +184,10 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // packet 10: savestate inputs client var name = this.getSavestateName(indexToSave).getBytes(); - TASmod.server.writeAll(ByteBuffer.allocate(8 + name.length).putInt(10).putInt(name.length).put(name)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(10).putInt(name.length).put(name)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } } @@ -215,9 +214,10 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // packet 11: close GuiSavestateScreen - TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(11)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(11)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } if (!tickrate0) { @@ -322,9 +322,10 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // packet 12: loadstate inputs client var name = this.getSavestateName(indexToLoad).getBytes(); - TASmod.server.writeAll(ByteBuffer.allocate(8 + name.length).putInt(12).putInt(name.length).put(name)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(12).putInt(name.length).put(name)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } } @@ -337,9 +338,10 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // packet 13: unload chunks on client - TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(13)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(13)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } // Unload chunks on the server @@ -696,4 +698,4 @@ public static enum SavestateState { NONE } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java index a6bcf3e6..0c56b042 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java @@ -1,14 +1,14 @@ package com.minecrafttas.tasmod.savestates.server.motion; -import java.nio.ByteBuffer; -import java.util.Map; - import com.google.common.collect.Maps; +import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; - +import lombok.var; import net.minecraft.entity.player.EntityPlayerMP; +import java.util.Map; + public class ClientMotionServer { private static Map motion = Maps.newHashMap(); @@ -22,9 +22,10 @@ public static void requestMotionFromClient() { motion.clear(); try { // packet 14: request client motion - TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(14)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(14)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } // TODO: is this still necessary? @@ -40,9 +41,10 @@ public static void requestMotionFromClient() { TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); try { // packet 14: request client motion - TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(14)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(14)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } } if (i == 1000) { diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index d715394a..213ea11d 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,13 +1,12 @@ package com.minecrafttas.tasmod.tickratechanger; -import java.nio.ByteBuffer; - import com.minecrafttas.common.events.EventClient.EventClientGameLoop; +import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; import com.minecrafttas.tasmod.util.LoggerMarkers; - +import lombok.var; import net.minecraft.client.Minecraft; /** @@ -96,9 +95,10 @@ public void changeServerTickrate(float tickrate) { try { // packet 4: request tickrate change - TASmodClient.client.write(ByteBuffer.allocate(8).putInt(4).putFloat(tickrate)); + var bufIndex = SecureList.POOL.available(); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(4).putFloat(tickrate)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server: {}", e); + TASmod.LOGGER.error("Unable to send packet to server:", e); } } @@ -109,7 +109,8 @@ public void togglePause() { if (Minecraft.getMinecraft().world != null) { try { // packet 6: toggle tickrate zero - TASmodClient.client.write(ByteBuffer.allocateDirect(6).putInt(6).putShort(State.TOGGLE.toShort())); + var bufIndex = SecureList.POOL.available(); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(6).putShort(State.TOGGLE.toShort())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server: {}", e); } @@ -173,9 +174,10 @@ public void advanceTick() { public void advanceServerTick() { try { // packet 7: request tick advance - TASmodClient.client.write(ByteBuffer.allocate(4).putInt(7)); + var bufIndex = SecureList.POOL.available(); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(7)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server: {}", e); + TASmod.LOGGER.error("Unable to send packet to server:", e); } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 6a08505d..b30ecbe0 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -1,16 +1,14 @@ package com.minecrafttas.tasmod.tickratechanger; -import java.nio.ByteBuffer; - -import org.apache.logging.log4j.Logger; - import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; +import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; - +import lombok.var; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; +import org.apache.logging.log4j.Logger; /** * Controls the tickrate on the server side @@ -87,9 +85,10 @@ public void changeClientTickrate(float tickrate, boolean log) { try { // packet 5: send new tickrate to clients - TASmod.server.writeAll(ByteBuffer.allocate(8).putInt(5).putFloat(tickrate)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(5).putFloat(tickrate)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } } @@ -175,9 +174,10 @@ public void advanceTick() { private static void advanceClientTick() { try { // packet 8: advance tick on clients - TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(8)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(8)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } } @@ -201,7 +201,8 @@ public void onPlayerJoinedServerSide(EntityPlayerMP player) { log("Sending the current tickrate ("+ticksPerSecond+") to " +player.getName()); try { // packet 9: change tickrate on client - TASmod.server.getClient(player.getUniqueID()).write(ByteBuffer.allocate(8).putInt(9).putFloat(ticksPerSecond)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.getClient(player.getUniqueID()).write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(9).putFloat(ticksPerSecond)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to {}: {}", player.getUniqueID(), e); } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index 5b8a755e..c51eac20 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -1,13 +1,13 @@ package com.minecrafttas.tasmod.ticksync; -import java.nio.ByteBuffer; -import java.util.concurrent.atomic.AtomicBoolean; - +import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; - +import lombok.var; import net.minecraft.client.Minecraft; +import java.util.concurrent.atomic.AtomicBoolean; + /** * This class manages tick sync * German: https://1drv.ms/p/s!Av_ysXerhm5CphLvLvguvL5QYe1A?e=MHPldP @@ -43,9 +43,10 @@ public static void clientPostTick(Minecraft mc) { try { // packet 3: notify server of tick pass - TASmodClient.client.write(ByteBuffer.allocate(4).putInt(3)); + var bufIndex = SecureList.POOL.available(); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(3)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server: {}", e); + TASmod.LOGGER.error("Unable to send packet to server:", e); } } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index b3f81b3f..c91da596 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -1,13 +1,14 @@ package com.minecrafttas.tasmod.ticksync; -import java.nio.ByteBuffer; +import com.minecrafttas.server.SecureList; +import com.minecrafttas.tasmod.TASmod; +import lombok.var; + import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; -import com.minecrafttas.tasmod.TASmod; - /** * This class manages tick sync * German: https://1drv.ms/p/s!Av_ysXerhm5CphLvLvguvL5QYe1A?e=MHPldP @@ -54,9 +55,10 @@ public static boolean shouldTick() { public static void serverPostTick() { try { // packet 2: tick clients - TASmod.server.writeAll(ByteBuffer.allocate(4).putInt(2)); + var bufIndex = SecureList.POOL.available(); + TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(2)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients: {}", e); + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } if(synchronizedList.size()>0) synchronizedList.clear(); From e2ee5b2b16144d60027f7f71ac6eb2034b5e8e9e Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Thu, 10 Aug 2023 21:51:13 +0200 Subject: [PATCH 11/60] Update loom --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 4ff403e9..41de9b46 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ org.gradle.jvmargs=-Xmx3G # Fabric properties minecraft_version=1.12.2 loader_version=0.14.19 -loom_version=1.2-SNAPSHOT +loom_version=1.3-SNAPSHOT # Mod properties mod_name=Tool-Assisted Speedrun Mod From bd3069bc75cbeef62b0cf0ebcdd5ce818269de3c Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Thu, 10 Aug 2023 21:51:59 +0200 Subject: [PATCH 12/60] Rewrite to enums --- .../java/com/minecrafttas/server/Client.java | 176 ++++++++++-------- .../java/com/minecrafttas/server/Packet.java | 5 + .../minecrafttas/server/PacketHandler.java | 8 + 3 files changed, 111 insertions(+), 78 deletions(-) create mode 100644 src/main/java/com/minecrafttas/server/Packet.java create mode 100644 src/main/java/com/minecrafttas/server/PacketHandler.java diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 004d15e0..b40950ae 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -6,10 +6,10 @@ import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; -import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer.Saver; -import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.ticksync.TickSyncServer; +import lombok.AllArgsConstructor; import lombok.Getter; import lombok.var; import net.minecraft.client.Minecraft; @@ -23,7 +23,6 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.Future; -import java.util.function.Consumer; import static com.minecrafttas.server.SecureList.BUFFER_SIZE; import static com.minecrafttas.tasmod.TASmod.LOGGER; @@ -31,7 +30,7 @@ public class Client { private final AsynchronousSocketChannel socket; - private final Map> handlers = new HashMap<>(); + private final Map packets = new HashMap<>(); private final ByteBuffer writeBuffer = ByteBuffer.allocate(BUFFER_SIZE); private final ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE); private Future future; @@ -142,20 +141,42 @@ public void close() throws IOException { * Register packet handlers for packets received on the client */ private void registerClientsidePacketHandlers() { - // packet 2: tick client - this.handlers.put(2, buf -> TickSyncClient.onPacket()); - - // packet 5: change client tickrate - this.handlers.put(5, buf -> TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())); - - // packet 8: advance tick on clients - this.handlers.put(8, buf -> TASmodClient.tickratechanger.advanceClientTick()); - - // packet 9: change tickrate on client - this.handlers.put(9, buf -> TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())); - - // packet 10: savestate inputs client - this.handlers.put(10, buf -> { + int id = 0; + + // move wherever you want - add client server packet handler + for (var packet : ClientPackets.values()) + this.packets.put(id++, packet); + } + + /** + * Register packet handlers for packets received on the server + */ + private void registerServersidePacketHandlers() { + int id = 0; + + // add authentication packet + this.packets.put(id++, () -> (pid, buf, uuid) -> { + this.id = new UUID(buf.getLong(), buf.getLong()); + LOGGER.info("Client authenticated: " + this.id); + }); + + // move wherever you want - add server packet handlers + for (var packet : ServerPackets.values()) + this.packets.put(id++, packet); + } + + // move wherever you want + @AllArgsConstructor + private enum ClientPackets implements Packet { + TICK_CLIENT((pid, buf, id) -> + TickSyncClient.onPacket()), + CHANGE_CLIENT_TICKRATE((pid, buf, id) -> + TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), + ADVANCE_TICK_ON_CLIENTS((pid, buf, id) -> + TASmodClient.tickratechanger.advanceClientTick()), + CHANGE_TICKRATE_ON_CLIENTS((pid, buf, id) -> + TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), // funny duplicate please fix + SAVESTATE_INPUTS_CLIENT((pid, buf, id) -> { try { var nameBytes = new byte[buf.getInt()]; buf.get(nameBytes); @@ -164,21 +185,15 @@ private void registerClientsidePacketHandlers() { } catch (Exception e) { TASmod.LOGGER.error("Exception occured during input savestate:", e); } - }); - - // packet 11: close GuiSavestateScreen on client - this.handlers.put(11, buf -> - Minecraft.getMinecraft().addScheduledTask(() -> { - var mc = Minecraft.getMinecraft(); - if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) - mc.displayGuiScreen(new GuiSavestateSavingScreen()); - else - mc.displayGuiScreen(null); - }) - ); - - // packet 12: loadstate inputs client - this.handlers.put(12, buf -> { + }), + CLOSE_GUISAVESTATESCREEN_ON_CLIENTS((pid, buf, id) -> { + var mc = Minecraft.getMinecraft(); + if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) + mc.displayGuiScreen(new GuiSavestateSavingScreen()); + else + mc.displayGuiScreen(null); + }), + LOADSTATE_INPUTS_CLIENT((pid, buf, id) -> { try { var nameBytes = new byte[buf.getInt()]; buf.get(nameBytes); @@ -187,71 +202,72 @@ private void registerClientsidePacketHandlers() { } catch (Exception e) { TASmod.LOGGER.error("Exception occured during input loadstate:", e); } - }); - - // packet 13: unload chunks on client - this.handlers.put(13, buf -> Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)); - - // packet 14: request client motion - this.handlers.put(14, buf -> { + }), + UNLOAD_CHUNKS_ON_CLIENTS((pid, buf, id) -> + Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)), + REQUEST_CLIENT_MOTION((pid, buf, id) -> { var player = Minecraft.getMinecraft().player; if (player != null) { if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); - + try { // packet 15: send client motion to server var bufIndex = SecureList.POOL.available(); TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(15) - .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) - .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) - .put((byte) (player.isSprinting() ? 1 : 0)) - .putFloat(player.jumpMovementFactor) + .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) + .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) + .put((byte) (player.isSprinting() ? 1 : 0)) + .putFloat(player.jumpMovementFactor) ); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } } }); + + private final PacketHandler handler; + + @Override + public PacketHandler handler() { + return this.handler; + } } - - /** - * Register packet handlers for packets received on the server - */ - private void registerServersidePacketHandlers() { - // packet 1: authentication packet - this.handlers.put(1, buf -> { - this.id = new UUID(buf.getLong(), buf.getLong()); - LOGGER.info("Client authenticated: " + this.id); - }); - - // packet 3: notify server of tick pass - this.handlers.put(3, buf -> TickSyncServer.onPacket(this.id)); - - // packet 4: request tickrate change - this.handlers.put(4, buf -> TASmod.tickratechanger.changeTickrate(buf.getFloat())); - - // packet 6: tickrate zero toggle - this.handlers.put(6, buf -> { - var state = State.fromShort(buf.getShort()); - if (state == State.PAUSE) + + private enum ServerPackets implements Packet { + NOTIFY_SERVER_OF_TICK_PASS((pid, buf, id) -> + TickSyncServer.onPacket(id)), + REQUEST_TICKRATE_CHANGE((pid, buf, id) -> + TASmod.tickratechanger.changeTickrate(buf.getFloat())), + TICKRATE_ZERO_TOGGLE((pid, buf, id) -> { + var state = TickrateChangerServer.State.fromShort(buf.getShort()); + if (state == TickrateChangerServer.State.PAUSE) TASmod.tickratechanger.pauseGame(true); - else if (state == State.UNPAUSE) + else if (state == TickrateChangerServer.State.UNPAUSE) TASmod.tickratechanger.pauseGame(false); - else if (state == State.TOGGLE) + else if (state == TickrateChangerServer.State.TOGGLE) TASmod.tickratechanger.togglePause(); - }); - - // packet 7: request tick advance - this.handlers.put(7, buf -> { + }), + REQUEST_TICK_ADVANCE((pid, buf, id) -> { if (TASmod.tickratechanger.ticksPerSecond == 0) TASmod.tickratechanger.advanceTick(); - }); - - // packet 15: send client motion to server - this.handlers.put(15, buf -> ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(this.id), new Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1, buf.getFloat()))); + }), + SEND_CLIENT_MOTION_TO_SERVER((pid, buf, id) -> + ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(id), new ClientMotionServer.Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1, buf.getFloat()))); + + + private final PacketHandler handler; + + private ServerPackets(PacketHandler handler) { + this.handler = handler; + } + + @Override + public PacketHandler handler() { + return this.handler; + } } - + /** * Sends then authentication packet to the server * @param id Unique ID @@ -266,7 +282,11 @@ public void authenticate(UUID id) throws Exception { private void handle(ByteBuffer buf) { var id = buf.getInt(); - this.handlers.getOrDefault(id, _buf -> LOGGER.error("Received invalid packet: {}", id)).accept(buf); + var packet = this.packets.get(id); + if (packet != null) + packet.handler().handle(packet, buf, this.id); + else + LOGGER.error("Received invalid packet: {}", this.id); } } diff --git a/src/main/java/com/minecrafttas/server/Packet.java b/src/main/java/com/minecrafttas/server/Packet.java new file mode 100644 index 00000000..adf11761 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/Packet.java @@ -0,0 +1,5 @@ +package com.minecrafttas.server; + +public interface Packet { + PacketHandler handler(); +} diff --git a/src/main/java/com/minecrafttas/server/PacketHandler.java b/src/main/java/com/minecrafttas/server/PacketHandler.java new file mode 100644 index 00000000..0a6c4ca5 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/PacketHandler.java @@ -0,0 +1,8 @@ +package com.minecrafttas.server; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public interface PacketHandler { + void handle(Packet pid, ByteBuffer buf, UUID id); +} From 749a60ed5efe0aad2e5fd1be43ca8598675377c0 Mon Sep 17 00:00:00 2001 From: PancakeTAS Date: Thu, 10 Aug 2023 22:12:02 +0200 Subject: [PATCH 13/60] Update method calls too --- .../java/com/minecrafttas/server/Client.java | 21 +++++++------------ .../savestates/server/SavestateHandler.java | 17 ++++++++------- .../server/motion/ClientMotionServer.java | 9 ++++---- .../TickrateChangerClient.java | 15 ++++++------- .../TickrateChangerServer.java | 13 ++++++------ .../tasmod/ticksync/TickSyncClient.java | 5 +++-- .../tasmod/ticksync/TickSyncServer.java | 5 +++-- 7 files changed, 43 insertions(+), 42 deletions(-) diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index b40950ae..6da555fb 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -145,29 +145,27 @@ private void registerClientsidePacketHandlers() { // move wherever you want - add client server packet handler for (var packet : ClientPackets.values()) - this.packets.put(id++, packet); + this.packets.put(packet.ordinal(), packet); } /** * Register packet handlers for packets received on the server */ private void registerServersidePacketHandlers() { - int id = 0; - // add authentication packet - this.packets.put(id++, () -> (pid, buf, uuid) -> { + this.packets.put(-1, () -> (pid, buf, uuid) -> { this.id = new UUID(buf.getLong(), buf.getLong()); LOGGER.info("Client authenticated: " + this.id); }); // move wherever you want - add server packet handlers for (var packet : ServerPackets.values()) - this.packets.put(id++, packet); + this.packets.put(packet.ordinal(), packet); } // move wherever you want @AllArgsConstructor - private enum ClientPackets implements Packet { + public static enum ClientPackets implements Packet { TICK_CLIENT((pid, buf, id) -> TickSyncClient.onPacket()), CHANGE_CLIENT_TICKRATE((pid, buf, id) -> @@ -212,9 +210,9 @@ private enum ClientPackets implements Packet { Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); try { - // packet 15: send client motion to server + // send client motion to server var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(15) + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(ServerPackets.SEND_CLIENT_MOTION_TO_SERVER.ordinal()) .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) .put((byte) (player.isSprinting() ? 1 : 0)) @@ -234,7 +232,8 @@ public PacketHandler handler() { } } - private enum ServerPackets implements Packet { + @AllArgsConstructor + public static enum ServerPackets implements Packet { NOTIFY_SERVER_OF_TICK_PASS((pid, buf, id) -> TickSyncServer.onPacket(id)), REQUEST_TICKRATE_CHANGE((pid, buf, id) -> @@ -258,10 +257,6 @@ else if (state == TickrateChangerServer.State.TOGGLE) private final PacketHandler handler; - private ServerPackets(PacketHandler handler) { - this.handler = handler; - } - @Override public PacketHandler handler() { return this.handler; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java index bc2c74d5..df8db31f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; +import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; @@ -182,10 +183,10 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex * recording on the client with that name */ try { - // packet 10: savestate inputs client + // savestate inputs client var name = this.getSavestateName(indexToSave).getBytes(); var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(10).putInt(name.length).put(name)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.SAVESTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -213,9 +214,9 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex server.getPlayerList().sendMessage(new TextComponentString(TextFormatting.GREEN + "Savestate " + indexToSave + " saved")); try { - // packet 11: close GuiSavestateScreen + // close GuiSavestateScreen var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(11)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CLOSE_GUISAVESTATESCREEN_ON_CLIENTS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -320,10 +321,10 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex */ if (savestateIndex != 0) { try { - // packet 12: loadstate inputs client + // loadstate inputs client var name = this.getSavestateName(indexToLoad).getBytes(); var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(12).putInt(name.length).put(name)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.LOADSTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -337,9 +338,9 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex try { - // packet 13: unload chunks on client + // unload chunks on client var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(13)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.UNLOAD_CHUNKS_ON_CLIENTS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java index 0c56b042..be24655b 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java @@ -1,6 +1,7 @@ package com.minecrafttas.tasmod.savestates.server.motion; import com.google.common.collect.Maps; +import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -21,9 +22,9 @@ public static void requestMotionFromClient() { TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); motion.clear(); try { - // packet 14: request client motion + // request client motion var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(14)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -40,9 +41,9 @@ public static void requestMotionFromClient() { if(i % 30 == 1) { TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); try { - // packet 14: request client motion + // request client motion var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(14)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index 213ea11d..532ebb6d 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,6 +1,7 @@ package com.minecrafttas.tasmod.tickratechanger; import com.minecrafttas.common.events.EventClient.EventClientGameLoop; +import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; @@ -94,9 +95,9 @@ public void changeServerTickrate(float tickrate) { } try { - // packet 4: request tickrate change + // request tickrate change var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(4).putFloat(tickrate)); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICKRATE_CHANGE.ordinal()).putFloat(tickrate)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } @@ -108,11 +109,11 @@ public void changeServerTickrate(float tickrate) { public void togglePause() { if (Minecraft.getMinecraft().world != null) { try { - // packet 6: toggle tickrate zero + // toggle tickrate zero var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(6).putShort(State.TOGGLE.toShort())); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.TICKRATE_ZERO_TOGGLE.ordinal()).putShort(State.TOGGLE.toShort())); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server: {}", e); + TASmod.LOGGER.error("Unable to send packet to server:", e); } } else { togglePauseClient(); @@ -173,9 +174,9 @@ public void advanceTick() { */ public void advanceServerTick() { try { - // packet 7: request tick advance + // request tick advance var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(7)); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICK_ADVANCE.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index b30ecbe0..43cbae55 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -2,6 +2,7 @@ import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; +import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -84,9 +85,9 @@ public void changeClientTickrate(float tickrate, boolean log) { log("Changing the tickrate "+ tickrate + " to all clients"); try { - // packet 5: send new tickrate to clients + // send new tickrate to clients var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(5).putFloat(tickrate)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(tickrate)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -173,9 +174,9 @@ public void advanceTick() { */ private static void advanceClientTick() { try { - // packet 8: advance tick on clients + // advance tick on clients var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(8)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.ADVANCE_TICK_ON_CLIENTS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -200,9 +201,9 @@ public void onPlayerJoinedServerSide(EntityPlayerMP player) { if(TASmod.getServerInstance().isDedicatedServer()) { log("Sending the current tickrate ("+ticksPerSecond+") to " +player.getName()); try { - // packet 9: change tickrate on client + // change tickrate on client var bufIndex = SecureList.POOL.available(); - TASmod.server.getClient(player.getUniqueID()).write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(9).putFloat(ticksPerSecond)); + TASmod.server.getClient(player.getUniqueID()).write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(ticksPerSecond)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to {}: {}", player.getUniqueID(), e); } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index c51eac20..15fa41fc 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.ticksync; +import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; @@ -42,9 +43,9 @@ public static void clientPostTick(Minecraft mc) { } try { - // packet 3: notify server of tick pass + // notify server of tick pass var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(3)); + TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.NOTIFY_SERVER_OF_TICK_PASS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index c91da596..d19858fe 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.ticksync; +import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import lombok.var; @@ -54,9 +55,9 @@ public static boolean shouldTick() { */ public static void serverPostTick() { try { - // packet 2: tick clients + // tick clients var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(SecureList.POOL.lock(bufIndex).putInt(2)); + TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.TICK_CLIENT.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } From 682683a72f7ef5d083d139dfe6665285f68ac9fd Mon Sep 17 00:00:00 2001 From: Scribble Date: Fri, 11 Aug 2023 23:31:47 +0200 Subject: [PATCH 14/60] Delombokified code It's var same thing var Pancake hating ducks. Var makes the code more unreadable var my opinion. As someone var values readable code var do not approve var this. --- build.gradle | 4 -- .../java/com/minecrafttas/server/Client.java | 49 +++++++++++-------- .../com/minecrafttas/server/SecureList.java | 6 +-- .../java/com/minecrafttas/server/Server.java | 18 +++---- 4 files changed, 39 insertions(+), 38 deletions(-) diff --git a/build.gradle b/build.gradle index dcb5d828..5c41a5a6 100644 --- a/build.gradle +++ b/build.gradle @@ -42,10 +42,6 @@ configurations { // dependencies dependencies { - // annotation processor - compileOnly 'org.projectlombok:lombok:1.18.28' - annotationProcessor 'org.projectlombok:lombok:1.18.28' - // tasmod dependencies embed group: 'com.dselent', name: 'bigarraylist', version: '1.0' compileOnly group: 'com.minecrafttas', name: 'killtherng', version: '2.0' diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 6da555fb..cdba1522 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -7,12 +7,11 @@ import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.ticksync.TickSyncServer; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.var; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import java.io.IOException; import java.net.InetSocketAddress; @@ -35,7 +34,6 @@ public class Client { private final ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE); private Future future; - @Getter private UUID id; /** @@ -141,10 +139,8 @@ public void close() throws IOException { * Register packet handlers for packets received on the client */ private void registerClientsidePacketHandlers() { - int id = 0; - // move wherever you want - add client server packet handler - for (var packet : ClientPackets.values()) + for (ClientPackets packet : ClientPackets.values()) this.packets.put(packet.ordinal(), packet); } @@ -159,12 +155,11 @@ private void registerServersidePacketHandlers() { }); // move wherever you want - add server packet handlers - for (var packet : ServerPackets.values()) + for (ServerPackets packet : ServerPackets.values()) this.packets.put(packet.ordinal(), packet); } // move wherever you want - @AllArgsConstructor public static enum ClientPackets implements Packet { TICK_CLIENT((pid, buf, id) -> TickSyncClient.onPacket()), @@ -176,16 +171,16 @@ public static enum ClientPackets implements Packet { TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), // funny duplicate please fix SAVESTATE_INPUTS_CLIENT((pid, buf, id) -> { try { - var nameBytes = new byte[buf.getInt()]; + byte[] nameBytes = new byte[buf.getInt()]; buf.get(nameBytes); - var name = new String(nameBytes); + String name = new String(nameBytes); InputSavestatesHandler.savestate(name); } catch (Exception e) { TASmod.LOGGER.error("Exception occured during input savestate:", e); } }), CLOSE_GUISAVESTATESCREEN_ON_CLIENTS((pid, buf, id) -> { - var mc = Minecraft.getMinecraft(); + Minecraft mc = Minecraft.getMinecraft(); if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) mc.displayGuiScreen(new GuiSavestateSavingScreen()); else @@ -193,9 +188,9 @@ public static enum ClientPackets implements Packet { }), LOADSTATE_INPUTS_CLIENT((pid, buf, id) -> { try { - var nameBytes = new byte[buf.getInt()]; + byte[] nameBytes = new byte[buf.getInt()]; buf.get(nameBytes); - var name = new String(nameBytes); + String name = new String(nameBytes); InputSavestatesHandler.loadstate(name); } catch (Exception e) { TASmod.LOGGER.error("Exception occured during input loadstate:", e); @@ -204,14 +199,14 @@ public static enum ClientPackets implements Packet { UNLOAD_CHUNKS_ON_CLIENTS((pid, buf, id) -> Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)), REQUEST_CLIENT_MOTION((pid, buf, id) -> { - var player = Minecraft.getMinecraft().player; + EntityPlayerSP player = Minecraft.getMinecraft().player; if (player != null) { if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); try { // send client motion to server - var bufIndex = SecureList.POOL.available(); + int bufIndex = SecureList.POOL.available(); TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(ServerPackets.SEND_CLIENT_MOTION_TO_SERVER.ordinal()) .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) @@ -226,20 +221,23 @@ public static enum ClientPackets implements Packet { private final PacketHandler handler; + ClientPackets(PacketHandler handler) { + this.handler = handler; + } + @Override public PacketHandler handler() { return this.handler; } } - @AllArgsConstructor public static enum ServerPackets implements Packet { NOTIFY_SERVER_OF_TICK_PASS((pid, buf, id) -> TickSyncServer.onPacket(id)), REQUEST_TICKRATE_CHANGE((pid, buf, id) -> TASmod.tickratechanger.changeTickrate(buf.getFloat())), TICKRATE_ZERO_TOGGLE((pid, buf, id) -> { - var state = TickrateChangerServer.State.fromShort(buf.getShort()); + State state = TickrateChangerServer.State.fromShort(buf.getShort()); if (state == TickrateChangerServer.State.PAUSE) TASmod.tickratechanger.pauseGame(true); else if (state == TickrateChangerServer.State.UNPAUSE) @@ -257,6 +255,10 @@ else if (state == TickrateChangerServer.State.TOGGLE) private final PacketHandler handler; + ServerPackets(PacketHandler handler) { + this.handler = handler; + } + @Override public PacketHandler handler() { return this.handler; @@ -271,17 +273,22 @@ public PacketHandler handler() { public void authenticate(UUID id) throws Exception { this.id = id; - var bufIndex = SecureList.POOL.available(); + int bufIndex = SecureList.POOL.available(); this.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(1).putLong(id.getMostSignificantBits()).putLong(id.getLeastSignificantBits())); } private void handle(ByteBuffer buf) { - var id = buf.getInt(); - var packet = this.packets.get(id); + int id = buf.getInt(); + Packet packet = this.packets.get(id); if (packet != null) packet.handler().handle(packet, buf, this.id); else LOGGER.error("Received invalid packet: {}", this.id); } + public UUID getId() { + // TODO Auto-generated method stub + return this.id; + } + } diff --git a/src/main/java/com/minecrafttas/server/SecureList.java b/src/main/java/com/minecrafttas/server/SecureList.java index f02e6af9..e60ff057 100644 --- a/src/main/java/com/minecrafttas/server/SecureList.java +++ b/src/main/java/com/minecrafttas/server/SecureList.java @@ -1,7 +1,5 @@ package com.minecrafttas.server; -import lombok.var; - import java.nio.ByteBuffer; /** @@ -36,7 +34,7 @@ public SecureList(int length, int size) { * @return Available byte buffer or -1 */ public int available() { - for (var i = 0; i < this.locked.length; i++) + for (int i = 0; i < this.locked.length; i++) if (!this.locked[i]) return i; return -1; @@ -52,7 +50,7 @@ public ByteBuffer lock(int i) { throw new RuntimeException("Tried to lock already locked buffer"); this.locked[i] = true; - return this.buffers[i].clear(); + return (ByteBuffer) this.buffers[i].clear(); } /** diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 2cadc9c1..16bea1e9 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -1,7 +1,6 @@ package com.minecrafttas.server; -import lombok.Getter; -import lombok.var; +import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.io.IOException; import java.net.InetSocketAddress; @@ -13,9 +12,6 @@ import java.util.List; import java.util.UUID; -import static com.minecrafttas.tasmod.TASmod.LOGGER; - -@Getter public class Server { private final AsynchronousServerSocketChannel socket; @@ -59,9 +55,9 @@ public void failed(Throwable exc, Object attachment) { */ public void writeAll(int id, ByteBuffer buf) throws Exception { int limit = buf.position(); - for (var client : this.clients) { - var sid = SecureList.POOL.available(); - client.write(sid, SecureList.POOL.lock(sid).put(buf.position(0).limit(limit))); + for (Client client : this.clients) { + int sid = SecureList.POOL.available(); + client.write(sid, SecureList.POOL.lock(sid).put((ByteBuffer) buf.position(0).limit(limit))); } SecureList.POOL.unlock(id); } @@ -84,11 +80,15 @@ public void close() throws IOException { * @param uniqueID UUID */ public Client getClient(UUID uniqueID) { - for (var client : this.clients) + for (Client client : this.clients) if (client.getId().equals(uniqueID)) return client; return null; } + public AsynchronousServerSocketChannel getAsynchronousSocketChannel() { + return this.socket; + } + } From e220f5bd32b9cd99880060dfb5063630913032c5 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sat, 12 Aug 2023 21:39:53 +0200 Subject: [PATCH 15/60] Adding packet handler interfaces and helpers for sending packets This system is a WIP mix between the Pancake method (lambda method) of only lambdas as packet handlers and my method of adding interfaces to classes for declaring packet handlers (class method). The class method is good for having one class declare multiple packet handlers, while the lambda method is better for simple handlers, that do not need a dedicated class. The lambda method also takes precedence over the class method, meaning you can quickly write packet handlers for debug purposes. --- .../common/events/CompactPacketHandler.java | 12 + .../common/events/EventClient.java | 22 +- ...stener.java => EventListenerRegistry.java} | 2 +- .../common/events/EventServer.java | 14 +- .../server/ByteBufferBuilder.java | 96 ++++++ .../java/com/minecrafttas/server/Client.java | 320 +++++++++--------- .../java/com/minecrafttas/server/Packet.java | 5 - .../minecrafttas/server/PacketHandler.java | 8 - .../server/PacketHandlerRegistry.java | 54 +++ .../java/com/minecrafttas/server/Server.java | 26 +- .../exception/HandlingPacketException.java | 9 + .../exception/InvalidPacketException.java | 17 + .../interfaces/ClientPacketHandler.java | 9 + .../server/interfaces/PacketHandlerBase.java | 11 + .../server/interfaces/PacketID.java | 12 + .../interfaces/ServerPacketHandler.java | 9 + .../java/com/minecrafttas/tasmod/TASmod.java | 103 +++--- .../com/minecrafttas/tasmod/TASmodClient.java | 47 ++- .../minecrafttas/tasmod/TASmodPackets.java | 62 ++++ .../clearinputs/ClearInputsPacket.java | 4 +- .../tasmod/commands/folder/FolderPacket.java | 4 +- .../commands/fullplay/FullPlayPacket.java | 3 +- .../commands/fullrecord/FullRecordPacket.java | 3 +- .../commands/loadtas/LoadTASPacket.java | 4 +- .../commands/playuntil/PlayUntilPacket.java | 4 +- .../restartandplay/RestartAndPlayPacket.java | 4 +- .../commands/savetas/SaveTASPacket.java | 4 +- .../tasmod/events/EventClient.java | 30 +- .../tasmod/events/EventServer.java | 33 +- .../tasmod/events/TASmodEventListener.java | 4 +- .../tasmod/ktrng/KTRNGSeedPacket.java | 4 +- .../tasmod/ktrng/KTRNGStartSeedPacket.java | 4 +- .../tasmod/ktrng/KillTheRNGHandler.java | 4 +- .../tasmod/mixin/MixinMinecraft.java | 4 +- .../tasmod/mixin/MixinMinecraftServer.java | 6 +- .../tasmod/playback/PlaybackController.java | 5 +- .../playback/server/SyncStatePacket.java | 3 +- .../playback/server/TASstateClient.java | 2 +- .../client/InputSavestatesPacket.java | 3 +- .../savestates/server/LoadstatePacket.java | 3 +- .../savestates/server/SavestateHandler.java | 35 +- .../savestates/server/SavestatePacket.java | 3 +- .../server/motion/ClientMotionServer.java | 10 +- .../SavestatePlayerLoadingPacket.java | 3 +- .../TickrateChangerClient.java | 8 +- .../TickrateChangerServer.java | 17 +- .../tasmod/ticksync/TickSyncClient.java | 35 +- .../tasmod/ticksync/TickSyncServer.java | 46 ++- 48 files changed, 761 insertions(+), 369 deletions(-) create mode 100644 src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java rename src/main/java/com/minecrafttas/common/events/{EventListener.java => EventListenerRegistry.java} (93%) create mode 100644 src/main/java/com/minecrafttas/server/ByteBufferBuilder.java delete mode 100644 src/main/java/com/minecrafttas/server/Packet.java delete mode 100644 src/main/java/com/minecrafttas/server/PacketHandler.java create mode 100644 src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java create mode 100644 src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java create mode 100644 src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java create mode 100644 src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java create mode 100644 src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java create mode 100644 src/main/java/com/minecrafttas/server/interfaces/PacketID.java create mode 100644 src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java create mode 100644 src/main/java/com/minecrafttas/tasmod/TASmodPackets.java diff --git a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java new file mode 100644 index 00000000..5d12f16e --- /dev/null +++ b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java @@ -0,0 +1,12 @@ +package com.minecrafttas.common.events; + +import java.nio.ByteBuffer; +import java.util.UUID; + +import com.minecrafttas.server.exception.HandlingPacketException; + +@FunctionalInterface +public interface CompactPacketHandler { + + public void onPacket(ByteBuffer buf, UUID clientID) throws HandlingPacketException; +} diff --git a/src/main/java/com/minecrafttas/common/events/EventClient.java b/src/main/java/com/minecrafttas/common/events/EventClient.java index 48cbb5d2..f7dab234 100644 --- a/src/main/java/com/minecrafttas/common/events/EventClient.java +++ b/src/main/java/com/minecrafttas/common/events/EventClient.java @@ -1,7 +1,7 @@ package com.minecrafttas.common.events; import com.minecrafttas.common.Common; -import com.minecrafttas.common.events.EventListener.EventBase; +import com.minecrafttas.common.events.EventListenerRegistry.EventBase; import com.mojang.authlib.GameProfile; import net.minecraft.client.Minecraft; @@ -26,7 +26,7 @@ public static interface EventOpenGui extends EventBase { public static GuiScreen fireOpenGuiEvent(GuiScreen gui) { Common.LOGGER.trace(Common.Event, "Firing OpenGuiEvent"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventOpenGui) { EventOpenGui event = (EventOpenGui) eventListener; GuiScreen newGui = event.onOpenGui(gui); @@ -53,7 +53,7 @@ public static interface EventLaunchIntegratedServer extends EventBase { public static void fireOnLaunchIntegratedServer() { Common.LOGGER.trace(Common.Event, "Firing LaunchIntegratedServer"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventLaunchIntegratedServer) { EventLaunchIntegratedServer event = (EventLaunchIntegratedServer) eventListener; event.onLaunchIntegratedServer(); @@ -76,7 +76,7 @@ public static interface EventDoneLoadingWorld extends EventBase { public static void fireOnDoneLoadingWorld() { Common.LOGGER.trace(Common.Event, "Firing DoneLoadingWorld"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventDoneLoadingWorld) { EventDoneLoadingWorld event = (EventDoneLoadingWorld) eventListener; event.onDoneLoadingWorld(); @@ -99,7 +99,7 @@ public static interface EventClientTick extends EventBase { public void onClientTick(Minecraft mc); public static void fireOnClientTick(Minecraft mc) { - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventClientTick) { EventClientTick event = (EventClientTick) eventListener; event.onClientTick(mc); @@ -123,7 +123,7 @@ public static interface EventClientInit extends EventBase { public static void fireOnClientInit(Minecraft mc) { Common.LOGGER.trace(Common.Event, "Firing ClientInit"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventClientInit) { EventClientInit event = (EventClientInit) eventListener; event.onClientInit(mc); @@ -146,7 +146,7 @@ public static interface EventClientGameLoop extends EventBase { public void onRunClientGameLoop(Minecraft mc); public static void fireOnClientGameLoop(Minecraft mc) { - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventClientGameLoop) { EventClientGameLoop event = (EventClientGameLoop) eventListener; event.onRunClientGameLoop(mc); @@ -170,7 +170,7 @@ public static interface EventCamera extends EventBase { public CameraData onCameraEvent(CameraData dataIn); public static CameraData fireCameraEvent(CameraData dataIn) { - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventCamera) { EventCamera event = (EventCamera) eventListener; CameraData data = event.onCameraEvent(dataIn); @@ -223,7 +223,7 @@ public static interface EventPlayerLeaveClientSide extends EventBase { public static void firePlayerLeaveClientSide(EntityPlayerSP player) { Common.LOGGER.trace(Common.Event, "Firing PlayerLeaveClientSideEvent"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventPlayerLeaveClientSide) { EventPlayerLeaveClientSide event = (EventPlayerLeaveClientSide) eventListener; event.onPlayerLeaveClientSide(player); @@ -247,7 +247,7 @@ public static interface EventPlayerJoinedClientSide extends EventBase { public static void firePlayerJoinedClientSide(EntityPlayerSP player) { Common.LOGGER.trace(Common.Event, "Firing PlayerJoinedClientSide"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventPlayerJoinedClientSide) { EventPlayerJoinedClientSide event = (EventPlayerJoinedClientSide) eventListener; event.onPlayerJoinedClientSide(player); @@ -272,7 +272,7 @@ public static interface EventOtherPlayerJoinedClientSide extends EventBase { */ public static void fireOtherPlayerJoinedClientSide(GameProfile profile) { Common.LOGGER.trace(Common.Event, "Firing OtherPlayerJoinedClientSide"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventOtherPlayerJoinedClientSide) { EventOtherPlayerJoinedClientSide event = (EventOtherPlayerJoinedClientSide) eventListener; event.onOtherPlayerJoinedClientSide(profile); diff --git a/src/main/java/com/minecrafttas/common/events/EventListener.java b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java similarity index 93% rename from src/main/java/com/minecrafttas/common/events/EventListener.java rename to src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java index b568e52c..65631b90 100644 --- a/src/main/java/com/minecrafttas/common/events/EventListener.java +++ b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java @@ -2,7 +2,7 @@ import java.util.ArrayList; -public class EventListener { +public class EventListenerRegistry { private static ArrayList EVENTLISTENER_REGISTRY = new ArrayList<>(); diff --git a/src/main/java/com/minecrafttas/common/events/EventServer.java b/src/main/java/com/minecrafttas/common/events/EventServer.java index 96b444d3..a44ab51a 100644 --- a/src/main/java/com/minecrafttas/common/events/EventServer.java +++ b/src/main/java/com/minecrafttas/common/events/EventServer.java @@ -1,7 +1,7 @@ package com.minecrafttas.common.events; import com.minecrafttas.common.Common; -import com.minecrafttas.common.events.EventListener.EventBase; +import com.minecrafttas.common.events.EventListenerRegistry.EventBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; @@ -23,7 +23,7 @@ public static interface EventServerInit extends EventBase { public static void fireServerStartEvent(MinecraftServer server) { Common.LOGGER.trace(Common.Event, "Firing ServerStartEvent"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if (eventListener instanceof EventServerInit) { EventServerInit event = (EventServerInit) eventListener; event.onServerInit(server); @@ -46,7 +46,7 @@ public static interface EventServerTick extends EventBase { public void onServerTick(MinecraftServer server); public static void fireOnServerTick(MinecraftServer server) { - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if (eventListener instanceof EventServerTick) { EventServerTick event = (EventServerTick) eventListener; event.onServerTick(server); @@ -70,7 +70,7 @@ public static interface EventServerStop extends EventBase { public static void fireOnServerStop(MinecraftServer server) { Common.LOGGER.trace(Common.Event, "Firing ServerStopEvent"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if (eventListener instanceof EventServerStop) { EventServerStop event = (EventServerStop) eventListener; event.onServerStop(server); @@ -93,7 +93,7 @@ public static interface EventServerGameLoop extends EventBase { public void onRunServerGameLoop(MinecraftServer server); public static void fireOnServerGameLoop(MinecraftServer server) { - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if (eventListener instanceof EventServerGameLoop) { EventServerGameLoop event = (EventServerGameLoop) eventListener; event.onRunServerGameLoop(server); @@ -108,7 +108,7 @@ public static interface EventPlayerJoinedServerSide extends EventBase { public static void firePlayerJoinedServerSide(EntityPlayerMP player) { Common.LOGGER.trace(Common.Event, "Firing PlayerJoinedServerSide"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if (eventListener instanceof EventPlayerJoinedServerSide) { EventPlayerJoinedServerSide event = (EventPlayerJoinedServerSide) eventListener; event.onPlayerJoinedServerSide(player); @@ -132,7 +132,7 @@ public static interface EventPlayerLeaveServerSide extends EventBase { public static void firePlayerLeaveServerSide(EntityPlayerMP player) { Common.LOGGER.trace(Common.Event, "Firing PlayerLeaveServerSideEvent"); - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if (eventListener instanceof EventPlayerLeaveServerSide) { EventPlayerLeaveServerSide event = (EventPlayerLeaveServerSide) eventListener; event.onPlayerLeaveServerSide(player); diff --git a/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java new file mode 100644 index 00000000..7e1b4105 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java @@ -0,0 +1,96 @@ +package com.minecrafttas.server; + +import java.nio.ByteBuffer; +import java.util.UUID; + +import com.minecrafttas.server.interfaces.PacketID; + +/** + * Helper method for creating byte buffers which get pooled from a {@link SecureList} + * @author Scribble + */ +public class ByteBufferBuilder{ + + private int bufferIndex; + private ByteBuffer buffer; + + public ByteBufferBuilder(int id) { + bufferIndex = SecureList.POOL.available(); + buffer = SecureList.POOL.lock(bufferIndex); + buffer.putInt(id); + } + + public ByteBufferBuilder(PacketID packet) { + this(packet.getID()); + } + + private ByteBufferBuilder(int bufferIndex, ByteBuffer buffer) { + this.bufferIndex = bufferIndex; + this.buffer = buffer; + } + + public ByteBuffer build() { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + return this.buffer; + } + + public ByteBufferBuilder writeInt(int value) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.putInt(value); + return this; + } + + public ByteBufferBuilder writeDouble(double value) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.putDouble(value); + return this; + } + + public ByteBufferBuilder writeFloat(float value) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.putFloat(value); + return this; + } + + public ByteBufferBuilder writeLong(long value) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.putLong(value); + return this; + } + + public ByteBufferBuilder writeShort(short value) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.putShort(value); + return this; + } + + public ByteBufferBuilder writeBoolean(boolean value) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.put((byte)(value ?1:0)); + return this; + } + + public ByteBufferBuilder writeUUID(UUID uuid) { + if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + buffer.putLong(uuid.getMostSignificantBits()); + buffer.putLong(uuid.getLeastSignificantBits()); + return this; + } + + /** + * Unlocks the buffer from the pool making it available for other uses + */ + public void close() { + if(buffer !=null) { + SecureList.POOL.unlock(bufferIndex); + this.buffer = null; + } + } + + @Override + protected ByteBufferBuilder clone() throws CloneNotSupportedException { + int limit = this.buffer.position(); + int sid = SecureList.POOL.available(); + return new ByteBufferBuilder(sid, SecureList.POOL.lock(sid).put((ByteBuffer) this.buffer.position(0).limit(limit))); + } +} diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index cdba1522..679d300d 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -1,40 +1,36 @@ package com.minecrafttas.server; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.savestates.client.InputSavestatesHandler; -import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; -import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; -import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; -import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; -import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; -import com.minecrafttas.tasmod.ticksync.TickSyncClient; -import com.minecrafttas.tasmod.ticksync.TickSyncServer; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; +import static com.minecrafttas.server.SecureList.BUFFER_SIZE; +import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; -import java.util.HashMap; -import java.util.Map; import java.util.UUID; import java.util.concurrent.Future; -import static com.minecrafttas.server.SecureList.BUFFER_SIZE; -import static com.minecrafttas.tasmod.TASmod.LOGGER; +import com.minecrafttas.server.exception.InvalidPacketException; +import com.minecrafttas.server.interfaces.PacketID; public class Client { private final AsynchronousSocketChannel socket; - private final Map packets = new HashMap<>(); + private final PacketID[] packetIDs; private final ByteBuffer writeBuffer = ByteBuffer.allocate(BUFFER_SIZE); private final ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE); private Future future; - private UUID id; + private UUID clientID; + + private Side side; + + + public enum Side { + CLIENT, + SERVER; + } /** * Create and connect socket @@ -42,24 +38,29 @@ public class Client { * @param port Port * @throws Exception Unable to connect */ - public Client(String host, int port) throws Exception { + public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exception { LOGGER.info("Connecting tasmod server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); + this.side = Side.CLIENT; + this.packetIDs = packetIDs; + this.createHandlers(); - this.registerClientsidePacketHandlers(); LOGGER.info("Connected to tasmod server"); + + authenticate(uuid); } /** * Fork existing socket * @param socket Socket */ - public Client(AsynchronousSocketChannel socket) { + public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs) { this.socket = socket; + this.packetIDs = packetIDs; this.createHandlers(); - this.registerServersidePacketHandlers(); + this.side = Side.SERVER; } /** @@ -105,11 +106,13 @@ public void failed(Throwable exc, Object attachment) { * @param buf Buffer * @throws Exception Networking exception */ - public void write(int id, ByteBuffer buf) throws Exception { + public void send(ByteBufferBuilder bufferBuilder) throws Exception { // wait for previous buffer to send if (this.future != null && !this.future.isDone()) this.future.get(); + ByteBuffer buf = bufferBuilder.build(); + // prepare buffer buf.flip(); this.writeBuffer.clear(); @@ -119,7 +122,7 @@ public void write(int id, ByteBuffer buf) throws Exception { // send buffer async this.future = this.socket.write(this.writeBuffer); - SecureList.POOL.unlock(id); + bufferBuilder.close(); } /** @@ -135,160 +138,151 @@ public void close() throws IOException { this.socket.close(); } - /** - * Register packet handlers for packets received on the client - */ - private void registerClientsidePacketHandlers() { - // move wherever you want - add client server packet handler - for (ClientPackets packet : ClientPackets.values()) - this.packets.put(packet.ordinal(), packet); - } - - /** - * Register packet handlers for packets received on the server - */ - private void registerServersidePacketHandlers() { - // add authentication packet - this.packets.put(-1, () -> (pid, buf, uuid) -> { - this.id = new UUID(buf.getLong(), buf.getLong()); - LOGGER.info("Client authenticated: " + this.id); - }); - - // move wherever you want - add server packet handlers - for (ServerPackets packet : ServerPackets.values()) - this.packets.put(packet.ordinal(), packet); - } - // move wherever you want - public static enum ClientPackets implements Packet { - TICK_CLIENT((pid, buf, id) -> - TickSyncClient.onPacket()), - CHANGE_CLIENT_TICKRATE((pid, buf, id) -> - TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), - ADVANCE_TICK_ON_CLIENTS((pid, buf, id) -> - TASmodClient.tickratechanger.advanceClientTick()), - CHANGE_TICKRATE_ON_CLIENTS((pid, buf, id) -> - TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), // funny duplicate please fix - SAVESTATE_INPUTS_CLIENT((pid, buf, id) -> { - try { - byte[] nameBytes = new byte[buf.getInt()]; - buf.get(nameBytes); - String name = new String(nameBytes); - InputSavestatesHandler.savestate(name); - } catch (Exception e) { - TASmod.LOGGER.error("Exception occured during input savestate:", e); - } - }), - CLOSE_GUISAVESTATESCREEN_ON_CLIENTS((pid, buf, id) -> { - Minecraft mc = Minecraft.getMinecraft(); - if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) - mc.displayGuiScreen(new GuiSavestateSavingScreen()); - else - mc.displayGuiScreen(null); - }), - LOADSTATE_INPUTS_CLIENT((pid, buf, id) -> { - try { - byte[] nameBytes = new byte[buf.getInt()]; - buf.get(nameBytes); - String name = new String(nameBytes); - InputSavestatesHandler.loadstate(name); - } catch (Exception e) { - TASmod.LOGGER.error("Exception occured during input loadstate:", e); - } - }), - UNLOAD_CHUNKS_ON_CLIENTS((pid, buf, id) -> - Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)), - REQUEST_CLIENT_MOTION((pid, buf, id) -> { - EntityPlayerSP player = Minecraft.getMinecraft().player; - if (player != null) { - if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) - Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); - - try { - // send client motion to server - int bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(ServerPackets.SEND_CLIENT_MOTION_TO_SERVER.ordinal()) - .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) - .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) - .put((byte) (player.isSprinting() ? 1 : 0)) - .putFloat(player.jumpMovementFactor) - ); - } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server:", e); - } - } - }); +// public static enum ClientPackets implements Packet { +// TICK_CLIENT((pid, buf, id) -> +// TickSyncClient.onPacket()), +// CHANGE_CLIENT_TICKRATE((pid, buf, id) -> +// TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), +// ADVANCE_TICK_ON_CLIENTS((pid, buf, id) -> +// TASmodClient.tickratechanger.advanceClientTick()), +// CHANGE_TICKRATE_ON_CLIENTS((pid, buf, id) -> +// TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), // funny duplicate please fix +// SAVESTATE_INPUTS_CLIENT((pid, buf, id) -> { +// try { +// byte[] nameBytes = new byte[buf.getInt()]; +// buf.get(nameBytes); +// String name = new String(nameBytes); +// InputSavestatesHandler.savestate(name); +// } catch (Exception e) { +// TASmod.LOGGER.error("Exception occured during input savestate:", e); +// } +// }), +// CLOSE_GUISAVESTATESCREEN_ON_CLIENTS((pid, buf, id) -> { +// Minecraft mc = Minecraft.getMinecraft(); +// if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) +// mc.displayGuiScreen(new GuiSavestateSavingScreen()); +// else +// mc.displayGuiScreen(null); +// }), +// LOADSTATE_INPUTS_CLIENT((pid, buf, id) -> { +// try { +// byte[] nameBytes = new byte[buf.getInt()]; +// buf.get(nameBytes); +// String name = new String(nameBytes); +// InputSavestatesHandler.loadstate(name); +// } catch (Exception e) { +// TASmod.LOGGER.error("Exception occured during input loadstate:", e); +// } +// }), +// UNLOAD_CHUNKS_ON_CLIENTS((pid, buf, id) -> +// Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)), +// REQUEST_CLIENT_MOTION((pid, buf, id) -> { +// EntityPlayerSP player = Minecraft.getMinecraft().player; +// if (player != null) { +// if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) +// Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); +// +// try { +// // send client motion to server +// int bufIndex = SecureList.POOL.available(); +// TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(ServerPackets.SEND_CLIENT_MOTION_TO_SERVER.ordinal()) +// .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) +// .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) +// .put((byte) (player.isSprinting() ? 1 : 0)) +// .putFloat(player.jumpMovementFactor) +// ); +// } catch (Exception e) { +// TASmod.LOGGER.error("Unable to send packet to server:", e); +// } +// } +// }); +// } - private final PacketHandler handler; - - ClientPackets(PacketHandler handler) { - this.handler = handler; - } - - @Override - public PacketHandler handler() { - return this.handler; - } - } - - public static enum ServerPackets implements Packet { - NOTIFY_SERVER_OF_TICK_PASS((pid, buf, id) -> - TickSyncServer.onPacket(id)), - REQUEST_TICKRATE_CHANGE((pid, buf, id) -> - TASmod.tickratechanger.changeTickrate(buf.getFloat())), - TICKRATE_ZERO_TOGGLE((pid, buf, id) -> { - State state = TickrateChangerServer.State.fromShort(buf.getShort()); - if (state == TickrateChangerServer.State.PAUSE) - TASmod.tickratechanger.pauseGame(true); - else if (state == TickrateChangerServer.State.UNPAUSE) - TASmod.tickratechanger.pauseGame(false); - else if (state == TickrateChangerServer.State.TOGGLE) - TASmod.tickratechanger.togglePause(); - }), - REQUEST_TICK_ADVANCE((pid, buf, id) -> { - if (TASmod.tickratechanger.ticksPerSecond == 0) - TASmod.tickratechanger.advanceTick(); - }), - SEND_CLIENT_MOTION_TO_SERVER((pid, buf, id) -> - ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(id), new ClientMotionServer.Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1, buf.getFloat()))); - - - private final PacketHandler handler; - - ServerPackets(PacketHandler handler) { - this.handler = handler; - } - - @Override - public PacketHandler handler() { - return this.handler; - } - } +// public static enum ServerPackets implements Packet { +// NOTIFY_SERVER_OF_TICK_PASS((pid, buf, id) -> +// TickSyncServer.onPacket(id)), +// REQUEST_TICKRATE_CHANGE((pid, buf, id) -> +// TASmod.tickratechanger.changeTickrate(buf.getFloat())), +// TICKRATE_ZERO_TOGGLE((pid, buf, id) -> { +// State state = TickrateChangerServer.State.fromShort(buf.getShort()); +// if (state == TickrateChangerServer.State.PAUSE) +// TASmod.tickratechanger.pauseGame(true); +// else if (state == TickrateChangerServer.State.UNPAUSE) +// TASmod.tickratechanger.pauseGame(false); +// else if (state == TickrateChangerServer.State.TOGGLE) +// TASmod.tickratechanger.togglePause(); +// }), +// REQUEST_TICK_ADVANCE((pid, buf, id) -> { +// if (TASmod.tickratechanger.ticksPerSecond == 0) +// TASmod.tickratechanger.advanceTick(); +// }), +// SEND_CLIENT_MOTION_TO_SERVER((pid, buf, id) -> +// ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(id), new ClientMotionServer.Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1, buf.getFloat()))); +// +// +// private final PacketHandler handler; +// +// ServerPackets(PacketHandler handler) { +// this.handler = handler; +// } +// +// @Override +// public PacketHandler handler() { +// return this.handler; +// } +// } /** * Sends then authentication packet to the server * @param id Unique ID * @throws Exception Unable to send packet */ - public void authenticate(UUID id) throws Exception { - this.id = id; + private void authenticate(UUID id) throws Exception { + this.clientID = id; - int bufIndex = SecureList.POOL.available(); - this.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(1).putLong(id.getMostSignificantBits()).putLong(id.getLeastSignificantBits())); + this.send(new ByteBufferBuilder(-1).writeUUID(id)); + } + + private void completeAuthentication(ByteBuffer buf) throws Exception { + if(this.clientID!=null) { + throw new Exception("The client tried to authenticate while being authenticated already"); + } + + long mostSignificant = buf.getLong(); + long leastSignificant = buf.getLong(); + + this.clientID = new UUID(mostSignificant, leastSignificant); } private void handle(ByteBuffer buf) { int id = buf.getInt(); - Packet packet = this.packets.get(id); - if (packet != null) - packet.handler().handle(packet, buf, this.id); - else - LOGGER.error("Received invalid packet: {}", this.id); - } + try { + if(id==-1) { + completeAuthentication(buf); + return; + } + PacketID packet = getPacketFromID(id); + PacketHandlerRegistry.handle(side, packet, buf, this.clientID); + } catch (InvalidPacketException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + public UUID getId() { - // TODO Auto-generated method stub - return this.id; + return this.clientID; } + + private PacketID getPacketFromID(int id) throws InvalidPacketException { + for(PacketID packet : packetIDs) { + if(packet.getID() == id) { + return packet; + } + } + throw new InvalidPacketException(String.format("Received invalid packet with id {}", id)); + } } diff --git a/src/main/java/com/minecrafttas/server/Packet.java b/src/main/java/com/minecrafttas/server/Packet.java deleted file mode 100644 index adf11761..00000000 --- a/src/main/java/com/minecrafttas/server/Packet.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.minecrafttas.server; - -public interface Packet { - PacketHandler handler(); -} diff --git a/src/main/java/com/minecrafttas/server/PacketHandler.java b/src/main/java/com/minecrafttas/server/PacketHandler.java deleted file mode 100644 index 0a6c4ca5..00000000 --- a/src/main/java/com/minecrafttas/server/PacketHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.minecrafttas.server; - -import java.nio.ByteBuffer; -import java.util.UUID; - -public interface PacketHandler { - void handle(Packet pid, ByteBuffer buf, UUID id); -} diff --git a/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java new file mode 100644 index 00000000..3ffc51bb --- /dev/null +++ b/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java @@ -0,0 +1,54 @@ +package com.minecrafttas.server; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang3.ArrayUtils; + +import com.minecrafttas.server.Client.Side; +import com.minecrafttas.server.exception.HandlingPacketException; +import com.minecrafttas.server.interfaces.ClientPacketHandler; +import com.minecrafttas.server.interfaces.PacketHandlerBase; +import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.server.interfaces.ServerPacketHandler; + +public class PacketHandlerRegistry { + private static final List REGISTRY = new ArrayList<>(); + + public static void registerClass(PacketHandlerBase handler) { + if (!REGISTRY.contains(handler)) { + REGISTRY.add(handler); + } else { + System.out.println("Warning..."); + } + } + + public static void unregisterClass(PacketHandlerBase handler) { + if (REGISTRY.contains(handler)) { + REGISTRY.remove(handler); + } else { + System.out.println("Warning..."); + } + } + + public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clientID) throws HandlingPacketException { + if (side != null && side == packet.getSide()) { + packet.getLambda().onPacket(buf, clientID); + return; + } + + for (PacketHandlerBase handler : REGISTRY) { + if (ArrayUtils.contains(handler.getAcceptedPacketIDs(), packet)) { // TODO Remove the third party library + if (side == Side.CLIENT && handler instanceof ClientPacketHandler) { + ClientPacketHandler clientHandler = (ClientPacketHandler) handler; + clientHandler.onClientPacket(packet, buf, clientID); + } else if (side == Side.SERVER && handler instanceof ServerPacketHandler) { + ServerPacketHandler serverHandler = (ServerPacketHandler) handler; + serverHandler.onServerPacket(packet, buf, clientID); + } + } + } + } +} diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 16bea1e9..0855a267 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.net.InetSocketAddress; -import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; @@ -12,6 +11,8 @@ import java.util.List; import java.util.UUID; +import com.minecrafttas.server.interfaces.PacketID; + public class Server { private final AsynchronousServerSocketChannel socket; @@ -22,7 +23,7 @@ public class Server { * @param port Port * @throws Exception Unable to bind */ - public Server(int port) throws Exception { + public Server(int port, PacketID[] packetIDs) throws Exception { // create connection LOGGER.info("Creating tasmod server on {}", port); this.socket = AsynchronousServerSocketChannel.open(); @@ -34,7 +35,7 @@ public Server(int port) throws Exception { @Override public void completed(AsynchronousSocketChannel clientSocket, Object attachment) { - clients.add(new Client(clientSocket)); + clients.add(new Client(clientSocket, packetIDs)); socket.accept(null, this); } @@ -53,13 +54,16 @@ public void failed(Throwable exc, Object attachment) { * @param buf Buffer * @throws Exception Networking exception */ - public void writeAll(int id, ByteBuffer buf) throws Exception { - int limit = buf.position(); + public void sendToAll(ByteBufferBuilder builder) throws Exception { for (Client client : this.clients) { - int sid = SecureList.POOL.available(); - client.write(sid, SecureList.POOL.lock(sid).put((ByteBuffer) buf.position(0).limit(limit))); + client.send(builder.clone()); } - SecureList.POOL.unlock(id); + builder.close(); + } + + public void sendTo(UUID uuid, ByteBufferBuilder builder) throws Exception{ + Client client = getClient(uuid); + client.send(builder); } /** @@ -79,7 +83,7 @@ public void close() throws IOException { * Get client from UUID * @param uniqueID UUID */ - public Client getClient(UUID uniqueID) { + private Client getClient(UUID uniqueID) { for (Client client : this.clients) if (client.getId().equals(uniqueID)) return client; @@ -87,6 +91,10 @@ public Client getClient(UUID uniqueID) { return null; } + public List getClients(){ + return this.clients; + } + public AsynchronousServerSocketChannel getAsynchronousSocketChannel() { return this.socket; } diff --git a/src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java b/src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java new file mode 100644 index 00000000..796445ca --- /dev/null +++ b/src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java @@ -0,0 +1,9 @@ +package com.minecrafttas.server.exception; + +public class HandlingPacketException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -8089503724361521594L; +} diff --git a/src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java b/src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java new file mode 100644 index 00000000..1e68db77 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java @@ -0,0 +1,17 @@ +package com.minecrafttas.server.exception; + +public class InvalidPacketException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 5253939281926562204L; + + public InvalidPacketException() { + super(); + } + + public InvalidPacketException(String msg) { + super(msg); + } +} diff --git a/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java b/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java new file mode 100644 index 00000000..2afe16ba --- /dev/null +++ b/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java @@ -0,0 +1,9 @@ +package com.minecrafttas.server.interfaces; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public interface ClientPacketHandler extends PacketHandlerBase{ + + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID); +} diff --git a/src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java b/src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java new file mode 100644 index 00000000..6dd1d47f --- /dev/null +++ b/src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java @@ -0,0 +1,11 @@ +package com.minecrafttas.server.interfaces; + +public interface PacketHandlerBase { + /** + * Declares all packet types that get routed into the {@link ClientPacketHandler#onClientPacket(PacketID, java.nio.ByteBuffer, java.util.UUID)}
+ *
+ * or {@link ServerPacketHandler#onServerPacket(PacketID, java.nio.ByteBuffer, java.util.UUID)} methods. + */ + public PacketID[] getAcceptedPacketIDs(); + +} diff --git a/src/main/java/com/minecrafttas/server/interfaces/PacketID.java b/src/main/java/com/minecrafttas/server/interfaces/PacketID.java new file mode 100644 index 00000000..226d61f9 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/interfaces/PacketID.java @@ -0,0 +1,12 @@ +package com.minecrafttas.server.interfaces; + +import com.minecrafttas.common.events.CompactPacketHandler; +import com.minecrafttas.server.Client.Side; + +public interface PacketID { + public int getID(); + + public CompactPacketHandler getLambda(); + + public Side getSide(); +} diff --git a/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java b/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java new file mode 100644 index 00000000..1338c473 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java @@ -0,0 +1,9 @@ +package com.minecrafttas.server.interfaces; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public interface ServerPacketHandler extends PacketHandlerBase{ + + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID); +} diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index d0254657..755e9962 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -7,46 +7,30 @@ import org.apache.logging.log4j.Logger; import com.minecrafttas.common.CommandRegistry; -import com.minecrafttas.common.events.EventListener; +import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.common.events.EventServer.EventServerInit; import com.minecrafttas.common.events.EventServer.EventServerStop; +import com.minecrafttas.server.PacketHandlerRegistry; import com.minecrafttas.server.Server; -import com.minecrafttas.tasmod.commands.clearinputs.ClearInputsPacket; import com.minecrafttas.tasmod.commands.clearinputs.CommandClearInputs; import com.minecrafttas.tasmod.commands.folder.CommandFolder; -import com.minecrafttas.tasmod.commands.folder.FolderPacket; import com.minecrafttas.tasmod.commands.fullplay.CommandFullPlay; -import com.minecrafttas.tasmod.commands.fullplay.FullPlayPacket; import com.minecrafttas.tasmod.commands.fullrecord.CommandFullRecord; -import com.minecrafttas.tasmod.commands.fullrecord.FullRecordPacket; import com.minecrafttas.tasmod.commands.loadtas.CommandLoadTAS; -import com.minecrafttas.tasmod.commands.loadtas.LoadTASPacket; import com.minecrafttas.tasmod.commands.playback.CommandPlay; import com.minecrafttas.tasmod.commands.playuntil.CommandPlayUntil; -import com.minecrafttas.tasmod.commands.playuntil.PlayUntilPacket; import com.minecrafttas.tasmod.commands.recording.CommandRecord; import com.minecrafttas.tasmod.commands.restartandplay.CommandRestartAndPlay; -import com.minecrafttas.tasmod.commands.restartandplay.RestartAndPlayPacket; import com.minecrafttas.tasmod.commands.savetas.CommandSaveTAS; -import com.minecrafttas.tasmod.commands.savetas.SaveTASPacket; -import com.minecrafttas.tasmod.ktrng.KTRNGSeedPacket; -import com.minecrafttas.tasmod.ktrng.KTRNGStartSeedPacket; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; -import com.minecrafttas.tasmod.playback.PlaybackController; -import com.minecrafttas.tasmod.playback.server.InitialSyncStatePacket; -import com.minecrafttas.tasmod.playback.server.SyncStatePacket; import com.minecrafttas.tasmod.playback.server.TASstateServer; -import com.minecrafttas.tasmod.savestates.client.InputSavestatesPacket; -import com.minecrafttas.tasmod.savestates.server.LoadstatePacket; import com.minecrafttas.tasmod.savestates.server.SavestateCommand; import com.minecrafttas.tasmod.savestates.server.SavestateHandler; -import com.minecrafttas.tasmod.savestates.server.SavestatePacket; import com.minecrafttas.tasmod.savestates.server.files.SavestateTrackerFile; -import com.minecrafttas.tasmod.savestates.server.motion.MotionPacket; -import com.minecrafttas.tasmod.savestates.server.motion.RequestMotionPacket; -import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoadingPacket; import com.minecrafttas.tasmod.tickratechanger.CommandTickrate; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; +import com.minecrafttas.tasmod.ticksync.TickSyncServer; +import com.minecrafttas.tasmod.util.LoggerMarkers; import com.minecrafttas.tasmod.util.TickScheduler; import net.fabricmc.api.ModInitializer; @@ -73,6 +57,8 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static TickrateChangerServer tickratechanger; + public static TickSyncServer ticksyncServer; + public static final TickScheduler tickSchedulerServer = new TickScheduler(); public static Server server; @@ -129,50 +115,59 @@ public static MinecraftServer getServerInstance() { @Override public void onInitialize() { + + // Events LOGGER.info("Initializing TASmod"); - EventListener.register(this); + EventListenerRegistry.register(this); + + ticksyncServer = new TickSyncServer(); + EventListenerRegistry.register(ticksyncServer); + PacketHandlerRegistry.registerClass(ticksyncServer); LOGGER.info("Testing connection with KillTheRNG"); ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); - EventListener.register(ktrngHandler); + EventListenerRegistry.register(ktrngHandler); tickratechanger = new TickrateChangerServer(LOGGER); - EventListener.register(tickratechanger); - - // Savestates - PacketSerializer.registerPacket(SavestatePacket.class); - PacketSerializer.registerPacket(LoadstatePacket.class); - - PacketSerializer.registerPacket(InputSavestatesPacket.class); - PacketSerializer.registerPacket(SavestatePlayerLoadingPacket.class); - - // KillTheRNG - PacketSerializer.registerPacket(KTRNGSeedPacket.class); - PacketSerializer.registerPacket(KTRNGStartSeedPacket.class); + EventListenerRegistry.register(tickratechanger); - // Recording/Playback - PacketSerializer.registerPacket(SyncStatePacket.class); - PacketSerializer.registerPacket(InitialSyncStatePacket.class); - - PacketSerializer.registerPacket(ClearInputsPacket.class); - - PacketSerializer.registerPacket(FullRecordPacket.class); - PacketSerializer.registerPacket(FullPlayPacket.class); - - PacketSerializer.registerPacket(RestartAndPlayPacket.class); - - // Storing - PacketSerializer.registerPacket(SaveTASPacket.class); - PacketSerializer.registerPacket(LoadTASPacket.class); - - // Misc - PacketSerializer.registerPacket(PlaybackController.TeleportPlayerPacket.class); - PacketSerializer.registerPacket(FolderPacket.class); + // Networking + LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); - PacketSerializer.registerPacket(PlayUntilPacket.class); +// // Savestates +// PacketSerializer.registerPacket(SavestatePacket.class); +// PacketSerializer.registerPacket(LoadstatePacket.class); +// +// PacketSerializer.registerPacket(InputSavestatesPacket.class); +// PacketSerializer.registerPacket(SavestatePlayerLoadingPacket.class); +// +// // KillTheRNG +// PacketSerializer.registerPacket(KTRNGSeedPacket.class); +// PacketSerializer.registerPacket(KTRNGStartSeedPacket.class); +// +// // Recording/Playback +// PacketSerializer.registerPacket(SyncStatePacket.class); +// PacketSerializer.registerPacket(InitialSyncStatePacket.class); +// +// PacketSerializer.registerPacket(ClearInputsPacket.class); +// +// PacketSerializer.registerPacket(FullRecordPacket.class); +// PacketSerializer.registerPacket(FullPlayPacket.class); +// +// PacketSerializer.registerPacket(RestartAndPlayPacket.class); +// +// // Storing +// PacketSerializer.registerPacket(SaveTASPacket.class); +// PacketSerializer.registerPacket(LoadTASPacket.class); +// +// // Misc +// PacketSerializer.registerPacket(PlaybackController.TeleportPlayerPacket.class); +// PacketSerializer.registerPacket(FolderPacket.class); +// +// PacketSerializer.registerPacket(PlayUntilPacket.class); try { - server = new Server(5555); + server = new Server(5555, TASmodPackets.values()); } catch (Exception e) { LOGGER.error("Unable to launch TASmod server: {}", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index e73076e4..4e3a9016 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -1,7 +1,6 @@ package com.minecrafttas.tasmod; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -15,19 +14,20 @@ import com.minecrafttas.common.events.EventClient.EventClientInit; import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventClient.EventPlayerLeaveClientSide; -import com.minecrafttas.common.events.EventListener; +import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.server.Client; +import com.minecrafttas.server.PacketHandlerRegistry; import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; import com.minecrafttas.tasmod.handlers.LoadingScreenHandler; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.playback.PlaybackSerialiser; -import com.minecrafttas.tasmod.playback.server.InitialSyncStatePacket; import com.minecrafttas.tasmod.playback.server.TASstateClient; import com.minecrafttas.tasmod.savestates.server.LoadstatePacket; import com.minecrafttas.tasmod.savestates.server.SavestatePacket; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerClient; +import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.util.ShieldDownloader; import com.minecrafttas.tasmod.util.TickScheduler; import com.minecrafttas.tasmod.virtual.VirtualInput; @@ -46,6 +46,8 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even public static VirtualInput virtual; + public static TickSyncClient ticksyncClient; + public static PlaybackSerialiser serialiser = new PlaybackSerialiser(); public static final String tasdirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath() + File.separator + "saves" + File.separator + "tasfiles"; @@ -88,7 +90,7 @@ public static void createSavestatesDir() { @Override public void onInitializeClient() { - EventListener.register(this); + EventListenerRegistry.register(this); isDevEnvironment = FabricLoaderImpl.INSTANCE.isDevelopmentEnvironment(); Minecraft mc = Minecraft.getMinecraft(); @@ -103,18 +105,22 @@ public void onInitializeClient() { } virtual=new VirtualInput(fileOnStart); - EventListener.register(virtual); - EventListener.register(virtual.getContainer()); + EventListenerRegistry.register(virtual); + EventListenerRegistry.register(virtual.getContainer()); hud = new InfoHud(); - EventListener.register(hud); + EventListenerRegistry.register(hud); shieldDownloader = new ShieldDownloader(); - EventListener.register(shieldDownloader); + EventListenerRegistry.register(shieldDownloader); loadingScreenHandler = new LoadingScreenHandler(); - EventListener.register(loadingScreenHandler); + EventListenerRegistry.register(loadingScreenHandler); + + ticksyncClient = new TickSyncClient(); + EventListenerRegistry.register(ticksyncClient); + PacketHandlerRegistry.registerClass(ticksyncClient); keybindManager = new KeybindManager() { @@ -123,17 +129,16 @@ protected boolean isKeyDown(KeyBinding i) { }; }; - EventListener.register(keybindManager); + EventListenerRegistry.register(keybindManager); - EventListener.register(interpolation); + EventListenerRegistry.register(interpolation); try { - // connect to server and authenticate - client = new Client("127.0.0.1", 5555); UUID uuid = mc.getSession().getProfile().getId(); if (uuid == null) // dev environment uuid = UUID.randomUUID(); - client.authenticate(uuid); + // connect to server and authenticate + client = new Client("127.0.0.1", 5555, TASmodPackets.values(), uuid); } catch (Exception e) { TASmod.LOGGER.error("Unable to connect TASmod client: {}", e); } @@ -146,8 +151,8 @@ public void onClientInit(Minecraft mc) { blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Tickrate 0 Key", "TASmod", Keyboard.KEY_F8, () -> TASmodClient.tickratechanger.togglePause()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Advance Tick", "TASmod", Keyboard.KEY_F9, () -> TASmodClient.tickratechanger.advanceTick()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Recording/Playback Stop", "TASmod", Keyboard.KEY_F10, () -> TASstateClient.setOrSend(TASstate.NONE)))); - blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Create Savestate", "TASmod", Keyboard.KEY_J, () -> TASmodClient.packetClient.sendToServer(new SavestatePacket())))); - blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Load Latest Savestate", "TASmod", Keyboard.KEY_K, () -> TASmodClient.packetClient.sendToServer(new LoadstatePacket())))); + blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Create Savestate", "TASmod", Keyboard.KEY_J, () -> TASmodClient.packetClient.send(new SavestatePacket())))); + blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Load Latest Savestate", "TASmod", Keyboard.KEY_K, () -> TASmodClient.packetClient.send(new LoadstatePacket())))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Open InfoGui Editor", "TASmod", Keyboard.KEY_F6, () -> Minecraft.getMinecraft().displayGuiScreen(TASmodClient.hud)))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Buffer View", "TASmod", Keyboard.KEY_NUMPAD0, () -> InputContainerView.startBufferView()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing", "TASmod", Keyboard.KEY_F12, () -> { @@ -172,6 +177,16 @@ public void onClientInit(Minecraft mc) { @Override public void onPlayerJoinedClientSide(EntityPlayerSP player) { // FIXME: ask how this works + + /* == Scribble == + * The playback state (Playing, Recording, Paused, None) of the client may be different from the server state, + * since we allow the fact that the player can start a playback in the main menu. + * + * So when joining the world, the player sends their current state over to the server. If another player is already on the server, + * then the server sends back the current server state, so everyone has the same playback state. + * + * Will be obsolete once we have a networking system that starts in the main menu. Then we can sync the state from there + */ // TASmodClient.packetClient.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java new file mode 100644 index 00000000..69f1fb25 --- /dev/null +++ b/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java @@ -0,0 +1,62 @@ +package com.minecrafttas.tasmod; + +import com.minecrafttas.common.events.CompactPacketHandler; +import com.minecrafttas.server.Client.Side; +import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; + +import net.minecraft.client.Minecraft; + +public enum TASmodPackets implements PacketID { + /** + *

Ticksync is a system to sync the tick execution between client and server. + * Both can tick independent from each other causing issues with playback. + * + *

This is used to notify the other to start ticking and shouldn't be used otherwise. + */ + TICKSYNC, + TICKRATE_SET, + TICKRATE_ADVANCE, + SAVESTATE_LOAD, + SAVESTATE_SAVE, + /** + *

CLIENT ONLY. + *

Opens or closes the savestate screen on the client + */ + SAVESTATE_SCREEN(Side.CLIENT, (buf, clientID) -> { + Minecraft mc = Minecraft.getMinecraft(); + if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) + mc.displayGuiScreen(new GuiSavestateSavingScreen()); + else + mc.displayGuiScreen(null); + }); + + private Side side; + private CompactPacketHandler lambda; + + private TASmodPackets() { + } + + private TASmodPackets(Side side, CompactPacketHandler lambda) { + this.side = side; + this.lambda = lambda; + } + + @Override + public int getID() { + return this.ordinal(); + } + + @Override + public CompactPacketHandler getLambda() { + return this.lambda; + } + + @Override + public Side getSide() { + return this.side; + } + + + +} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java index 31979c42..0a4b9dfe 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java @@ -1,13 +1,15 @@ package com.minecrafttas.tasmod.commands.clearinputs; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; + import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.PacketBuffer; -public class ClearInputsPacket implements Packet{ +public class ClearInputsPacket implements PacketID{ @Override public void handle(PacketSide side, EntityPlayer playerz) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java index 3c9906d9..24dbdddc 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java @@ -1,9 +1,11 @@ package com.minecrafttas.tasmod.commands.folder; +import com.minecrafttas.server.interfaces.PacketID; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class FolderPacket implements Packet { +public class FolderPacket implements PacketID { int command; public FolderPacket() { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java index 6800706b..e906ee74 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.commands.fullplay; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; @@ -10,7 +11,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class FullPlayPacket implements Packet { +public class FullPlayPacket implements PacketID { @Override public void handle(PacketSide side, EntityPlayer player) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java index 3d556d65..85dc7542 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.commands.fullrecord; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; @@ -10,7 +11,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class FullRecordPacket implements Packet{ +public class FullRecordPacket implements PacketID{ @Override public void handle(PacketSide side, EntityPlayer player) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java index 4af9941e..945d0ece 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java @@ -4,8 +4,10 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; + import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -13,7 +15,7 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; -public class LoadTASPacket implements Packet{ +public class LoadTASPacket implements PacketID{ private String name; public LoadTASPacket() { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java index 48a0408a..16167558 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java @@ -1,10 +1,12 @@ package com.minecrafttas.tasmod.commands.playuntil; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmodClient; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class PlayUntilPacket implements Packet { +public class PlayUntilPacket implements PacketID { private int until; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java index 7f3811aa..2cadda76 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java @@ -3,12 +3,14 @@ import java.nio.charset.Charset; import com.minecrafttas.common.Configuration.ConfigOptions; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmodClient; + import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class RestartAndPlayPacket implements Packet{ +public class RestartAndPlayPacket implements PacketID{ private String name; public RestartAndPlayPacket() { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java index 048cbca8..b8559468 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java @@ -3,8 +3,10 @@ import java.io.IOException; import java.nio.charset.Charset; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; + import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -12,7 +14,7 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; -public class SaveTASPacket implements Packet { +public class SaveTASPacket implements PacketID { String name; public SaveTASPacket() { diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventClient.java b/src/main/java/com/minecrafttas/tasmod/events/EventClient.java index cf8ad171..096e9fbe 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventClient.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventClient.java @@ -1,7 +1,9 @@ package com.minecrafttas.tasmod.events; -import com.minecrafttas.common.events.EventListener; -import com.minecrafttas.common.events.EventListener.EventBase; +import com.minecrafttas.common.events.EventListenerRegistry; +import com.minecrafttas.common.events.EventListenerRegistry.EventBase; + +import net.minecraft.client.Minecraft; public interface EventClient { @@ -17,7 +19,7 @@ public static interface EventDrawHotbar extends EventBase{ public void onDrawHotbar(); public static void fireOnDrawHotbar() { - for (EventBase eventListener : EventListener.getEventListeners()) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { if(eventListener instanceof EventDrawHotbar) { EventDrawHotbar event = (EventDrawHotbar) eventListener; event.onDrawHotbar(); @@ -25,4 +27,26 @@ public static void fireOnDrawHotbar() { } } } + + /** + * Fired at the end of a client tick + * @author Scribble + * + */ + public static interface EventClientTickPost extends EventBase{ + + /** + * Fired at the end of a client tick + */ + public void onClientTickPost(Minecraft mc); + + public static void fireOnClientPostTick(Minecraft mc) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if(eventListener instanceof EventClientTickPost) { + EventClientTickPost event = (EventClientTickPost) eventListener; + event.onClientTickPost(mc); + } + } + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java index 80acd424..def054c2 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java @@ -2,10 +2,12 @@ import java.io.File; -import com.minecrafttas.common.events.EventListener.EventBase; +import com.minecrafttas.common.events.EventListenerRegistry.EventBase; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; +import net.minecraft.server.MinecraftServer; + public interface EventServer { /** @@ -24,7 +26,7 @@ public static interface EventSavestate extends EventBase { public void onSavestateEvent(int index, File target, File current); public static void fireSavestateEvent(int index, File target, File current) { - TASmod.logger.trace(LoggerMarkers.Event, "SavestateEvent {} {} {}", index, target, current); + TASmod.LOGGER.trace(LoggerMarkers.Event, "SavestateEvent {} {} {}", index, target, current); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventSavestate) { EventSavestate event = (EventSavestate) eventListener; @@ -50,7 +52,7 @@ public static interface EventLoadstate extends EventBase { public void onLoadstateEvent(int index, File target, File current); public static void fireLoadstateEvent(int index, File target, File current) { - TASmod.logger.trace(LoggerMarkers.Event, "LoadstateEvent {} {} {}", index, target, current); + TASmod.LOGGER.trace(LoggerMarkers.Event, "LoadstateEvent {} {} {}", index, target, current); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventLoadstate) { EventLoadstate event = (EventLoadstate) eventListener; @@ -74,7 +76,7 @@ public static interface EventCompleteLoadstate extends EventBase{ public void onLoadstateComplete(); public static void fireLoadstateComplete() { - TASmod.logger.trace(LoggerMarkers.Event, "LoadstateCompleteEvent"); + TASmod.LOGGER.trace(LoggerMarkers.Event, "LoadstateCompleteEvent"); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventCompleteLoadstate) { EventCompleteLoadstate event = (EventCompleteLoadstate) eventListener; @@ -83,5 +85,28 @@ public static void fireLoadstateComplete() { } } } + + /** + * Fired at the end of a server tick + * @author Scribble + * + */ + public static interface EventServerTickPost extends EventBase{ + + /** + * Fired at the end of a server tick + */ + public void onServerTickPost(MinecraftServer minecraftServer); + + public static void fireServerTickPost(MinecraftServer minecraftServer) { + TASmod.LOGGER.trace(LoggerMarkers.Event, "ServerTickPostEvent"); + for (EventBase eventListener : TASmodEventListener.getEventListeners()) { + if(eventListener instanceof EventServerTickPost) { + EventServerTickPost event = (EventServerTickPost) eventListener; + event.onServerTickPost(minecraftServer); + } + } + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/events/TASmodEventListener.java b/src/main/java/com/minecrafttas/tasmod/events/TASmodEventListener.java index 94a158b3..2b0e7b9f 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/TASmodEventListener.java +++ b/src/main/java/com/minecrafttas/tasmod/events/TASmodEventListener.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.events; -import com.minecrafttas.common.events.EventListener; +import com.minecrafttas.common.events.EventListenerRegistry; -public class TASmodEventListener extends EventListener{ +public class TASmodEventListener extends EventListenerRegistry{ } diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java index b943d7ed..99511e1f 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java @@ -1,10 +1,12 @@ package com.minecrafttas.tasmod.ktrng; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class KTRNGSeedPacket implements Packet { +public class KTRNGSeedPacket implements PacketID { private long seed; diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java index 329486b9..6eb737d9 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java @@ -1,11 +1,13 @@ package com.minecrafttas.tasmod.ktrng; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class KTRNGStartSeedPacket implements Packet{ +public class KTRNGStartSeedPacket implements PacketID{ private long seed; diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index 506ce0f2..247abbf4 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -100,7 +100,7 @@ public void setGlobalSeedServer(long seedIn) { public void sendGlobalSeedToServer(long seedIn) { if(isLoaded()) { if(TASmodClient.client != null) - TASmodClient.packetClient.sendToServer(new KTRNGSeedPacket(seedIn)); + TASmodClient.packetClient.send(new KTRNGSeedPacket(seedIn)); else setGlobalSeedClient(seedIn); } @@ -131,7 +131,7 @@ public void broadcastStartSeed() { public void setInitialSeed(long initialSeed) { if(TASmodClient.client != null) { TASmod.LOGGER.info("Sending initial client seed: {}", initialSeed); - TASmodClient.packetClient.sendToServer(new KTRNGStartSeedPacket(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD + TASmodClient.packetClient.send(new KTRNGStartSeedPacket(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD } else { TASmod.ktrngHandler.setGlobalSeedClient(initialSeed); } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java index 566bf0e2..67dc763b 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java @@ -14,10 +14,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.savestates.server.SavestateHandler; import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoading; -import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.util.Ducks.GuiScreenDuck; import com.minecrafttas.tasmod.util.Ducks.SubtickDuck; @@ -76,7 +76,7 @@ public void redirectRunTick(Minecraft mc) { TASmodClient.tickratechanger.advanceTick = false; TASmodClient.tickratechanger.changeClientTickrate(0F); } - TickSyncClient.clientPostTick((Minecraft)(Object)this); + EventClientTickPost.fireOnClientPostTick((Minecraft)(Object)this); } @Shadow diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java index cbba1bf2..9185dc23 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java @@ -12,8 +12,8 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; +import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; -import com.minecrafttas.tasmod.ticksync.TickSyncServer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -68,7 +68,7 @@ public void redirectThreadSleep(long msToTick) { /* The server should tick if: * (shouldTick in ticksync is true OR there are no players connected to the custom server) AND the tickrate is not zero. That or advance tick is true*/ - if( (TickSyncServer.shouldTick() && TASmod.tickratechanger.ticksPerSecond != 0) || TASmod.tickratechanger.advanceTick) { + if( (TASmod.ticksyncServer.shouldTick() && TASmod.tickratechanger.ticksPerSecond != 0) || TASmod.tickratechanger.advanceTick) { long timeBeforeTick = System.currentTimeMillis(); if (TASmod.savestateHandler.state == SavestateState.WASLOADING) { @@ -83,7 +83,7 @@ public void redirectThreadSleep(long msToTick) { TASmod.tickratechanger.changeServerTickrate(0F); TASmod.tickratechanger.advanceTick = false; } - TickSyncServer.serverPostTick(); + EventServerTickPost.fireServerTickPost((MinecraftServer)(Object)this); long tickDuration = System.currentTimeMillis() - timeBeforeTick; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 9e1a52c5..9313f05a 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -10,6 +10,7 @@ import com.dselent.bigarraylist.BigArrayList; import com.minecrafttas.common.events.EventClient.EventOpenGui; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; @@ -631,7 +632,7 @@ private void tpPlayer(String startLocation) throws NumberFormatException { float angleYaw = Float.parseFloat(section[3]); float anglePitch = Float.parseFloat(section[4]); - TASmodClient.packetClient.sendToServer(new TeleportPlayerPacket(x, y, z, angleYaw, anglePitch)); + TASmodClient.packetClient.send(new TeleportPlayerPacket(x, y, z, angleYaw, anglePitch)); } /** @@ -640,7 +641,7 @@ private void tpPlayer(String startLocation) throws NumberFormatException { * @author Scribble * */ - public static class TeleportPlayerPacket implements Packet { + public static class TeleportPlayerPacket implements PacketID { double x; double y; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java index eddf53d3..346f83f5 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.playback.server; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.PlaybackController; @@ -18,7 +19,7 @@ * @author Scribble * */ -public class SyncStatePacket implements Packet { +public class SyncStatePacket implements PacketID { private short state; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java index 0e6dc062..a0dfc6ae 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java @@ -13,7 +13,7 @@ public static void setStateClient(TASstate state) { public static void setOrSend(TASstate state) { if(Minecraft.getMinecraft().player!=null) { - TASmodClient.packetClient.sendToServer(new SyncStatePacket(state)); + TASmodClient.packetClient.send(new SyncStatePacket(state)); }else { TASmodClient.virtual.getContainer().setTASState(state); } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java index a0daf78b..0ccfc1a3 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java @@ -3,13 +3,14 @@ import java.io.IOException; import java.nio.charset.Charset; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer; -public class InputSavestatesPacket implements Packet{ +public class InputSavestatesPacket implements PacketID{ private boolean mode; private String name; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java index 2709ed24..93b0fcd5 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; @@ -12,7 +13,7 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; -public class LoadstatePacket implements Packet { +public class LoadstatePacket implements PacketID { public int index; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java index df8db31f..27751eb8 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java @@ -1,5 +1,18 @@ package com.minecrafttas.tasmod.savestates.server; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.Logger; + import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; @@ -18,7 +31,7 @@ import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoading; import com.minecrafttas.tasmod.util.LoggerMarkers; -import lombok.var; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; @@ -30,18 +43,6 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.storage.AnvilChunkLoader; -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.Logger; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * Creates and loads savestates on both client and server without closing the @@ -186,7 +187,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex // savestate inputs client var name = this.getSavestateName(indexToSave).getBytes(); var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.SAVESTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.SAVESTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -216,7 +217,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // close GuiSavestateScreen var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CLOSE_GUISAVESTATESCREEN_ON_CLIENTS.ordinal())); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CLOSE_GUISAVESTATESCREEN_ON_CLIENTS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -324,7 +325,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex // loadstate inputs client var name = this.getSavestateName(indexToLoad).getBytes(); var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.LOADSTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.LOADSTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -340,7 +341,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // unload chunks on client var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.UNLOAD_CHUNKS_ON_CLIENTS.ordinal())); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.UNLOAD_CHUNKS_ON_CLIENTS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java index fb5809be..59744918 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; @@ -12,7 +13,7 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; -public class SavestatePacket implements Packet { +public class SavestatePacket implements PacketID { public int index; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java index be24655b..07524ad6 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java @@ -1,14 +1,14 @@ package com.minecrafttas.tasmod.savestates.server.motion; +import java.util.Map; + import com.google.common.collect.Maps; import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; -import lombok.var; -import net.minecraft.entity.player.EntityPlayerMP; -import java.util.Map; +import net.minecraft.entity.player.EntityPlayerMP; public class ClientMotionServer { @@ -24,7 +24,7 @@ public static void requestMotionFromClient() { try { // request client motion var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -43,7 +43,7 @@ public static void requestMotionFromClient() { try { // request client motion var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java index 4f7f816f..8b02283b 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java @@ -1,5 +1,6 @@ package com.minecrafttas.tasmod.savestates.server.playerloading; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import net.minecraft.client.Minecraft; @@ -16,7 +17,7 @@ * @author Scribble * */ -public class SavestatePlayerLoadingPacket implements Packet { +public class SavestatePlayerLoadingPacket implements PacketID { private NBTTagCompound compound; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index 532ebb6d..70b7193d 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -7,7 +7,7 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; import com.minecrafttas.tasmod.util.LoggerMarkers; -import lombok.var; + import net.minecraft.client.Minecraft; /** @@ -97,7 +97,7 @@ public void changeServerTickrate(float tickrate) { try { // request tickrate change var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICKRATE_CHANGE.ordinal()).putFloat(tickrate)); + TASmodClient.client.sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICKRATE_CHANGE.ordinal()).putFloat(tickrate)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } @@ -111,7 +111,7 @@ public void togglePause() { try { // toggle tickrate zero var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.TICKRATE_ZERO_TOGGLE.ordinal()).putShort(State.TOGGLE.toShort())); + TASmodClient.client.sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.TICKRATE_ZERO_TOGGLE.ordinal()).putShort(State.TOGGLE.toShort())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } @@ -176,7 +176,7 @@ public void advanceServerTick() { try { // request tick advance var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICK_ADVANCE.ordinal())); + TASmodClient.client.sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICK_ADVANCE.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 43cbae55..ecc6f68f 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -1,15 +1,16 @@ package com.minecrafttas.tasmod.tickratechanger; +import org.apache.logging.log4j.Logger; + import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; import com.minecrafttas.server.Client; import com.minecrafttas.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; -import lombok.var; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; -import org.apache.logging.log4j.Logger; /** * Controls the tickrate on the server side @@ -86,8 +87,8 @@ public void changeClientTickrate(float tickrate, boolean log) { try { // send new tickrate to clients - var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(tickrate)); + int bufIndex = SecureList.POOL.available(); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(tickrate)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -175,8 +176,8 @@ public void advanceTick() { private static void advanceClientTick() { try { // advance tick on clients - var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.ADVANCE_TICK_ON_CLIENTS.ordinal())); + int bufIndex = SecureList.POOL.available(); + TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.ADVANCE_TICK_ON_CLIENTS.ordinal())); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -202,8 +203,8 @@ public void onPlayerJoinedServerSide(EntityPlayerMP player) { log("Sending the current tickrate ("+ticksPerSecond+") to " +player.getName()); try { // change tickrate on client - var bufIndex = SecureList.POOL.available(); - TASmod.server.getClient(player.getUniqueID()).write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(ticksPerSecond)); + int bufIndex = SecureList.POOL.available(); + TASmod.server.getClient(player.getUniqueID()).sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(ticksPerSecond)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to {}: {}", player.getUniqueID(), e); } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index 15fa41fc..20d55a79 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -1,13 +1,18 @@ package com.minecrafttas.tasmod.ticksync; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.SecureList; +import java.nio.ByteBuffer; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.server.interfaces.ClientPacketHandler; +import com.minecrafttas.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import lombok.var; -import net.minecraft.client.Minecraft; +import com.minecrafttas.tasmod.TASmodPackets; +import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; -import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.client.Minecraft; /** * This class manages tick sync @@ -16,10 +21,16 @@ * * @author Pancake */ -public class TickSyncClient { +public class TickSyncClient implements ClientPacketHandler, EventClientTickPost{ public static final AtomicBoolean shouldTick = new AtomicBoolean(true); + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] {TASmodPackets.TICKSYNC}; + } + + /** * Handles incoming tick packets from the server to the client * This will simply tick the client as long as the tick is correct @@ -27,28 +38,28 @@ public class TickSyncClient { * @param uuid Server UUID, null * @param tick Current tick of the server */ - public static void onPacket() { + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) { shouldTick.set(true); } + /** * Called after a client tick. This will send a packet * to the server making it tick * * @param mc Instance of Minecraft */ - public static void clientPostTick(Minecraft mc) { + @Override + public void onClientTickPost(Minecraft mc) { if (mc.player == null) { return; } try { - // notify server of tick pass - var bufIndex = SecureList.POOL.available(); - TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.NOTIFY_SERVER_OF_TICK_PASS.ordinal())); + TASmodClient.client.send(new ByteBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } } - } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index d19858fe..16d05a6a 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -1,15 +1,20 @@ package com.minecrafttas.tasmod.ticksync; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.SecureList; -import com.minecrafttas.tasmod.TASmod; -import lombok.var; - +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; +import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.server.interfaces.ServerPacketHandler; +import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodPackets; +import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; + +import net.minecraft.server.MinecraftServer; + /** * This class manages tick sync * German: https://1drv.ms/p/s!Av_ysXerhm5CphLvLvguvL5QYe1A?e=MHPldP @@ -17,10 +22,11 @@ * * @author Pancake */ -public class TickSyncServer { +public class TickSyncServer implements ServerPacketHandler, EventServerTickPost { private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); + /** * Handles incoming tick packets from the client to the server * This will put the uuid into a list of ticked clients and once every client @@ -29,7 +35,8 @@ public class TickSyncServer { * @param uuid Player UUID * @param tick Current tick of the player */ - public static void onPacket(UUID uuid) { + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID uuid) { synchronized (synchronizedList) { if(!synchronizedList.contains(uuid)) { synchronizedList.add(uuid); @@ -37,7 +44,7 @@ public static void onPacket(UUID uuid) { } } - public static boolean shouldTick() { + public boolean shouldTick() { synchronized (synchronizedList) { int acknowledged = synchronizedList.size(); int totalConnections = TASmod.server.getClients().size(); @@ -53,11 +60,23 @@ public static boolean shouldTick() { * Called after a server tick. This will send a packet * to all clients making them tick */ - public static void serverPostTick() { + public void serverPostTick() { + + } + + public static void clearList() { + synchronizedList.clear(); + } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[]{TASmodPackets.TICKSYNC}; + } + + @Override + public void onServerTickPost(MinecraftServer server) { try { - // tick clients - var bufIndex = SecureList.POOL.available(); - TASmod.server.writeAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.TICK_CLIENT.ordinal())); + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -65,7 +84,4 @@ public static void serverPostTick() { synchronizedList.clear(); } - public static void clearList() { - synchronizedList.clear(); - } } From 690b8c3cd662bdecf5cb7ba6c9736edfc2e2b33d Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 13 Aug 2023 15:38:39 +0200 Subject: [PATCH 16/60] WIP Packet rewrite --- .../common/events/CompactPacketHandler.java | 4 +- .../server/ByteBufferBuilder.java | 99 +++++++++---- .../java/com/minecrafttas/server/Client.java | 2 - .../server/PacketHandlerRegistry.java | 14 +- .../java/com/minecrafttas/server/Server.java | 7 + .../exception/HandlingPacketException.java | 9 -- .../PacketNotImplementedException.java | 22 +++ .../server/exception/WrongSideException.java | 18 +++ .../interfaces/ClientPacketHandler.java | 5 +- .../server/interfaces/PacketID.java | 2 + .../interfaces/ServerPacketHandler.java | 5 +- .../java/com/minecrafttas/tasmod/TASmod.java | 26 ++-- .../com/minecrafttas/tasmod/TASmodClient.java | 2 +- .../minecrafttas/tasmod/TASmodPackets.java | 62 +++++++- .../{clearinputs => }/CommandClearInputs.java | 10 +- .../commands/{folder => }/CommandFolder.java | 41 +++++- .../{fullplay => }/CommandFullPlay.java | 10 +- .../{fullrecord => }/CommandFullRecord.java | 2 +- .../{loadtas => }/CommandLoadTAS.java | 2 +- .../commands/{playback => }/CommandPlay.java | 2 +- .../{playuntil => }/CommandPlayUntil.java | 2 +- .../{recording => }/CommandRecord.java | 2 +- .../CommandRestartAndPlay.java | 2 +- .../{savetas => }/CommandSaveTAS.java | 2 +- .../clearinputs/ClearInputsPacket.java | 40 ----- .../tasmod/commands/folder/FolderPacket.java | 48 ------ .../tasmod/commands/folder/OpenStuff.java | 35 ----- .../commands/fullplay/FullPlayPacket.java | 37 ----- .../commands/fullrecord/FullRecordPacket.java | 40 ----- .../commands/loadtas/LoadTASPacket.java | 62 -------- .../commands/playuntil/PlayUntilPacket.java | 37 ----- .../restartandplay/RestartAndPlayPacket.java | 50 ------- .../commands/savetas/SaveTASPacket.java | 61 -------- .../networking/TASmodBufferBuilder.java | 21 +++ .../tasmod/playback/PlaybackController.java | 137 +++++++++++++----- .../playback/server/SyncStatePacket.java | 4 +- .../savestates/server/LoadstatePacket.java | 73 ---------- .../server/files/SavestateDataFile.java | 2 +- 38 files changed, 402 insertions(+), 597 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java create mode 100644 src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java create mode 100644 src/main/java/com/minecrafttas/server/exception/WrongSideException.java rename src/main/java/com/minecrafttas/tasmod/commands/{clearinputs => }/CommandClearInputs.java (71%) rename src/main/java/com/minecrafttas/tasmod/commands/{folder => }/CommandFolder.java (52%) rename src/main/java/com/minecrafttas/tasmod/commands/{fullplay => }/CommandFullPlay.java (83%) rename src/main/java/com/minecrafttas/tasmod/commands/{fullrecord => }/CommandFullRecord.java (96%) rename src/main/java/com/minecrafttas/tasmod/commands/{loadtas => }/CommandLoadTAS.java (98%) rename src/main/java/com/minecrafttas/tasmod/commands/{playback => }/CommandPlay.java (96%) rename src/main/java/com/minecrafttas/tasmod/commands/{playuntil => }/CommandPlayUntil.java (95%) rename src/main/java/com/minecrafttas/tasmod/commands/{recording => }/CommandRecord.java (96%) rename src/main/java/com/minecrafttas/tasmod/commands/{restartandplay => }/CommandRestartAndPlay.java (98%) rename src/main/java/com/minecrafttas/tasmod/commands/{savetas => }/CommandSaveTAS.java (98%) delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java create mode 100644 src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java diff --git a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java index 5d12f16e..cb5eed97 100644 --- a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java @@ -3,10 +3,10 @@ import java.nio.ByteBuffer; import java.util.UUID; -import com.minecrafttas.server.exception.HandlingPacketException; +import com.minecrafttas.server.exception.PacketNotImplementedException; @FunctionalInterface public interface CompactPacketHandler { - public void onPacket(ByteBuffer buf, UUID clientID) throws HandlingPacketException; + public void onPacket(ByteBuffer buf, UUID clientID) throws PacketNotImplementedException; } diff --git a/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java index 7e1b4105..5897f31d 100644 --- a/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java @@ -6,72 +6,91 @@ import com.minecrafttas.server.interfaces.PacketID; /** - * Helper method for creating byte buffers which get pooled from a {@link SecureList} + * Helper method for creating byte buffers which get pooled from a + * {@link SecureList} + * * @author Scribble */ -public class ByteBufferBuilder{ - +public class ByteBufferBuilder { + private int bufferIndex; private ByteBuffer buffer; - + public ByteBufferBuilder(int id) { bufferIndex = SecureList.POOL.available(); buffer = SecureList.POOL.lock(bufferIndex); buffer.putInt(id); } - + public ByteBufferBuilder(PacketID packet) { this(packet.getID()); } - + private ByteBufferBuilder(int bufferIndex, ByteBuffer buffer) { this.bufferIndex = bufferIndex; this.buffer = buffer; } - + public ByteBuffer build() { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); return this.buffer; } - + public ByteBufferBuilder writeInt(int value) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); buffer.putInt(value); return this; } - + public ByteBufferBuilder writeDouble(double value) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); buffer.putDouble(value); return this; } - + public ByteBufferBuilder writeFloat(float value) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); buffer.putFloat(value); return this; } - + public ByteBufferBuilder writeLong(long value) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); buffer.putLong(value); return this; } - + public ByteBufferBuilder writeShort(short value) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); buffer.putShort(value); return this; } - + public ByteBufferBuilder writeBoolean(boolean value) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); - buffer.put((byte)(value ?1:0)); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); + buffer.put((byte) (value ? 1 : 0)); return this; } - + + public ByteBufferBuilder writeString(String value) { + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); + byte[] stringbytes = value.getBytes(); + buffer.putInt(stringbytes.length); + buffer.put(stringbytes); + return this; + } + public ByteBufferBuilder writeUUID(UUID uuid) { - if(buffer == null) throw new IllegalStateException("This buffer is already closed"); + if (buffer == null) + throw new IllegalStateException("This buffer is already closed"); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); return this; @@ -81,16 +100,46 @@ public ByteBufferBuilder writeUUID(UUID uuid) { * Unlocks the buffer from the pool making it available for other uses */ public void close() { - if(buffer !=null) { + if (buffer != null) { SecureList.POOL.unlock(bufferIndex); this.buffer = null; } } - + @Override protected ByteBufferBuilder clone() throws CloneNotSupportedException { int limit = this.buffer.position(); int sid = SecureList.POOL.available(); return new ByteBufferBuilder(sid, SecureList.POOL.lock(sid).put((ByteBuffer) this.buffer.position(0).limit(limit))); } + + public static int readInt(ByteBuffer buf) { + return buf.getInt(); + } + + public static double readDouble(ByteBuffer buf) { + return buf.getInt(); + } + + public static float readFloat(ByteBuffer buf) { + return buf.getFloat(); + } + + public static long readLong(ByteBuffer buf) { + return buf.getLong(); + } + + public static float readShort(ByteBuffer buf) { + return buf.getShort(); + } + + public static boolean readBoolean(ByteBuffer buf) { + return buf.get() == 1 ? true : false; + } + + public static String readString(ByteBuffer buf) { + byte[] nameBytes = new byte[buf.getInt()]; + buf.get(nameBytes); + return new String(nameBytes); + } } diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/server/Client.java index 679d300d..3d215a5a 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/server/Client.java @@ -264,8 +264,6 @@ private void handle(ByteBuffer buf) { } PacketID packet = getPacketFromID(id); PacketHandlerRegistry.handle(side, packet, buf, this.clientID); - } catch (InvalidPacketException e) { - e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java index 3ffc51bb..95af7c2e 100644 --- a/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java +++ b/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java @@ -8,7 +8,7 @@ import org.apache.commons.lang3.ArrayUtils; import com.minecrafttas.server.Client.Side; -import com.minecrafttas.server.exception.HandlingPacketException; +import com.minecrafttas.server.exception.PacketNotImplementedException; import com.minecrafttas.server.interfaces.ClientPacketHandler; import com.minecrafttas.server.interfaces.PacketHandlerBase; import com.minecrafttas.server.interfaces.PacketID; @@ -17,7 +17,7 @@ public class PacketHandlerRegistry { private static final List REGISTRY = new ArrayList<>(); - public static void registerClass(PacketHandlerBase handler) { + public static void register(PacketHandlerBase handler) { if (!REGISTRY.contains(handler)) { REGISTRY.add(handler); } else { @@ -25,7 +25,7 @@ public static void registerClass(PacketHandlerBase handler) { } } - public static void unregisterClass(PacketHandlerBase handler) { + public static void unregister(PacketHandlerBase handler) { if (REGISTRY.contains(handler)) { REGISTRY.remove(handler); } else { @@ -33,22 +33,28 @@ public static void unregisterClass(PacketHandlerBase handler) { } } - public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clientID) throws HandlingPacketException { + public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clientID) throws Exception { if (side != null && side == packet.getSide()) { packet.getLambda().onPacket(buf, clientID); return; } + boolean isImplemented = false; for (PacketHandlerBase handler : REGISTRY) { if (ArrayUtils.contains(handler.getAcceptedPacketIDs(), packet)) { // TODO Remove the third party library if (side == Side.CLIENT && handler instanceof ClientPacketHandler) { ClientPacketHandler clientHandler = (ClientPacketHandler) handler; clientHandler.onClientPacket(packet, buf, clientID); + isImplemented = true; } else if (side == Side.SERVER && handler instanceof ServerPacketHandler) { ServerPacketHandler serverHandler = (ServerPacketHandler) handler; serverHandler.onServerPacket(packet, buf, clientID); + isImplemented = true; } } } + if(!isImplemented) { + throw new PacketNotImplementedException(packet); + } } } diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/server/Server.java index 0855a267..e6fe1217 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/server/Server.java @@ -13,6 +13,8 @@ import com.minecrafttas.server.interfaces.PacketID; +import net.minecraft.entity.player.EntityPlayer; + public class Server { private final AsynchronousServerSocketChannel socket; @@ -66,6 +68,11 @@ public void sendTo(UUID uuid, ByteBufferBuilder builder) throws Exception{ client.send(builder); } + public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Exception{ + Client client = getClient(player.getUniqueID()); + client.send(builder); + } + /** * Try to close socket * @throws IOException Unable to close diff --git a/src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java b/src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java deleted file mode 100644 index 796445ca..00000000 --- a/src/main/java/com/minecrafttas/server/exception/HandlingPacketException.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.minecrafttas.server.exception; - -public class HandlingPacketException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -8089503724361521594L; -} diff --git a/src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java b/src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java new file mode 100644 index 00000000..c82923fa --- /dev/null +++ b/src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java @@ -0,0 +1,22 @@ +package com.minecrafttas.server.exception; + +import com.minecrafttas.server.interfaces.PacketHandlerBase; +import com.minecrafttas.server.interfaces.PacketID; + +public class PacketNotImplementedException extends Exception { + + private static final long serialVersionUID = -8089503724361521594L; + + public PacketNotImplementedException(String msg) { + super(msg); + } + + public PacketNotImplementedException(PacketID packet, Class clazz) { + super(String.format("The packet %s is not implemented in %s", packet.getName(), clazz.getCanonicalName())); + } + + public PacketNotImplementedException(PacketID packet) { + super(String.format("The packet %s is not implemented", packet.getName())); + } + +} diff --git a/src/main/java/com/minecrafttas/server/exception/WrongSideException.java b/src/main/java/com/minecrafttas/server/exception/WrongSideException.java new file mode 100644 index 00000000..d234bc06 --- /dev/null +++ b/src/main/java/com/minecrafttas/server/exception/WrongSideException.java @@ -0,0 +1,18 @@ +package com.minecrafttas.server.exception; + +import com.minecrafttas.server.Client; +import com.minecrafttas.server.interfaces.PacketID; + +public class WrongSideException extends Exception { + + private static final long serialVersionUID = 1439028694540465537L; + + public WrongSideException(PacketID packet, Client.Side side) { + super(String.format("The packet %s is sent to the wrong side: %s", packet.getName(), side.name())); + } + + public WrongSideException(String msg) { + super(msg); + } + +} diff --git a/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java b/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java index 2afe16ba..0b3598e0 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java +++ b/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java @@ -3,7 +3,10 @@ import java.nio.ByteBuffer; import java.util.UUID; +import com.minecrafttas.server.exception.PacketNotImplementedException; +import com.minecrafttas.server.exception.WrongSideException; + public interface ClientPacketHandler extends PacketHandlerBase{ - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID); + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception; } diff --git a/src/main/java/com/minecrafttas/server/interfaces/PacketID.java b/src/main/java/com/minecrafttas/server/interfaces/PacketID.java index 226d61f9..3897f236 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/PacketID.java +++ b/src/main/java/com/minecrafttas/server/interfaces/PacketID.java @@ -9,4 +9,6 @@ public interface PacketID { public CompactPacketHandler getLambda(); public Side getSide(); + + public String getName(); } diff --git a/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java b/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java index 1338c473..7154551d 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java +++ b/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java @@ -3,7 +3,10 @@ import java.nio.ByteBuffer; import java.util.UUID; +import com.minecrafttas.server.exception.PacketNotImplementedException; +import com.minecrafttas.server.exception.WrongSideException; + public interface ServerPacketHandler extends PacketHandlerBase{ - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID); + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception; } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 755e9962..11e965b1 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -12,16 +12,16 @@ import com.minecrafttas.common.events.EventServer.EventServerStop; import com.minecrafttas.server.PacketHandlerRegistry; import com.minecrafttas.server.Server; -import com.minecrafttas.tasmod.commands.clearinputs.CommandClearInputs; -import com.minecrafttas.tasmod.commands.folder.CommandFolder; -import com.minecrafttas.tasmod.commands.fullplay.CommandFullPlay; -import com.minecrafttas.tasmod.commands.fullrecord.CommandFullRecord; -import com.minecrafttas.tasmod.commands.loadtas.CommandLoadTAS; -import com.minecrafttas.tasmod.commands.playback.CommandPlay; -import com.minecrafttas.tasmod.commands.playuntil.CommandPlayUntil; -import com.minecrafttas.tasmod.commands.recording.CommandRecord; -import com.minecrafttas.tasmod.commands.restartandplay.CommandRestartAndPlay; -import com.minecrafttas.tasmod.commands.savetas.CommandSaveTAS; +import com.minecrafttas.tasmod.commands.CommandClearInputs; +import com.minecrafttas.tasmod.commands.CommandFolder; +import com.minecrafttas.tasmod.commands.CommandFullPlay; +import com.minecrafttas.tasmod.commands.CommandFullRecord; +import com.minecrafttas.tasmod.commands.CommandLoadTAS; +import com.minecrafttas.tasmod.commands.CommandPlay; +import com.minecrafttas.tasmod.commands.CommandPlayUntil; +import com.minecrafttas.tasmod.commands.CommandRecord; +import com.minecrafttas.tasmod.commands.CommandRestartAndPlay; +import com.minecrafttas.tasmod.commands.CommandSaveTAS; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; import com.minecrafttas.tasmod.playback.server.TASstateServer; import com.minecrafttas.tasmod.savestates.server.SavestateCommand; @@ -60,7 +60,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static TickSyncServer ticksyncServer; public static final TickScheduler tickSchedulerServer = new TickScheduler(); - + public static Server server; @Override @@ -122,7 +122,9 @@ public void onInitialize() { ticksyncServer = new TickSyncServer(); EventListenerRegistry.register(ticksyncServer); - PacketHandlerRegistry.registerClass(ticksyncServer); + PacketHandlerRegistry.register(ticksyncServer); + + PacketHandlerRegistry.register(TASmodClient.virtual.getContainer()); LOGGER.info("Testing connection with KillTheRNG"); ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 4e3a9016..941e98f7 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -120,7 +120,7 @@ public void onInitializeClient() { ticksyncClient = new TickSyncClient(); EventListenerRegistry.register(ticksyncClient); - PacketHandlerRegistry.registerClass(ticksyncClient); + PacketHandlerRegistry.register(ticksyncClient); keybindManager = new KeybindManager() { diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java index 69f1fb25..44feeef6 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java @@ -3,6 +3,7 @@ import com.minecrafttas.common.events.CompactPacketHandler; import com.minecrafttas.server.Client.Side; import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.tasmod.commands.CommandFolder; import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; import net.minecraft.client.Minecraft; @@ -13,15 +14,30 @@ public enum TASmodPackets implements PacketID { * Both can tick independent from each other causing issues with playback. * *

This is used to notify the other to start ticking and shouldn't be used otherwise. + * + *

SIDE: Both
+ * ARGS: None */ TICKSYNC, + /** + *

Sets the tickrate/gamespeed + * + *

SIDE: Both
+ * ARGS: int tickrate + */ TICKRATE_SET, + /** + *

Sets the tickrate to 0, pausing the game. Also unpauses the game + * + */ + TICKRATE_ZERO, TICKRATE_ADVANCE, SAVESTATE_LOAD, SAVESTATE_SAVE, /** - *

CLIENT ONLY. *

Opens or closes the savestate screen on the client + *

SIDE: Client
+ * ARGS: none */ SAVESTATE_SCREEN(Side.CLIENT, (buf, clientID) -> { Minecraft mc = Minecraft.getMinecraft(); @@ -29,7 +45,44 @@ public enum TASmodPackets implements PacketID { mc.displayGuiScreen(new GuiSavestateSavingScreen()); else mc.displayGuiScreen(null); - }); + }), + SAVESTATE_MOTION, + CLEAR_INNPUTS, + PLAYBACK_RECORD, + PLAYBACK_PLAY, + PLAYBACK_FULLRECORD, + PLAYBACK_FULLPLAY, + PLAYBACK_RESTARTANDPLAY, + PLAYBACK_SAVE, + PLAYBACK_LOAD, + PLAYBACK_PLAYUNTIL, + STATESYNC_INITIAL, + STATESYNC, + /** + *

Opens a TASmod related folder on the file system + *

The action describes which folder to open: + *

    + *
  1. Savestate-Folder
  2. + *
  3. TASFiles-Folder
  4. + *
+ * + *

Side: CLIENT
+ * ARGS: short action + */ + OPEN_FOLDER(Side.CLIENT, (buf, clientID) -> { + short action = buf.getShort(); + switch (action) { + case 0: + CommandFolder.openSavestates(); + break; + case 1: + CommandFolder.openTASFolder(); + default: + break; + } + }), + KILLTHERNG_SEED, + KILLTHERNG_STARTSEED; private Side side; private CompactPacketHandler lambda; @@ -57,6 +110,9 @@ public Side getSide() { return this.side; } - + @Override + public String getName() { + return this.name(); + } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/CommandClearInputs.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java similarity index 71% rename from src/main/java/com/minecrafttas/tasmod/commands/clearinputs/CommandClearInputs.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java index e37f89f8..2a5e9275 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/CommandClearInputs.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java @@ -1,6 +1,8 @@ -package com.minecrafttas.tasmod.commands.clearinputs; +package com.minecrafttas.tasmod.commands; +import com.minecrafttas.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodPackets; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; @@ -23,7 +25,11 @@ public String getUsage(ICommandSender sender) { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if(sender instanceof EntityPlayer) { - TASmod.packetServer.sendToAll(new ClearInputsPacket()); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + } catch (Exception e) { + e.printStackTrace(); + } } } @Override diff --git a/src/main/java/com/minecrafttas/tasmod/commands/folder/CommandFolder.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java similarity index 52% rename from src/main/java/com/minecrafttas/tasmod/commands/folder/CommandFolder.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java index 1876c9cd..000c7a70 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/folder/CommandFolder.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java @@ -1,9 +1,15 @@ -package com.minecrafttas.tasmod.commands.folder; +package com.minecrafttas.tasmod.commands; +import java.awt.Desktop; +import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.List; +import com.minecrafttas.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.TASmodPackets; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; @@ -32,10 +38,16 @@ public int getRequiredPermissionLevel() { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 1) { + short action = 0; if (args[0].equalsIgnoreCase("savestates")) { - TASmod.packetServer.sendTo(new FolderPacket(0), (EntityPlayerMP) sender); + action = 0; } else if (args[0].equalsIgnoreCase("tasfiles")) { - TASmod.packetServer.sendTo(new FolderPacket(1), (EntityPlayerMP) sender); + action = 1; + } + try { + TASmod.server.sendTo((EntityPlayerMP) sender, new ByteBufferBuilder(TASmodPackets.OPEN_FOLDER).writeShort(action)); + } catch (Exception e) { + e.printStackTrace(); } } } @@ -51,4 +63,27 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen return tab; } + public static void openTASFolder() { + File file = new File(TASmodClient.tasdirectory); + try { + if (!file.exists()) + file.mkdir(); + Desktop.getDesktop().open(file); + } catch (IOException e) { + TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); + e.printStackTrace(); + } + } + + public static void openSavestates() { + File file = new File(TASmodClient.savestatedirectory); + try { + if (!file.exists()) + file.mkdir(); + Desktop.getDesktop().open(file); + } catch (IOException e) { + TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); + e.printStackTrace(); + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java similarity index 83% rename from src/main/java/com/minecrafttas/tasmod/commands/fullplay/CommandFullPlay.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index cfd0521a..b6d727ca 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -1,6 +1,8 @@ -package com.minecrafttas.tasmod.commands.fullplay; +package com.minecrafttas.tasmod.commands; +import com.minecrafttas.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; @@ -39,7 +41,11 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args TASmod.savestateHandler.state=SavestateState.NONE; } TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); - TASmod.packetServer.sendToAll(new FullPlayPacket()); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_FULLPLAY)); + } catch (Exception e) { + e.printStackTrace(); + } } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/commands/fullrecord/CommandFullRecord.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index b2b438be..06ae04f8 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.fullrecord; +package com.minecrafttas.tasmod.commands; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/CommandLoadTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java similarity index 98% rename from src/main/java/com/minecrafttas/tasmod/commands/loadtas/CommandLoadTAS.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java index e2f18298..9f1ff8df 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/CommandLoadTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.loadtas; +package com.minecrafttas.tasmod.commands; import java.io.File; import java.io.FileFilter; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/playback/CommandPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/commands/playback/CommandPlay.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java index 096ffff6..ea4e4dab 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/playback/CommandPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.playback; +package com.minecrafttas.tasmod.commands; import java.util.List; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/CommandPlayUntil.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java similarity index 95% rename from src/main/java/com/minecrafttas/tasmod/commands/playuntil/CommandPlayUntil.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java index 9140f222..70464e79 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/CommandPlayUntil.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.playuntil; +package com.minecrafttas.tasmod.commands; import com.minecrafttas.tasmod.TASmod; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/recording/CommandRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/commands/recording/CommandRecord.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java index 85411b30..63495bb3 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/recording/CommandRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.recording; +package com.minecrafttas.tasmod.commands; import java.util.List; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java similarity index 98% rename from src/main/java/com/minecrafttas/tasmod/commands/restartandplay/CommandRestartAndPlay.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index dcec9534..3b81ae0f 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.restartandplay; +package com.minecrafttas.tasmod.commands; import java.io.File; import java.io.FileFilter; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/savetas/CommandSaveTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java similarity index 98% rename from src/main/java/com/minecrafttas/tasmod/commands/savetas/CommandSaveTAS.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java index 58922bd5..6f6632c0 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/savetas/CommandSaveTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.commands.savetas; +package com.minecrafttas.tasmod.commands; import java.io.File; import java.io.FileFilter; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java deleted file mode 100644 index 0a4b9dfe..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/clearinputs/ClearInputsPacket.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.minecrafttas.tasmod.commands.clearinputs; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; - -public class ClearInputsPacket implements PacketID{ - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if(side.isServer()) { - EntityPlayerMP player = (EntityPlayerMP)playerz; - player.getServerWorld().addScheduledTask(()->{ - if(player.canUseCommand(2, "clearinputs")) { - TASmod.packetServer.sendToAll(this); - } - }); - } else { - Minecraft.getMinecraft().addScheduledTask(()->{ - TASmodClient.virtual.getContainer().clear(); - }); - } - - } - - @Override - public void serialize(PacketBuffer buf) { - - } - - @Override - public void deserialize(PacketBuffer buf) { - - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java deleted file mode 100644 index 24dbdddc..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/folder/FolderPacket.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.minecrafttas.tasmod.commands.folder; - -import com.minecrafttas.server.interfaces.PacketID; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class FolderPacket implements PacketID { - int command; - - public FolderPacket() { - } - - /** - * 0: Open savestates folder - * 1: Open TASdir folder - * @param command The folder to open - */ - public FolderPacket(int command) { - this.command=command; - } - - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - switch(command) { - case 0: - OpenStuff.openSavestates(); - break; - case 1: - OpenStuff.openTASFolder(); - break; - } - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(command); - } - - @Override - public void deserialize(PacketBuffer buf) { - command=buf.readInt(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java b/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java deleted file mode 100644 index 16b6e8c8..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/folder/OpenStuff.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.minecrafttas.tasmod.commands.folder; - -import java.awt.Desktop; -import java.io.File; -import java.io.IOException; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; - -public class OpenStuff { - - public static void openTASFolder() { - File file = new File(TASmodClient.tasdirectory); - try { - if (!file.exists()) - file.mkdir(); - Desktop.getDesktop().open(file); - } catch (IOException e) { - TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); - e.printStackTrace(); - } - } - - public static void openSavestates() { - File file = new File(TASmodClient.savestatedirectory); - try { - if (!file.exists()) - file.mkdir(); - Desktop.getDesktop().open(file); - } catch (IOException e) { - TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java deleted file mode 100644 index e906ee74..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullplay/FullPlayPacket.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.minecrafttas.tasmod.commands.fullplay; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.events.OpenGuiEvents; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class FullPlayPacket implements PacketID { - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; - Minecraft mc = Minecraft.getMinecraft(); - TASmodClient.tickSchedulerClient.add(()->{ - mc.world.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient) null); - mc.displayGuiScreen(new GuiMainMenu()); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - } - - @Override - public void deserialize(PacketBuffer buf) { - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java deleted file mode 100644 index 85dc7542..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/fullrecord/FullRecordPacket.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.minecrafttas.tasmod.commands.fullrecord; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.events.OpenGuiEvents; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class FullRecordPacket implements PacketID{ - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - OpenGuiEvents.stateWhenOpened = TASstate.RECORDING; - TASmodClient.virtual.getContainer().clear(); - Minecraft mc = Minecraft.getMinecraft(); - TASmodClient.tickSchedulerClient.add(()->{ - mc.world.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient) null); - mc.displayGuiScreen(new GuiMainMenu()); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - - } - - @Override - public void deserialize(PacketBuffer buf) { - - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java deleted file mode 100644 index 945d0ece..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/loadtas/LoadTASPacket.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.minecrafttas.tasmod.commands.loadtas; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextFormatting; - -public class LoadTASPacket implements PacketID{ - private String name; - - public LoadTASPacket() { - } - - public LoadTASPacket(String name) { - this.name=name; - } - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if (side.isServer()) { - EntityPlayerMP player = (EntityPlayerMP) playerz; - player.getServerWorld().addScheduledTask(() -> { - if (player.canUseCommand(2, "loadtas")) { - TASmod.packetServer.sendToAll(this); - } - }); - } else { - Minecraft mc = Minecraft.getMinecraft(); - mc.addScheduledTask(() -> { - try { - TASmodClient.virtual.loadInputs(name); - } catch (IOException e) { - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); - return; - } - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Loaded inputs from " + name + ".mctas")); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(name.getBytes().length); - buf.writeCharSequence(name, Charset.defaultCharset()); - } - - @Override - public void deserialize(PacketBuffer buf) { - int length = buf.readInt(); - name = (String) buf.readCharSequence(length, StandardCharsets.UTF_8); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java deleted file mode 100644 index 16167558..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/playuntil/PlayUntilPacket.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.minecrafttas.tasmod.commands.playuntil; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmodClient; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class PlayUntilPacket implements PacketID { - - private int until; - - public PlayUntilPacket() { - } - - public PlayUntilPacket(int until) { - this.until = until; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - TASmodClient.virtual.getContainer().setPlayUntil(until); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(until); - } - - @Override - public void deserialize(PacketBuffer buf) { - until = buf.readInt(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java deleted file mode 100644 index 2cadda76..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/restartandplay/RestartAndPlayPacket.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.minecrafttas.tasmod.commands.restartandplay; - -import java.nio.charset.Charset; - -import com.minecrafttas.common.Configuration.ConfigOptions; -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmodClient; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class RestartAndPlayPacket implements PacketID{ - private String name; - - public RestartAndPlayPacket() { - } - - public RestartAndPlayPacket(String name) { - this.name=name; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - try { - Thread.sleep(100L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Minecraft.getMinecraft().addScheduledTask(() -> { - TASmodClient.config.set(ConfigOptions.FileToOpen, name); - System.exit(0); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(name.getBytes().length); - buf.writeCharSequence(name, Charset.defaultCharset()); - - } - - @Override - public void deserialize(PacketBuffer buf) { - int length = buf.readInt(); - name = (String) buf.readCharSequence(length, Charset.defaultCharset()); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java b/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java deleted file mode 100644 index b8559468..00000000 --- a/src/main/java/com/minecrafttas/tasmod/commands/savetas/SaveTASPacket.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.minecrafttas.tasmod.commands.savetas; - -import java.io.IOException; -import java.nio.charset.Charset; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextFormatting; - -public class SaveTASPacket implements PacketID { - String name; - - public SaveTASPacket() { - } - - public SaveTASPacket(String recordingName) { - name = recordingName; - } - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if (side.isClient()) { - Minecraft mc = Minecraft.getMinecraft(); - mc.addScheduledTask(() -> { - try { - TASmodClient.virtual.saveInputs(name); - } catch (IOException e) { - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); - return; - } - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Saved inputs to " + name + ".mctas")); - }); - } else { - EntityPlayerMP player = (EntityPlayerMP) playerz; - player.getServerWorld().addScheduledTask(() -> { - if (player.canUseCommand(2, "savetas")) { - TASmod.packetServer.sendToAll(this); - } - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(name.getBytes().length); - buf.writeCharSequence(name, Charset.defaultCharset()); - } - - @Override - public void deserialize(PacketBuffer buf) { - int length = buf.readInt(); - name = (String) buf.readCharSequence(length, Charset.defaultCharset()); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java new file mode 100644 index 00000000..0bcb56f0 --- /dev/null +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -0,0 +1,21 @@ +package com.minecrafttas.tasmod.networking; + +import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; + +public class TASmodBufferBuilder extends ByteBufferBuilder{ + + public TASmodBufferBuilder(int id) { + super(id); + } + + public TASmodBufferBuilder(PacketID packet) { + super(packet); + } + + public TASmodBufferBuilder writeTASState(TASstate state) { + this.writeShort((short)state.ordinal()); + return this; + } +} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 9313f05a..7a8aa999 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -1,18 +1,28 @@ package com.minecrafttas.tasmod.playback; import java.io.File; +import java.io.IOException; import java.io.Serializable; +import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import org.lwjgl.opengl.Display; import com.dselent.bigarraylist.BigArrayList; import com.minecrafttas.common.events.EventClient.EventOpenGui; +import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.server.exception.PacketNotImplementedException; +import com.minecrafttas.server.exception.WrongSideException; +import com.minecrafttas.server.interfaces.ClientPacketHandler; import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.TASmodPackets; +import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import com.minecrafttas.tasmod.playback.server.TASstateClient; @@ -28,6 +38,7 @@ import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.PacketBuffer; @@ -52,7 +63,7 @@ * @author Scribble * */ -public class PlaybackController implements EventOpenGui{ +public class PlaybackController implements EventOpenGui, ServerPacketHandler, ClientPacketHandler{ /** * The current state of the controller. @@ -806,51 +817,21 @@ public TickInputContainer clone() { */ public static enum TASstate { /** - * The game records inputs to the {@link InputContainer}. + * The game is neither recording, playing back or paused, is also set when aborting all mentioned states. */ - RECORDING, + NONE, /** * The game plays back the inputs loaded in {@link InputContainer} and locks user interaction. */ PLAYBACK, /** - * The playback or recording is paused and may be resumed. Note that the game isn't paused, only the playback. Useful for debugging things. + * The game records inputs to the {@link InputContainer}. */ - PAUSED, // #124 + RECORDING, /** - * The game is neither recording, playing back or paused, is also set when aborting all mentioned states. + * The playback or recording is paused and may be resumed. Note that the game isn't paused, only the playback. Useful for debugging things. */ - NONE; - - public int getIndex() { - switch(this) { - case NONE: - return 0; - case PLAYBACK: - return 1; - case RECORDING: - return 2; - case PAUSED: - return 3; - default: - return 0; - } - } - - public static TASstate fromIndex(int state) { - switch (state) { - case 0: - return NONE; - case 1: - return PLAYBACK; - case 2: - return RECORDING; - case 3: - return PAUSED; - default: - return NONE; - } - } + PAUSED; // #124 } private TASstate stateWhenOpened; @@ -875,4 +856,86 @@ public GuiScreen onOpenGui(GuiScreen gui) { } return gui; } + + // ====================================== Networking + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] { + TASmodPackets.PLAYBACK_PLAY, + TASmodPackets.PLAYBACK_RECORD, + TASmodPackets.PLAYBACK_SAVE, + TASmodPackets.PLAYBACK_LOAD, + TASmodPackets.PLAYBACK_FULLPLAY, + TASmodPackets.PLAYBACK_FULLRECORD, + TASmodPackets.PLAYBACK_RESTARTANDPLAY, + TASmodPackets.PLAYBACK_PLAYUNTIL + + }; + } + + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + + Minecraft mc = Minecraft.getMinecraft(); + + switch (packet) { + + case PLAYBACK_PLAY: + break; + + case PLAYBACK_RECORD: + break; + + case PLAYBACK_SAVE: + break; + + case PLAYBACK_LOAD: + mc.addScheduledTask(() -> { + String name = ByteBufferBuilder.readString(buf); + try { + TASmodClient.virtual.loadInputs(name); + } catch (IOException e) { + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); + return; + } + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Loaded inputs from " + name + ".mctas")); + }); + break; + + case PLAYBACK_FULLPLAY: + OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; + TASmodClient.tickSchedulerClient.add(() -> { + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + mc.displayGuiScreen(new GuiMainMenu()); + }); + break; + + case PLAYBACK_FULLRECORD: + OpenGuiEvents.stateWhenOpened = TASstate.RECORDING; + TASmodClient.virtual.getContainer().clear(); + TASmodClient.tickSchedulerClient.add(() -> { + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + mc.displayGuiScreen(new GuiMainMenu()); + }); + break; + + case PLAYBACK_RESTARTANDPLAY: + break; + + case PLAYBACK_PLAYUNTIL: + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + + } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java index 346f83f5..117ea5e9 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java @@ -31,12 +31,12 @@ public SyncStatePacket() { public SyncStatePacket(TASstate state) { verbose = true; - this.state = (short) state.getIndex(); + this.state = (short) state.ordinal(); } public SyncStatePacket(TASstate state, boolean verbose) { this.verbose = verbose; - this.state = (short) state.getIndex(); + this.state = (short) state.ordinal(); } @Override diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java deleted file mode 100644 index 93b0fcd5..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/LoadstatePacket.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server; - -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; -import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; -import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextFormatting; - -public class LoadstatePacket implements PacketID { - - public int index; - - /** - * Load a savestate at the current index - */ - public LoadstatePacket() { - index = -1; - } - - /** - * Load the savestate at the specified index - * - * @param index The index to load the savestate - */ - public LoadstatePacket(int index) { - this.index = index; - } - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if (side.isServer()) { - EntityPlayerMP player = (EntityPlayerMP) playerz; - player.getServerWorld().addScheduledTask(()->{ - if (!player.canUseCommand(2, "tickrate")) { - player.sendMessage(new TextComponentString(TextFormatting.RED + "You don't have permission to do that")); - return; - } - try { - TASmod.savestateHandler.loadState(index, true); - } catch (LoadstateException e) { - player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getMessage())); - } catch (Exception e) { - player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getCause().toString())); - e.printStackTrace(); - } finally { - TASmod.savestateHandler.state = SavestateState.NONE; - } - }); - } else { - Minecraft.getMinecraft().addScheduledTask(()->{ - SavestatesChunkControl.unloadAllClientChunks(); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(index); - } - - @Override - public void deserialize(PacketBuffer buf) { - index = buf.readInt(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java index 90dad8bb..f5689bbe 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java @@ -14,7 +14,7 @@ public class SavestateDataFile { public enum DataValues { INDEX("currentIndex"), - Name("savestateName"), + NAME("savestateName"), SEED("ktrngSeed"); From 71a015e0f00d18ada708309f478327faa604d1a2 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 13 Aug 2023 22:34:27 +0200 Subject: [PATCH 17/60] Added tests for bufferbuilder and server - Started converting packets --- .../common/events/CompactPacketHandler.java | 2 +- .../server/ByteBufferBuilder.java | 26 +- .../{ => common}/server/Client.java | 22 +- .../server/PacketHandlerRegistry.java | 17 +- .../{ => common}/server/SecureList.java | 2 +- .../{ => common}/server/Server.java | 14 +- .../exception/InvalidPacketException.java | 2 +- .../PacketNotImplementedException.java | 6 +- .../server/exception/WrongSideException.java | 6 +- .../interfaces/ClientPacketHandler.java | 6 +- .../server/interfaces/PacketHandlerBase.java | 2 +- .../server/interfaces/PacketID.java | 4 +- .../interfaces/ServerPacketHandler.java | 6 +- .../java/com/minecrafttas/tasmod/TASmod.java | 4 +- .../com/minecrafttas/tasmod/TASmodClient.java | 4 +- .../minecrafttas/tasmod/TASmodPackets.java | 4 +- .../tasmod/commands/CommandClearInputs.java | 2 +- .../tasmod/commands/CommandFolder.java | 2 +- .../tasmod/commands/CommandFullPlay.java | 2 +- .../tasmod/ktrng/KTRNGSeedPacket.java | 2 +- .../tasmod/ktrng/KTRNGStartSeedPacket.java | 2 +- .../networking/TASmodBufferBuilder.java | 4 +- .../tasmod/playback/PlaybackController.java | 12 +- .../playback/server/SyncStatePacket.java | 2 +- .../client/InputSavestatesPacket.java | 2 +- .../savestates/server/SavestateHandler.java | 4 +- .../savestates/server/SavestatePacket.java | 2 +- .../server/motion/ClientMotionServer.java | 4 +- .../SavestatePlayerLoadingPacket.java | 2 +- .../TickrateChangerClient.java | 4 +- .../TickrateChangerServer.java | 4 +- .../tasmod/ticksync/TickSyncClient.java | 6 +- .../tasmod/ticksync/TickSyncServer.java | 6 +- src/main/resources/log4j.xml | 3 + .../common/server/ByteBufferBuilderTest.java | 261 ++++++++++++++++++ src/test/java/common/server/ServerTest.java | 175 ++++++++++++ 36 files changed, 544 insertions(+), 84 deletions(-) rename src/main/java/com/minecrafttas/{ => common}/server/ByteBufferBuilder.java (83%) rename src/main/java/com/minecrafttas/{ => common}/server/Client.java (91%) rename src/main/java/com/minecrafttas/{ => common}/server/PacketHandlerRegistry.java (72%) rename src/main/java/com/minecrafttas/{ => common}/server/SecureList.java (97%) rename src/main/java/com/minecrafttas/{ => common}/server/Server.java (87%) rename src/main/java/com/minecrafttas/{ => common}/server/exception/InvalidPacketException.java (83%) rename src/main/java/com/minecrafttas/{ => common}/server/exception/PacketNotImplementedException.java (76%) rename src/main/java/com/minecrafttas/{ => common}/server/exception/WrongSideException.java (69%) rename src/main/java/com/minecrafttas/{ => common}/server/interfaces/ClientPacketHandler.java (57%) rename src/main/java/com/minecrafttas/{ => common}/server/interfaces/PacketHandlerBase.java (87%) rename src/main/java/com/minecrafttas/{ => common}/server/interfaces/PacketID.java (67%) rename src/main/java/com/minecrafttas/{ => common}/server/interfaces/ServerPacketHandler.java (57%) create mode 100644 src/test/java/common/server/ByteBufferBuilderTest.java create mode 100644 src/test/java/common/server/ServerTest.java diff --git a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java index cb5eed97..2cf6b7e3 100644 --- a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java @@ -3,7 +3,7 @@ import java.nio.ByteBuffer; import java.util.UUID; -import com.minecrafttas.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; @FunctionalInterface public interface CompactPacketHandler { diff --git a/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java similarity index 83% rename from src/main/java/com/minecrafttas/server/ByteBufferBuilder.java rename to src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 5897f31d..21684ee2 100644 --- a/src/main/java/com/minecrafttas/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -1,9 +1,9 @@ -package com.minecrafttas.server; +package com.minecrafttas.common.server; import java.nio.ByteBuffer; import java.util.UUID; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; /** * Helper method for creating byte buffers which get pooled from a @@ -107,10 +107,18 @@ public void close() { } @Override - protected ByteBufferBuilder clone() throws CloneNotSupportedException { - int limit = this.buffer.position(); + public ByteBufferBuilder clone() throws CloneNotSupportedException { + int current = this.buffer.position(); int sid = SecureList.POOL.available(); - return new ByteBufferBuilder(sid, SecureList.POOL.lock(sid).put((ByteBuffer) this.buffer.position(0).limit(limit))); + ByteBuffer clone = SecureList.POOL.lock(sid); + + this.buffer.position(0); //Reset buffer pos + + clone.put(this.buffer).limit(current).position(0); + + this.buffer.position(current); + + return new ByteBufferBuilder(sid, clone); } public static int readInt(ByteBuffer buf) { @@ -118,7 +126,7 @@ public static int readInt(ByteBuffer buf) { } public static double readDouble(ByteBuffer buf) { - return buf.getInt(); + return buf.getDouble(); } public static float readFloat(ByteBuffer buf) { @@ -129,13 +137,17 @@ public static long readLong(ByteBuffer buf) { return buf.getLong(); } - public static float readShort(ByteBuffer buf) { + public static short readShort(ByteBuffer buf) { return buf.getShort(); } public static boolean readBoolean(ByteBuffer buf) { return buf.get() == 1 ? true : false; } + + public static UUID readUUID(ByteBuffer buf) { + return new UUID(buf.getLong(), buf.getLong()); + } public static String readString(ByteBuffer buf) { byte[] nameBytes = new byte[buf.getInt()]; diff --git a/src/main/java/com/minecrafttas/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java similarity index 91% rename from src/main/java/com/minecrafttas/server/Client.java rename to src/main/java/com/minecrafttas/common/server/Client.java index 3d215a5a..da5514b7 100644 --- a/src/main/java/com/minecrafttas/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -1,6 +1,6 @@ -package com.minecrafttas.server; +package com.minecrafttas.common.server; -import static com.minecrafttas.server.SecureList.BUFFER_SIZE; +import static com.minecrafttas.common.server.SecureList.BUFFER_SIZE; import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.io.IOException; @@ -11,8 +11,12 @@ import java.util.UUID; import java.util.concurrent.Future; -import com.minecrafttas.server.exception.InvalidPacketException; -import com.minecrafttas.server.interfaces.PacketID; +import org.apache.logging.log4j.Level; + +import com.minecrafttas.common.server.exception.InvalidPacketException; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.PacketID; public class Client { @@ -47,7 +51,7 @@ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exc this.packetIDs = packetIDs; this.createHandlers(); - LOGGER.info("Connected to tasmod server"); + Server.LOGGER.info("Connected to tasmod server"); authenticate(uuid); } @@ -88,13 +92,13 @@ public void completed(Integer result, Object attachment) { readBuffer.clear().limit(4); socket.read(readBuffer, null, this); } catch (Throwable exc) { - LOGGER.error("Unable to read packet!", exc); + Server.LOGGER.error("Unable to read packet!", exc); } } @Override public void failed(Throwable exc, Object attachment) { - LOGGER.error("Unable to read packet!", exc); + Server.LOGGER.error("Unable to read packet!", exc); } }); @@ -264,8 +268,10 @@ private void handle(ByteBuffer buf) { } PacketID packet = getPacketFromID(id); PacketHandlerRegistry.handle(side, packet, buf, this.clientID); + } catch (PacketNotImplementedException | WrongSideException e) { + Server.LOGGER.throwing(Level.ERROR, e); } catch (Exception e) { - e.printStackTrace(); + Server.LOGGER.throwing(Level.ERROR, e); } } diff --git a/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java similarity index 72% rename from src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java rename to src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java index 95af7c2e..63df8c43 100644 --- a/src/main/java/com/minecrafttas/server/PacketHandlerRegistry.java +++ b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java @@ -1,4 +1,4 @@ -package com.minecrafttas.server; +package com.minecrafttas.common.server; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -7,12 +7,13 @@ import org.apache.commons.lang3.ArrayUtils; -import com.minecrafttas.server.Client.Side; -import com.minecrafttas.server.exception.PacketNotImplementedException; -import com.minecrafttas.server.interfaces.ClientPacketHandler; -import com.minecrafttas.server.interfaces.PacketHandlerBase; -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.server.interfaces.ServerPacketHandler; +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketHandlerBase; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; public class PacketHandlerRegistry { private static final List REGISTRY = new ArrayList<>(); @@ -33,7 +34,7 @@ public static void unregister(PacketHandlerBase handler) { } } - public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clientID) throws Exception { + public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { if (side != null && side == packet.getSide()) { packet.getLambda().onPacket(buf, clientID); return; diff --git a/src/main/java/com/minecrafttas/server/SecureList.java b/src/main/java/com/minecrafttas/common/server/SecureList.java similarity index 97% rename from src/main/java/com/minecrafttas/server/SecureList.java rename to src/main/java/com/minecrafttas/common/server/SecureList.java index e60ff057..cb1ea11e 100644 --- a/src/main/java/com/minecrafttas/server/SecureList.java +++ b/src/main/java/com/minecrafttas/common/server/SecureList.java @@ -1,4 +1,4 @@ -package com.minecrafttas.server; +package com.minecrafttas.common.server; import java.nio.ByteBuffer; diff --git a/src/main/java/com/minecrafttas/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java similarity index 87% rename from src/main/java/com/minecrafttas/server/Server.java rename to src/main/java/com/minecrafttas/common/server/Server.java index e6fe1217..e6a42bfd 100644 --- a/src/main/java/com/minecrafttas/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -1,6 +1,4 @@ -package com.minecrafttas.server; - -import static com.minecrafttas.tasmod.TASmod.LOGGER; +package com.minecrafttas.common.server; import java.io.IOException; import java.net.InetSocketAddress; @@ -11,13 +9,17 @@ import java.util.List; import java.util.UUID; -import com.minecrafttas.server.interfaces.PacketID; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.minecrafttas.common.server.interfaces.PacketID; import net.minecraft.entity.player.EntityPlayer; public class Server { private final AsynchronousServerSocketChannel socket; + public static final Logger LOGGER = LogManager.getLogger("PacketServer"); private final List clients; /** @@ -27,7 +29,7 @@ public class Server { */ public Server(int port, PacketID[] packetIDs) throws Exception { // create connection - LOGGER.info("Creating tasmod server on {}", port); + LOGGER.info("Creating server on port {}", port); this.socket = AsynchronousServerSocketChannel.open(); this.socket.bind(new InetSocketAddress(port)); @@ -47,7 +49,7 @@ public void failed(Throwable exc, Object attachment) { } }); - LOGGER.info("TASmod server created"); + LOGGER.info("Server created"); } /** diff --git a/src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java b/src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java similarity index 83% rename from src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java rename to src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java index 1e68db77..6176afa5 100644 --- a/src/main/java/com/minecrafttas/server/exception/InvalidPacketException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java @@ -1,4 +1,4 @@ -package com.minecrafttas.server.exception; +package com.minecrafttas.common.server.exception; public class InvalidPacketException extends Exception { diff --git a/src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java similarity index 76% rename from src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java rename to src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java index c82923fa..8d033acc 100644 --- a/src/main/java/com/minecrafttas/server/exception/PacketNotImplementedException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java @@ -1,7 +1,7 @@ -package com.minecrafttas.server.exception; +package com.minecrafttas.common.server.exception; -import com.minecrafttas.server.interfaces.PacketHandlerBase; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketHandlerBase; +import com.minecrafttas.common.server.interfaces.PacketID; public class PacketNotImplementedException extends Exception { diff --git a/src/main/java/com/minecrafttas/server/exception/WrongSideException.java b/src/main/java/com/minecrafttas/common/server/exception/WrongSideException.java similarity index 69% rename from src/main/java/com/minecrafttas/server/exception/WrongSideException.java rename to src/main/java/com/minecrafttas/common/server/exception/WrongSideException.java index d234bc06..f18d7725 100644 --- a/src/main/java/com/minecrafttas/server/exception/WrongSideException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/WrongSideException.java @@ -1,7 +1,7 @@ -package com.minecrafttas.server.exception; +package com.minecrafttas.common.server.exception; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.interfaces.PacketID; public class WrongSideException extends Exception { diff --git a/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java b/src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java similarity index 57% rename from src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java rename to src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java index 0b3598e0..9687ce5e 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/ClientPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java @@ -1,10 +1,10 @@ -package com.minecrafttas.server.interfaces; +package com.minecrafttas.common.server.interfaces; import java.nio.ByteBuffer; import java.util.UUID; -import com.minecrafttas.server.exception.PacketNotImplementedException; -import com.minecrafttas.server.exception.WrongSideException; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; public interface ClientPacketHandler extends PacketHandlerBase{ diff --git a/src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java b/src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java similarity index 87% rename from src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java rename to src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java index 6dd1d47f..a8663271 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/PacketHandlerBase.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java @@ -1,4 +1,4 @@ -package com.minecrafttas.server.interfaces; +package com.minecrafttas.common.server.interfaces; public interface PacketHandlerBase { /** diff --git a/src/main/java/com/minecrafttas/server/interfaces/PacketID.java b/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java similarity index 67% rename from src/main/java/com/minecrafttas/server/interfaces/PacketID.java rename to src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java index 3897f236..62070642 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/PacketID.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java @@ -1,7 +1,7 @@ -package com.minecrafttas.server.interfaces; +package com.minecrafttas.common.server.interfaces; import com.minecrafttas.common.events.CompactPacketHandler; -import com.minecrafttas.server.Client.Side; +import com.minecrafttas.common.server.Client.Side; public interface PacketID { public int getID(); diff --git a/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java b/src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java similarity index 57% rename from src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java rename to src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java index 7154551d..8037e1bf 100644 --- a/src/main/java/com/minecrafttas/server/interfaces/ServerPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java @@ -1,10 +1,10 @@ -package com.minecrafttas.server.interfaces; +package com.minecrafttas.common.server.interfaces; import java.nio.ByteBuffer; import java.util.UUID; -import com.minecrafttas.server.exception.PacketNotImplementedException; -import com.minecrafttas.server.exception.WrongSideException; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; public interface ServerPacketHandler extends PacketHandlerBase{ diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 11e965b1..0ed16120 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -10,8 +10,8 @@ import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.common.events.EventServer.EventServerInit; import com.minecrafttas.common.events.EventServer.EventServerStop; -import com.minecrafttas.server.PacketHandlerRegistry; -import com.minecrafttas.server.Server; +import com.minecrafttas.common.server.PacketHandlerRegistry; +import com.minecrafttas.common.server.Server; import com.minecrafttas.tasmod.commands.CommandClearInputs; import com.minecrafttas.tasmod.commands.CommandFolder; import com.minecrafttas.tasmod.commands.CommandFullPlay; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 941e98f7..375829f8 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -14,9 +14,9 @@ import com.minecrafttas.common.events.EventClient.EventClientInit; import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventClient.EventPlayerLeaveClientSide; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.PacketHandlerRegistry; import com.minecrafttas.common.events.EventListenerRegistry; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.PacketHandlerRegistry; import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java index 44feeef6..389ad4d8 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java @@ -1,8 +1,8 @@ package com.minecrafttas.tasmod; import com.minecrafttas.common.events.CompactPacketHandler; -import com.minecrafttas.server.Client.Side; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.commands.CommandFolder; import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java index 2a5e9275..81928924 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.commands; -import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodPackets; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java index 000c7a70..d732209c 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java @@ -6,7 +6,7 @@ import java.util.ArrayList; import java.util.List; -import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.TASmodPackets; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index b6d727ca..6f5f6f5c 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.commands; -import com.minecrafttas.server.ByteBufferBuilder; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java index 99511e1f..5c8f68af 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.ktrng; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import net.minecraft.entity.player.EntityPlayer; diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java index 6eb737d9..8ab0a49b 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.ktrng; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index 0bcb56f0..153f9b8e 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -1,7 +1,7 @@ package com.minecrafttas.tasmod.networking; -import com.minecrafttas.server.ByteBufferBuilder; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; public class TASmodBufferBuilder extends ByteBufferBuilder{ diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 7a8aa999..69748319 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -13,12 +13,12 @@ import com.dselent.bigarraylist.BigArrayList; import com.minecrafttas.common.events.EventClient.EventOpenGui; -import com.minecrafttas.server.ByteBufferBuilder; -import com.minecrafttas.server.exception.PacketNotImplementedException; -import com.minecrafttas.server.exception.WrongSideException; -import com.minecrafttas.server.interfaces.ClientPacketHandler; -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.server.interfaces.ServerPacketHandler; +import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.TASmodPackets; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java index 117ea5e9..0a1e2585 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.playback.server; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.PlaybackController; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java index 0ccfc1a3..2cbf469f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java @@ -3,7 +3,7 @@ import java.io.IOException; import java.nio.charset.Charset; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java index 27751eb8..1bd99cce 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java @@ -13,8 +13,8 @@ import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Logger; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.SecureList; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; import com.minecrafttas.tasmod.events.EventServer.EventLoadstate; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java index 59744918..f733599c 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.savestates.server; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java index 07524ad6..209a8ae3 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java @@ -3,8 +3,8 @@ import java.util.Map; import com.google.common.collect.Maps; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.SecureList; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java index 8b02283b..de31b7f7 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java @@ -1,6 +1,6 @@ package com.minecrafttas.tasmod.savestates.server.playerloading; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index 70b7193d..ebcafafe 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,8 +1,8 @@ package com.minecrafttas.tasmod.tickratechanger; import com.minecrafttas.common.events.EventClient.EventClientGameLoop; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.SecureList; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index ecc6f68f..2993dd3a 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -4,8 +4,8 @@ import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; -import com.minecrafttas.server.Client; -import com.minecrafttas.server.SecureList; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index 20d55a79..ed3a3f3b 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -4,9 +4,9 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; -import com.minecrafttas.server.ByteBufferBuilder; -import com.minecrafttas.server.interfaces.ClientPacketHandler; -import com.minecrafttas.server.interfaces.PacketID; +import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.TASmodPackets; diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index 16d05a6a..558b3b17 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -6,9 +6,9 @@ import java.util.List; import java.util.UUID; -import com.minecrafttas.server.ByteBufferBuilder; -import com.minecrafttas.server.interfaces.PacketID; -import com.minecrafttas.server.interfaces.ServerPacketHandler; +import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodPackets; import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml index d59c5699..bad101f8 100644 --- a/src/main/resources/log4j.xml +++ b/src/main/resources/log4j.xml @@ -25,6 +25,9 @@ + + + \ No newline at end of file diff --git a/src/test/java/common/server/ByteBufferBuilderTest.java b/src/test/java/common/server/ByteBufferBuilderTest.java new file mode 100644 index 00000000..3edd64e9 --- /dev/null +++ b/src/test/java/common/server/ByteBufferBuilderTest.java @@ -0,0 +1,261 @@ +package common.server; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + +import java.nio.ByteBuffer; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import com.minecrafttas.common.events.CompactPacketHandler; +import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.interfaces.PacketID; + +class ByteBufferBuilderTest { + + + private enum TestPacketIDs implements PacketID { + TESTID_1, + TESTID_2, + TESTID_3; + + private Side side; + private CompactPacketHandler lambda; + + private TestPacketIDs() { + } + + private TestPacketIDs(Side side, CompactPacketHandler lambda) { + this.side = side; + this.lambda = lambda; + } + + @Override + public int getID() { + return this.ordinal(); + } + + @Override + public CompactPacketHandler getLambda() { + return this.lambda; + } + + @Override + public Side getSide() { + return this.side; + } + + @Override + public String getName() { + return this.name(); + } + + } + + @Test + void testId() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + ByteBuffer buf = builder.build(); + buf.position(0); + + assertEquals(0, buf.getInt()); + } + + @Test + void testId2() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_2); + ByteBuffer buf = builder.build(); + buf.position(0); + + assertEquals(1, buf.getInt()); + } + + @Test + void testId3() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_3); + ByteBuffer buf = builder.build(); + buf.position(0); + + assertEquals(2, buf.getInt()); + } + + @Test + void testInt() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeInt(1234); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(1234, ByteBufferBuilder.readInt(buf)); + } + + @Test + void testFloat() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeFloat(12.2F); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(12.2F, ByteBufferBuilder.readFloat(buf)); + } + + @Test + void testDouble() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeDouble(60.9D); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(60.9D, ByteBufferBuilder.readDouble(buf)); + } + + @Test + void testLong() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeLong(800815L); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(800815L, ByteBufferBuilder.readLong(buf)); + } + + @Test + void testShort() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeShort((short)12); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(12, ByteBufferBuilder.readShort(buf)); + } + + @Test + void testBoolean() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeBoolean(true); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(true, ByteBufferBuilder.readBoolean(buf)); + } + + @Test + void testBoolean2() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeBoolean(false); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals(false, ByteBufferBuilder.readBoolean(buf)); + } + + @Test + void testString() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeString("Test"); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals("Test", ByteBufferBuilder.readString(buf)); + } + + @Test + void testUUID() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeUUID(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8")); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertEquals("b8abdafc-5002-40df-ab68-63206ea4c7e8", ByteBufferBuilder.readUUID(buf).toString()); + } + + + // ==================================== + + @Test + void testClone() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + builder.writeInt(1234); + + ByteBufferBuilder clone; + try { + clone = builder.clone(); + } catch (CloneNotSupportedException e) { + fail(e); + return; + } + + ByteBuffer buf = clone.build(); + buf.position(4); + + assertEquals(1234, ByteBufferBuilder.readInt(buf)); + } + + // ===================================== + + @Test + void testClosed() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + builder.close(); + builder.close(); + + Exception exception; + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeInt(0); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeDouble(0D); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeFloat(0F); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeLong(0L); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeShort((short)0); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeBoolean(true); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeString(""); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeUUID(UUID.randomUUID()); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.build(); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + } +} diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java new file mode 100644 index 00000000..2b4d93ef --- /dev/null +++ b/src/test/java/common/server/ServerTest.java @@ -0,0 +1,175 @@ +package common.server; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +import java.nio.ByteBuffer; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.minecrafttas.common.events.CompactPacketHandler; +import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.Client; +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.PacketHandlerRegistry; +import com.minecrafttas.common.server.Server; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; + +import net.minecraft.client.renderer.BufferBuilder; + +class ServerTest { + + private enum TestPacketIDs implements PacketID { + TEST_INTERFACE, TEST_LAMBDA_CLIENT(Side.CLIENT, (buf, clientID) -> { + latch.countDown(); + }), TEST_LAMBDA_SERVER(Side.SERVER, (buf, clientID) -> { + latch.countDown(); + }); + + private Side side; + private CompactPacketHandler lambda; + + private TestPacketIDs() { + } + + private TestPacketIDs(Side side, CompactPacketHandler lambda) { + this.side = side; + this.lambda = lambda; + } + + @Override + public int getID() { + return this.ordinal(); + } + + @Override + public CompactPacketHandler getLambda() { + return this.lambda; + } + + @Override + public Side getSide() { + return this.side; + } + + @Override + public String getName() { + return this.name(); + } + + } + + private static Client.Side side; + + private static class TestingClass implements ClientPacketHandler, ServerPacketHandler { + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TestPacketIDs[] { TestPacketIDs.TEST_INTERFACE }; + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TestPacketIDs packet = (TestPacketIDs) id; + switch (packet) { + case TEST_INTERFACE: + latch.countDown(); + side = Side.SERVER; + break; + default: + throw new PacketNotImplementedException(id, this.getClass()); + } + } + + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TestPacketIDs packet = (TestPacketIDs) id; + switch (packet) { + case TEST_INTERFACE: + latch.countDown(); + side = Side.SERVER; + break; + default: + throw new PacketNotImplementedException(id, this.getClass()); + } + } + + } + + private static Server server; + private static Client client; + + private Integer result = null; + + private static TestingClass clazz=new TestingClass(); + + @BeforeAll + static void setUpBeforeClass() throws Exception { + try { + server = new Server(25565, TestPacketIDs.values()); + } catch (Exception e) { + e.printStackTrace(); + } + + UUID uuid = UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"); + + client = new Client("127.0.0.1", 25565, TestPacketIDs.values(), uuid); + + PacketHandlerRegistry.register(clazz); + } + + @AfterAll + static void tearDownAfterClass() throws Exception { + server.close(); + client.close(); + PacketHandlerRegistry.unregister(clazz); + } + + private static CountDownLatch latch; + + @BeforeEach + void setUp() throws Exception { + latch = new CountDownLatch(1); + } + + @AfterEach + void tearDown() throws Exception { + side = null; + result = null; + } + + @Test + void testSendClient() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + try { + client.send(new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE).writeInt(1)); + } catch (Exception e) { + fail(e); + return; + } + try { + latch.await(2, TimeUnit.SECONDS); + } catch (InterruptedException e) { + fail(e); + return; + } + assertEquals(1, result); + } + +} From b78e1b307253eaf5f9a7ab761e760769d5d0eff4 Mon Sep 17 00:00:00 2001 From: Scribble Date: Mon, 14 Aug 2023 21:37:43 +0200 Subject: [PATCH 18/60] Adding tests for the Client/Server --- .../common/server/ByteBufferBuilder.java | 4 +- .../minecrafttas/common/server/Client.java | 24 ++- .../minecrafttas/common/server/Server.java | 43 +++-- .../PacketNotImplementedException.java | 2 +- src/test/java/common/server/ServerTest.java | 168 +++++++++++++++--- 5 files changed, 194 insertions(+), 47 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 21684ee2..8b643a5e 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -112,9 +112,9 @@ public ByteBufferBuilder clone() throws CloneNotSupportedException { int sid = SecureList.POOL.available(); ByteBuffer clone = SecureList.POOL.lock(sid); - this.buffer.position(0); //Reset buffer pos + this.buffer.limit(current).position(0); - clone.put(this.buffer).limit(current).position(0); + clone.put(this.buffer); this.buffer.position(current); diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index da5514b7..ffa68bd5 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -13,11 +13,17 @@ import org.apache.logging.log4j.Level; +import com.minecrafttas.common.Common; import com.minecrafttas.common.server.exception.InvalidPacketException; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.PacketID; +/** + * A custom asynchronous client + * + * @author Pancake + */ public class Client { private final AsynchronousSocketChannel socket; @@ -40,6 +46,8 @@ public enum Side { * Create and connect socket * @param host Host * @param port Port + * @param packetIDs A list of PacketIDs which are registered + * @param uuid The UUID of the client * @throws Exception Unable to connect */ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exception { @@ -51,7 +59,7 @@ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exc this.packetIDs = packetIDs; this.createHandlers(); - Server.LOGGER.info("Connected to tasmod server"); + Common.LOGGER.info("Connected to tasmod server"); authenticate(uuid); } @@ -92,13 +100,13 @@ public void completed(Integer result, Object attachment) { readBuffer.clear().limit(4); socket.read(readBuffer, null, this); } catch (Throwable exc) { - Server.LOGGER.error("Unable to read packet!", exc); + Common.LOGGER.error("Unable to read packet!", exc); } } @Override public void failed(Throwable exc, Object attachment) { - Server.LOGGER.error("Unable to read packet!", exc); + Common.LOGGER.error("Unable to read packet!", exc); } }); @@ -135,7 +143,7 @@ public void send(ByteBufferBuilder bufferBuilder) throws Exception { */ public void close() throws IOException { if (this.socket == null || !this.socket.isOpen()) { - LOGGER.warn("Tried to close dead socket"); + Common.LOGGER.warn("Tried to close dead socket"); return; } @@ -269,9 +277,9 @@ private void handle(ByteBuffer buf) { PacketID packet = getPacketFromID(id); PacketHandlerRegistry.handle(side, packet, buf, this.clientID); } catch (PacketNotImplementedException | WrongSideException e) { - Server.LOGGER.throwing(Level.ERROR, e); + Common.LOGGER.throwing(Level.ERROR, e); } catch (Exception e) { - Server.LOGGER.throwing(Level.ERROR, e); + Common.LOGGER.throwing(Level.ERROR, e); } } @@ -289,4 +297,8 @@ private PacketID getPacketFromID(int id) throws InvalidPacketException { } throw new InvalidPacketException(String.format("Received invalid packet with id {}", id)); } + + public boolean isClosed() { + return this.socket == null || !this.socket.isOpen(); + } } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index e6a42bfd..9deff9d1 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -9,17 +9,19 @@ import java.util.List; import java.util.UUID; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - +import com.minecrafttas.common.Common; import com.minecrafttas.common.server.interfaces.PacketID; import net.minecraft.entity.player.EntityPlayer; +/** + * A custom asynchronous server + * + * @author Pancake + */ public class Server { private final AsynchronousServerSocketChannel socket; - public static final Logger LOGGER = LogManager.getLogger("PacketServer"); private final List clients; /** @@ -29,7 +31,7 @@ public class Server { */ public Server(int port, PacketID[] packetIDs) throws Exception { // create connection - LOGGER.info("Creating server on port {}", port); + Common.LOGGER.info("Creating server on port {}", port); this.socket = AsynchronousServerSocketChannel.open(); this.socket.bind(new InetSocketAddress(port)); @@ -45,17 +47,16 @@ public void completed(AsynchronousSocketChannel clientSocket, Object attachment) @Override public void failed(Throwable exc, Object attachment) { - LOGGER.error("Unable to accept client!", exc); + Common.LOGGER.error("Unable to accept client!", exc); } }); - LOGGER.info("Server created"); + Common.LOGGER.info("Server created"); } /** * Write packet to all clients - * @param id Buffer id - * @param buf Buffer + * @param builder The packet contents * @throws Exception Networking exception */ public void sendToAll(ByteBufferBuilder builder) throws Exception { @@ -65,14 +66,28 @@ public void sendToAll(ByteBufferBuilder builder) throws Exception { builder.close(); } + /** + * Send a packet to the specified uuid + * @param uuid The UUID to send to + * @param builder The packet contents + * @throws Exception Networking exception + */ public void sendTo(UUID uuid, ByteBufferBuilder builder) throws Exception{ Client client = getClient(uuid); client.send(builder); } + /** + * Send a packet to a specified player + * + * Similar to {@link #sendTo(UUID, ByteBufferBuilder)} + * + * @param player The player to send to + * @param builder The packet contents + * @throws Exception Networking exception + */ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Exception{ - Client client = getClient(player.getUniqueID()); - client.send(builder); + sendTo(player.getUniqueID(), builder); } /** @@ -81,13 +96,17 @@ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Except */ public void close() throws IOException { if (this.socket == null || !this.socket.isOpen()) { - LOGGER.warn("Tried to close dead socket"); + Common.LOGGER.warn("Tried to close dead socket"); return; } this.socket.close(); } + public boolean isClosed() { + return this.socket == null || !this.socket.isOpen(); + } + /** * Get client from UUID * @param uniqueID UUID diff --git a/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java index 8d033acc..a67b4189 100644 --- a/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java @@ -16,7 +16,7 @@ public PacketNotImplementedException(PacketID packet, Class { + TEST_INTERFACE_INT, + TEST_INTERFACE_STRING, + TEST_LAMBDA_CLIENT(Side.CLIENT, (buf, clientID) -> { + result = ByteBufferBuilder.readInt(buf); + ServerTest.side = Side.CLIENT; latch.countDown(); }), TEST_LAMBDA_SERVER(Side.SERVER, (buf, clientID) -> { + result = ByteBufferBuilder.readInt(buf); + ServerTest.side = Side.SERVER; latch.countDown(); }); @@ -71,22 +74,28 @@ public String getName() { } - private static Client.Side side; + private static Client.Side side = null; private static class TestingClass implements ClientPacketHandler, ServerPacketHandler { @Override public PacketID[] getAcceptedPacketIDs() { - return new TestPacketIDs[] { TestPacketIDs.TEST_INTERFACE }; + return new TestPacketIDs[] { TestPacketIDs.TEST_INTERFACE_INT, TestPacketIDs.TEST_INTERFACE_STRING }; } @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TestPacketIDs packet = (TestPacketIDs) id; switch (packet) { - case TEST_INTERFACE: + case TEST_INTERFACE_INT: + result = ByteBufferBuilder.readInt(buf); + side = Side.SERVER; latch.countDown(); + break; + case TEST_INTERFACE_STRING: + result2 = ByteBufferBuilder.readString(buf); side = Side.SERVER; + latch.countDown(); break; default: throw new PacketNotImplementedException(id, this.getClass()); @@ -97,9 +106,10 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TestPacketIDs packet = (TestPacketIDs) id; switch (packet) { - case TEST_INTERFACE: + case TEST_INTERFACE_INT: + result = ByteBufferBuilder.readInt(buf); + side = Side.CLIENT; latch.countDown(); - side = Side.SERVER; break; default: throw new PacketNotImplementedException(id, this.getClass()); @@ -111,29 +121,30 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa private static Server server; private static Client client; - private Integer result = null; - - private static TestingClass clazz=new TestingClass(); - + private static Integer result = null; + private static String result2 = null; + + private static TestingClass clazz = new TestingClass(); + @BeforeAll static void setUpBeforeClass() throws Exception { try { - server = new Server(25565, TestPacketIDs.values()); + server = new Server(25566, TestPacketIDs.values()); } catch (Exception e) { e.printStackTrace(); } - UUID uuid = UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"); - client = new Client("127.0.0.1", 25565, TestPacketIDs.values(), uuid); - + try { + client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), uuid); + } catch (Exception e) { + e.printStackTrace(); + } PacketHandlerRegistry.register(clazz); } @AfterAll static void tearDownAfterClass() throws Exception { - server.close(); - client.close(); PacketHandlerRegistry.unregister(clazz); } @@ -151,25 +162,130 @@ void tearDown() throws Exception { } @Test - void testSendClient() { + void testSendToServerInterface() { + try { + client.send(new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE_INT).writeInt(1)); + } catch (Exception e) { + fail(e); + return; + } try { - Thread.sleep(1000); + latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + fail(e); + return; } + assertEquals(1, result); + assertEquals(Client.Side.SERVER, side); + } + + @Test + void testSendToAllClientsInterface() { try { - client.send(new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE).writeInt(1)); + server.sendToAll(new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE_INT).writeInt(2)); } catch (Exception e) { fail(e); return; } try { - latch.await(2, TimeUnit.SECONDS); + latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; } - assertEquals(1, result); + assertEquals(2, result); + assertEquals(Client.Side.CLIENT, side); + } + + @Test + void testSendToClientInterface() { + try { + server.sendTo(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"), new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE_INT).writeInt(3)); + } catch (Exception e) { + fail(e); + return; + } + try { + latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + fail(e); + return; + } + assertEquals(3, result); + assertEquals(Client.Side.CLIENT, side); + } + + @Test + void testSendToServerInterface2() { + try { + client.send(new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE_STRING).writeString("TEST")); + } catch (Exception e) { + fail(e); + return; + } + try { + latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + fail(e); + return; + } + assertEquals("TEST", result2); + assertEquals(Client.Side.SERVER, side); + } + + // ============================ Lambda + + @Test + void testSendToServerLambda() { + try { + client.send(new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_SERVER).writeInt(4)); + } catch (Exception e) { + fail(e); + return; + } + try { + latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + fail(e); + return; + } + assertEquals(4, result); + assertEquals(Client.Side.SERVER, side); + } + + @Test + void testSendToAllClientsLambda() { + try { + server.sendToAll(new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_CLIENT).writeInt(2)); + } catch (Exception e) { + fail(e); + return; + } + try { + latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + fail(e); + return; + } + assertEquals(2, result); + assertEquals(Client.Side.CLIENT, side); + } + + @Test + void testSendToClientLambda() { + try { + server.sendTo(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"), new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_CLIENT).writeInt(6)); + } catch (Exception e) { + fail(e); + return; + } + try { + latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + fail(e); + return; + } + assertEquals(6, result); + assertEquals(Client.Side.CLIENT, side); } - } From 98aae990c1f35586e4052df78b2aa80fba0d5744 Mon Sep 17 00:00:00 2001 From: Scribble Date: Tue, 15 Aug 2023 22:20:38 +0200 Subject: [PATCH 19/60] Continued rewriting packets --- .../java/com/minecrafttas/tasmod/TASmod.java | 1 + .../com/minecrafttas/tasmod/TASmodClient.java | 3 +- .../tasmod/commands/CommandClearInputs.java | 2 +- .../tasmod/commands/CommandFolder.java | 2 +- .../tasmod/commands/CommandFullPlay.java | 2 +- .../tasmod/commands/CommandFullRecord.java | 9 +- .../tasmod/commands/CommandLoadTAS.java | 8 +- .../tasmod/commands/CommandPlayUntil.java | 8 +- .../commands/CommandRestartAndPlay.java | 8 +- .../tasmod/commands/CommandSaveTAS.java | 9 +- .../tasmod/events/OpenGuiEvents.java | 1 + .../tasmod/ktrng/KillTheRNGHandler.java | 2 +- .../networking/TASmodBufferBuilder.java | 6 + .../{ => networking}/TASmodPackets.java | 9 +- .../tasmod/playback/PlaybackController.java | 103 +++++++++++++----- .../server/InitialSyncStatePacket.java | 31 ------ .../playback/server/SyncStatePacket.java | 91 ---------------- .../playback/server/TASstateClient.java | 72 +++++++++++- .../playback/server/TASstateServer.java | 56 +++++++--- .../tasmod/ticksync/TickSyncClient.java | 2 +- .../tasmod/ticksync/TickSyncServer.java | 2 +- 21 files changed, 247 insertions(+), 180 deletions(-) rename src/main/java/com/minecrafttas/tasmod/{ => networking}/TASmodPackets.java (94%) delete mode 100644 src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 0ed16120..032689c8 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -23,6 +23,7 @@ import com.minecrafttas.tasmod.commands.CommandRestartAndPlay; import com.minecrafttas.tasmod.commands.CommandSaveTAS; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.server.TASstateServer; import com.minecrafttas.tasmod.savestates.server.SavestateCommand; import com.minecrafttas.tasmod.savestates.server.SavestateHandler; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 375829f8..7a7dc059 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -14,13 +14,14 @@ import com.minecrafttas.common.events.EventClient.EventClientInit; import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventClient.EventPlayerLeaveClientSide; +import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.common.server.Client; import com.minecrafttas.common.server.PacketHandlerRegistry; -import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; import com.minecrafttas.tasmod.handlers.LoadingScreenHandler; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.playback.PlaybackSerialiser; import com.minecrafttas.tasmod.playback.server.TASstateClient; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java index 81928924..b728e5ab 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java @@ -2,7 +2,7 @@ import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodPackets; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java index d732209c..ee900533 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java @@ -9,7 +9,7 @@ import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.TASmodPackets; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index 6f5f6f5c..3ae5c1a4 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -2,7 +2,7 @@ import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodPackets; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index 06ae04f8..a527a96d 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -1,6 +1,8 @@ package com.minecrafttas.tasmod.commands; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; @@ -39,7 +41,10 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args TASmod.savestateHandler.state = SavestateState.NONE; } TASmod.containerStateServer.setServerState(TASstate.RECORDING); - TASmod.packetServer.sendToAll(new FullRecordPacket()); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_FULLRECORD)); + } catch (Exception e) { + e.printStackTrace(); + } } - } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java index 9f1ff8df..7baa6783 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java @@ -5,7 +5,9 @@ import java.util.ArrayList; import java.util.List; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.client.Minecraft; import net.minecraft.command.CommandBase; @@ -44,7 +46,11 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } name=name.concat(args[i]+spacer); } - TASmod.packetServer.sendToAll(new LoadTASPacket(name)); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_LOAD).writeString(name)); + } catch (Exception e) { + e.printStackTrace(); + } } } else { sender.sendMessage(new TextComponentString(TextFormatting.RED + "You have no permission to use this command")); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java index 70464e79..ba77d42e 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java @@ -1,6 +1,8 @@ package com.minecrafttas.tasmod.commands; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; @@ -29,7 +31,11 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } catch (NumberFormatException e) { throw new CommandException("{} is not a number", args[0]); } - TASmod.packetServer.sendToAll(new PlayUntilPacket(i)); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_PLAYUNTIL).writeInt(i)); + } catch (Exception e) { + e.printStackTrace(); + } } else { sender.sendMessage(new TextComponentString("Stops the next playback one tick before the specified tick and lets you record from there:\n\n/playuntil 10, runs the playback until tick 9 and will record from there. Useful when you can't savestate")); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index 3b81ae0f..a5a9302d 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -6,7 +6,9 @@ import java.util.ArrayList; import java.util.List; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; @@ -53,7 +55,11 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args e.printStackTrace(); } TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); - TASmod.packetServer.sendToAll(new RestartAndPlayPacket(args[0])); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_RESTARTANDPLAY).writeString(args[0])); + } catch (Exception e) { + e.printStackTrace(); + } } } else { sender.sendMessage(new TextComponentString(TextFormatting.RED + "You have no permission to use this command")); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java index 6f6632c0..53cda2d1 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java @@ -6,7 +6,9 @@ import java.util.List; import com.google.common.collect.ImmutableList; +import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.client.Minecraft; import net.minecraft.command.CommandBase; @@ -52,7 +54,11 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } name = name.concat(args[i] + spacer); } - TASmod.packetServer.sendToAll(new SaveTASPacket(name)); + try { + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_SAVE).writeString(name)); + } catch (Exception e) { + e.printStackTrace(); + } } } else { sender.sendMessage(new TextComponentString(TextFormatting.RED + "You have no permission to use this command")); @@ -81,6 +87,7 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen public List getFilenames() { List tab = new ArrayList(); File folder = new File(Minecraft.getMinecraft().mcDataDir, "saves" + File.separator + "tasfiles"); + File[] listOfFiles = folder.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java index eb9fd0f2..e5d18447 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java @@ -9,6 +9,7 @@ import net.minecraft.client.gui.GuiIngameMenu; import net.minecraft.client.gui.GuiMainMenu; +@Deprecated public class OpenGuiEvents { /** * The state that should be used when the main menu opens diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index 247abbf4..531341b8 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -100,7 +100,7 @@ public void setGlobalSeedServer(long seedIn) { public void sendGlobalSeedToServer(long seedIn) { if(isLoaded()) { if(TASmodClient.client != null) - TASmodClient.packetClient.send(new KTRNGSeedPacket(seedIn)); + TASmodClient.client.send(new KTRNGSeedPacket(seedIn)); else setGlobalSeedClient(seedIn); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index 153f9b8e..53c97327 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.networking; +import java.nio.ByteBuffer; + import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; @@ -18,4 +20,8 @@ public TASmodBufferBuilder writeTASState(TASstate state) { this.writeShort((short)state.ordinal()); return this; } + + public static TASstate readTASState(ByteBuffer buf) { + return TASstate.values()[buf.getShort()]; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java similarity index 94% rename from src/main/java/com/minecrafttas/tasmod/TASmodPackets.java rename to src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index 389ad4d8..62eb592f 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod; +package com.minecrafttas.tasmod.networking; import com.minecrafttas.common.events.CompactPacketHandler; import com.minecrafttas.common.server.Client.Side; @@ -8,6 +8,11 @@ import net.minecraft.client.Minecraft; +/** + * PacketIDs and handlers specifically for TASmod + * + * @author Pancake, Scribble + */ public enum TASmodPackets implements PacketID { /** *

Ticksync is a system to sync the tick execution between client and server. @@ -48,8 +53,6 @@ public enum TASmodPackets implements PacketID { }), SAVESTATE_MOTION, CLEAR_INNPUTS, - PLAYBACK_RECORD, - PLAYBACK_PLAY, PLAYBACK_FULLRECORD, PLAYBACK_FULLPLAY, PLAYBACK_RESTARTANDPLAY, diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 69748319..d49e46e6 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -12,6 +12,7 @@ import org.lwjgl.opengl.Display; import com.dselent.bigarraylist.BigArrayList; +import com.minecrafttas.common.Configuration.ConfigOptions; import com.minecrafttas.common.events.EventClient.EventOpenGui; import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -21,9 +22,9 @@ import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.TASmodPackets; import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import com.minecrafttas.tasmod.playback.server.TASstateClient; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -862,14 +863,13 @@ public GuiScreen onOpenGui(GuiScreen gui) { @Override public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] { - TASmodPackets.PLAYBACK_PLAY, - TASmodPackets.PLAYBACK_RECORD, TASmodPackets.PLAYBACK_SAVE, TASmodPackets.PLAYBACK_LOAD, TASmodPackets.PLAYBACK_FULLPLAY, TASmodPackets.PLAYBACK_FULLRECORD, TASmodPackets.PLAYBACK_RESTARTANDPLAY, - TASmodPackets.PLAYBACK_PLAYUNTIL + TASmodPackets.PLAYBACK_PLAYUNTIL, + TASmodPackets.CLEAR_INNPUTS }; } @@ -882,51 +882,74 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa switch (packet) { - case PLAYBACK_PLAY: - break; - - case PLAYBACK_RECORD: - break; - case PLAYBACK_SAVE: break; case PLAYBACK_LOAD: - mc.addScheduledTask(() -> { - String name = ByteBufferBuilder.readString(buf); - try { - TASmodClient.virtual.loadInputs(name); - } catch (IOException e) { + String name = ByteBufferBuilder.readString(buf); + try { + TASmodClient.virtual.loadInputs(name); + } catch (IOException e) { + if (mc.world != null) mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); - return; - } + else + e.printStackTrace(); + return; + } + if (mc.world != null) mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Loaded inputs from " + name + ".mctas")); - }); + else + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Loaded inputs from " + name + ".mctas"); break; case PLAYBACK_FULLPLAY: - OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; - TASmodClient.tickSchedulerClient.add(() -> { - mc.world.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient) null); + OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; // Set the state to PLAYBACK when the main menu is opened + + TASmodClient.tickSchedulerClient.add(() -> { // Schedule code to be executed on the next tick + // Exit the server if you are in one + if (mc.world != null) { + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + } mc.displayGuiScreen(new GuiMainMenu()); }); break; case PLAYBACK_FULLRECORD: - OpenGuiEvents.stateWhenOpened = TASstate.RECORDING; - TASmodClient.virtual.getContainer().clear(); + OpenGuiEvents.stateWhenOpened = TASstate.RECORDING; // Set the state to RECORDING when the main menu is opened + + TASmodClient.virtual.getContainer().clear(); // Clear inputs + + // Schedule code to be executed on the next tick TASmodClient.tickSchedulerClient.add(() -> { - mc.world.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient) null); + if (mc.world != null) { // Exit the server if you are in one + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + } mc.displayGuiScreen(new GuiMainMenu()); }); break; case PLAYBACK_RESTARTANDPLAY: + name = ByteBufferBuilder.readString(buf); + try { + Thread.sleep(100L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + Minecraft.getMinecraft().addScheduledTask(() -> { + TASmodClient.config.set(ConfigOptions.FileToOpen, name); + System.exit(0); + }); break; case PLAYBACK_PLAYUNTIL: + int until = ByteBufferBuilder.readInt(buf); + TASmodClient.virtual.getContainer().setPlayUntil(until); + break; + + case CLEAR_INNPUTS: + TASmodClient.virtual.getContainer().clear(); break; default: @@ -936,6 +959,34 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + //TODO #181 Permissions + switch (packet) { + case PLAYBACK_SAVE: + break; + + case PLAYBACK_LOAD: + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_LOAD)); + break; + + case PLAYBACK_FULLPLAY: + break; + + case PLAYBACK_FULLRECORD: + break; + + case PLAYBACK_RESTARTANDPLAY: + break; + + case PLAYBACK_PLAYUNTIL: + break; + + case CLEAR_INNPUTS: + TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java deleted file mode 100644 index 39559d05..00000000 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/InitialSyncStatePacket.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.minecrafttas.tasmod.playback.server; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - -/** - * Sends the state of the client to the server on server join. Is only applied if you are the first player on the server and if you are operator - * - * @author Scribble - * - */ -public class InitialSyncStatePacket extends SyncStatePacket { - - public InitialSyncStatePacket() { - super(); - } - - public InitialSyncStatePacket(TASstate state) { - super(state); - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isServer()) - TASmod.containerStateServer.onInitialPacket((EntityPlayerMP)player, this.getState()); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java b/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java deleted file mode 100644 index 0a1e2585..00000000 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/SyncStatePacket.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.minecrafttas.tasmod.playback.server; - -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.PlaybackController; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.util.TickScheduler.TickTask; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.text.TextComponentString; - -/** - * Syncs the current state of the input recorder with the state on the server side and with the state on all other clients - * - * @author Scribble - * - */ -public class SyncStatePacket implements PacketID { - - - private short state; - private boolean verbose; - - public SyncStatePacket() { - state = 0; - } - - public SyncStatePacket(TASstate state) { - verbose = true; - this.state = (short) state.ordinal(); - } - - public SyncStatePacket(TASstate state, boolean verbose) { - this.verbose = verbose; - this.state = (short) state.ordinal(); - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeShort(state); - buf.writeBoolean(verbose); - } - - @Override - public void deserialize(PacketBuffer buf) { - state = buf.readShort(); - verbose = buf.readBoolean(); - } - - protected TASstate getState() { - return TASstate.fromIndex(state); - } - - public boolean isVerbose() { - return verbose; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isServer()) { - TASmod.containerStateServer.onPacket((EntityPlayerMP)player, getState()); - } - else { - - TASstate state = getState(); - - TickTask task = ()->{ - - PlaybackController container = TASmodClient.virtual.getContainer(); - if (state != container.getState()) { - String chatMessage = container.setTASState(state, verbose); - if (!chatMessage.isEmpty()) { - Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(chatMessage)); - } - } - - }; - - - if((state == TASstate.RECORDING || state == TASstate.PLAYBACK) && TASmodClient.tickratechanger.ticksPerSecond != 0) { - TASmodClient.tickSchedulerClient.add(task); // Starts a recording in the next tick - } else { - TASmodClient.gameLoopSchedulerClient.add(task); // Starts a recording in the next frame - } - } - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java index a0dfc6ae..18698a67 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java @@ -1,11 +1,26 @@ package com.minecrafttas.tasmod.playback.server; +import java.nio.ByteBuffer; +import java.util.UUID; + +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; +import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.util.LoggerMarkers; +import com.minecrafttas.tasmod.util.TickScheduler.TickTask; import net.minecraft.client.Minecraft; +import net.minecraft.util.text.TextComponentString; -public class TASstateClient { +public class TASstateClient implements ClientPacketHandler{ public static void setStateClient(TASstate state) { TASmodClient.virtual.getContainer().setTASState(state); @@ -13,9 +28,60 @@ public static void setStateClient(TASstate state) { public static void setOrSend(TASstate state) { if(Minecraft.getMinecraft().player!=null) { - TASmodClient.packetClient.send(new SyncStatePacket(state)); - }else { + try { + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(state)); + } catch (Exception e) { + e.printStackTrace(); + } + } else { TASmodClient.virtual.getContainer().setTASState(state); } } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] {TASmodPackets.STATESYNC_INITIAL, TASmodPackets.STATESYNC}; + } + + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + TASstate networkState = TASmodBufferBuilder.readTASState(buf); + + switch(packet) { + case STATESYNC_INITIAL: + throw new WrongSideException(id, Side.CLIENT); + + case STATESYNC: + + boolean verbose = TASmodBufferBuilder.readBoolean(buf); + TickTask task = ()->{ + PlaybackController container = TASmodClient.virtual.getContainer(); + if (networkState != container.getState()) { + + String message = container.setTASState(networkState, verbose); + + if (!message.isEmpty()) { + if(Minecraft.getMinecraft().world != null) + Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(message)); + else + TASmod.LOGGER.debug(LoggerMarkers.Playback, message); + } + } + + }; + + + if((networkState == TASstate.RECORDING || networkState == TASstate.PLAYBACK) && TASmodClient.tickratechanger.ticksPerSecond != 0) { + TASmodClient.tickSchedulerClient.add(task); // Starts a recording in the next tick + } else { + TASmodClient.gameLoopSchedulerClient.add(task); // Starts a recording in the next frame + } + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } + } + } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java index 340fd7dd..a2ef1b44 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java @@ -1,6 +1,15 @@ package com.minecrafttas.tasmod.playback.server; +import java.nio.ByteBuffer; +import java.util.UUID; + +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import net.minecraft.entity.player.EntityPlayerMP; @@ -20,7 +29,7 @@ * @author Scribble * */ -public class TASstateServer { +public class TASstateServer implements ServerPacketHandler{ private TASstate state; @@ -31,20 +40,36 @@ public TASstateServer() { shouldChange = true; } - public void onInitialPacket(EntityPlayerMP player, TASstate tasState) { - if(player.canUseCommand(2, "") && shouldChange) { - setState(tasState); - shouldChange = false; - }else { - TASmod.packetServer.sendTo(new SyncStatePacket(tasState), player); - } + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] {TASmodPackets.STATESYNC_INITIAL, TASmodPackets.STATESYNC}; } - - public void onPacket(EntityPlayerMP player, TASstate tasState) { - if(player.canUseCommand(2, "")) { - setState(tasState); + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + TASstate networkState = TASmodBufferBuilder.readTASState(buf); + + switch (packet) { + case STATESYNC_INITIAL: + if (/* TODO Permissions && */ shouldChange) { + setState(networkState); + shouldChange = false; + } else { + TASmod.server.sendTo(clientID, new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(networkState)); + } + break; + + case STATESYNC: + /* TODO Permissions */ + setState(networkState); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); } } + public void leaveServer(EntityPlayerMP player) { MinecraftServer server = TASmod.getServerInstance(); @@ -58,7 +83,11 @@ public void leaveServer(EntityPlayerMP player) { public void setState(TASstate stateIn) { setServerState(stateIn); - TASmod.packetServer.sendToAll(new SyncStatePacket(state, true)); + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.STATESYNC).writeTASState(state).writeBoolean(true)); + } catch (Exception e) { + e.printStackTrace(); + } } public void setServerState(TASstate stateIn) { @@ -84,4 +113,5 @@ public void togglePlayback() { public TASstate getState() { return state; } + } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index ed3a3f3b..8025d462 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -9,8 +9,8 @@ import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.TASmodPackets; import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index 558b3b17..e8d937e5 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -10,8 +10,8 @@ import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodPackets; import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; +import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.server.MinecraftServer; From ef8c655862ef1c97b43d7784504892f6d602aeb7 Mon Sep 17 00:00:00 2001 From: Scribble Date: Thu, 17 Aug 2023 22:30:04 +0200 Subject: [PATCH 20/60] Continued with packets - Switched from ByteBufferBuilder to TASmodBufferbuilder in most cases --- .../tasmod/commands/CommandClearInputs.java | 4 +- .../tasmod/commands/CommandFolder.java | 4 +- .../tasmod/commands/CommandFullPlay.java | 4 +- .../tasmod/commands/CommandFullRecord.java | 4 +- .../tasmod/commands/CommandLoadTAS.java | 4 +- .../tasmod/commands/CommandPlayUntil.java | 4 +- .../commands/CommandRestartAndPlay.java | 4 +- .../tasmod/commands/CommandSaveTAS.java | 4 +- .../tasmod/ktrng/KTRNGSeedPacket.java | 39 --------- .../tasmod/ktrng/KTRNGStartSeedPacket.java | 49 ----------- .../tasmod/ktrng/KillTheRNGHandler.java | 81 +++++++++++++++++-- .../tasmod/playback/PlaybackController.java | 7 +- .../tasmod/ticksync/TickSyncClient.java | 4 +- .../tasmod/ticksync/TickSyncServer.java | 4 +- 14 files changed, 100 insertions(+), 116 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java index b728e5ab..ab6fcc5b 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java @@ -1,7 +1,7 @@ package com.minecrafttas.tasmod.commands; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.command.CommandBase; @@ -26,7 +26,7 @@ public String getUsage(ICommandSender sender) { public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if(sender instanceof EntityPlayer) { try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java index ee900533..787d19fb 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java @@ -6,9 +6,9 @@ import java.util.ArrayList; import java.util.List; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.command.CommandBase; @@ -45,7 +45,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args action = 1; } try { - TASmod.server.sendTo((EntityPlayerMP) sender, new ByteBufferBuilder(TASmodPackets.OPEN_FOLDER).writeShort(action)); + TASmod.server.sendTo((EntityPlayerMP) sender, new TASmodBufferBuilder(TASmodPackets.OPEN_FOLDER).writeShort(action)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index 3ae5c1a4..b5d6acb1 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -1,7 +1,7 @@ package com.minecrafttas.tasmod.commands; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; @@ -42,7 +42,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_FULLPLAY)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_FULLPLAY)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index a527a96d..84c4dfad 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -1,7 +1,7 @@ package com.minecrafttas.tasmod.commands; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; @@ -42,7 +42,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } TASmod.containerStateServer.setServerState(TASstate.RECORDING); try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_FULLRECORD)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_FULLRECORD)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java index 7baa6783..858b4de2 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java @@ -5,8 +5,8 @@ import java.util.ArrayList; import java.util.List; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.client.Minecraft; @@ -47,7 +47,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args name=name.concat(args[i]+spacer); } try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_LOAD).writeString(name)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_LOAD).writeString(name)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java index ba77d42e..d9f284af 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlayUntil.java @@ -1,7 +1,7 @@ package com.minecrafttas.tasmod.commands; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.command.CommandBase; @@ -32,7 +32,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args throw new CommandException("{} is not a number", args[0]); } try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_PLAYUNTIL).writeInt(i)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_PLAYUNTIL).writeInt(i)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index a5a9302d..43e75f76 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -6,8 +6,8 @@ import java.util.ArrayList; import java.util.List; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; @@ -56,7 +56,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_RESTARTANDPLAY).writeString(args[0])); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_RESTARTANDPLAY).writeString(args[0])); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java index 53cda2d1..4eaa6202 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java @@ -6,8 +6,8 @@ import java.util.List; import com.google.common.collect.ImmutableList; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.client.Minecraft; @@ -55,7 +55,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args name = name.concat(args[i] + spacer); } try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_SAVE).writeString(name)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_SAVE).writeString(name)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java deleted file mode 100644 index 5c8f68af..00000000 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGSeedPacket.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.minecrafttas.tasmod.ktrng; - -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class KTRNGSeedPacket implements PacketID { - - private long seed; - - public KTRNGSeedPacket() { - } - - public KTRNGSeedPacket(long seed) { - this.seed = seed; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if (side.isClient()) { - TASmod.ktrngHandler.setGlobalSeedClient(seed); - } else { - TASmod.ktrngHandler.setGlobalSeedServer(seed); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeLong(seed); - } - - @Override - public void deserialize(PacketBuffer buf) { - seed = buf.readLong(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java deleted file mode 100644 index 8ab0a49b..00000000 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGStartSeedPacket.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.minecrafttas.tasmod.ktrng; - -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class KTRNGStartSeedPacket implements PacketID{ - - private long seed; - - /** - * Do not use! - */ - @Deprecated - public KTRNGStartSeedPacket() { - } - - /** - * Set's the start seed of the client - * @param seed - */ - public KTRNGStartSeedPacket(long seed) { - this.seed = seed; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - TASmodClient.virtual.getContainer().setStartSeed(seed); - } else { - TASmod.tickSchedulerServer.add(()->{ - TASmod.ktrngHandler.setGlobalSeedServer(seed); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeLong(seed); - } - - @Override - public void deserialize(PacketBuffer buf) { - seed = buf.readLong(); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index 531341b8..3a4c36bd 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -1,11 +1,21 @@ package com.minecrafttas.tasmod.ktrng; +import java.nio.ByteBuffer; +import java.util.UUID; + import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventServer.EventServerTick; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.killtherng.KillTheRNG; import com.minecrafttas.killtherng.SeedingModes; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import net.fabricmc.api.EnvType; @@ -19,7 +29,7 @@ * @author Scribble * */ -public class KillTheRNGHandler implements EventServerTick, EventPlayerJoinedClientSide{ +public class KillTheRNGHandler implements EventServerTick, EventPlayerJoinedClientSide, ClientPacketHandler, ServerPacketHandler{ private boolean isLoaded; @@ -100,7 +110,11 @@ public void setGlobalSeedServer(long seedIn) { public void sendGlobalSeedToServer(long seedIn) { if(isLoaded()) { if(TASmodClient.client != null) - TASmodClient.client.send(new KTRNGSeedPacket(seedIn)); + try { + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(seedIn)); + } catch (Exception e) { + e.printStackTrace(); + } else setGlobalSeedClient(seedIn); } @@ -114,7 +128,11 @@ public void sendGlobalSeedToServer(long seedIn) { public void onServerTick(MinecraftServer server) { if(isLoaded()) { if(TASmod.containerStateServer.getState() != TASstate.PAUSED) - TASmod.packetServer.sendToAll(new KTRNGSeedPacket(advanceGlobalSeedServer())); + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(advanceGlobalSeedServer())); + } catch (Exception e) { + e.printStackTrace(); + } } } @@ -123,7 +141,11 @@ public void onServerTick(MinecraftServer server) { public void broadcastStartSeed() { if(isLoaded()) { long seed = getGlobalSeedServer(); - TASmod.packetServer.sendToAll(new KTRNGStartSeedPacket(seed)); + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(seed)); + } catch (Exception e) { + e.printStackTrace(); + } } } @@ -131,7 +153,11 @@ public void broadcastStartSeed() { public void setInitialSeed(long initialSeed) { if(TASmodClient.client != null) { TASmod.LOGGER.info("Sending initial client seed: {}", initialSeed); - TASmodClient.packetClient.send(new KTRNGStartSeedPacket(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD + try { + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_STARTSEED).writeLong(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD + } catch (Exception e) { + e.printStackTrace(); + } } else { TASmod.ktrngHandler.setGlobalSeedClient(initialSeed); } @@ -142,6 +168,51 @@ public void setInitialSeed(long initialSeed) { public void onPlayerJoinedClientSide(EntityPlayerSP player) { setInitialSeed(getGlobalSeedClient()); } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] {TASmodPackets.KILLTHERNG_SEED, TASmodPackets.KILLTHERNG_STARTSEED}; + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + long seed = TASmodBufferBuilder.readLong(buf); + TASmodPackets packet = (TASmodPackets) id; + + switch (packet) { + case KILLTHERNG_SEED: + setGlobalSeedServer(seed); + break; + + case KILLTHERNG_STARTSEED: + TASmod.tickSchedulerServer.add(()->{ + TASmod.ktrngHandler.setGlobalSeedServer(seed); + }); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } + } + + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + long seed = TASmodBufferBuilder.readLong(buf); + TASmodPackets packet = (TASmodPackets) id; + + switch (packet) { + case KILLTHERNG_SEED: + setGlobalSeedClient(seed); + break; + + case KILLTHERNG_STARTSEED: + TASmodClient.virtual.getContainer().setStartSeed(seed); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index d49e46e6..2943d806 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -24,6 +24,7 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import com.minecrafttas.tasmod.playback.server.TASstateClient; @@ -886,7 +887,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case PLAYBACK_LOAD: - String name = ByteBufferBuilder.readString(buf); + String name = TASmodBufferBuilder.readString(buf); try { TASmodClient.virtual.loadInputs(name); } catch (IOException e) { @@ -967,7 +968,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case PLAYBACK_LOAD: - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.PLAYBACK_LOAD)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_LOAD)); break; case PLAYBACK_FULLPLAY: @@ -983,7 +984,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case CLEAR_INNPUTS: - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); default: throw new PacketNotImplementedException(packet, this.getClass()); diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index 8025d462..f0f495d6 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -4,12 +4,12 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.client.Minecraft; @@ -57,7 +57,7 @@ public void onClientTickPost(Minecraft mc) { } try { - TASmodClient.client.send(new ByteBufferBuilder(TASmodPackets.TICKSYNC)); + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to server:", e); } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index e8d937e5..a7c8ee61 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -6,11 +6,11 @@ import java.util.List; import java.util.UUID; -import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import net.minecraft.server.MinecraftServer; @@ -76,7 +76,7 @@ public PacketID[] getAcceptedPacketIDs() { @Override public void onServerTickPost(MinecraftServer server) { try { - TASmod.server.sendToAll(new ByteBufferBuilder(TASmodPackets.TICKSYNC)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } From a9d36226650f29570fb7bdca313d111a1f5d1c2a Mon Sep 17 00:00:00 2001 From: Scribble Date: Sat, 19 Aug 2023 19:45:07 +0200 Subject: [PATCH 21/60] Finishing packets, renaming and removing classes - Added writeNBTTagCompound() to TASmodBufferBuilder ! This commit will start, but crash as soon as you try and join a world ! --- gradle.properties | 2 +- .../common/server/ByteBufferBuilder.java | 2 +- .../java/com/minecrafttas/tasmod/TASmod.java | 18 +- .../com/minecrafttas/tasmod/TASmodClient.java | 21 +- .../tasmod/commands/CommandFullPlay.java | 4 +- .../tasmod/commands/CommandFullRecord.java | 4 +- .../commands/CommandRestartAndPlay.java | 2 +- .../CommandSavestate.java} | 12 +- .../CommandTickrate.java | 2 +- .../tasmod/events/OpenGuiEvents.java | 2 +- .../com/minecrafttas/tasmod/gui/InfoHud.java | 2 +- .../tasmod/handlers/InterpolationHandler.java | 2 +- .../tasmod/mixin/MixinMinecraft.java | 9 +- .../tasmod/mixin/MixinMinecraftServer.java | 2 +- .../mixin/savestates/MixinEntityPlayerMP.java | 9 +- .../savestates/MixinNetHandlerPlayServer.java | 2 +- .../networking/TASmodBufferBuilder.java | 181 +++++++ .../tasmod/networking/TASmodPackets.java | 17 +- .../ControlByteHandler.java | 2 +- .../tasmod/playback/PlaybackController.java | 96 ++-- .../tasmod/playback/PlaybackSerialiser.java | 1 - .../playback/{server => }/TASstateClient.java | 3 +- .../playback/{server => }/TASstateServer.java | 2 +- .../savestates/SavestateHandlerClient.java | 270 ++++++++++ ...ndler.java => SavestateHandlerServer.java} | 492 ++++++++++++++++-- .../client/InputSavestatesHandler.java | 89 ---- .../client/InputSavestatesPacket.java | 62 --- .../exceptions/LoadstateException.java | 2 +- .../exceptions/SavestateDeleteException.java | 2 +- .../exceptions/SavestateException.java | 2 +- .../{server => }/files/SavestateDataFile.java | 2 +- .../files/SavestateTrackerFile.java | 2 +- .../gui/GuiSavestateLoadingScreen.java | 2 +- .../gui/GuiSavestateSavingScreen.java | 2 +- .../savestates/server/SavestatePacket.java | 81 --- .../chunkloading/SavestatesChunkControl.java | 224 -------- .../server/motion/ClientMotionServer.java | 114 ---- .../playerloading/SavestatePlayerLoading.java | 121 ----- .../SavestatePlayerLoadingPacket.java | 83 --- .../TickrateChangerClient.java | 24 +- .../TickrateChangerServer.java | 29 +- .../tasmod/virtual/VirtualInput.java | 2 +- .../TASmodByteBufferBuilderTest.java | 108 ++++ 43 files changed, 1135 insertions(+), 975 deletions(-) rename src/main/java/com/minecrafttas/tasmod/{savestates/server/SavestateCommand.java => commands/CommandSavestate.java} (95%) rename src/main/java/com/minecrafttas/tasmod/{tickratechanger => commands}/CommandTickrate.java (96%) rename src/main/java/com/minecrafttas/tasmod/playback/{controlbytes => }/ControlByteHandler.java (97%) rename src/main/java/com/minecrafttas/tasmod/playback/{server => }/TASstateClient.java (96%) rename src/main/java/com/minecrafttas/tasmod/playback/{server => }/TASstateServer.java (98%) create mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java rename src/main/java/com/minecrafttas/tasmod/savestates/{server/SavestateHandler.java => SavestateHandlerServer.java} (56%) delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java rename src/main/java/com/minecrafttas/tasmod/savestates/{server => }/exceptions/LoadstateException.java (75%) rename src/main/java/com/minecrafttas/tasmod/savestates/{server => }/exceptions/SavestateDeleteException.java (76%) rename src/main/java/com/minecrafttas/tasmod/savestates/{server => }/exceptions/SavestateException.java (75%) rename src/main/java/com/minecrafttas/tasmod/savestates/{server => }/files/SavestateDataFile.java (96%) rename src/main/java/com/minecrafttas/tasmod/savestates/{server => }/files/SavestateTrackerFile.java (96%) rename src/main/java/com/minecrafttas/tasmod/savestates/{client => }/gui/GuiSavestateLoadingScreen.java (93%) rename src/main/java/com/minecrafttas/tasmod/savestates/{client => }/gui/GuiSavestateSavingScreen.java (93%) delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java create mode 100644 src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java diff --git a/gradle.properties b/gradle.properties index 41de9b46..b4c2796e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx3G # Fabric properties minecraft_version=1.12.2 -loader_version=0.14.19 +loader_version=0.14.21 loom_version=1.3-SNAPSHOT # Mod properties diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 8b643a5e..5b2c310c 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -14,7 +14,7 @@ public class ByteBufferBuilder { private int bufferIndex; - private ByteBuffer buffer; + protected ByteBuffer buffer; public ByteBufferBuilder(int id) { bufferIndex = SecureList.POOL.available(); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 032689c8..f6c54be0 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -22,13 +22,13 @@ import com.minecrafttas.tasmod.commands.CommandRecord; import com.minecrafttas.tasmod.commands.CommandRestartAndPlay; import com.minecrafttas.tasmod.commands.CommandSaveTAS; +import com.minecrafttas.tasmod.commands.CommandTickrate; +import com.minecrafttas.tasmod.commands.CommandSavestate; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.server.TASstateServer; -import com.minecrafttas.tasmod.savestates.server.SavestateCommand; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler; -import com.minecrafttas.tasmod.savestates.server.files.SavestateTrackerFile; -import com.minecrafttas.tasmod.tickratechanger.CommandTickrate; +import com.minecrafttas.tasmod.playback.TASstateServer; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; +import com.minecrafttas.tasmod.savestates.files.SavestateTrackerFile; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; import com.minecrafttas.tasmod.ticksync.TickSyncServer; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -52,7 +52,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static TASstateServer containerStateServer; - public static SavestateHandler savestateHandler; + public static SavestateHandlerServer savestateHandler; public static KillTheRNGHandler ktrngHandler; @@ -77,7 +77,7 @@ public void onServerInit(MinecraftServer server) { CommandRegistry.registerServerCommand(new CommandLoadTAS(), server); CommandRegistry.registerServerCommand(new CommandFolder(), server); CommandRegistry.registerServerCommand(new CommandClearInputs(), server); - CommandRegistry.registerServerCommand(new SavestateCommand(), server); + CommandRegistry.registerServerCommand(new CommandSavestate(), server); CommandRegistry.registerServerCommand(new CommandFullRecord(), server); CommandRegistry.registerServerCommand(new CommandFullPlay(), server); CommandRegistry.registerServerCommand(new CommandRestartAndPlay(), server); @@ -91,7 +91,7 @@ public void onServerInit(MinecraftServer server) { e.printStackTrace(); } - savestateHandler=new SavestateHandler(server, LOGGER); + savestateHandler=new SavestateHandlerServer(server, LOGGER); if(!server.isDedicatedServer()) { TASmod.tickratechanger.ticksPerSecond=0F; @@ -125,8 +125,6 @@ public void onInitialize() { EventListenerRegistry.register(ticksyncServer); PacketHandlerRegistry.register(ticksyncServer); - PacketHandlerRegistry.register(TASmodClient.virtual.getContainer()); - LOGGER.info("Testing connection with KillTheRNG"); ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); EventListenerRegistry.register(ktrngHandler); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 7a7dc059..7cada79d 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -21,12 +21,11 @@ import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; import com.minecrafttas.tasmod.handlers.LoadingScreenHandler; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.playback.PlaybackSerialiser; -import com.minecrafttas.tasmod.playback.server.TASstateClient; -import com.minecrafttas.tasmod.savestates.server.LoadstatePacket; -import com.minecrafttas.tasmod.savestates.server.SavestatePacket; +import com.minecrafttas.tasmod.playback.TASstateClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerClient; import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.util.ShieldDownloader; @@ -152,8 +151,20 @@ public void onClientInit(Minecraft mc) { blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Tickrate 0 Key", "TASmod", Keyboard.KEY_F8, () -> TASmodClient.tickratechanger.togglePause()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Advance Tick", "TASmod", Keyboard.KEY_F9, () -> TASmodClient.tickratechanger.advanceTick()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Recording/Playback Stop", "TASmod", Keyboard.KEY_F10, () -> TASstateClient.setOrSend(TASstate.NONE)))); - blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Create Savestate", "TASmod", Keyboard.KEY_J, () -> TASmodClient.packetClient.send(new SavestatePacket())))); - blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Load Latest Savestate", "TASmod", Keyboard.KEY_K, () -> TASmodClient.packetClient.send(new LoadstatePacket())))); + blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Create Savestate", "TASmod", Keyboard.KEY_J, () -> { + try { + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SAVE).writeInt(-1)); + } catch (Exception e) { + e.printStackTrace(); + } + }))); + blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Load Latest Savestate", "TASmod", Keyboard.KEY_K, () -> { + try { + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_LOAD).writeInt(-1)); + } catch (Exception e) { + e.printStackTrace(); + } + }))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Open InfoGui Editor", "TASmod", Keyboard.KEY_F6, () -> Minecraft.getMinecraft().displayGuiScreen(TASmodClient.hud)))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Buffer View", "TASmod", Keyboard.KEY_NUMPAD0, () -> InputContainerView.startBufferView()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing", "TASmod", Keyboard.KEY_F12, () -> { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index b5d6acb1..b6e29238 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -4,8 +4,8 @@ import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; -import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; +import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index 84c4dfad..907a5124 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -4,8 +4,8 @@ import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index 43e75f76..668b1864 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -10,7 +10,7 @@ import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; +import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; import net.minecraft.client.Minecraft; import net.minecraft.command.CommandBase; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateCommand.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java similarity index 95% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateCommand.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java index 26048d98..bfef39ec 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateCommand.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java @@ -1,13 +1,13 @@ -package com.minecrafttas.tasmod.savestates.server; +package com.minecrafttas.tasmod.commands; import java.io.IOException; import java.util.List; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; -import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateDeleteException; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; +import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateDeleteException; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; @@ -18,7 +18,7 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; -public class SavestateCommand extends CommandBase { +public class CommandSavestate extends CommandBase { @Override public String getName() { diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/CommandTickrate.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/tickratechanger/CommandTickrate.java rename to src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java index e0bf9e1b..e004798e 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/CommandTickrate.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.tickratechanger; +package com.minecrafttas.tasmod.commands; import java.util.List; diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java index e5d18447..7587c739 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java @@ -2,8 +2,8 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.playback.TASstateClient; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.playback.server.TASstateClient; import net.minecraft.client.gui.GuiControls; import net.minecraft.client.gui.GuiIngameMenu; diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index d8c9b0c9..44be169a 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -18,8 +18,8 @@ import com.minecrafttas.tasmod.events.EventClient.EventDrawHotbar; import com.minecrafttas.tasmod.handlers.InterpolationHandler; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; +import com.minecrafttas.tasmod.playback.ControlByteHandler; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import com.minecrafttas.tasmod.util.TrajectoriesCalculator; import com.mojang.realmsclient.gui.ChatFormatting; diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java index ce8325ae..eae90d4d 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java @@ -2,8 +2,8 @@ import com.minecrafttas.common.events.EventClient.EventCamera; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.playback.ControlByteHandler; import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; -import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import net.minecraft.client.Minecraft; import net.minecraft.util.math.MathHelper; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java index 67dc763b..11421e49 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java @@ -16,8 +16,7 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; import com.minecrafttas.tasmod.externalGui.InputContainerView; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler; -import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoading; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; import com.minecrafttas.tasmod.util.Ducks.GuiScreenDuck; import com.minecrafttas.tasmod.util.Ducks.SubtickDuck; @@ -100,11 +99,11 @@ public void inject_shutdownMinecraftApplet(CallbackInfo ci) { public void injectRunTick(CallbackInfo ci) throws IOException { InputContainerView.update(TASmodClient.virtual); - if (SavestatePlayerLoading.wasLoading) { - SavestatePlayerLoading.wasLoading = false; + if (SavestateHandlerServer.wasLoading) { + SavestateHandlerServer.wasLoading = false; if(Minecraft.getMinecraft().player!=null) { //The player can be null when loading a savestate and quitting to the main menu - SavestateHandler.playerLoadSavestateEventClient(); + SavestateHandlerServer.playerLoadSavestateEventClient(); } } } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java index 9185dc23..be8f1ac8 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java @@ -13,7 +13,7 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java index 9885bd96..f0572cec 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java @@ -5,8 +5,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; -import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer.Saver; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; @@ -17,7 +16,7 @@ public class MixinEntityPlayerMP { @Inject(method = "writeEntityToNBT", at = @At(value = "RETURN")) public void writeClientMotion(NBTTagCompound compound, CallbackInfo ci) { NBTTagCompound nbttagcompound = new NBTTagCompound(); - ClientMotionServer.Saver saver = ClientMotionServer.getMotion().get((EntityPlayerMP) (Object) this); + SavestateHandlerServer.Saver saver = SavestateHandlerServer.getMotion().get((EntityPlayerMP) (Object) this); if (saver != null) { nbttagcompound.setDouble("x", saver.getClientX()); nbttagcompound.setDouble("y", saver.getClientY()); @@ -52,8 +51,8 @@ public void readClientMotion(NBTTagCompound compound, CallbackInfo ci) { boolean sprinting = nbttagcompound.getBoolean("Sprinting"); float jumpVector = nbttagcompound.getFloat("JumpFactor"); - ClientMotionServer.Saver saver = new Saver(clientmotionX, clientmotionY, clientmotionZ, clientmotionrX, clientmotionrY, clientmotionrZ, sprinting, jumpVector); - ClientMotionServer.getMotion().put((EntityPlayerMP) (Object) this, saver); + SavestateHandlerServer.Saver saver = new SavestateHandlerServer.Saver(clientmotionX, clientmotionY, clientmotionZ, clientmotionrX, clientmotionrY, clientmotionrZ, sprinting, jumpVector); + SavestateHandlerServer.getMotion().put((EntityPlayerMP) (Object) this, saver); } } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java index c41a1568..4c0dc039 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java @@ -5,7 +5,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index 53c97327..180efce1 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -1,10 +1,18 @@ package com.minecrafttas.tasmod.networking; +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; import java.nio.ByteBuffer; import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; + +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTSizeTracker; +import net.minecraft.nbt.NBTTagCompound; public class TASmodBufferBuilder extends ByteBufferBuilder{ @@ -21,7 +29,180 @@ public TASmodBufferBuilder writeTASState(TASstate state) { return this; } + public TASmodBufferBuilder writeNBTTagCompound(NBTTagCompound compound) { + DataOutput out = new DataOutput() { + + @Override + public void writeUTF(String s) throws IOException { + writeString(s); + } + + @Override + public void writeShort(int v) throws IOException { + buffer.putShort((short) v); + } + + @Override + public void writeLong(long v) throws IOException { + buffer.putLong(v); + } + + @Override + public void writeInt(int v) throws IOException { + buffer.putInt(v); + } + + @Override + public void writeFloat(float v) throws IOException { + buffer.putFloat(v); + } + + @Override + public void writeDouble(double v) throws IOException { + buffer.putDouble(v); + } + + @Override + public void writeChars(String s) throws IOException { + writeString(s); + } + + @Override + public void writeChar(int v) throws IOException { + buffer.putChar((char) v); + } + + @Override + public void writeBytes(String s) throws IOException { + writeString(s); + } + + @Override + public void writeByte(int v) throws IOException { + buffer.put((byte) v); + } + + @Override + public void writeBoolean(boolean v) throws IOException { + writeBoolean(v); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + throw new IOException("Not implemented"); + } + + @Override + public void write(byte[] b) throws IOException { + buffer.put(b); + } + + @Override + public void write(int b) throws IOException { + buffer.put((byte) b); + } + }; + + try { + CompressedStreamTools.write(compound, out); + } catch (IOException e) { + e.printStackTrace(); + } + return this; + } + + public TASmodBufferBuilder writeTickratePauseState(TickratePauseState state) { + writeShort((short) state.ordinal()); + return this; + } + public static TASstate readTASState(ByteBuffer buf) { return TASstate.values()[buf.getShort()]; } + + public static NBTTagCompound readNBTTagCompound(ByteBuffer buf) throws IOException { + DataInput input = new DataInput() { + + @Override + public int skipBytes(int n) throws IOException { + throw new IOException("Not implemented"); + } + + @Override + public int readUnsignedShort() throws IOException { + throw new IOException("Not implemented"); + } + + @Override + public int readUnsignedByte() throws IOException { + throw new IOException("Not implemented"); + } + + @Override + public String readUTF() throws IOException { + return TASmodBufferBuilder.readString(buf); + } + + @Override + public short readShort() throws IOException { + return TASmodBufferBuilder.readShort(buf); + } + + @Override + public long readLong() throws IOException { + return TASmodBufferBuilder.readLong(buf); + } + + @Override + public String readLine() throws IOException { + throw new IOException("Not implemented"); + } + + @Override + public int readInt() throws IOException { + return TASmodBufferBuilder.readInt(buf); + } + + @Override + public void readFully(byte[] b, int off, int len) throws IOException { + buf.get(b, off, len); + } + + @Override + public void readFully(byte[] b) throws IOException { + buf.get(b); + } + + @Override + public float readFloat() throws IOException { + return TASmodBufferBuilder.readFloat(buf); + } + + @Override + public double readDouble() throws IOException { + return TASmodBufferBuilder.readDouble(buf); + } + + @Override + public char readChar() throws IOException { + return buf.getChar(); + } + + @Override + public byte readByte() throws IOException { + return buf.get(); + } + + @Override + public boolean readBoolean() throws IOException { + return TASmodBufferBuilder.readBoolean(buf); + } + }; + + return CompressedStreamTools.read(input, NBTSizeTracker.INFINITE); + } + + public TickratePauseState readTickratePauseState(ByteBuffer buf) { + return TickratePauseState.values()[buf.getShort()]; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index 62eb592f..64952eea 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -4,9 +4,6 @@ import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.commands.CommandFolder; -import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; - -import net.minecraft.client.Minecraft; /** * PacketIDs and handlers specifically for TASmod @@ -30,7 +27,7 @@ public enum TASmodPackets implements PacketID { *

SIDE: Both
* ARGS: int tickrate */ - TICKRATE_SET, + TICKRATE_CHANGE, /** *

Sets the tickrate to 0, pausing the game. Also unpauses the game * @@ -44,14 +41,9 @@ public enum TASmodPackets implements PacketID { *

SIDE: Client
* ARGS: none */ - SAVESTATE_SCREEN(Side.CLIENT, (buf, clientID) -> { - Minecraft mc = Minecraft.getMinecraft(); - if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) - mc.displayGuiScreen(new GuiSavestateSavingScreen()); - else - mc.displayGuiScreen(null); - }), - SAVESTATE_MOTION, + SAVESTATE_SCREEN, + SAVESTATE_PLAYER, + SAVESTATE_UNLOAD_CHUNKS, CLEAR_INNPUTS, PLAYBACK_FULLRECORD, PLAYBACK_FULLPLAY, @@ -59,6 +51,7 @@ public enum TASmodPackets implements PacketID { PLAYBACK_SAVE, PLAYBACK_LOAD, PLAYBACK_PLAYUNTIL, + PLAYBACK_TELEPORT, STATESYNC_INITIAL, STATESYNC, /** diff --git a/src/main/java/com/minecrafttas/tasmod/playback/controlbytes/ControlByteHandler.java b/src/main/java/com/minecrafttas/tasmod/playback/ControlByteHandler.java similarity index 97% rename from src/main/java/com/minecrafttas/tasmod/playback/controlbytes/ControlByteHandler.java rename to src/main/java/com/minecrafttas/tasmod/playback/ControlByteHandler.java index 055caa9b..c3bfaed2 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/controlbytes/ControlByteHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/ControlByteHandler.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.playback.controlbytes; +package com.minecrafttas.tasmod.playback; import java.util.List; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 2943d806..8b493004 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -15,6 +15,7 @@ import com.minecrafttas.common.Configuration.ConfigOptions; import com.minecrafttas.common.events.EventClient.EventOpenGui; import com.minecrafttas.common.server.ByteBufferBuilder; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; @@ -26,8 +27,6 @@ import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; -import com.minecrafttas.tasmod.playback.server.TASstateClient; import com.minecrafttas.tasmod.util.LoggerMarkers; import com.minecrafttas.tasmod.virtual.VirtualInput; import com.minecrafttas.tasmod.virtual.VirtualKeyboard; @@ -41,9 +40,7 @@ import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; @@ -645,70 +642,19 @@ private void tpPlayer(String startLocation) throws NumberFormatException { float angleYaw = Float.parseFloat(section[3]); float anglePitch = Float.parseFloat(section[4]); - TASmodClient.packetClient.send(new TeleportPlayerPacket(x, y, z, angleYaw, anglePitch)); - } - - /** - * Permissionless player teleporting packet - * - * @author Scribble - * - */ - public static class TeleportPlayerPacket implements PacketID { - - double x; - double y; - double z; - - float angleYaw; - float anglePitch; - - public TeleportPlayerPacket(double x, double y, double z, float angleYaw, float anglePitch) { - this.x = x; - this.y = y; - this.z = z; - this.angleYaw = angleYaw; - this.anglePitch = anglePitch; - } - - public TeleportPlayerPacket() { - } - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if (side.isServer()) { - EntityPlayerMP player = (EntityPlayerMP) playerz; - player.getServerWorld().addScheduledTask(() -> { - player.rotationPitch = anglePitch; - player.rotationYaw = angleYaw; - - player.setPositionAndUpdate(x, y, z); - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeDouble(x); - buf.writeDouble(y); - buf.writeDouble(z); - - buf.writeFloat(angleYaw); - buf.writeFloat(anglePitch); - } - - @Override - public void deserialize(PacketBuffer buf) { - this.x = buf.readDouble(); - this.y = buf.readDouble(); - this.z = buf.readDouble(); - this.angleYaw = buf.readFloat(); - this.anglePitch = buf.readFloat(); + try { + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_TELEPORT) + .writeDouble(x) + .writeDouble(y) + .writeDouble(z) + .writeFloat(angleYaw) + .writeFloat(anglePitch) + ); + } catch (Exception e) { + e.printStackTrace(); } - } - // ============================================================== /** @@ -870,6 +816,7 @@ public PacketID[] getAcceptedPacketIDs() { TASmodPackets.PLAYBACK_FULLRECORD, TASmodPackets.PLAYBACK_RESTARTANDPLAY, TASmodPackets.PLAYBACK_PLAYUNTIL, + TASmodPackets.PLAYBACK_TELEPORT, TASmodPackets.CLEAR_INNPUTS }; @@ -952,6 +899,9 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa case CLEAR_INNPUTS: TASmodClient.virtual.getContainer().clear(); break; + + case PLAYBACK_TELEPORT: + throw new WrongSideException(packet, Side.CLIENT); default: throw new PacketNotImplementedException(packet, this.getClass()); @@ -983,6 +933,22 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa case PLAYBACK_PLAYUNTIL: break; + case PLAYBACK_TELEPORT: + double x = TASmodBufferBuilder.readDouble(buf); + double y = TASmodBufferBuilder.readDouble(buf); + double z = TASmodBufferBuilder.readDouble(buf); + float angleYaw = TASmodBufferBuilder.readFloat(buf); + float anglePitch = TASmodBufferBuilder.readFloat(buf); + + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(clientID); + player.getServerWorld().addScheduledTask(() -> { + player.rotationPitch = anglePitch; + player.rotationYaw = angleYaw; + + player.setPositionAndUpdate(x, y, z); + }); + break; + case CLEAR_INNPUTS: TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java index 1d0fe9ee..e696ba5c 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java @@ -14,7 +14,6 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; -import com.minecrafttas.tasmod.playback.controlbytes.ControlByteHandler; import com.minecrafttas.tasmod.util.FileThread; import com.minecrafttas.tasmod.util.LoggerMarkers; import com.minecrafttas.tasmod.virtual.VirtualKey; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java rename to src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java index 18698a67..d51d9c74 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.playback.server; +package com.minecrafttas.tasmod.playback; import java.nio.ByteBuffer; import java.util.UUID; @@ -12,7 +12,6 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.util.LoggerMarkers; import com.minecrafttas.tasmod.util.TickScheduler.TickTask; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java similarity index 98% rename from src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java rename to src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java index a2ef1b44..30176ad3 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/server/TASstateServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.playback.server; +package com.minecrafttas.tasmod.playback; import java.nio.ByteBuffer; import java.util.UUID; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java new file mode 100644 index 00000000..91fc7845 --- /dev/null +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -0,0 +1,270 @@ +package com.minecrafttas.tasmod.savestates; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.UUID; + +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderClient; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; +import com.minecrafttas.tasmod.playback.PlaybackController; +import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; +import com.minecrafttas.tasmod.savestates.gui.GuiSavestateSavingScreen; +import com.minecrafttas.tasmod.util.Ducks.ChunkProviderDuck; +import com.minecrafttas.tasmod.util.LoggerMarkers; +import com.mojang.realmsclient.gui.ChatFormatting; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.ChunkProviderClient; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.GameType; +import net.minecraft.world.chunk.Chunk; + +/** + * Various savestate steps and actions for the client side + * + * @author Scribble + */ +public class SavestateHandlerClient implements ClientPacketHandler{ + + /** + * A bug occurs when unloading the client world. The client world has a "unloadedEntityList" which, as the name implies, stores all unloaded entities
+ *
+ * Strange things happen, when the client player is unloaded, which is what happens when we use {@linkplain SavestateHandlerClient#unloadAllClientChunks()}.
+ *
+ * This method ensures that the player is loaded by removing the player from the unloadedEntityList.
+ *
+ * TLDR:
+ * Makes sure that the player is not removed from the loaded entity list
+ *
+ * Side: Client + */ + @Environment(EnvType.CLIENT) + public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.EntityPlayer player) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Keep player {} in loaded entity list", player.getName()); + Minecraft.getMinecraft().world.unloadedEntityList.remove(player); + } + + /** + * Similar to {@linkplain keepPlayerInLoadedEntityList}, the chunks themselves have a list with loaded entities
+ *
+ * Even after adding the player to the world, the chunks may not load the player correctly.
+ *
+ * Without this, no model is shown in third person
+ * This state is fixed, once the player moves into a different chunk, since the new chunk adds the player to it's list.
+ *
+ * + * TLDR:
+ * Adds the player to the chunk so the player is shown in third person
+ *
+ * Side: Client + */ + @Environment(EnvType.CLIENT) + public static void addPlayerToClientChunk(EntityPlayer player) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to loaded entity list", player.getName()); + int i = MathHelper.floor(player.posX / 16.0D); + int j = MathHelper.floor(player.posZ / 16.0D); + Chunk chunk = Minecraft.getMinecraft().world.getChunkFromChunkCoords(i, j); + for (int k = 0; k < chunk.getEntityLists().length; k++) { + if (chunk.getEntityLists()[k].contains(player)) { + return; + } + } + chunk.addEntity(player); + } + + /** + * Makes a copy of the recording that is currently running. Gets triggered when + * a savestate is made on the server
+ * Side: Client + * + * @param nameOfSavestate coming from the server + * @throws SavestateException + * @throws IOException + */ + public static void savestate(String nameOfSavestate) throws SavestateException, IOException { + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Saving client savestate {}", nameOfSavestate); + if (nameOfSavestate.isEmpty()) { + TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); + return; + } + + SavestateHandlerClient.savestateDirectory.mkdir(); + + File targetfile = new File(SavestateHandlerClient.savestateDirectory, nameOfSavestate + ".mctas"); + + PlaybackController container = TASmodClient.virtual.getContainer(); + if (container.isRecording()) { + TASmodClient.serialiser.saveToFileV1(targetfile, container); //If the container is recording, store it entirely + } else if(container.isPlayingback()){ + TASmodClient.serialiser.saveToFileV1Until(targetfile, container, container.index()); //If the container is playing, store it until the current index + } + } + + public final static File savestateDirectory = new File(TASmodClient.tasdirectory + File.separator + "savestates"); + + /** + * Replaces the current recording with the recording from the savestate. + * Gets triggered when a savestate is loaded on the server
+ * Side: Client + * + * @param nameOfSavestate coming from the server + * @throws IOException + */ + public static void loadstate(String nameOfSavestate) throws IOException { + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Loading client savestate {}", nameOfSavestate); + if (nameOfSavestate.isEmpty()) { + TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); + return; + } + + savestateDirectory.mkdir(); + + File targetfile = new File(savestateDirectory, nameOfSavestate + ".mctas"); + + PlaybackController container = TASmodClient.virtual.getContainer(); + if (!container.isNothingPlaying()) { // If the file exists and the container is recording or playing, load the clientSavestate + if (targetfile.exists()) { + TASmodClient.virtual.loadClientSavestate(TASmodClient.serialiser.fromEntireFileV1(targetfile)); + } else { + TASmodClient.virtual.getContainer().setTASState(TASstate.NONE, false); + Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); + TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); + } + } + } + + public static void loadPlayer(NBTTagCompound compound) { + Minecraft mc = Minecraft.getMinecraft(); + EntityPlayerSP player = mc.player; + + player.readFromNBT(compound); + NBTTagCompound motion = compound.getCompoundTag("clientMotion"); + + double x = motion.getDouble("x"); + double y = motion.getDouble("y"); + double z = motion.getDouble("z"); + player.motionX = x; + player.motionY = y; + player.motionZ = z; + + float rx = motion.getFloat("RelativeX"); + float ry = motion.getFloat("RelativeY"); + float rz = motion.getFloat("RelativeZ"); + player.moveForward = rx; + player.moveVertical = ry; + player.moveStrafing = rz; + + boolean sprinting = motion.getBoolean("Sprinting"); + float jumpVector = motion.getFloat("JumpFactor"); + player.setSprinting(sprinting); + player.jumpMovementFactor = jumpVector; + + // #86 + int gamemode = compound.getInteger("playerGameType"); + GameType type = GameType.getByID(gamemode); + Minecraft.getMinecraft().playerController.setGameType(type); + + // #?? Player rotation does not change when loading a savestate +// CameraInterpolationEvents.rotationPitch = player.rotationPitch; +// CameraInterpolationEvents.rotationYaw = player.rotationYaw + 180f; + + SavestateHandlerClient.keepPlayerInLoadedEntityList(player); + } + + /** + * Unloads all chunks and reloads the renderer so no chunks will be visible throughout the unloading progress
+ *
+ * Side: Client + * @see MixinChunkProviderClient#unloadAllChunks() + */ + @Environment(EnvType.CLIENT) + public static void unloadAllClientChunks() { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); + Minecraft mc = Minecraft.getMinecraft(); + + ChunkProviderClient chunkProvider=mc.world.getChunkProvider(); + + ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); + Minecraft.getMinecraft().renderGlobal.loadRenderers(); + } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] { + TASmodPackets.SAVESTATE_SAVE, + TASmodPackets.SAVESTATE_LOAD, + TASmodPackets.SAVESTATE_PLAYER, + TASmodPackets.SAVESTATE_SCREEN, + TASmodPackets.SAVESTATE_UNLOAD_CHUNKS + }; + } + + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + String name = null; + Minecraft mc = Minecraft.getMinecraft(); + + switch (packet) { + case SAVESTATE_SAVE: + // Create client savestate + name = TASmodBufferBuilder.readString(buf); + try { + SavestateHandlerClient.savestate(name); + } catch (SavestateException e) { + TASmod.LOGGER.error(e.getMessage()); + } catch (IOException e) { + e.printStackTrace(); + } + break; + case SAVESTATE_LOAD: + // Load client savestate + name = TASmodBufferBuilder.readString(buf); + try { + SavestateHandlerClient.loadstate(name); + } catch (IOException e) { + e.printStackTrace(); + } + break; + case SAVESTATE_PLAYER: + NBTTagCompound compound = TASmodBufferBuilder.readNBTTagCompound(buf); + SavestateHandlerClient.loadPlayer(compound); + break; + + case SAVESTATE_SCREEN: + // Open/Close Savestate screen + boolean open = TASmodBufferBuilder.readBoolean(buf); + if (open) { + mc.displayGuiScreen(new GuiSavestateSavingScreen()); + } else { + mc.displayGuiScreen(null); + } + break; + + case SAVESTATE_UNLOAD_CHUNKS: + SavestateHandlerClient.unloadAllClientChunks(); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } + + } + +} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java similarity index 56% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java rename to src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 1bd99cce..853029e4 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestateHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -1,48 +1,65 @@ -package com.minecrafttas.tasmod.savestates.server; +package com.minecrafttas.tasmod.savestates; import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Logger; -import com.minecrafttas.common.server.Client; -import com.minecrafttas.common.server.SecureList; +import com.google.common.collect.Maps; +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; import com.minecrafttas.tasmod.events.EventServer.EventLoadstate; import com.minecrafttas.tasmod.events.EventServer.EventSavestate; import com.minecrafttas.tasmod.mixin.savestates.AccessorAnvilChunkLoader; import com.minecrafttas.tasmod.mixin.savestates.AccessorChunkLoader; -import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; -import com.minecrafttas.tasmod.savestates.server.exceptions.LoadstateException; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateDeleteException; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; -import com.minecrafttas.tasmod.savestates.server.files.SavestateDataFile; -import com.minecrafttas.tasmod.savestates.server.files.SavestateDataFile.DataValues; -import com.minecrafttas.tasmod.savestates.server.files.SavestateTrackerFile; -import com.minecrafttas.tasmod.savestates.server.motion.ClientMotionServer; -import com.minecrafttas.tasmod.savestates.server.playerloading.SavestatePlayerLoading; +import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderServer; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; +import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateDeleteException; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; +import com.minecrafttas.tasmod.savestates.files.SavestateDataFile; +import com.minecrafttas.tasmod.savestates.files.SavestateDataFile.DataValues; +import com.minecrafttas.tasmod.savestates.files.SavestateTrackerFile; +import com.minecrafttas.tasmod.util.Ducks.ChunkProviderDuck; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.PlayerList; +import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.NextTickListEntry; +import net.minecraft.world.World; import net.minecraft.world.WorldServer; +import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.AnvilChunkLoader; +import net.minecraft.world.gen.ChunkProviderServer; +import net.minecraft.world.storage.SaveHandler; +import net.minecraft.world.storage.WorldInfo; /** * Creates and loads savestates on both client and server without closing the @@ -52,10 +69,10 @@ * "https://www.curseforge.com/minecraft/mc-mods/worldstatecheckpoints">WorldStateCheckpoints, * but this new version is completely self written. * - * @author ScribbleLP + * @author Scribble * */ -public class SavestateHandler implements EventCompleteLoadstate{ +public class SavestateHandlerServer implements EventCompleteLoadstate, ServerPacketHandler { private MinecraftServer server; private File savestateDirectory; @@ -68,6 +85,8 @@ public class SavestateHandler implements EventCompleteLoadstate{ private int currentIndex; private final Logger logger; + public static boolean wasLoading; + public static Map motion = Maps.newHashMap(); /** * Creates a savestate handler on the specified server @@ -75,7 +94,7 @@ public class SavestateHandler implements EventCompleteLoadstate{ * * @param The server that should store the savestates */ - public SavestateHandler(MinecraftServer server, Logger logger) { + public SavestateHandlerServer(MinecraftServer server, Logger logger) { this.server = server; this.logger = logger; createSavestateDirectory(); @@ -127,6 +146,14 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex if (state == SavestateState.LOADING) { throw new SavestateException("A loadstate operation is being carried out"); } + + try { + // Open GuiSavestateScreen + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SCREEN).writeBoolean(true)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients:", e); + } + // Lock savestating and loadstating state = SavestateState.SAVING; @@ -140,7 +167,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex server = TASmod.getServerInstance(); // Get the motion from the client - ClientMotionServer.requestMotionFromClient(); + SavestateHandlerServer.requestMotionFromClient(); // Save the world! server.getPlayerList().saveAllPlayerData(); @@ -185,9 +212,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex */ try { // savestate inputs client - var name = this.getSavestateName(indexToSave).getBytes(); - var bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.SAVESTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SAVE).writeString(getSavestateName(indexToSave))); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -216,8 +241,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // close GuiSavestateScreen - var bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CLOSE_GUISAVESTATESCREEN_ON_CLIENTS.ordinal())); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SCREEN).writeBoolean(false)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -323,9 +347,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex if (savestateIndex != 0) { try { // loadstate inputs client - var name = this.getSavestateName(indexToLoad).getBytes(); - var bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.LOADSTATE_INPUTS_CLIENT.ordinal()).putInt(name.length).put(name)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_LOAD).writeString(getSavestateName(savestateIndex))); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } @@ -340,16 +362,15 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex try { // unload chunks on client - var bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.UNLOAD_CHUNKS_ON_CLIENTS.ordinal())); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_UNLOAD_CHUNKS)); } catch (Exception e) { TASmod.LOGGER.error("Unable to send packet to all clients:", e); } // Unload chunks on the server - SavestatesChunkControl.disconnectPlayersFromChunkMap(server); - SavestatesChunkControl.unloadAllServerChunks(server); - SavestatesChunkControl.flushSaveHandler(server); + SavestateHandlerServer.disconnectPlayersFromChunkMap(server); + SavestateHandlerServer.unloadAllServerChunks(server); + SavestateHandlerServer.flushSaveHandler(server); // Delete and copy directories FileUtils.deleteDirectory(currentfolder); @@ -359,11 +380,11 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex loadSavestateDataFile(); // Update the player and the client - SavestatePlayerLoading.loadAndSendMotionToPlayer(server); + SavestateHandlerServer.loadAndSendMotionToPlayer(server); // Update the session.lock file so minecraft behaves and saves the world - SavestatesChunkControl.updateSessionLock(server); + SavestateHandlerServer.updateSessionLock(server); // Load the chunks and send them to the client - SavestatesChunkControl.addPlayersToChunkMap(server); + SavestateHandlerServer.addPlayersToChunkMap(server); // Enable level saving again for (WorldServer world : server.worlds) { @@ -380,7 +401,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex // Add players to the chunk server.getPlayerList().getPlayers().forEach(player->{ - SavestatesChunkControl.addPlayerToServerChunk(player); + SavestateHandlerServer.addPlayerToServerChunk(player); }); WorldServer[] worlds = server.worlds; @@ -660,15 +681,15 @@ public void onLoadstateComplete() { PlayerList playerList = TASmod.getServerInstance().getPlayerList(); for (EntityPlayerMP player : playerList.getPlayers()) { NBTTagCompound nbttagcompound = playerList.readPlayerDataFromFile(player); - SavestatePlayerLoading.reattachEntityToPlayer(nbttagcompound, player.getServerWorld(), player); + SavestateHandlerServer.reattachEntityToPlayer(nbttagcompound, player.getServerWorld(), player); } // Updating redstone component timers to the new world time (#136) - SavestatesChunkControl.updateWorldServerTickListEntries(); + SavestateHandlerServer.updateWorldServerTickListEntries(); } @Environment(EnvType.CLIENT) public static void playerLoadSavestateEventClient() { - SavestatesChunkControl.addPlayerToClientChunk(Minecraft.getMinecraft().player); + SavestateHandlerClient.addPlayerToClientChunk(Minecraft.getMinecraft().player); } private int legacyIndexFile(File savestateDat) { @@ -700,4 +721,403 @@ public static enum SavestateState { NONE } + public static class Saver { + private double clientX; + private double clientY; + private double clientZ; + private float clientrX; + private float clientrY; + private float clientrZ; + private boolean sprinting; + private float jumpMovementVector; + + public Saver(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { + clientX = x; + clientY = y; + clientZ = z; + clientrX = rx; + clientrY = ry; + clientrZ = rz; + this.sprinting = sprinting; + this.jumpMovementVector = jumpMovementVector; + } + + public double getClientX() { + return clientX; + } + + public double getClientY() { + return clientY; + } + + public double getClientZ() { + return clientZ; + } + + public float getClientrX() { + return clientrX; + } + + public float getClientrY() { + return clientrY; + } + + public float getClientrZ() { + return clientrZ; + } + + public boolean isSprinting() { + return sprinting; + } + + public float getJumpMovementVector() { + return jumpMovementVector; + } + } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] { + TASmodPackets.SAVESTATE_SAVE, + TASmodPackets.SAVESTATE_LOAD, + TASmodPackets.SAVESTATE_PLAYER, + TASmodPackets.SAVESTATE_SCREEN, + TASmodPackets.SAVESTATE_UNLOAD_CHUNKS + }; + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + // TODO Permissions + TASmodPackets packet = (TASmodPackets) id; + + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(clientID); + Integer index = null; + + + switch (packet) { + case SAVESTATE_SAVE: + index = TASmodBufferBuilder.readInt(buf); +// if (player!=null && !player.canUseCommand(2, "savestate")) { +// player.sendMessage(new TextComponentString(TextFormatting.RED+"You don't have permission to do that")); +// return; +// } + try { + TASmod.savestateHandler.saveState(index, true); + } catch (SavestateException e) { + if(player!=null) + player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getMessage())); + + TASmod.LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: "+ e.getMessage()); + } catch (Exception e) { + if(player!=null) + player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getCause().toString())); + + TASmod.LOGGER.error(e); + } finally { + TASmod.savestateHandler.state=SavestateState.NONE; + } + break; + + case SAVESTATE_LOAD: + break; + case SAVESTATE_PLAYER: + double x = TASmodBufferBuilder.readDouble(buf); + double y = TASmodBufferBuilder.readDouble(buf); + double z = TASmodBufferBuilder.readDouble(buf); + float rx = TASmodBufferBuilder.readFloat(buf); + float ry = TASmodBufferBuilder.readFloat(buf); + float rz = TASmodBufferBuilder.readFloat(buf); + boolean sprinting = TASmodBufferBuilder.readBoolean(buf); + float jumpMovementVector = TASmodBufferBuilder.readFloat(buf); + SavestateHandlerServer.getMotion().put(player, new SavestateHandlerServer.Saver(x, y, z, rx, ry, rz, sprinting, jumpMovementVector)); + break; + case SAVESTATE_SCREEN: + case SAVESTATE_UNLOAD_CHUNKS: + throw new WrongSideException(id, Side.SERVER); + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } + } + + /** + * Tries to reattach the player to an entity, if the player was riding it it while savestating. + * + * Side: Server + * @param nbttagcompound where the ridden entity is saved + * @param worldserver that needs to spawn the entity + * @param playerIn that needs to ride the entity + */ + public static void reattachEntityToPlayer(NBTTagCompound nbttagcompound, World worldserver, Entity playerIn) { + if (nbttagcompound != null && nbttagcompound.hasKey("RootVehicle", 10)) + { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("RootVehicle"); + Entity entity1 = AnvilChunkLoader.readWorldEntity(nbttagcompound1.getCompoundTag("Entity"), worldserver, true); + + + if(entity1==null) { + for (Entity entity : worldserver.loadedEntityList) { + if(entity.getUniqueID().equals(nbttagcompound1.getUniqueId("Attach"))) entity1=entity; + } + } + + if (entity1 != null) + { + UUID uuid = nbttagcompound1.getUniqueId("Attach"); + + if (entity1.getUniqueID().equals(uuid)) + { + playerIn.startRiding(entity1, true); + } + else + { + for (Entity entity : entity1.getRecursivePassengers()) + { + if (entity.getUniqueID().equals(uuid)) + { + playerIn.startRiding(entity, true); + break; + } + } + } + + if (!playerIn.isRiding()) + { + TASmod.LOGGER.warn("Couldn't reattach entity to player"); + worldserver.removeEntityDangerously(entity1); + + for (Entity entity2 : entity1.getRecursivePassengers()) + { + worldserver.removeEntityDangerously(entity2); + } + } + } + } + else { + if(playerIn.isRiding()) { + playerIn.dismountRidingEntity(); + } + } + } + + /** + * Loads all worlds and players from the disk. Also sends the playerdata to the client in {@linkplain SavestatePlayerLoadingPacketHandler} + * + * Side: Server + */ + public static void loadAndSendMotionToPlayer(MinecraftServer server) { + + List players=server.getPlayerList().getPlayers(); + PlayerList list=server.getPlayerList(); + + WorldServer[] worlds=server.worlds; + for (WorldServer world : worlds) { + WorldInfo info=world.getSaveHandler().loadWorldInfo(); + world.worldInfo = info; + } + for(EntityPlayerMP player : players) { + + int dimensionPrev=player.dimension; + + NBTTagCompound nbttagcompound = server.getPlayerList().readPlayerDataFromFile(player); + + int dimensionNow=0; + if (nbttagcompound.hasKey("Dimension")) + { + dimensionNow = nbttagcompound.getInteger("Dimension"); + } + + if(dimensionNow!=dimensionPrev) { + list.changePlayerDimension(player, dimensionNow); + }else { + player.getServerWorld().unloadedEntityList.remove(player); + } + + player.readFromNBT(nbttagcompound); + + try { + TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER).writeNBTTagCompound(nbttagcompound)); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public static void requestMotionFromClient() { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); + motion.clear(); + try { + // request client motion + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients:", e); + } + + // TODO: is this still necessary? + int i = 1; + while (motion.size() != TASmod.getServerInstance().getPlayerList().getCurrentPlayerCount()) { + i++; + try { + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if(i % 30 == 1) { + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); + try { + // request client motion + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients:", e); + } + } + if (i == 1000) { + TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); + break; + } + + } + } + + public static Map getMotion() { + return motion; + } + + /** + * Updates ticklist entries to the current world time, allowing them to not be stuck in a pressed state #136 + */ + public static void updateWorldServerTickListEntries() { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); + MinecraftServer server=TASmod.getServerInstance(); + for (WorldServer world : server.worlds) { + for (NextTickListEntry nextticklistentry : world.pendingTickListEntriesHashSet) { + nextticklistentry.setScheduledTime(world.getTotalWorldTime()); + } + } + } + + /** + * Just like {@link SavestateHandlerClient#addPlayerToClientChunk(EntityPlayer)}, adds the player to the chunk on the server. + * This prevents the player from being able to place block inside of him + * + * Side: Server + */ + public static void addPlayerToServerChunk(EntityPlayerMP player) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); + int i = MathHelper.floor(player.posX / 16.0D); + int j = MathHelper.floor(player.posZ / 16.0D); + WorldServer world = player.getServerWorld(); + Chunk chunk = world.getChunkFromChunkCoords(i, j); + for (int k = 0; k < chunk.getEntityLists().length; k++) { + if (chunk.getEntityLists()[k].contains(player)) { + return; + } + } + chunk.addEntity(player); + } + + /** + * The session lock is minecrafts failsafe system when it comes to saving. It prevents writing to the world folder from 2 different locations
+ *
+ * That works by storing system time to a session.lock file, when the server started. The integrated server also saves the time when it started in a variable.
+ *
+ * Those two times are then compared every time minecraft tries to save and fails if the times are different.
+ *
+ * Since we never close the integrated server, but copy an "old" session.lock file with the savestate, the session.lock will always mismatch.
+ * Thus we need to update the session lock once the loadstating is completed
+ *
+ * TLDR:
+ * Updates the session lock to allow for vanilla saving again
+ *
+ * Side: Server + */ + public static void updateSessionLock(MinecraftServer server) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); + WorldServer[] worlds=server.worlds; + for(WorldServer world : worlds) { + ((SaveHandler) world.getSaveHandler()).setSessionLock(); + } + } + + /** + * Tells the save handler to save all changes to disk and remove all references to the region files, making them editable on disc
+ *
+ * Side: Server + */ + public static void flushSaveHandler(MinecraftServer server) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); + //Vanilla + WorldServer[] worlds=server.worlds; + for(WorldServer world : worlds) { + world.getSaveHandler().flush(); + } + } + + /** + * The player chunk map keeps track of which chunks need to be sent to the client.
+ * This adds the player to the chunk map so the server knows it can send the information to the client
+ *
+ * Side: Server + * @see disconnectPlayersFromChunkMap + */ + public static void addPlayersToChunkMap(MinecraftServer server) { + List players=server.getPlayerList().getPlayers(); + //Vanilla + WorldServer[] worlds=server.worlds; + for (EntityPlayerMP player : players) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); + switch (player.dimension) { + case -1: + worlds[1].getPlayerChunkMap().addPlayer(player); + worlds[1].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); + break; + case 0: + worlds[0].getPlayerChunkMap().addPlayer(player); + worlds[0].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); + break; + case 1: + worlds[2].getPlayerChunkMap().addPlayer(player); + worlds[2].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); + break; + } + } + } + + /** + * The player chunk map keeps track of which chunks need to be sent to the client.
+ * Removing the player stops the server from sending chunks to the client.
+ *
+ * Side: Server + * @see SavestatesChunkControl#addPlayersToChunkMap() + */ + public static void disconnectPlayersFromChunkMap(MinecraftServer server) { + List players=server.getPlayerList().getPlayers(); + //Vanilla + WorldServer[] worlds=server.worlds; + for (WorldServer world : worlds) { + for (EntityPlayerMP player : players) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); + world.getPlayerChunkMap().removePlayer(player); + } + } + } + + /** + * Unloads all chunks on the server
+ *
+ * Side: Server + * @see MixinChunkProviderServer#unloadAllChunks() + */ + public static void unloadAllServerChunks(MinecraftServer server) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); + //Vanilla + WorldServer[] worlds=server.worlds; + + for (WorldServer world:worlds) { + ChunkProviderServer chunkProvider=world.getChunkProvider(); + + ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); + } + + } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java deleted file mode 100644 index 923dd528..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesHandler.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.minecrafttas.tasmod.savestates.client; - -import java.io.File; -import java.io.IOException; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.PlaybackController; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; -import com.minecrafttas.tasmod.util.LoggerMarkers; -import com.mojang.realmsclient.gui.ChatFormatting; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.util.text.TextComponentString; - -/** - * Creating savestates of the inputs on the client
- * Side: Client - * - * @author ScribbleLP - */ -@Environment(EnvType.CLIENT) -public class InputSavestatesHandler { - - private final static File savestateDirectory = new File(TASmodClient.tasdirectory + File.separator + "savestates"); - - /** - * Makes a copy of the recording that is currently running. Gets triggered when - * a savestate is made on the server
- * Side: Client - * - * @param nameOfSavestate coming from the server - * @throws SavestateException - * @throws IOException - */ - public static void savestate(String nameOfSavestate) throws SavestateException, IOException { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Saving client savestate {}", nameOfSavestate); - if (nameOfSavestate.isEmpty()) { - TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); - return; - } - - savestateDirectory.mkdir(); - - File targetfile = new File(savestateDirectory, nameOfSavestate + ".mctas"); - - PlaybackController container = TASmodClient.virtual.getContainer(); - if (container.isRecording()) { - TASmodClient.serialiser.saveToFileV1(targetfile, container); //If the container is recording, store it entirely - } else if(container.isPlayingback()){ - TASmodClient.serialiser.saveToFileV1Until(targetfile, container, container.index()); //If the container is playing, store it until the current index - } - } - - /** - * Replaces the current recording with the recording from the savestate. - * Gets triggered when a savestate is loaded on the server
- * Side: Client - * - * @param nameOfSavestate coming from the server - * @throws IOException - */ - public static void loadstate(String nameOfSavestate) throws IOException { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Loading client savestate {}", nameOfSavestate); - if (nameOfSavestate.isEmpty()) { - TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); - return; - } - - savestateDirectory.mkdir(); - - File targetfile = new File(savestateDirectory, nameOfSavestate + ".mctas"); - - PlaybackController container = TASmodClient.virtual.getContainer(); - if (!container.isNothingPlaying()) { // If the file exists and the container is recording or playing, load the clientSavestate - if (targetfile.exists()) { - TASmodClient.virtual.loadClientSavestate(TASmodClient.serialiser.fromEntireFileV1(targetfile)); - } else { - TASmodClient.virtual.getContainer().setTASState(TASstate.NONE, false); - Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW - + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); - TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); - } - } - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java deleted file mode 100644 index 2cbf469f..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/InputSavestatesPacket.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.minecrafttas.tasmod.savestates.client; - -import java.io.IOException; -import java.nio.charset.Charset; - -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.PacketBuffer; - -public class InputSavestatesPacket implements PacketID{ - private boolean mode; - private String name; - - public InputSavestatesPacket() { - } - /** - * Makes a savestate of the recording on the Client - * @param mode If true: Make a savestate, else load the savestate - * @param name Name of the savestated file - */ - public InputSavestatesPacket(boolean mode,String name) { - this.mode=mode; - this.name=name; - } - - @Override - public void handle(PacketSide side, EntityPlayer player) { - if(side.isClient()) { - if (mode == true) { - try { - InputSavestatesHandler.savestate(name); - } catch (SavestateException e) { - TASmod.LOGGER.error(e.getMessage()); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - try { - InputSavestatesHandler.loadstate(name); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - } - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(name.length()); - buf.writeCharSequence(name, Charset.defaultCharset()); - buf.writeBoolean(mode); - } - @Override - public void deserialize(PacketBuffer buf) { - int length=buf.readInt(); - name=(String) buf.readCharSequence(length, Charset.defaultCharset()); - mode=buf.readBoolean(); - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/LoadstateException.java b/src/main/java/com/minecrafttas/tasmod/savestates/exceptions/LoadstateException.java similarity index 75% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/LoadstateException.java rename to src/main/java/com/minecrafttas/tasmod/savestates/exceptions/LoadstateException.java index 849e1e80..aa6419f6 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/LoadstateException.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/exceptions/LoadstateException.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.server.exceptions; +package com.minecrafttas.tasmod.savestates.exceptions; public class LoadstateException extends Exception{ /** diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/SavestateDeleteException.java b/src/main/java/com/minecrafttas/tasmod/savestates/exceptions/SavestateDeleteException.java similarity index 76% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/SavestateDeleteException.java rename to src/main/java/com/minecrafttas/tasmod/savestates/exceptions/SavestateDeleteException.java index df7d12ac..83764627 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/SavestateDeleteException.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/exceptions/SavestateDeleteException.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.server.exceptions; +package com.minecrafttas.tasmod.savestates.exceptions; public class SavestateDeleteException extends Exception { /** diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/SavestateException.java b/src/main/java/com/minecrafttas/tasmod/savestates/exceptions/SavestateException.java similarity index 75% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/SavestateException.java rename to src/main/java/com/minecrafttas/tasmod/savestates/exceptions/SavestateException.java index a68c9610..bfe1ff33 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/exceptions/SavestateException.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/exceptions/SavestateException.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.server.exceptions; +package com.minecrafttas.tasmod.savestates.exceptions; public class SavestateException extends Exception{ /** diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java b/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateDataFile.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java rename to src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateDataFile.java index f5689bbe..c41b4f8f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateDataFile.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateDataFile.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.server.files; +package com.minecrafttas.tasmod.savestates.files; import java.io.File; import java.io.FileNotFoundException; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateTrackerFile.java b/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateTrackerFile.java rename to src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java index 825ca960..95a64fdd 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/files/SavestateTrackerFile.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.server.files; +package com.minecrafttas.tasmod.savestates.files; import java.io.File; import java.io.IOException; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/gui/GuiSavestateLoadingScreen.java b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java similarity index 93% rename from src/main/java/com/minecrafttas/tasmod/savestates/client/gui/GuiSavestateLoadingScreen.java rename to src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java index e07da96c..a1ec7ed7 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/gui/GuiSavestateLoadingScreen.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.client.gui; +package com.minecrafttas.tasmod.savestates.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/client/gui/GuiSavestateSavingScreen.java b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java similarity index 93% rename from src/main/java/com/minecrafttas/tasmod/savestates/client/gui/GuiSavestateSavingScreen.java rename to src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java index db1d5ba1..5fc851d0 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/client/gui/GuiSavestateSavingScreen.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java @@ -1,4 +1,4 @@ -package com.minecrafttas.tasmod.savestates.client.gui; +package com.minecrafttas.tasmod.savestates.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java deleted file mode 100644 index f733599c..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/SavestatePacket.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server; - -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.savestates.client.gui.GuiSavestateSavingScreen; -import com.minecrafttas.tasmod.savestates.server.SavestateHandler.SavestateState; -import com.minecrafttas.tasmod.savestates.server.exceptions.SavestateException; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextFormatting; - -public class SavestatePacket implements PacketID { - - public int index; - - /** - * Make a savestate at the next index - */ - public SavestatePacket() { - index=-1; - } - - /** - * Make a savestate at the specified index - * - * @param index The index where to make a savestate - */ - public SavestatePacket(int index) { - this.index=index; - } - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if(side.isServer()) { - EntityPlayerMP player = (EntityPlayerMP) playerz; - player.getServerWorld().addScheduledTask(()->{ - if (!player.canUseCommand(2, "savestate")) { - player.sendMessage(new TextComponentString(TextFormatting.RED+"You don't have permission to do that")); - return; - } - try { - TASmod.savestateHandler.saveState(index, true); - } catch (SavestateException e) { - player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getMessage())); - - } catch (Exception e) { - e.printStackTrace(); - player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getCause().toString())); - } finally { - TASmod.savestateHandler.state=SavestateState.NONE; - } - }); - - } - else { - Minecraft.getMinecraft().addScheduledTask(() -> { - Minecraft mc = Minecraft.getMinecraft(); - if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) { - mc.displayGuiScreen(new GuiSavestateSavingScreen()); - } else { - mc.displayGuiScreen(null); - } - }); - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeInt(index); - } - - @Override - public void deserialize(PacketBuffer buf) { - index=buf.readInt(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java deleted file mode 100644 index 508949d9..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/chunkloading/SavestatesChunkControl.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server.chunkloading; - -import java.util.List; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderClient; -import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderServer; -import com.minecrafttas.tasmod.util.Ducks.ChunkProviderDuck; -import com.minecrafttas.tasmod.util.LoggerMarkers; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ChunkProviderClient; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.MathHelper; -import net.minecraft.world.NextTickListEntry; -import net.minecraft.world.WorldServer; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.gen.ChunkProviderServer; -import net.minecraft.world.storage.SaveHandler; -/** - * Various methods to unload/reload chunks and make loadless savestates possible - * @author Scribble - * - */ -public class SavestatesChunkControl { - /** - * Unloads all chunks and reloads the renderer so no chunks will be visible throughout the unloading progress
- *
- * Side: Client - * @see MixinChunkProviderClient#unloadAllChunks() - */ - @Environment(EnvType.CLIENT) - public static void unloadAllClientChunks() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); - Minecraft mc = Minecraft.getMinecraft(); - - ChunkProviderClient chunkProvider=mc.world.getChunkProvider(); - - ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); - Minecraft.getMinecraft().renderGlobal.loadRenderers(); - } - /** - * Unloads all chunks on the server
- *
- * Side: Server - * @see MixinChunkProviderServer#unloadAllChunks() - */ - public static void unloadAllServerChunks(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); - //Vanilla - WorldServer[] worlds=server.worlds; - - for (WorldServer world:worlds) { - ChunkProviderServer chunkProvider=world.getChunkProvider(); - - ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); - } - - } - /** - * The player chunk map keeps track of which chunks need to be sent to the client.
- * Removing the player stops the server from sending chunks to the client.
- *
- * Side: Server - * @see #addPlayersToChunkMap() - */ - public static void disconnectPlayersFromChunkMap(MinecraftServer server) { - List players=server.getPlayerList().getPlayers(); - //Vanilla - WorldServer[] worlds=server.worlds; - for (WorldServer world : worlds) { - for (EntityPlayerMP player : players) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); - world.getPlayerChunkMap().removePlayer(player); - } - } - } - /** - * The player chunk map keeps track of which chunks need to be sent to the client.
- * This adds the player to the chunk map so the server knows it can send the information to the client
- *
- * Side: Server - * @see #disconnectPlayersFromChunkMap() - */ - public static void addPlayersToChunkMap(MinecraftServer server) { - List players=server.getPlayerList().getPlayers(); - //Vanilla - WorldServer[] worlds=server.worlds; - for (EntityPlayerMP player : players) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); - switch (player.dimension) { - case -1: - worlds[1].getPlayerChunkMap().addPlayer(player); - worlds[1].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); - break; - case 0: - worlds[0].getPlayerChunkMap().addPlayer(player); - worlds[0].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); - break; - case 1: - worlds[2].getPlayerChunkMap().addPlayer(player); - worlds[2].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); - break; - } - } - } - /** - * Tells the save handler to save all changes to disk and remove all references to the region files, making them editable on disc
- *
- * Side: Server - */ - public static void flushSaveHandler(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); - //Vanilla - WorldServer[] worlds=server.worlds; - for(WorldServer world : worlds) { - world.getSaveHandler().flush(); - } - } - /** - * The session lock is minecrafts failsafe system when it comes to saving. It prevents writing to the world folder from 2 different locations
- *
- * That works by storing system time to a session.lock file, when the server started. The integrated server also saves the time when it started in a variable.
- *
- * Those two times are then compared every time minecraft tries to save and fails if the times are different.
- *
- * Since we never close the integrated server, but copy an "old" session.lock file with the savestate, the session.lock will always mismatch.
- * Thus we need to update the session lock once the loadstating is completed
- *
- * TLDR:
- * Updates the session lock to allow for vanilla saving again
- *
- * Side: Server - */ - public static void updateSessionLock(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); - WorldServer[] worlds=server.worlds; - for(WorldServer world : worlds) { - ((SaveHandler) world.getSaveHandler()).setSessionLock(); - } - } - /** - * A bug occurs when unloading the client world. The client world has a "unloadedEntityList" which, as the name implies, stores all unloaded entities
- *
- * Strange things happen, when the client player is unloaded, which is what happens when we use {@linkplain #unloadAllClientChunks()}.
- *
- * This method ensures that the player is loaded by removing the player from the unloadedEntityList.
- *
- * TLDR:
- * Makes sure that the player is not removed from the loaded entity list
- *
- * Side: Client - */ - @Environment(EnvType.CLIENT) - public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.EntityPlayer player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Keep player {} in loaded entity list", player.getName()); - Minecraft.getMinecraft().world.unloadedEntityList.remove(player); - } - - /** - * Similar to {@linkplain #keepPlayerInLoadedEntityList(EntityPlayer)}, the chunks themselves have a list with loaded entities
- *
- * Even after adding the player to the world, the chunks may not load the player correctly.
- *
- * Without this, no model is shown in third person
- * This state is fixed, once the player moves into a different chunk, since the new chunk adds the player to it's list.
- *
- * - * TLDR:
- * Adds the player to the chunk so the player is shown in third person
- *
- * Side: Client - */ - @Environment(EnvType.CLIENT) - public static void addPlayerToClientChunk(EntityPlayer player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to loaded entity list", player.getName()); - int i = MathHelper.floor(player.posX / 16.0D); - int j = MathHelper.floor(player.posZ / 16.0D); - Chunk chunk = Minecraft.getMinecraft().world.getChunkFromChunkCoords(i, j); - for (int k = 0; k < chunk.getEntityLists().length; k++) { - if (chunk.getEntityLists()[k].contains(player)) { - return; - } - } - chunk.addEntity(player); - } - - /** - * Just like {@link #addPlayerToClientChunk(EntityPlayer)}, adds the player to the chunk on the server. - * This prevents the player from being able to place block inside of him - * - * Side: Server - */ - public static void addPlayerToServerChunk(EntityPlayerMP player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); - int i = MathHelper.floor(player.posX / 16.0D); - int j = MathHelper.floor(player.posZ / 16.0D); - WorldServer world = player.getServerWorld(); - Chunk chunk = world.getChunkFromChunkCoords(i, j); - for (int k = 0; k < chunk.getEntityLists().length; k++) { - if (chunk.getEntityLists()[k].contains(player)) { - return; - } - } - chunk.addEntity(player); - } - - /** - * Updates ticklist entries to the current world time, allowing them to not be stuck in a pressed state #136 - */ - public static void updateWorldServerTickListEntries() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); - MinecraftServer server=TASmod.getServerInstance(); - for (WorldServer world : server.worlds) { - for (NextTickListEntry nextticklistentry : world.pendingTickListEntriesHashSet) { - nextticklistentry.setScheduledTime(world.getTotalWorldTime()); - } - } - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java deleted file mode 100644 index 209a8ae3..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/motion/ClientMotionServer.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server.motion; - -import java.util.Map; - -import com.google.common.collect.Maps; -import com.minecrafttas.common.server.Client; -import com.minecrafttas.common.server.SecureList; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.util.LoggerMarkers; - -import net.minecraft.entity.player.EntityPlayerMP; - -public class ClientMotionServer { - - private static Map motion = Maps.newHashMap(); - - public static Map getMotion() { - return motion; - } - - public static void requestMotionFromClient() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); - motion.clear(); - try { - // request client motion - var bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); - } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); - } - - // TODO: is this still necessary? - int i = 1; - while (motion.size() != TASmod.getServerInstance().getPlayerList().getCurrentPlayerCount()) { - i++; - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if(i % 30 == 1) { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); - try { - // request client motion - var bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.REQUEST_CLIENT_MOTION.ordinal())); - } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); - } - } - if (i == 1000) { - TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); - break; - } - - } - } - - // =========================================================== - - public static class Saver { - private double clientX; - private double clientY; - private double clientZ; - private float clientrX; - private float clientrY; - private float clientrZ; - private boolean sprinting; - private float jumpMovementVector; - - public Saver(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { - clientX = x; - clientY = y; - clientZ = z; - clientrX = rx; - clientrY = ry; - clientrZ = rz; - this.sprinting = sprinting; - this.jumpMovementVector = jumpMovementVector; - } - - public double getClientX() { - return clientX; - } - - public double getClientY() { - return clientY; - } - - public double getClientZ() { - return clientZ; - } - - public float getClientrX() { - return clientrX; - } - - public float getClientrY() { - return clientrY; - } - - public float getClientrZ() { - return clientrZ; - } - - public boolean isSprinting() { - return sprinting; - } - - public float getJumpMovementVector() { - return jumpMovementVector; - } - } -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java deleted file mode 100644 index c64de2bd..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoading.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server.playerloading; - -import java.util.List; -import java.util.UUID; - -import com.minecrafttas.tasmod.TASmod; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.management.PlayerList; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; -import net.minecraft.world.chunk.storage.AnvilChunkLoader; -import net.minecraft.world.storage.WorldInfo; - -public class SavestatePlayerLoading { - - public static boolean wasLoading; - - /** - * Loads all worlds and players from the disk. Also sends the playerdata to the client in {@linkplain SavestatePlayerLoadingPacketHandler} - * - * Side: Server - */ - public static void loadAndSendMotionToPlayer(MinecraftServer server) { - - List players=server.getPlayerList().getPlayers(); - PlayerList list=server.getPlayerList(); - - WorldServer[] worlds=server.worlds; - for (WorldServer world : worlds) { - WorldInfo info=world.getSaveHandler().loadWorldInfo(); - world.worldInfo = info; - } - for(EntityPlayerMP player : players) { - - int dimensionPrev=player.dimension; - - NBTTagCompound nbttagcompound = server.getPlayerList().readPlayerDataFromFile(player); - - int dimensionNow=0; - if (nbttagcompound.hasKey("Dimension")) - { - dimensionNow = nbttagcompound.getInteger("Dimension"); - } - - if(dimensionNow!=dimensionPrev) { - list.changePlayerDimension(player, dimensionNow); - }else { - player.getServerWorld().unloadedEntityList.remove(player); - } - - player.readFromNBT(nbttagcompound); - - TASmod.packetServer.sendTo(new SavestatePlayerLoadingPacket(nbttagcompound), player); - } - } - - /** - * Tries to reattach the player to an entity, if the player was riding it it while savestating. - * - * Side: Server - * @param nbttagcompound where the ridden entity is saved - * @param worldserver that needs to spawn the entity - * @param playerIn that needs to ride the entity - */ - public static void reattachEntityToPlayer(NBTTagCompound nbttagcompound, World worldserver, Entity playerIn) { - if (nbttagcompound != null && nbttagcompound.hasKey("RootVehicle", 10)) - { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("RootVehicle"); - Entity entity1 = AnvilChunkLoader.readWorldEntity(nbttagcompound1.getCompoundTag("Entity"), worldserver, true); - - - if(entity1==null) { - for (Entity entity : worldserver.loadedEntityList) { - if(entity.getUniqueID().equals(nbttagcompound1.getUniqueId("Attach"))) entity1=entity; - } - } - - if (entity1 != null) - { - UUID uuid = nbttagcompound1.getUniqueId("Attach"); - - if (entity1.getUniqueID().equals(uuid)) - { - playerIn.startRiding(entity1, true); - } - else - { - for (Entity entity : entity1.getRecursivePassengers()) - { - if (entity.getUniqueID().equals(uuid)) - { - playerIn.startRiding(entity, true); - break; - } - } - } - - if (!playerIn.isRiding()) - { - TASmod.LOGGER.warn("Couldn't reattach entity to player"); - worldserver.removeEntityDangerously(entity1); - - for (Entity entity2 : entity1.getRecursivePassengers()) - { - worldserver.removeEntityDangerously(entity2); - } - } - } - } - else { - if(playerIn.isRiding()) { - playerIn.dismountRidingEntity(); - } - } - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java b/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java deleted file mode 100644 index de31b7f7..00000000 --- a/src/main/java/com/minecrafttas/tasmod/savestates/server/playerloading/SavestatePlayerLoadingPacket.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.minecrafttas.tasmod.savestates.server.playerloading; - -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.savestates.server.chunkloading.SavestatesChunkControl; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; -import net.minecraft.world.GameType; - -/** - * Reads the playerdata coming from the server and also applies motion, relative - * motion and other things from the player - * - * @author Scribble - * - */ -public class SavestatePlayerLoadingPacket implements PacketID { - - private NBTTagCompound compound; - - public SavestatePlayerLoadingPacket() { - } - - public SavestatePlayerLoadingPacket(NBTTagCompound nbttagcompound) { - compound = nbttagcompound; - }; - - - @Override - public void handle(PacketSide side, EntityPlayer playerz) { - if(side.isClient()) { - EntityPlayerSP player = (EntityPlayerSP)playerz; - - player.readFromNBT(compound); - NBTTagCompound motion = compound.getCompoundTag("clientMotion"); - - double x = motion.getDouble("x"); - double y = motion.getDouble("y"); - double z = motion.getDouble("z"); - player.motionX = x; - player.motionY = y; - player.motionZ = z; - - float rx = motion.getFloat("RelativeX"); - float ry = motion.getFloat("RelativeY"); - float rz = motion.getFloat("RelativeZ"); - player.moveForward = rx; - player.moveVertical = ry; - player.moveStrafing = rz; - - boolean sprinting = motion.getBoolean("Sprinting"); - float jumpVector = motion.getFloat("JumpFactor"); - player.setSprinting(sprinting); - player.jumpMovementFactor = jumpVector; - - // #86 - int gamemode = compound.getInteger("playerGameType"); - GameType type = GameType.getByID(gamemode); - Minecraft.getMinecraft().playerController.setGameType(type); - - // #?? Player rotation does not change when loading a savestate -// CameraInterpolationEvents.rotationPitch = player.rotationPitch; -// CameraInterpolationEvents.rotationYaw = player.rotationYaw + 180f; - - SavestatesChunkControl.keepPlayerInLoadedEntityList(player); - SavestatePlayerLoading.wasLoading = true; - } - } - - @Override - public void serialize(PacketBuffer buf) { - buf.writeCompoundTag(compound); - } - - @Override - public void deserialize(PacketBuffer buf) { - compound = buf.readCompoundTag(); - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index ebcafafe..0625a71c 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,11 +1,11 @@ package com.minecrafttas.tasmod.tickratechanger; import com.minecrafttas.common.events.EventClient.EventClientGameLoop; -import com.minecrafttas.common.server.Client; -import com.minecrafttas.common.server.SecureList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.State; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.client.Minecraft; @@ -96,10 +96,9 @@ public void changeServerTickrate(float tickrate) { try { // request tickrate change - var bufIndex = SecureList.POOL.available(); - TASmodClient.client.sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICKRATE_CHANGE.ordinal()).putFloat(tickrate)); + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(tickrate)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server:", e); + e.printStackTrace(); } } @@ -109,11 +108,10 @@ public void changeServerTickrate(float tickrate) { public void togglePause() { if (Minecraft.getMinecraft().world != null) { try { - // toggle tickrate zero - var bufIndex = SecureList.POOL.available(); - TASmodClient.client.sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.TICKRATE_ZERO_TOGGLE.ordinal()).putShort(State.TOGGLE.toShort())); + // request tickrate change + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ZERO).writeTickratePauseState(TickratePauseState.TOGGLE)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server:", e); + e.printStackTrace(); } } else { togglePauseClient(); @@ -174,11 +172,9 @@ public void advanceTick() { */ public void advanceServerTick() { try { - // request tick advance - var bufIndex = SecureList.POOL.available(); - TASmodClient.client.sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ServerPackets.REQUEST_TICK_ADVANCE.ordinal())); + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server:", e); + e.printStackTrace(); } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 2993dd3a..f7a4a855 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -4,9 +4,9 @@ import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; -import com.minecrafttas.common.server.Client; -import com.minecrafttas.common.server.SecureList; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.entity.player.EntityPlayerMP; @@ -86,11 +86,9 @@ public void changeClientTickrate(float tickrate, boolean log) { log("Changing the tickrate "+ tickrate + " to all clients"); try { - // send new tickrate to clients - int bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(tickrate)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(tickrate)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } } @@ -175,11 +173,9 @@ public void advanceTick() { */ private static void advanceClientTick() { try { - // advance tick on clients - int bufIndex = SecureList.POOL.available(); - TASmod.server.sendToAll(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.ADVANCE_TICK_ON_CLIENTS.ordinal())); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } } @@ -201,12 +197,11 @@ private void advanceServerTick() { public void onPlayerJoinedServerSide(EntityPlayerMP player) { if(TASmod.getServerInstance().isDedicatedServer()) { log("Sending the current tickrate ("+ticksPerSecond+") to " +player.getName()); + try { - // change tickrate on client - int bufIndex = SecureList.POOL.available(); - TASmod.server.getClient(player.getUniqueID()).sendToServer(bufIndex, SecureList.POOL.lock(bufIndex).putInt(Client.ClientPackets.CHANGE_TICKRATE_ON_CLIENTS.ordinal()).putFloat(ticksPerSecond)); + TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(ticksPerSecond)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to {}: {}", player.getUniqueID(), e); + e.printStackTrace(); } } } @@ -226,7 +221,7 @@ public void onServerStop(MinecraftServer server) { } } - public static enum State { + public static enum TickratePauseState { /** * Set's the game to tickrate 0 */ @@ -242,7 +237,7 @@ public static enum State { private short id; - State(short i) { + TickratePauseState(short i) { id = i; } @@ -250,7 +245,7 @@ public short toShort() { return id; } - public static State fromShort(short i) { + public static TickratePauseState fromShort(short i) { switch (i) { case 1: return PAUSE; diff --git a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java index c32ba999..130b9dc3 100644 --- a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java +++ b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java @@ -449,7 +449,7 @@ public void setContainer(PlaybackController container) { * Loads and preloads the inputs from the new InputContainer to * {@link #container} * - * Saving a savestate is done via {@linkplain com.minecrafttas.tasmod.playback.PlaybackSerialiser#saveToFileV1(File, PlaybackController)} in {@linkplain com.minecrafttas.tasmod.savestates.client.InputSavestatesHandler#savestate(String)} + * Saving a savestate is done via {@linkplain com.minecrafttas.tasmod.playback.PlaybackSerialiser#saveToFileV1(File, PlaybackController)} in {@linkplain com.minecrafttas.tasmod.savestates.SavestateHandlerClient#savestate(String)} * * @param savestatecontainer The container that should be loaded. */ diff --git a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java new file mode 100644 index 00000000..c97f0ac7 --- /dev/null +++ b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java @@ -0,0 +1,108 @@ +package tasmod.networking; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import com.minecrafttas.common.events.CompactPacketHandler; +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; + +import net.minecraft.nbt.NBTTagCompound; + +class TASmodByteBufferBuilderTest { + + private enum TestPacketIDs implements PacketID { + TESTID_1; + + private Side side; + private CompactPacketHandler lambda; + + private TestPacketIDs() { + } + + private TestPacketIDs(Side side, CompactPacketHandler lambda) { + this.side = side; + this.lambda = lambda; + } + + @Override + public int getID() { + return this.ordinal(); + } + + @Override + public CompactPacketHandler getLambda() { + return this.lambda; + } + + @Override + public Side getSide() { + return this.side; + } + + @Override + public String getName() { + return this.name(); + } + + } + + + @Test + void testNBT() { + + NBTTagCompound tag = new NBTTagCompound(); + NBTTagCompound tag2 = new NBTTagCompound(); + + tag.setString("String", "What"); + tag.setShort("Short", (short) 3); + tag.setLong("Long", 8008132L); + tag.setInteger("Int", -5); + tag.setIntArray("IntArray", new int[] {1, 2, 3}); + tag.setDouble("Double", 1.2D); + tag.setByte("Byte", (byte) 1); + tag.setUniqueId("UUID", UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8")); + tag.setFloat("Float", 1.0F); + tag.setBoolean("Boolean", true); + tag.setByteArray("ByteArray", new byte[] {1, 0, 0}); + + tag2.setTag("Data", tag); + + TASmodBufferBuilder bufferBuilder = new TASmodBufferBuilder(TestPacketIDs.TESTID_1).writeNBTTagCompound(tag2); + + ByteBuffer buf = bufferBuilder.build(); + + buf.position(4); + + NBTTagCompound tag3 = null; + try { + tag3 = TASmodBufferBuilder.readNBTTagCompound(buf); + } catch (IOException e) { + fail(e); + return; + } + + NBTTagCompound tag4 = tag3.getCompoundTag("Data"); + + assertEquals("What", tag4.getString("String")); + assertEquals((short)3, tag4.getShort("Short")); + assertEquals(8008132L, tag4.getLong("Long")); + assertEquals(-5, tag4.getInteger("Int")); + assertArrayEquals(new int[] {1, 2, 3}, tag4.getIntArray("IntArray")); + assertEquals(1.2D, tag4.getDouble("Double")); + assertEquals((byte) 1, tag4.getByte("Byte")); + assertEquals(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"), tag4.getUniqueId("UUID")); + assertEquals(1.0F, tag4.getFloat("Float")); + assertEquals(true, tag4.getBoolean("Boolean")); + assertArrayEquals(new byte[] {1, 0, 0}, tag4.getByteArray("ByteArray")); + } + +} From 620ab76f48854ce6ccacf459cee61144afc0b672 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sat, 19 Aug 2023 20:54:16 +0200 Subject: [PATCH 22/60] Increased ttl for ServerTest --- .../TickrateChangerClient.java | 22 +++++++++++++++- .../TickrateChangerServer.java | 23 ++++++++++++++++- src/test/java/common/server/ServerTest.java | 25 +++++++++++-------- 3 files changed, 57 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index 0625a71c..da8c552b 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,6 +1,13 @@ package com.minecrafttas.tasmod.tickratechanger; +import java.nio.ByteBuffer; +import java.util.UUID; + import com.minecrafttas.common.events.EventClient.EventClientGameLoop; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.ClientPacketHandler; +import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; @@ -15,7 +22,7 @@ * @author Scribble * */ -public class TickrateChangerClient implements EventClientGameLoop{ +public class TickrateChangerClient implements EventClientGameLoop, ClientPacketHandler{ /** * The current tickrate of the client */ @@ -201,4 +208,17 @@ public void onRunClientGameLoop(Minecraft mc) { } + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] { + TASmodPackets.TICKRATE_CHANGE, + TASmodPackets.TICKRATE_ADVANCE, + TASmodPackets.TICKRATE_ZERO, + }; + } + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + + } + } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index f7a4a855..a23bae88 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -1,9 +1,16 @@ package com.minecrafttas.tasmod.tickratechanger; +import java.nio.ByteBuffer; +import java.util.UUID; + import org.apache.logging.log4j.Logger; import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; @@ -26,7 +33,7 @@ * @author Scribble * */ -public class TickrateChangerServer implements EventServerStop, EventPlayerJoinedServerSide{ +public class TickrateChangerServer implements EventServerStop, EventPlayerJoinedServerSide, ServerPacketHandler{ /** * The current tickrate of the client @@ -256,5 +263,19 @@ public static TickratePauseState fromShort(short i) { } } } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] { + TASmodPackets.TICKRATE_CHANGE, + TASmodPackets.TICKRATE_ADVANCE, + TASmodPackets.TICKRATE_ZERO, + }; + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + + } } diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index 0719a614..f0840c34 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -28,6 +28,8 @@ class ServerTest { + private static int ttl = 5; + private enum TestPacketIDs implements PacketID { TEST_INTERFACE_INT, TEST_INTERFACE_STRING, @@ -35,7 +37,8 @@ private enum TestPacketIDs implements PacketID { result = ByteBufferBuilder.readInt(buf); ServerTest.side = Side.CLIENT; latch.countDown(); - }), TEST_LAMBDA_SERVER(Side.SERVER, (buf, clientID) -> { + }), + TEST_LAMBDA_SERVER(Side.SERVER, (buf, clientID) -> { result = ByteBufferBuilder.readInt(buf); ServerTest.side = Side.SERVER; latch.countDown(); @@ -170,12 +173,12 @@ void testSendToServerInterface() { return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; } - assertEquals(1, result); + assertEquals(ttl, result); assertEquals(Client.Side.SERVER, side); } @@ -188,7 +191,7 @@ void testSendToAllClientsInterface() { return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; @@ -206,7 +209,7 @@ void testSendToClientInterface() { return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; @@ -224,7 +227,7 @@ void testSendToServerInterface2() { return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; @@ -244,7 +247,7 @@ void testSendToServerLambda() { return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; @@ -256,18 +259,18 @@ void testSendToServerLambda() { @Test void testSendToAllClientsLambda() { try { - server.sendToAll(new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_CLIENT).writeInt(2)); + server.sendToAll(new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_CLIENT).writeInt(5)); } catch (Exception e) { fail(e); return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; } - assertEquals(2, result); + assertEquals(5, result); assertEquals(Client.Side.CLIENT, side); } @@ -280,7 +283,7 @@ void testSendToClientLambda() { return; } try { - latch.await(1, TimeUnit.SECONDS); + latch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e); return; From c6a02e11c880e4e707283cc59f7a93e38098e153 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sat, 19 Aug 2023 20:59:38 +0200 Subject: [PATCH 23/60] Disabled ServerTest for now, doesn't seem to work with github... --- src/test/java/common/server/ServerTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index f0840c34..4c098a32 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -12,6 +12,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import com.minecrafttas.common.events.CompactPacketHandler; @@ -26,9 +27,10 @@ import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; +@Disabled class ServerTest { - private static int ttl = 5; + private static int ttl = 1; private enum TestPacketIDs implements PacketID { TEST_INTERFACE_INT, From 4937f58d329857e09a2203ab89e058227ec972aa Mon Sep 17 00:00:00 2001 From: Scribble Date: Mon, 21 Aug 2023 22:01:26 +0200 Subject: [PATCH 24/60] Added scheduler for opening the main menu - Reintroduced some classes in SavestateHandlerServer for better visibility --- .../common/server/ByteBufferBuilder.java | 6 + .../java/com/minecrafttas/tasmod/TASmod.java | 6 +- .../com/minecrafttas/tasmod/TASmodClient.java | 22 +- .../tasmod/events/OpenGuiEvents.java | 2 +- .../mixin/savestates/MixinEntityPlayerMP.java | 8 +- .../networking/TASmodBufferBuilder.java | 4 + .../tasmod/playback/PlaybackController.java | 82 ++- .../tasmod/playback/TASstateClient.java | 4 +- .../savestates/SavestateHandlerClient.java | 4 +- .../savestates/SavestateHandlerServer.java | 626 +++++++++--------- .../{TickScheduler.java => Scheduler.java} | 12 +- .../tasmod/virtual/VirtualInput.java | 3 +- 12 files changed, 403 insertions(+), 376 deletions(-) rename src/main/java/com/minecrafttas/tasmod/util/{TickScheduler.java => Scheduler.java} (60%) diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 5b2c310c..87fe2413 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -25,6 +25,12 @@ public ByteBufferBuilder(int id) { public ByteBufferBuilder(PacketID packet) { this(packet.getID()); } + + public ByteBufferBuilder(ByteBuffer buf) { + bufferIndex = SecureList.POOL.available(); + buffer = SecureList.POOL.lock(bufferIndex); + buffer.put(buf); + } private ByteBufferBuilder(int bufferIndex, ByteBuffer buffer) { this.bufferIndex = bufferIndex; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index f6c54be0..dbffee25 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -22,8 +22,8 @@ import com.minecrafttas.tasmod.commands.CommandRecord; import com.minecrafttas.tasmod.commands.CommandRestartAndPlay; import com.minecrafttas.tasmod.commands.CommandSaveTAS; -import com.minecrafttas.tasmod.commands.CommandTickrate; import com.minecrafttas.tasmod.commands.CommandSavestate; +import com.minecrafttas.tasmod.commands.CommandTickrate; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.TASstateServer; @@ -32,7 +32,7 @@ import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; import com.minecrafttas.tasmod.ticksync.TickSyncServer; import com.minecrafttas.tasmod.util.LoggerMarkers; -import com.minecrafttas.tasmod.util.TickScheduler; +import com.minecrafttas.tasmod.util.Scheduler; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.impl.FabricLoaderImpl; @@ -60,7 +60,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static TickSyncServer ticksyncServer; - public static final TickScheduler tickSchedulerServer = new TickScheduler(); + public static final Scheduler tickSchedulerServer = new Scheduler(); public static Server server; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 7cada79d..41c1388c 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -12,6 +12,7 @@ import com.minecrafttas.common.KeybindManager; import com.minecrafttas.common.KeybindManager.Keybind; import com.minecrafttas.common.events.EventClient.EventClientInit; +import com.minecrafttas.common.events.EventClient.EventOpenGui; import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventClient.EventPlayerLeaveClientSide; import com.minecrafttas.common.events.EventListenerRegistry; @@ -28,8 +29,8 @@ import com.minecrafttas.tasmod.playback.TASstateClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerClient; import com.minecrafttas.tasmod.ticksync.TickSyncClient; +import com.minecrafttas.tasmod.util.Scheduler; import com.minecrafttas.tasmod.util.ShieldDownloader; -import com.minecrafttas.tasmod.util.TickScheduler; import com.minecrafttas.tasmod.virtual.VirtualInput; import com.minecrafttas.tasmod.virtual.VirtualKeybindings; @@ -37,6 +38,7 @@ import net.fabricmc.loader.impl.FabricLoaderImpl; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.settings.KeyBinding; public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide{ @@ -60,9 +62,11 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even public static TickrateChangerClient tickratechanger = new TickrateChangerClient(); - public static TickScheduler gameLoopSchedulerClient = new TickScheduler(); + public static Scheduler gameLoopSchedulerClient = new Scheduler(); - public static TickScheduler tickSchedulerClient = new TickScheduler(); + public static Scheduler tickSchedulerClient = new Scheduler(); + + public static Scheduler openMainMenuScheduler = new Scheduler(); public static Configuration config; @@ -106,8 +110,6 @@ public void onInitializeClient() { virtual=new VirtualInput(fileOnStart); EventListenerRegistry.register(virtual); - EventListenerRegistry.register(virtual.getContainer()); - hud = new InfoHud(); EventListenerRegistry.register(hud); @@ -133,6 +135,16 @@ protected boolean isKeyDown(KeyBinding i) { EventListenerRegistry.register(interpolation); + + EventListenerRegistry.register((EventOpenGui)(gui -> { + if(gui instanceof GuiMainMenu) { + openMainMenuScheduler.runAllTasks(); + } + return gui; + })); + + EventListenerRegistry.register(hud); + try { UUID uuid = mc.getSession().getProfile().getId(); if (uuid == null) // dev environment diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java index 7587c739..d2c3cdbb 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java @@ -2,8 +2,8 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.TASstateClient; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.TASstateClient; import net.minecraft.client.gui.GuiControls; import net.minecraft.client.gui.GuiIngameMenu; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java index f0572cec..ff17e04b 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java @@ -5,7 +5,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; @@ -16,7 +16,7 @@ public class MixinEntityPlayerMP { @Inject(method = "writeEntityToNBT", at = @At(value = "RETURN")) public void writeClientMotion(NBTTagCompound compound, CallbackInfo ci) { NBTTagCompound nbttagcompound = new NBTTagCompound(); - SavestateHandlerServer.Saver saver = SavestateHandlerServer.getMotion().get((EntityPlayerMP) (Object) this); + PlayerHandler.Saver saver = PlayerHandler.getMotion().get((EntityPlayerMP) (Object) this); if (saver != null) { nbttagcompound.setDouble("x", saver.getClientX()); nbttagcompound.setDouble("y", saver.getClientY()); @@ -51,8 +51,8 @@ public void readClientMotion(NBTTagCompound compound, CallbackInfo ci) { boolean sprinting = nbttagcompound.getBoolean("Sprinting"); float jumpVector = nbttagcompound.getFloat("JumpFactor"); - SavestateHandlerServer.Saver saver = new SavestateHandlerServer.Saver(clientmotionX, clientmotionY, clientmotionZ, clientmotionrX, clientmotionrY, clientmotionrZ, sprinting, jumpVector); - SavestateHandlerServer.getMotion().put((EntityPlayerMP) (Object) this, saver); + PlayerHandler.Saver saver = new PlayerHandler.Saver(clientmotionX, clientmotionY, clientmotionZ, clientmotionrX, clientmotionrY, clientmotionrZ, sprinting, jumpVector); + PlayerHandler.getMotion().put((EntityPlayerMP) (Object) this, saver); } } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index 180efce1..ae782b62 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -24,6 +24,10 @@ public TASmodBufferBuilder(PacketID packet) { super(packet); } + public TASmodBufferBuilder(ByteBuffer buf) { + super(buf); + } + public TASmodBufferBuilder writeTASState(TASstate state) { this.writeShort((short)state.ordinal()); return this; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 8b493004..4a61199c 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -13,7 +13,6 @@ import com.dselent.bigarraylist.BigArrayList; import com.minecrafttas.common.Configuration.ConfigOptions; -import com.minecrafttas.common.events.EventClient.EventOpenGui; import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -23,7 +22,6 @@ import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; @@ -38,7 +36,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.text.TextComponentString; @@ -62,7 +59,7 @@ * @author Scribble * */ -public class PlaybackController implements EventOpenGui, ServerPacketHandler, ClientPacketHandler{ +public class PlaybackController implements ServerPacketHandler, ClientPacketHandler{ /** * The current state of the controller. @@ -782,29 +779,18 @@ public static enum TASstate { PAUSED; // #124 } - private TASstate stateWhenOpened; public void setStateWhenOpened(TASstate state) { - TASmod.LOGGER.trace(LoggerMarkers.Playback, "Set state when opened to {}", state); - stateWhenOpened = state; - } - - @Override - public GuiScreen onOpenGui(GuiScreen gui) { - if(gui instanceof GuiMainMenu) { - if (stateWhenOpened != null) { + TASmodClient.openMainMenuScheduler.add(()->{ PlaybackController container = TASmodClient.virtual.getContainer(); - if(stateWhenOpened == TASstate.RECORDING) { + if(state == TASstate.RECORDING) { long seed = TASmod.ktrngHandler.getGlobalSeedClient(); container.setStartSeed(seed); } - container.setTASState(stateWhenOpened); - stateWhenOpened = null; - } - } - return gui; + TASstateClient.setOrSend(state); + }); } - + // ====================================== Networking @Override @@ -825,16 +811,30 @@ public PacketID[] getAcceptedPacketIDs() { @Override public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; - + String name = null; Minecraft mc = Minecraft.getMinecraft(); switch (packet) { case PLAYBACK_SAVE: + name = TASmodBufferBuilder.readString(buf); + try { + TASmodClient.virtual.saveInputs(name); + } catch (IOException e) { + if (mc.world != null) + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); + else + e.printStackTrace(); + return; + } + if (mc.world != null) + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Saved inputs to " + name + ".mctas")); + else + TASmod.LOGGER.debug(LoggerMarkers.Playback, "Saved inputs to " + name + ".mctas"); break; case PLAYBACK_LOAD: - String name = TASmodBufferBuilder.readString(buf); + name = TASmodBufferBuilder.readString(buf); try { TASmodClient.virtual.loadInputs(name); } catch (IOException e) { @@ -851,7 +851,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case PLAYBACK_FULLPLAY: - OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; // Set the state to PLAYBACK when the main menu is opened + setStateWhenOpened(TASstate.PLAYBACK); // Set the state to PLAYBACK when the main menu is opened TASmodClient.tickSchedulerClient.add(() -> { // Schedule code to be executed on the next tick // Exit the server if you are in one @@ -864,7 +864,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case PLAYBACK_FULLRECORD: - OpenGuiEvents.stateWhenOpened = TASstate.RECORDING; // Set the state to RECORDING when the main menu is opened + setStateWhenOpened(TASstate.RECORDING); // Set the state to RECORDING when the main menu is opened TASmodClient.virtual.getContainer().clear(); // Clear inputs @@ -879,14 +879,15 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case PLAYBACK_RESTARTANDPLAY: - name = ByteBufferBuilder.readString(buf); + final String finalname = ByteBufferBuilder.readString(buf); + try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } Minecraft.getMinecraft().addScheduledTask(() -> { - TASmodClient.config.set(ConfigOptions.FileToOpen, name); + TASmodClient.config.set(ConfigOptions.FileToOpen, finalname); System.exit(0); }); break; @@ -911,28 +912,11 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; + + //TODO #181 Permissions switch (packet) { - - case PLAYBACK_SAVE: - break; - - case PLAYBACK_LOAD: - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_LOAD)); - break; - - case PLAYBACK_FULLPLAY: - break; - - case PLAYBACK_FULLRECORD: - break; - case PLAYBACK_RESTARTANDPLAY: - break; - - case PLAYBACK_PLAYUNTIL: - break; - case PLAYBACK_TELEPORT: double x = TASmodBufferBuilder.readDouble(buf); double y = TASmodBufferBuilder.readDouble(buf); @@ -952,6 +936,14 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa case CLEAR_INNPUTS: TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + case PLAYBACK_FULLPLAY: + case PLAYBACK_FULLRECORD: + case PLAYBACK_RESTARTANDPLAY: + case PLAYBACK_PLAYUNTIL: + case PLAYBACK_SAVE: + case PLAYBACK_LOAD: + TASmod.server.sendToAll(new TASmodBufferBuilder(buf)); + break; default: throw new PacketNotImplementedException(packet, this.getClass()); } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java index d51d9c74..734f6922 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java @@ -14,7 +14,7 @@ import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.util.LoggerMarkers; -import com.minecrafttas.tasmod.util.TickScheduler.TickTask; +import com.minecrafttas.tasmod.util.Scheduler.Task; import net.minecraft.client.Minecraft; import net.minecraft.util.text.TextComponentString; @@ -54,7 +54,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa case STATESYNC: boolean verbose = TASmodBufferBuilder.readBoolean(buf); - TickTask task = ()->{ + Task task = ()->{ PlaybackController container = TASmodClient.virtual.getContainer(); if (networkState != container.getState()) { diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index 91fc7845..6cd84976 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -41,6 +41,8 @@ */ public class SavestateHandlerClient implements ClientPacketHandler{ + public final static File savestateDirectory = new File(TASmodClient.tasdirectory + File.separator + "savestates"); + /** * A bug occurs when unloading the client world. The client world has a "unloadedEntityList" which, as the name implies, stores all unloaded entities
*
@@ -115,8 +117,6 @@ public static void savestate(String nameOfSavestate) throws SavestateException, } } - public final static File savestateDirectory = new File(TASmodClient.tasdirectory + File.separator + "savestates"); - /** * Replaces the current recording with the recording from the savestate. * Gets triggered when a savestate is loaded on the server
diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 853029e4..fa6d75cd 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -86,8 +86,7 @@ public class SavestateHandlerServer implements EventCompleteLoadstate, ServerPac private final Logger logger; public static boolean wasLoading; - public static Map motion = Maps.newHashMap(); - + /** * Creates a savestate handler on the specified server * @param logger @@ -167,7 +166,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex server = TASmod.getServerInstance(); // Get the motion from the client - SavestateHandlerServer.requestMotionFromClient(); + PlayerHandler.requestMotionFromClient(); // Save the world! server.getPlayerList().saveAllPlayerData(); @@ -368,9 +367,9 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex } // Unload chunks on the server - SavestateHandlerServer.disconnectPlayersFromChunkMap(server); - SavestateHandlerServer.unloadAllServerChunks(server); - SavestateHandlerServer.flushSaveHandler(server); + ChunkHandler.disconnectPlayersFromChunkMap(server); + ChunkHandler.unloadAllServerChunks(server); + ChunkHandler.flushSaveHandler(server); // Delete and copy directories FileUtils.deleteDirectory(currentfolder); @@ -380,11 +379,11 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex loadSavestateDataFile(); // Update the player and the client - SavestateHandlerServer.loadAndSendMotionToPlayer(server); + PlayerHandler.loadAndSendMotionToPlayer(server); // Update the session.lock file so minecraft behaves and saves the world - SavestateHandlerServer.updateSessionLock(server); + ChunkHandler.updateSessionLock(server); // Load the chunks and send them to the client - SavestateHandlerServer.addPlayersToChunkMap(server); + ChunkHandler.addPlayersToChunkMap(server); // Enable level saving again for (WorldServer world : server.worlds) { @@ -401,7 +400,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex // Add players to the chunk server.getPlayerList().getPlayers().forEach(player->{ - SavestateHandlerServer.addPlayerToServerChunk(player); + ChunkHandler.addPlayerToServerChunk(player); }); WorldServer[] worlds = server.worlds; @@ -681,10 +680,10 @@ public void onLoadstateComplete() { PlayerList playerList = TASmod.getServerInstance().getPlayerList(); for (EntityPlayerMP player : playerList.getPlayers()) { NBTTagCompound nbttagcompound = playerList.readPlayerDataFromFile(player); - SavestateHandlerServer.reattachEntityToPlayer(nbttagcompound, player.getServerWorld(), player); + PlayerHandler.reattachEntityToPlayer(nbttagcompound, player.getServerWorld(), player); } // Updating redstone component timers to the new world time (#136) - SavestateHandlerServer.updateWorldServerTickListEntries(); + ChunkHandler.updateWorldServerTickListEntries(); } @Environment(EnvType.CLIENT) @@ -721,60 +720,6 @@ public static enum SavestateState { NONE } - public static class Saver { - private double clientX; - private double clientY; - private double clientZ; - private float clientrX; - private float clientrY; - private float clientrZ; - private boolean sprinting; - private float jumpMovementVector; - - public Saver(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { - clientX = x; - clientY = y; - clientZ = z; - clientrX = rx; - clientrY = ry; - clientrZ = rz; - this.sprinting = sprinting; - this.jumpMovementVector = jumpMovementVector; - } - - public double getClientX() { - return clientX; - } - - public double getClientY() { - return clientY; - } - - public double getClientZ() { - return clientZ; - } - - public float getClientrX() { - return clientrX; - } - - public float getClientrY() { - return clientrY; - } - - public float getClientrZ() { - return clientrZ; - } - - public boolean isSprinting() { - return sprinting; - } - - public float getJumpMovementVector() { - return jumpMovementVector; - } - } - @Override public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] { @@ -830,7 +775,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa float rz = TASmodBufferBuilder.readFloat(buf); boolean sprinting = TASmodBufferBuilder.readBoolean(buf); float jumpMovementVector = TASmodBufferBuilder.readFloat(buf); - SavestateHandlerServer.getMotion().put(player, new SavestateHandlerServer.Saver(x, y, z, rx, ry, rz, sprinting, jumpMovementVector)); + PlayerHandler.getMotion().put(player, new PlayerHandler.Saver(x, y, z, rx, ry, rz, sprinting, jumpMovementVector)); break; case SAVESTATE_SCREEN: case SAVESTATE_UNLOAD_CHUNKS: @@ -841,283 +786,352 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } /** - * Tries to reattach the player to an entity, if the player was riding it it while savestating. - * - * Side: Server - * @param nbttagcompound where the ridden entity is saved - * @param worldserver that needs to spawn the entity - * @param playerIn that needs to ride the entity + * Contains player related classes */ - public static void reattachEntityToPlayer(NBTTagCompound nbttagcompound, World worldserver, Entity playerIn) { - if (nbttagcompound != null && nbttagcompound.hasKey("RootVehicle", 10)) - { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("RootVehicle"); - Entity entity1 = AnvilChunkLoader.readWorldEntity(nbttagcompound1.getCompoundTag("Entity"), worldserver, true); - - - if(entity1==null) { - for (Entity entity : worldserver.loadedEntityList) { - if(entity.getUniqueID().equals(nbttagcompound1.getUniqueId("Attach"))) entity1=entity; - } - } - - if (entity1 != null) - { - UUID uuid = nbttagcompound1.getUniqueId("Attach"); - - if (entity1.getUniqueID().equals(uuid)) - { - playerIn.startRiding(entity1, true); - } - else - { - for (Entity entity : entity1.getRecursivePassengers()) - { - if (entity.getUniqueID().equals(uuid)) - { - playerIn.startRiding(entity, true); - break; - } - } - } - - if (!playerIn.isRiding()) - { - TASmod.LOGGER.warn("Couldn't reattach entity to player"); - worldserver.removeEntityDangerously(entity1); - - for (Entity entity2 : entity1.getRecursivePassengers()) - { - worldserver.removeEntityDangerously(entity2); - } - } - } - } - else { - if(playerIn.isRiding()) { - playerIn.dismountRidingEntity(); + public static class PlayerHandler { + + public static class Saver { + private double clientX; + private double clientY; + private double clientZ; + private float clientrX; + private float clientrY; + private float clientrZ; + private boolean sprinting; + private float jumpMovementVector; + + public Saver(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { + clientX = x; + clientY = y; + clientZ = z; + clientrX = rx; + clientrY = ry; + clientrZ = rz; + this.sprinting = sprinting; + this.jumpMovementVector = jumpMovementVector; + } + + public double getClientX() { + return clientX; + } + + public double getClientY() { + return clientY; + } + + public double getClientZ() { + return clientZ; + } + + public float getClientrX() { + return clientrX; + } + + public float getClientrY() { + return clientrY; + } + + public float getClientrZ() { + return clientrZ; + } + + public boolean isSprinting() { + return sprinting; + } + + public float getJumpMovementVector() { + return jumpMovementVector; } } - } - /** - * Loads all worlds and players from the disk. Also sends the playerdata to the client in {@linkplain SavestatePlayerLoadingPacketHandler} - * - * Side: Server - */ - public static void loadAndSendMotionToPlayer(MinecraftServer server) { + /** + * Tries to reattach the player to an entity, if the player was riding it it while savestating. + * + * Side: Server + * @param nbttagcompound where the ridden entity is saved + * @param worldserver that needs to spawn the entity + * @param playerIn that needs to ride the entity + */ + public static void reattachEntityToPlayer(NBTTagCompound nbttagcompound, World worldserver, Entity playerIn) { + if (nbttagcompound != null && nbttagcompound.hasKey("RootVehicle", 10)) + { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("RootVehicle"); + Entity entity1 = AnvilChunkLoader.readWorldEntity(nbttagcompound1.getCompoundTag("Entity"), worldserver, true); + + + if(entity1==null) { + for (Entity entity : worldserver.loadedEntityList) { + if(entity.getUniqueID().equals(nbttagcompound1.getUniqueId("Attach"))) entity1=entity; + } + } + + if (entity1 != null) + { + UUID uuid = nbttagcompound1.getUniqueId("Attach"); - List players=server.getPlayerList().getPlayers(); - PlayerList list=server.getPlayerList(); + if (entity1.getUniqueID().equals(uuid)) + { + playerIn.startRiding(entity1, true); + } + else + { + for (Entity entity : entity1.getRecursivePassengers()) + { + if (entity.getUniqueID().equals(uuid)) + { + playerIn.startRiding(entity, true); + break; + } + } + } - WorldServer[] worlds=server.worlds; - for (WorldServer world : worlds) { - WorldInfo info=world.getSaveHandler().loadWorldInfo(); - world.worldInfo = info; + if (!playerIn.isRiding()) + { + TASmod.LOGGER.warn("Couldn't reattach entity to player"); + worldserver.removeEntityDangerously(entity1); + + for (Entity entity2 : entity1.getRecursivePassengers()) + { + worldserver.removeEntityDangerously(entity2); + } + } + } + } + else { + if(playerIn.isRiding()) { + playerIn.dismountRidingEntity(); + } + } } - for(EntityPlayerMP player : players) { - - int dimensionPrev=player.dimension; - - NBTTagCompound nbttagcompound = server.getPlayerList().readPlayerDataFromFile(player); + + /** + * Loads all worlds and players from the disk. Also sends the playerdata to the client in {@linkplain SavestatePlayerLoadingPacketHandler} + * + * Side: Server + */ + public static void loadAndSendMotionToPlayer(MinecraftServer server) { - int dimensionNow=0; - if (nbttagcompound.hasKey("Dimension")) - { - dimensionNow = nbttagcompound.getInteger("Dimension"); - } + List players=server.getPlayerList().getPlayers(); + PlayerList list=server.getPlayerList(); - if(dimensionNow!=dimensionPrev) { - list.changePlayerDimension(player, dimensionNow); - }else { - player.getServerWorld().unloadedEntityList.remove(player); + WorldServer[] worlds=server.worlds; + for (WorldServer world : worlds) { + WorldInfo info=world.getSaveHandler().loadWorldInfo(); + world.worldInfo = info; } - - player.readFromNBT(nbttagcompound); - - try { - TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER).writeNBTTagCompound(nbttagcompound)); - } catch (Exception e) { - e.printStackTrace(); + for(EntityPlayerMP player : players) { + + int dimensionPrev=player.dimension; + + NBTTagCompound nbttagcompound = server.getPlayerList().readPlayerDataFromFile(player); + + int dimensionNow=0; + if (nbttagcompound.hasKey("Dimension")) + { + dimensionNow = nbttagcompound.getInteger("Dimension"); + } + + if(dimensionNow!=dimensionPrev) { + list.changePlayerDimension(player, dimensionNow); + }else { + player.getServerWorld().unloadedEntityList.remove(player); + } + + player.readFromNBT(nbttagcompound); + + try { + TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER).writeNBTTagCompound(nbttagcompound)); + } catch (Exception e) { + e.printStackTrace(); + } } } - } - public static void requestMotionFromClient() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); - motion.clear(); - try { - // request client motion - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); - } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); - } - - // TODO: is this still necessary? - int i = 1; - while (motion.size() != TASmod.getServerInstance().getPlayerList().getCurrentPlayerCount()) { - i++; + public static void requestMotionFromClient() { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); + PlayerHandler.motion.clear(); try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); + // request client motion + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients:", e); } - if(i % 30 == 1) { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); + + // TODO: is this still necessary? + int i = 1; + while (PlayerHandler.motion.size() != TASmod.getServerInstance().getPlayerList().getCurrentPlayerCount()) { + i++; try { - // request client motion - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); - } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); } + if(i % 30 == 1) { + TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); + try { + // request client motion + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); + } catch (Exception e) { + TASmod.LOGGER.error("Unable to send packet to all clients:", e); + } + } + if (i == 1000) { + TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); + break; + } + } - if (i == 1000) { - TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); - break; - } - } - } - - public static Map getMotion() { - return motion; - } - /** - * Updates ticklist entries to the current world time, allowing them to not be stuck in a pressed state #136 - */ - public static void updateWorldServerTickListEntries() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); - MinecraftServer server=TASmod.getServerInstance(); - for (WorldServer world : server.worlds) { - for (NextTickListEntry nextticklistentry : world.pendingTickListEntriesHashSet) { - nextticklistentry.setScheduledTime(world.getTotalWorldTime()); - } + public static Map getMotion() { + return PlayerHandler.motion; } - } + public static Map motion = Maps.newHashMap(); + + } + /** - * Just like {@link SavestateHandlerClient#addPlayerToClientChunk(EntityPlayer)}, adds the player to the chunk on the server. - * This prevents the player from being able to place block inside of him - * - * Side: Server + * Contains static chunk actions, which can be triggered indiviadually for testing */ - public static void addPlayerToServerChunk(EntityPlayerMP player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); - int i = MathHelper.floor(player.posX / 16.0D); - int j = MathHelper.floor(player.posZ / 16.0D); - WorldServer world = player.getServerWorld(); - Chunk chunk = world.getChunkFromChunkCoords(i, j); - for (int k = 0; k < chunk.getEntityLists().length; k++) { - if (chunk.getEntityLists()[k].contains(player)) { - return; + public static class ChunkHandler{ + + /** + * Updates ticklist entries to the current world time, allowing them to not be stuck in a pressed state #136 + */ + public static void updateWorldServerTickListEntries() { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); + MinecraftServer server=TASmod.getServerInstance(); + for (WorldServer world : server.worlds) { + for (NextTickListEntry nextticklistentry : world.pendingTickListEntriesHashSet) { + nextticklistentry.setScheduledTime(world.getTotalWorldTime()); + } } } - chunk.addEntity(player); - } - /** - * The session lock is minecrafts failsafe system when it comes to saving. It prevents writing to the world folder from 2 different locations
- *
- * That works by storing system time to a session.lock file, when the server started. The integrated server also saves the time when it started in a variable.
- *
- * Those two times are then compared every time minecraft tries to save and fails if the times are different.
- *
- * Since we never close the integrated server, but copy an "old" session.lock file with the savestate, the session.lock will always mismatch.
- * Thus we need to update the session lock once the loadstating is completed
- *
- * TLDR:
- * Updates the session lock to allow for vanilla saving again
- *
- * Side: Server - */ - public static void updateSessionLock(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); - WorldServer[] worlds=server.worlds; - for(WorldServer world : worlds) { - ((SaveHandler) world.getSaveHandler()).setSessionLock(); + /** + * Just like {@link SavestateHandlerClient#addPlayerToClientChunk(EntityPlayer)}, adds the player to the chunk on the server. + * This prevents the player from being able to place block inside of him + * + * Side: Server + */ + public static void addPlayerToServerChunk(EntityPlayerMP player) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); + int i = MathHelper.floor(player.posX / 16.0D); + int j = MathHelper.floor(player.posZ / 16.0D); + WorldServer world = player.getServerWorld(); + Chunk chunk = world.getChunkFromChunkCoords(i, j); + for (int k = 0; k < chunk.getEntityLists().length; k++) { + if (chunk.getEntityLists()[k].contains(player)) { + return; + } + } + chunk.addEntity(player); + } + + /** + * The session lock is minecrafts failsafe system when it comes to saving. It prevents writing to the world folder from 2 different locations
+ *
+ * That works by storing system time to a session.lock file, when the server started. The integrated server also saves the time when it started in a variable.
+ *
+ * Those two times are then compared every time minecraft tries to save and fails if the times are different.
+ *
+ * Since we never close the integrated server, but copy an "old" session.lock file with the savestate, the session.lock will always mismatch.
+ * Thus we need to update the session lock once the loadstating is completed
+ *
+ * TLDR:
+ * Updates the session lock to allow for vanilla saving again
+ *
+ * Side: Server + */ + public static void updateSessionLock(MinecraftServer server) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); + WorldServer[] worlds=server.worlds; + for(WorldServer world : worlds) { + ((SaveHandler) world.getSaveHandler()).setSessionLock(); + } } - } - /** - * Tells the save handler to save all changes to disk and remove all references to the region files, making them editable on disc
- *
- * Side: Server - */ - public static void flushSaveHandler(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); - //Vanilla - WorldServer[] worlds=server.worlds; - for(WorldServer world : worlds) { - world.getSaveHandler().flush(); + /** + * Tells the save handler to save all changes to disk and remove all references to the region files, making them editable on disc
+ *
+ * Side: Server + */ + public static void flushSaveHandler(MinecraftServer server) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); + //Vanilla + WorldServer[] worlds=server.worlds; + for(WorldServer world : worlds) { + world.getSaveHandler().flush(); + } } - } - /** - * The player chunk map keeps track of which chunks need to be sent to the client.
- * This adds the player to the chunk map so the server knows it can send the information to the client
- *
- * Side: Server - * @see disconnectPlayersFromChunkMap - */ - public static void addPlayersToChunkMap(MinecraftServer server) { - List players=server.getPlayerList().getPlayers(); - //Vanilla - WorldServer[] worlds=server.worlds; - for (EntityPlayerMP player : players) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); - switch (player.dimension) { - case -1: - worlds[1].getPlayerChunkMap().addPlayer(player); - worlds[1].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); - break; - case 0: - worlds[0].getPlayerChunkMap().addPlayer(player); - worlds[0].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); - break; - case 1: - worlds[2].getPlayerChunkMap().addPlayer(player); - worlds[2].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); - break; + /** + * The player chunk map keeps track of which chunks need to be sent to the client.
+ * This adds the player to the chunk map so the server knows it can send the information to the client
+ *
+ * Side: Server + * @see disconnectPlayersFromChunkMap + */ + public static void addPlayersToChunkMap(MinecraftServer server) { + List players=server.getPlayerList().getPlayers(); + //Vanilla + WorldServer[] worlds=server.worlds; + for (EntityPlayerMP player : players) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); + switch (player.dimension) { + case -1: + worlds[1].getPlayerChunkMap().addPlayer(player); + worlds[1].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); + break; + case 0: + worlds[0].getPlayerChunkMap().addPlayer(player); + worlds[0].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); + break; + case 1: + worlds[2].getPlayerChunkMap().addPlayer(player); + worlds[2].getChunkProvider().provideChunk((int)player.posX >> 4, (int)player.posZ >> 4); + break; + } } } - } - /** - * The player chunk map keeps track of which chunks need to be sent to the client.
- * Removing the player stops the server from sending chunks to the client.
- *
- * Side: Server - * @see SavestatesChunkControl#addPlayersToChunkMap() - */ - public static void disconnectPlayersFromChunkMap(MinecraftServer server) { - List players=server.getPlayerList().getPlayers(); - //Vanilla - WorldServer[] worlds=server.worlds; - for (WorldServer world : worlds) { - for (EntityPlayerMP player : players) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); - world.getPlayerChunkMap().removePlayer(player); + /** + * The player chunk map keeps track of which chunks need to be sent to the client.
+ * Removing the player stops the server from sending chunks to the client.
+ *
+ * Side: Server + * @see SavestatesChunkControl#addPlayersToChunkMap() + */ + public static void disconnectPlayersFromChunkMap(MinecraftServer server) { + List players=server.getPlayerList().getPlayers(); + //Vanilla + WorldServer[] worlds=server.worlds; + for (WorldServer world : worlds) { + for (EntityPlayerMP player : players) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); + world.getPlayerChunkMap().removePlayer(player); + } } } - } - /** - * Unloads all chunks on the server
- *
- * Side: Server - * @see MixinChunkProviderServer#unloadAllChunks() - */ - public static void unloadAllServerChunks(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); - //Vanilla - WorldServer[] worlds=server.worlds; - - for (WorldServer world:worlds) { - ChunkProviderServer chunkProvider=world.getChunkProvider(); + /** + * Unloads all chunks on the server
+ *
+ * Side: Server + * @see MixinChunkProviderServer#unloadAllChunks() + */ + public static void unloadAllServerChunks(MinecraftServer server) { + TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); + //Vanilla + WorldServer[] worlds=server.worlds; + + for (WorldServer world:worlds) { + ChunkProviderServer chunkProvider=world.getChunkProvider(); + + ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); + } - ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); } - } } diff --git a/src/main/java/com/minecrafttas/tasmod/util/TickScheduler.java b/src/main/java/com/minecrafttas/tasmod/util/Scheduler.java similarity index 60% rename from src/main/java/com/minecrafttas/tasmod/util/TickScheduler.java rename to src/main/java/com/minecrafttas/tasmod/util/Scheduler.java index 1df52a54..fd13454b 100644 --- a/src/main/java/com/minecrafttas/tasmod/util/TickScheduler.java +++ b/src/main/java/com/minecrafttas/tasmod/util/Scheduler.java @@ -4,28 +4,28 @@ import java.util.concurrent.ConcurrentLinkedQueue; /** - * Schedules a lambda to be run in the next tick + * A simple scheduling interface * * @author Scribble * */ -public class TickScheduler { +public class Scheduler { - Queue queue = new ConcurrentLinkedQueue<>(); + Queue queue = new ConcurrentLinkedQueue<>(); public void runAllTasks() { - TickTask task; + Task task; while((task = queue.poll()) != null) { task.runTask(); } } - public void add(TickTask task) { + public void add(Task task) { queue.add(task); } @FunctionalInterface - public interface TickTask { + public interface Task { public void runTask(); } } diff --git a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java index 130b9dc3..425b245c 100644 --- a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java +++ b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java @@ -9,7 +9,6 @@ import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.events.OpenGuiEvents; import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; @@ -130,7 +129,7 @@ public VirtualInput(String fileToLoad) { if (fileToLoad != null) { try { loadInputs(fileToLoad); - OpenGuiEvents.stateWhenOpened = TASstate.PLAYBACK; + container.setStateWhenOpened(TASstate.PLAYBACK); } catch (IOException e) { TASmod.LOGGER.error("Cannot load inputs from the start of the TAS: {}", e.getMessage()); } From 9cc75c55f62e7820954ae0fb31b377a26497dea6 Mon Sep 17 00:00:00 2001 From: Scribble Date: Tue, 22 Aug 2023 20:37:29 +0200 Subject: [PATCH 25/60] Added logger as static import --- .../minecrafttas/common/server/Client.java | 11 +++-- .../com/minecrafttas/tasmod/TASmodClient.java | 4 +- .../tasmod/commands/CommandFolder.java | 6 ++- .../tasmod/events/EventServer.java | 11 ++--- .../tasmod/events/OpenGuiEvents.java | 7 +-- .../tasmod/handlers/LoadingScreenHandler.java | 8 ++-- .../tasmod/ktrng/KillTheRNGHandler.java | 6 ++- .../tasmod/playback/PlaybackController.java | 42 +++++++++--------- .../tasmod/playback/PlaybackSerialiser.java | 8 ++-- .../tasmod/playback/TASstateClient.java | 5 ++- .../tasmod/playback/TASstateServer.java | 4 +- .../savestates/SavestateHandlerClient.java | 21 ++++----- .../savestates/SavestateHandlerServer.java | 44 ++++++++++--------- .../TickrateChangerClient.java | 5 ++- .../tasmod/ticksync/TickSyncClient.java | 5 ++- .../tasmod/ticksync/TickSyncServer.java | 5 ++- .../tasmod/util/LoggerMarkers.java | 2 +- .../tasmod/virtual/VirtualInput.java | 7 +-- 18 files changed, 113 insertions(+), 88 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index ffa68bd5..242ae657 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -1,7 +1,6 @@ package com.minecrafttas.common.server; import static com.minecrafttas.common.server.SecureList.BUFFER_SIZE; -import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.io.IOException; import java.net.InetSocketAddress; @@ -51,7 +50,7 @@ public enum Side { * @throws Exception Unable to connect */ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exception { - LOGGER.info("Connecting tasmod server to {}:{}", host, port); + Common.LOGGER.info("Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); @@ -59,7 +58,7 @@ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exc this.packetIDs = packetIDs; this.createHandlers(); - Common.LOGGER.info("Connected to tasmod server"); + Common.LOGGER.info("Connected to server"); authenticate(uuid); } @@ -167,7 +166,7 @@ public void close() throws IOException { // String name = new String(nameBytes); // InputSavestatesHandler.savestate(name); // } catch (Exception e) { -// TASmod.LOGGER.error("Exception occured during input savestate:", e); +// LOGGER.error("Exception occured during input savestate:", e); // } // }), // CLOSE_GUISAVESTATESCREEN_ON_CLIENTS((pid, buf, id) -> { @@ -184,7 +183,7 @@ public void close() throws IOException { // String name = new String(nameBytes); // InputSavestatesHandler.loadstate(name); // } catch (Exception e) { -// TASmod.LOGGER.error("Exception occured during input loadstate:", e); +// LOGGER.error("Exception occured during input loadstate:", e); // } // }), // UNLOAD_CHUNKS_ON_CLIENTS((pid, buf, id) -> @@ -205,7 +204,7 @@ public void close() throws IOException { // .putFloat(player.jumpMovementFactor) // ); // } catch (Exception e) { -// TASmod.LOGGER.error("Unable to send packet to server:", e); +// LOGGER.error("Unable to send packet to server:", e); // } // } // }); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 41c1388c..c42462e3 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -152,7 +154,7 @@ protected boolean isKeyDown(KeyBinding i) { // connect to server and authenticate client = new Client("127.0.0.1", 5555, TASmodPackets.values(), uuid); } catch (Exception e) { - TASmod.LOGGER.error("Unable to connect TASmod client: {}", e); + LOGGER.error("Unable to connect TASmod client: {}", e); } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java index 787d19fb..3642126f 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFolder.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.commands; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.awt.Desktop; import java.io.File; import java.io.IOException; @@ -70,7 +72,7 @@ public static void openTASFolder() { file.mkdir(); Desktop.getDesktop().open(file); } catch (IOException e) { - TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); + LOGGER.error("Something went wrong while opening ", file.getPath()); e.printStackTrace(); } } @@ -82,7 +84,7 @@ public static void openSavestates() { file.mkdir(); Desktop.getDesktop().open(file); } catch (IOException e) { - TASmod.LOGGER.error("Something went wrong while opening ", file.getPath()); + LOGGER.error("Something went wrong while opening ", file.getPath()); e.printStackTrace(); } } diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java index def054c2..9d115509 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java @@ -1,9 +1,10 @@ package com.minecrafttas.tasmod.events; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import com.minecrafttas.common.events.EventListenerRegistry.EventBase; -import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.server.MinecraftServer; @@ -26,7 +27,7 @@ public static interface EventSavestate extends EventBase { public void onSavestateEvent(int index, File target, File current); public static void fireSavestateEvent(int index, File target, File current) { - TASmod.LOGGER.trace(LoggerMarkers.Event, "SavestateEvent {} {} {}", index, target, current); + LOGGER.trace(LoggerMarkers.Event, "SavestateEvent {} {} {}", index, target, current); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventSavestate) { EventSavestate event = (EventSavestate) eventListener; @@ -52,7 +53,7 @@ public static interface EventLoadstate extends EventBase { public void onLoadstateEvent(int index, File target, File current); public static void fireLoadstateEvent(int index, File target, File current) { - TASmod.LOGGER.trace(LoggerMarkers.Event, "LoadstateEvent {} {} {}", index, target, current); + LOGGER.trace(LoggerMarkers.Event, "LoadstateEvent {} {} {}", index, target, current); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventLoadstate) { EventLoadstate event = (EventLoadstate) eventListener; @@ -76,7 +77,7 @@ public static interface EventCompleteLoadstate extends EventBase{ public void onLoadstateComplete(); public static void fireLoadstateComplete() { - TASmod.LOGGER.trace(LoggerMarkers.Event, "LoadstateCompleteEvent"); + LOGGER.trace(LoggerMarkers.Event, "LoadstateCompleteEvent"); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventCompleteLoadstate) { EventCompleteLoadstate event = (EventCompleteLoadstate) eventListener; @@ -99,7 +100,7 @@ public static interface EventServerTickPost extends EventBase{ public void onServerTickPost(MinecraftServer minecraftServer); public static void fireServerTickPost(MinecraftServer minecraftServer) { - TASmod.LOGGER.trace(LoggerMarkers.Event, "ServerTickPostEvent"); + LOGGER.trace(LoggerMarkers.Event, "ServerTickPostEvent"); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventServerTickPost) { EventServerTickPost event = (EventServerTickPost) eventListener; diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java index d2c3cdbb..535ef209 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java @@ -1,6 +1,7 @@ package com.minecrafttas.tasmod.events; -import com.minecrafttas.tasmod.TASmod; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; import com.minecrafttas.tasmod.playback.TASstateClient; @@ -41,7 +42,7 @@ public static void openGuiIngameMenu(GuiIngameMenu guiIngameMenu) { */ public static void openGuiControls(GuiControls guiControls) { if (TASmodClient.tickratechanger.ticksPerSecond == 0 || TASmodClient.tickratechanger.advanceTick) { - TASmod.LOGGER.info("Pausing game during GuiControls"); + LOGGER.info("Pausing game during GuiControls"); TASmodClient.tickratechanger.pauseGame(false); TASstateClient.setOrSend(stateWhenOpened); waszero = true; @@ -55,7 +56,7 @@ public static void openGuiControls(GuiControls guiControls) { */ public static void closeGuiControls(GuiControls guiControls) { if (waszero) { - TASmod.LOGGER.info("Unpausing the game again"); + LOGGER.info("Unpausing the game again"); waszero = false; TASmodClient.tickratechanger.pauseGame(true); } diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java index 09234a50..bccc9940 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.handlers; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import com.minecrafttas.common.events.EventClient.EventClientGameLoop; import com.minecrafttas.common.events.EventClient.EventDoneLoadingWorld; import com.minecrafttas.common.events.EventClient.EventLaunchIntegratedServer; @@ -24,7 +26,7 @@ public class LoadingScreenHandler implements EventLaunchIntegratedServer, EventC @Override public void onLaunchIntegratedServer() { - TASmod.LOGGER.debug(LoggerMarkers.Event, "Starting the integrated server"); + LOGGER.debug(LoggerMarkers.Event, "Starting the integrated server"); PlaybackController container = TASmodClient.virtual.getContainer(); if(!container.isNothingPlaying() && !container.isPaused()) { container.pause(true); @@ -39,7 +41,7 @@ public void onLaunchIntegratedServer() { public void onRunClientGameLoop(Minecraft mc) { if (loadingScreenDelay > -1) { if (loadingScreenDelay == 0) { - TASmod.LOGGER.debug(LoggerMarkers.Event, "Finished loading screen on the client"); + LOGGER.debug(LoggerMarkers.Event, "Finished loading screen on the client"); TASmodClient.tickratechanger.joinServer(); if (!waszero) { if(TASmod.getServerInstance()!=null) { //Check if a server is running and if it's an integrated server @@ -58,7 +60,7 @@ public void onRunClientGameLoop(Minecraft mc) { @Override public void onDoneLoadingWorld() { if(TASmod.getServerInstance()!=null) { //Check if a server is running and if it's an integrated server - TASmod.LOGGER.debug(LoggerMarkers.Event, "Finished loading the world on the client"); + LOGGER.debug(LoggerMarkers.Event, "Finished loading the world on the client"); loadingScreenDelay = 1; } } diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index 3a4c36bd..f70fb1ed 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.ktrng; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.nio.ByteBuffer; import java.util.UUID; @@ -48,7 +50,7 @@ public KillTheRNGHandler(boolean isLoaded) { KillTheRNG.annotations.register(new KTRNGMonitor()); }else { - TASmod.LOGGER.info("KillTheRNG doesn't appear to be loaded"); + LOGGER.info("KillTheRNG doesn't appear to be loaded"); } } @@ -152,7 +154,7 @@ public void broadcastStartSeed() { @Environment(EnvType.CLIENT) public void setInitialSeed(long initialSeed) { if(TASmodClient.client != null) { - TASmod.LOGGER.info("Sending initial client seed: {}", initialSeed); + LOGGER.info("Sending initial client seed: {}", initialSeed); try { TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_STARTSEED).writeLong(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 4a61199c..4f24ff5c 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.playback; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import java.io.IOException; import java.io.Serializable; @@ -159,7 +161,7 @@ public String setTASState(TASstate stateIn, boolean verbose) { } else if (state == TASstate.NONE) { // If the container is currently doing nothing switch (stateIn) { case PLAYBACK: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Starting playback"); + LOGGER.debug(LoggerMarkers.Playback, "Starting playback"); if (Minecraft.getMinecraft().player != null && !startLocation.isEmpty()) { try { tpPlayer(startLocation); @@ -176,7 +178,7 @@ public String setTASState(TASstate stateIn, boolean verbose) { TASmod.ktrngHandler.setInitialSeed(startSeed); return verbose ? TextFormatting.GREEN + "Starting playback" : ""; case RECORDING: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Starting recording"); + LOGGER.debug(LoggerMarkers.Playback, "Starting recording"); if (Minecraft.getMinecraft().player != null && startLocation.isEmpty()) { startLocation = getStartLocation(Minecraft.getMinecraft().player); } @@ -198,12 +200,12 @@ public String setTASState(TASstate stateIn, boolean verbose) { case RECORDING: return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Recording)"; case PAUSED: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Pausing a recording"); + LOGGER.debug(LoggerMarkers.Playback, "Pausing a recording"); state = TASstate.PAUSED; tempPause = TASstate.RECORDING; return verbose ? TextFormatting.GREEN + "Pausing a recording" : ""; case NONE: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Stopping a recording"); + LOGGER.debug(LoggerMarkers.Playback, "Stopping a recording"); TASmodClient.virtual.unpressEverything(); state = TASstate.NONE; return verbose ? TextFormatting.GREEN + "Stopping the recording" : ""; @@ -215,13 +217,13 @@ public String setTASState(TASstate stateIn, boolean verbose) { case RECORDING: return verbose ? TextFormatting.RED + "A playback is currently running. Please stop the playback first before starting a recording" : ""; case PAUSED: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Pausing a playback"); + LOGGER.debug(LoggerMarkers.Playback, "Pausing a playback"); state = TASstate.PAUSED; tempPause = TASstate.PLAYBACK; TASmodClient.virtual.unpressEverything(); return verbose ? TextFormatting.GREEN + "Pausing a playback" : ""; case NONE: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Stopping a playback"); + LOGGER.debug(LoggerMarkers.Playback, "Stopping a playback"); Minecraft.getMinecraft().gameSettings.chatLinks = true; TASmodClient.virtual.unpressEverything(); state = TASstate.NONE; @@ -230,19 +232,19 @@ public String setTASState(TASstate stateIn, boolean verbose) { } else if (state == TASstate.PAUSED) { switch (stateIn) { case PLAYBACK: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Resuming a playback"); + LOGGER.debug(LoggerMarkers.Playback, "Resuming a playback"); state=TASstate.PLAYBACK; tempPause=TASstate.NONE; return verbose ? TextFormatting.GREEN + "Resuming a playback" : ""; case RECORDING: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Resuming a recording"); + LOGGER.debug(LoggerMarkers.Playback, "Resuming a recording"); state=TASstate.RECORDING; tempPause=TASstate.NONE; return verbose ? TextFormatting.GREEN + "Resuming a recording" : ""; case PAUSED: return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Paused)"; case NONE: - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Aborting pausing"); + LOGGER.debug(LoggerMarkers.Playback, "Aborting pausing"); state=TASstate.NONE; TASstate statey=tempPause; tempPause=TASstate.NONE; @@ -270,7 +272,7 @@ public TASstate togglePause() { * @param pause True, if it should be paused */ public void pause(boolean pause) { - TASmod.LOGGER.trace(LoggerMarkers.Playback, "Pausing {}", pause); + LOGGER.trace(LoggerMarkers.Playback, "Pausing {}", pause); if(pause) { if(state!=TASstate.NONE) { setTASState(TASstate.PAUSED, false); @@ -397,7 +399,7 @@ private void recordNextTick() { index++; if(inputs.size()<=index) { if(inputs.size()(directory + File.separator + "temp"); controlBytes.clear(); comments.clear(); @@ -604,7 +606,7 @@ public String getStartLocation() { * @param startLocation The start location of the TAS */ public void setStartLocation(String startLocation) { - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Setting start location"); + LOGGER.debug(LoggerMarkers.Playback, "Setting start location"); this.startLocation = startLocation; } @@ -615,7 +617,7 @@ public void setStartLocation(String startLocation) { * @return The start location from the player */ private String getStartLocation(EntityPlayerSP player) { - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Retrieving player start location"); + LOGGER.debug(LoggerMarkers.Playback, "Retrieving player start location"); String pos = player.posX + "," + player.posY + "," + player.posZ; String pitch = Float.toString(player.rotationPitch); String yaw = Float.toString(player.rotationYaw); @@ -630,7 +632,7 @@ private String getStartLocation(EntityPlayerSP player) { * @throws NumberFormatException If the location can't be parsed */ private void tpPlayer(String startLocation) throws NumberFormatException { - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Teleporting the player to the start location"); + LOGGER.debug(LoggerMarkers.Playback, "Teleporting the player to the start location"); String[] section = startLocation.split(","); double x = Double.parseDouble(section[0]); double y = Double.parseDouble(section[1]); @@ -658,7 +660,7 @@ private void tpPlayer(String startLocation) throws NumberFormatException { * Clears {@link #keyboard} and {@link #mouse} */ public void unpressContainer() { - TASmod.LOGGER.trace(LoggerMarkers.Playback, "Unpressing container"); + LOGGER.trace(LoggerMarkers.Playback, "Unpressing container"); keyboard.clear(); mouse.clear(); } @@ -666,7 +668,7 @@ public void unpressContainer() { // ============================================================== public void printCredits() { - TASmod.LOGGER.trace(LoggerMarkers.Playback, "Printing credits"); + LOGGER.trace(LoggerMarkers.Playback, "Printing credits"); if (state == TASstate.PLAYBACK&&!creditsPrinted) { creditsPrinted=true; printMessage(title, ChatFormatting.GOLD); @@ -830,7 +832,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa if (mc.world != null) mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Saved inputs to " + name + ".mctas")); else - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Saved inputs to " + name + ".mctas"); + LOGGER.debug(LoggerMarkers.Playback, "Saved inputs to " + name + ".mctas"); break; case PLAYBACK_LOAD: @@ -847,7 +849,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa if (mc.world != null) mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Loaded inputs from " + name + ".mctas")); else - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Loaded inputs from " + name + ".mctas"); + LOGGER.debug(LoggerMarkers.Playback, "Loaded inputs from " + name + ".mctas"); break; case PLAYBACK_FULLPLAY: diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java index e696ba5c..25cbda2b 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.playback; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -97,7 +99,7 @@ public void saveToFileV1(File file, PlaybackController container) throws IOExcep * @throws IOException When the input container is empty */ public void saveToFileV1Until(File file, PlaybackController container, int index) throws IOException{ - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Saving playback controller to file {}", file); + LOGGER.debug(LoggerMarkers.Playback, "Saving playback controller to file {}", file); if (container.size() == 0) { throw new IOException("There are no inputs to save to a file"); } @@ -163,7 +165,7 @@ public void saveToFileV1Until(File file, PlaybackController container, int index } public int getFileVersion(File file) throws IOException { - TASmod.LOGGER.trace(LoggerMarkers.Playback, "Retrieving file version from {}", file); + LOGGER.trace(LoggerMarkers.Playback, "Retrieving file version from {}", file); List lines = FileUtils.readLines(file, Charset.defaultCharset()); for (String line : lines) { if (line.contains("Version")) { @@ -181,7 +183,7 @@ public int getFileVersion(File file) throws IOException { } public PlaybackController fromEntireFileV1(File file) throws IOException { - TASmod.LOGGER.debug(LoggerMarkers.Playback, "Loading playback controller to file {}", file); + LOGGER.debug(LoggerMarkers.Playback, "Loading playback controller to file {}", file); List lines = FileUtils.readLines(file, StandardCharsets.UTF_8); File monitorFile=new File(file, "../"+file.getName().replace(".mctas", "")+".mon"); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java index 734f6922..95704561 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.playback; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.nio.ByteBuffer; import java.util.UUID; @@ -8,7 +10,6 @@ import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; @@ -64,7 +65,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa if(Minecraft.getMinecraft().world != null) Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(message)); else - TASmod.LOGGER.debug(LoggerMarkers.Playback, message); + LOGGER.debug(LoggerMarkers.Playback, message); } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java index 30176ad3..dc2f73dc 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.playback; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.nio.ByteBuffer; import java.util.UUID; @@ -98,7 +100,7 @@ public void setServerState(TASstate stateIn) { return; } this.state = stateIn; - TASmod.LOGGER.info(String.format("Set the server state to %s", stateIn.toString())); + LOGGER.info(String.format("Set the server state to %s", stateIn.toString())); } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index 6cd84976..53023225 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.savestates; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; @@ -9,7 +11,6 @@ import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; @@ -57,7 +58,7 @@ public class SavestateHandlerClient implements ClientPacketHandler{ */ @Environment(EnvType.CLIENT) public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.EntityPlayer player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Keep player {} in loaded entity list", player.getName()); + LOGGER.trace(LoggerMarkers.Savestate, "Keep player {} in loaded entity list", player.getName()); Minecraft.getMinecraft().world.unloadedEntityList.remove(player); } @@ -77,7 +78,7 @@ public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.Enti */ @Environment(EnvType.CLIENT) public static void addPlayerToClientChunk(EntityPlayer player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to loaded entity list", player.getName()); + LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to loaded entity list", player.getName()); int i = MathHelper.floor(player.posX / 16.0D); int j = MathHelper.floor(player.posZ / 16.0D); Chunk chunk = Minecraft.getMinecraft().world.getChunkFromChunkCoords(i, j); @@ -99,9 +100,9 @@ public static void addPlayerToClientChunk(EntityPlayer player) { * @throws IOException */ public static void savestate(String nameOfSavestate) throws SavestateException, IOException { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Saving client savestate {}", nameOfSavestate); + LOGGER.debug(LoggerMarkers.Savestate, "Saving client savestate {}", nameOfSavestate); if (nameOfSavestate.isEmpty()) { - TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); + LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); return; } @@ -126,9 +127,9 @@ public static void savestate(String nameOfSavestate) throws SavestateException, * @throws IOException */ public static void loadstate(String nameOfSavestate) throws IOException { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Loading client savestate {}", nameOfSavestate); + LOGGER.debug(LoggerMarkers.Savestate, "Loading client savestate {}", nameOfSavestate); if (nameOfSavestate.isEmpty()) { - TASmod.LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); + LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); return; } @@ -144,7 +145,7 @@ public static void loadstate(String nameOfSavestate) throws IOException { TASmodClient.virtual.getContainer().setTASState(TASstate.NONE, false); Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); - TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); + LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); } } } @@ -195,7 +196,7 @@ public static void loadPlayer(NBTTagCompound compound) { */ @Environment(EnvType.CLIENT) public static void unloadAllClientChunks() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); + LOGGER.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); Minecraft mc = Minecraft.getMinecraft(); ChunkProviderClient chunkProvider=mc.world.getChunkProvider(); @@ -228,7 +229,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa try { SavestateHandlerClient.savestate(name); } catch (SavestateException e) { - TASmod.LOGGER.error(e.getMessage()); + LOGGER.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index fa6d75cd..ee36f433 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.savestates; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import java.io.FileFilter; import java.io.IOException; @@ -150,7 +152,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex // Open GuiSavestateScreen TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SCREEN).writeBoolean(true)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } // Lock savestating and loadstating @@ -213,7 +215,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex // savestate inputs client TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SAVE).writeString(getSavestateName(indexToSave))); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } } @@ -242,7 +244,7 @@ public void saveState(int savestateIndex, boolean tickrate0, boolean changeIndex // close GuiSavestateScreen TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SCREEN).writeBoolean(false)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } if (!tickrate0) { @@ -348,7 +350,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex // loadstate inputs client TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_LOAD).writeString(getSavestateName(savestateIndex))); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } } @@ -363,7 +365,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex // unload chunks on client TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_UNLOAD_CHUNKS)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } // Unload chunks on the server @@ -676,7 +678,7 @@ public int getCurrentIndex() { @Override public void onLoadstateComplete() { - TASmod.LOGGER.trace(LoggerMarkers.Event, "Running loadstate complete event"); + logger.trace(LoggerMarkers.Event, "Running loadstate complete event"); PlayerList playerList = TASmod.getServerInstance().getPlayerList(); for (EntityPlayerMP player : playerList.getPlayers()) { NBTTagCompound nbttagcompound = playerList.readPlayerDataFromFile(player); @@ -753,12 +755,12 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa if(player!=null) player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getMessage())); - TASmod.LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: "+ e.getMessage()); + LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: "+ e.getMessage()); } catch (Exception e) { if(player!=null) player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getCause().toString())); - TASmod.LOGGER.error(e); + LOGGER.error(e); } finally { TASmod.savestateHandler.state=SavestateState.NONE; } @@ -887,7 +889,7 @@ public static void reattachEntityToPlayer(NBTTagCompound nbttagcompound, World w if (!playerIn.isRiding()) { - TASmod.LOGGER.warn("Couldn't reattach entity to player"); + LOGGER.warn("Couldn't reattach entity to player"); worldserver.removeEntityDangerously(entity1); for (Entity entity2 : entity1.getRecursivePassengers()) @@ -948,13 +950,13 @@ public static void loadAndSendMotionToPlayer(MinecraftServer server) { } public static void requestMotionFromClient() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); + LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); PlayerHandler.motion.clear(); try { // request client motion TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + e.printStackTrace(); } // TODO: is this still necessary? @@ -967,16 +969,16 @@ public static void requestMotionFromClient() { e.printStackTrace(); } if(i % 30 == 1) { - TASmod.LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); + LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); try { // request client motion TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + LOGGER.error("Unable to send packet to all clients:", e); } } if (i == 1000) { - TASmod.LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); + LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); break; } @@ -1000,7 +1002,7 @@ public static class ChunkHandler{ * Updates ticklist entries to the current world time, allowing them to not be stuck in a pressed state #136 */ public static void updateWorldServerTickListEntries() { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); + LOGGER.trace(LoggerMarkers.Savestate, "Update server tick list entries"); MinecraftServer server=TASmod.getServerInstance(); for (WorldServer world : server.worlds) { for (NextTickListEntry nextticklistentry : world.pendingTickListEntriesHashSet) { @@ -1016,7 +1018,7 @@ public static void updateWorldServerTickListEntries() { * Side: Server */ public static void addPlayerToServerChunk(EntityPlayerMP player) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); + LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to server chunk", player.getName()); int i = MathHelper.floor(player.posX / 16.0D); int j = MathHelper.floor(player.posZ / 16.0D); WorldServer world = player.getServerWorld(); @@ -1045,7 +1047,7 @@ public static void addPlayerToServerChunk(EntityPlayerMP player) { * Side: Server */ public static void updateSessionLock(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); + LOGGER.trace(LoggerMarkers.Savestate, "Update the session lock"); WorldServer[] worlds=server.worlds; for(WorldServer world : worlds) { ((SaveHandler) world.getSaveHandler()).setSessionLock(); @@ -1058,7 +1060,7 @@ public static void updateSessionLock(MinecraftServer server) { * Side: Server */ public static void flushSaveHandler(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); + LOGGER.trace(LoggerMarkers.Savestate, "Flush the save handler"); //Vanilla WorldServer[] worlds=server.worlds; for(WorldServer world : worlds) { @@ -1078,7 +1080,7 @@ public static void addPlayersToChunkMap(MinecraftServer server) { //Vanilla WorldServer[] worlds=server.worlds; for (EntityPlayerMP player : players) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); + LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); switch (player.dimension) { case -1: worlds[1].getPlayerChunkMap().addPlayer(player); @@ -1109,7 +1111,7 @@ public static void disconnectPlayersFromChunkMap(MinecraftServer server) { WorldServer[] worlds=server.worlds; for (WorldServer world : worlds) { for (EntityPlayerMP player : players) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); + LOGGER.trace(LoggerMarkers.Savestate, "Disconnect player {} from the chunk map", player.getName()); world.getPlayerChunkMap().removePlayer(player); } } @@ -1122,7 +1124,7 @@ public static void disconnectPlayersFromChunkMap(MinecraftServer server) { * @see MixinChunkProviderServer#unloadAllChunks() */ public static void unloadAllServerChunks(MinecraftServer server) { - TASmod.LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); + LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); //Vanilla WorldServer[] worlds=server.worlds; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index da8c552b..9d32235d 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.tickratechanger; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.nio.ByteBuffer; import java.util.UUID; @@ -8,7 +10,6 @@ import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; @@ -200,7 +201,7 @@ public void joinServer() { } private static void log(String msg) { - TASmod.LOGGER.debug(LoggerMarkers.Tickrate, msg); + LOGGER.debug(LoggerMarkers.Tickrate, msg); } @Override diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index f0f495d6..aa3d5801 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -1,12 +1,13 @@ package com.minecrafttas.tasmod.ticksync; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.nio.ByteBuffer; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; @@ -59,7 +60,7 @@ public void onClientTickPost(Minecraft mc) { try { TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to server:", e); + LOGGER.error("Unable to send packet to server:", e); } } } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index a7c8ee61..b72001b0 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -1,5 +1,8 @@ package com.minecrafttas.tasmod.ticksync; + +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; @@ -78,7 +81,7 @@ public void onServerTickPost(MinecraftServer server) { try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { - TASmod.LOGGER.error("Unable to send packet to all clients:", e); + LOGGER.error("Unable to send packet to all clients:", e); } if(synchronizedList.size()>0) synchronizedList.clear(); diff --git a/src/main/java/com/minecrafttas/tasmod/util/LoggerMarkers.java b/src/main/java/com/minecrafttas/tasmod/util/LoggerMarkers.java index 5d06536f..c0fb439f 100644 --- a/src/main/java/com/minecrafttas/tasmod/util/LoggerMarkers.java +++ b/src/main/java/com/minecrafttas/tasmod/util/LoggerMarkers.java @@ -7,7 +7,7 @@ *

A list of Log4J markers which can be added to logging statements. * *

Simply add the marker as the first argument: - *

TASmod.logger.info({@linkplain LoggerMarkers}.{@link #Event}, "Message");
+ *
LOGGER.info({@linkplain LoggerMarkers}.{@link #Event}, "Message");
* *

You can then turn off log messages by adding a VM option to your run configuration: *

-Dtasmod.marker.event=DENY
diff --git a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java index 425b245c..e6bf1c5c 100644 --- a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java +++ b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java @@ -1,5 +1,7 @@ package com.minecrafttas.tasmod.virtual; +import static com.minecrafttas.tasmod.TASmod.LOGGER; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -7,7 +9,6 @@ import java.util.List; import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; -import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; @@ -131,7 +132,7 @@ public VirtualInput(String fileToLoad) { loadInputs(fileToLoad); container.setStateWhenOpened(TASstate.PLAYBACK); } catch (IOException e) { - TASmod.LOGGER.error("Cannot load inputs from the start of the TAS: {}", e.getMessage()); + LOGGER.error("Cannot load inputs from the start of the TAS: {}", e.getMessage()); } } } @@ -531,7 +532,7 @@ private void preloadInput(PlaybackController container, int index) { // "currentKeyboard" Minecraft.getMinecraft().runTickMouse(); } else { - TASmod.LOGGER.warn("Can't preload inputs, specified inputs are null!"); + LOGGER.warn("Can't preload inputs, specified inputs are null!"); } } // ================================Load/Save Inputs===================================== From b4c0c3a90514336db4a4ba3cc5d0ca7940836b60 Mon Sep 17 00:00:00 2001 From: Scribble Date: Tue, 22 Aug 2023 21:51:30 +0200 Subject: [PATCH 26/60] Changed default port, added static import for logger - Added *proper* logging in PacketHandlerRegistry - Removed serial verion id --- .../minecrafttas/common/server/PacketHandlerRegistry.java | 5 +++-- .../common/server/exception/InvalidPacketException.java | 6 +----- .../server/exception/PacketNotImplementedException.java | 3 +-- src/main/java/com/minecrafttas/tasmod/TASmod.java | 7 ++++--- src/main/java/com/minecrafttas/tasmod/TASmodClient.java | 4 ++-- .../tasmod/tickratechanger/TickrateChangerClient.java | 8 +------- 6 files changed, 12 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java index 63df8c43..e5110386 100644 --- a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java +++ b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java @@ -7,6 +7,7 @@ import org.apache.commons.lang3.ArrayUtils; +import com.minecrafttas.common.Common; import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; @@ -22,7 +23,7 @@ public static void register(PacketHandlerBase handler) { if (!REGISTRY.contains(handler)) { REGISTRY.add(handler); } else { - System.out.println("Warning..."); + Common.LOGGER.warn("Trying to register packet handler {}, but it is already registered!", handler.getClass().getName()); } } @@ -30,7 +31,7 @@ public static void unregister(PacketHandlerBase handler) { if (REGISTRY.contains(handler)) { REGISTRY.remove(handler); } else { - System.out.println("Warning..."); + Common.LOGGER.warn("Trying to unregister packet handler {}, but is was not registered!", handler.getClass().getName()); } } diff --git a/src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java b/src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java index 6176afa5..b7d04661 100644 --- a/src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/InvalidPacketException.java @@ -1,12 +1,8 @@ package com.minecrafttas.common.server.exception; +@SuppressWarnings("serial") public class InvalidPacketException extends Exception { - /** - * - */ - private static final long serialVersionUID = 5253939281926562204L; - public InvalidPacketException() { super(); } diff --git a/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java index a67b4189..3b00ca4c 100644 --- a/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java @@ -3,10 +3,9 @@ import com.minecrafttas.common.server.interfaces.PacketHandlerBase; import com.minecrafttas.common.server.interfaces.PacketID; +@SuppressWarnings("serial") public class PacketNotImplementedException extends Exception { - private static final long serialVersionUID = -8089503724361521594L; - public PacketNotImplementedException(String msg) { super(msg); } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index dbffee25..9a1f52e0 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -63,6 +63,8 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static final Scheduler tickSchedulerServer = new Scheduler(); public static Server server; + + public static int networkingport = 8999; @Override public void onServerInit(MinecraftServer server) { @@ -168,10 +170,9 @@ public void onInitialize() { // PacketSerializer.registerPacket(PlayUntilPacket.class); try { - server = new Server(5555, TASmodPackets.values()); + server = new Server(networkingport, TASmodPackets.values()); } catch (Exception e) { - LOGGER.error("Unable to launch TASmod server: {}", e); + LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); } - } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index c42462e3..f02bdc51 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -152,9 +152,9 @@ protected boolean isKeyDown(KeyBinding i) { if (uuid == null) // dev environment uuid = UUID.randomUUID(); // connect to server and authenticate - client = new Client("127.0.0.1", 5555, TASmodPackets.values(), uuid); + client = new Client("127.0.0.1", TASmod.networkingport, TASmodPackets.values(), uuid); } catch (Exception e) { - LOGGER.error("Unable to connect TASmod client: {}", e); + LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index 9d32235d..eb679ab7 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -5,7 +5,6 @@ import java.nio.ByteBuffer; import java.util.UUID; -import com.minecrafttas.common.events.EventClient.EventClientGameLoop; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; @@ -23,7 +22,7 @@ * @author Scribble * */ -public class TickrateChangerClient implements EventClientGameLoop, ClientPacketHandler{ +public class TickrateChangerClient implements ClientPacketHandler{ /** * The current tickrate of the client */ @@ -204,11 +203,6 @@ private static void log(String msg) { LOGGER.debug(LoggerMarkers.Tickrate, msg); } - @Override - public void onRunClientGameLoop(Minecraft mc) { - - } - @Override public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] { From 58a577e17ad60f1f754445b4888222f4f5e1727f Mon Sep 17 00:00:00 2001 From: Scribble Date: Wed, 23 Aug 2023 21:43:04 +0200 Subject: [PATCH 27/60] Implementing tickrate packets, registering packet handlers --- .../java/com/minecrafttas/tasmod/TASmod.java | 2 + .../com/minecrafttas/tasmod/TASmodClient.java | 2 + .../networking/TASmodBufferBuilder.java | 2 +- .../TickrateChangerClient.java | 29 +++++++++++++ .../TickrateChangerServer.java | 43 ++++++++++++++++--- 5 files changed, 71 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 9a1f52e0..5d49f574 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -130,9 +130,11 @@ public void onInitialize() { LOGGER.info("Testing connection with KillTheRNG"); ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); EventListenerRegistry.register(ktrngHandler); + PacketHandlerRegistry.register(ktrngHandler); tickratechanger = new TickrateChangerServer(LOGGER); EventListenerRegistry.register(tickratechanger); + PacketHandlerRegistry.register(tickratechanger); // Networking LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index f02bdc51..ba556ca7 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -125,6 +125,8 @@ public void onInitializeClient() { ticksyncClient = new TickSyncClient(); EventListenerRegistry.register(ticksyncClient); PacketHandlerRegistry.register(ticksyncClient); + + PacketHandlerRegistry.register(tickratechanger); keybindManager = new KeybindManager() { diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index ae782b62..f118c3b9 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -206,7 +206,7 @@ public boolean readBoolean() throws IOException { return CompressedStreamTools.read(input, NBTSizeTracker.INFINITE); } - public TickratePauseState readTickratePauseState(ByteBuffer buf) { + public static TickratePauseState readTickratePauseState(ByteBuffer buf) { return TickratePauseState.values()[buf.getShort()]; } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index eb679ab7..6896d64f 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -213,7 +213,36 @@ public PacketID[] getAcceptedPacketIDs() { } @Override public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + switch (packet) { + case TICKRATE_CHANGE: + float tickrate = TASmodBufferBuilder.readFloat(buf); + changeClientTickrate(tickrate); + break; + case TICKRATE_ADVANCE: + advanceClientTick(); + break; + case TICKRATE_ZERO: + TickratePauseState state = TASmodBufferBuilder.readTickratePauseState(buf); + + switch (state) { + case PAUSE: + pauseClientGame(true); + break; + case UNPAUSE: + pauseClientGame(false); + break; + case TOGGLE: + togglePauseClient(); + default: + break; + } + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index a23bae88..7a204056 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -178,12 +178,14 @@ public void advanceTick() { /** * Sends a {@link AdvanceTickratePacket} to all clients */ - private static void advanceClientTick() { - try { - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); - } catch (Exception e) { - e.printStackTrace(); - } + private void advanceClientTick() { + if(ticksPerSecond == 0) { + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); + } catch (Exception e) { + e.printStackTrace(); + } + } } /** @@ -275,7 +277,36 @@ public PacketID[] getAcceptedPacketIDs() { @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + switch (packet) { + case TICKRATE_CHANGE: + float tickrate = TASmodBufferBuilder.readFloat(buf); + changeTickrate(tickrate); + break; + case TICKRATE_ADVANCE: + advanceTick(); + break; + case TICKRATE_ZERO: + TickratePauseState state = TASmodBufferBuilder.readTickratePauseState(buf); + + switch (state) { + case PAUSE: + pauseGame(true); + break; + case UNPAUSE: + pauseGame(false); + break; + case TOGGLE: + togglePause(); + default: + break; + } + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass()); + } } } From 57c89fe03ef9dbe7c78bde6083fa2d6e109f6afa Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 27 Aug 2023 19:52:32 +0200 Subject: [PATCH 28/60] Documentation and small code improvements --- .../minecrafttas/common/KeybindManager.java | 26 +- .../minecrafttas/common/server/Client.java | 155 +---- .../common/server/PacketHandlerRegistry.java | 13 +- .../minecrafttas/common/server/Server.java | 41 +- .../PacketNotImplementedException.java | 9 +- .../java/com/minecrafttas/tasmod/TASmod.java | 37 +- .../com/minecrafttas/tasmod/TASmodClient.java | 5 + .../tasmod/commands/CommandFullPlay.java | 4 +- .../tasmod/commands/CommandFullRecord.java | 4 +- .../commands/CommandRestartAndPlay.java | 2 +- .../tasmod/commands/CommandSavestate.java | 32 +- .../tasmod/gui/GuiMultiplayerTimeOut.java | 27 +- .../tasmod/gui/GuiMultiplayerWarn.java | 26 +- .../com/minecrafttas/tasmod/gui/InfoHud.java | 34 +- .../tasmod/handlers/InterpolationHandler.java | 12 +- .../tasmod/handlers/LoadingScreenHandler.java | 16 +- .../tasmod/ktrng/KillTheRNGHandler.java | 127 ++-- .../tasmod/mixin/MixinMinecraftServer.java | 4 +- .../savestates/MixinNetHandlerPlayServer.java | 2 +- .../tasmod/playback/PlaybackController.java | 602 +++++++++--------- .../tasmod/playback/TASstateClient.java | 2 +- .../tasmod/playback/TASstateServer.java | 3 +- .../savestates/SavestateHandlerClient.java | 165 ++--- .../savestates/SavestateHandlerServer.java | 8 +- .../TickrateChangerClient.java | 93 +-- .../TickrateChangerServer.java | 247 +++---- .../tasmod/ticksync/TickSyncServer.java | 9 +- src/test/java/common/TestConfiguration.java | 21 + .../common/server/ByteBufferBuilderTest.java | 42 ++ src/test/java/common/server/ServerTest.java | 34 +- .../TASmodByteBufferBuilderTest.java | 4 +- 31 files changed, 907 insertions(+), 899 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/KeybindManager.java b/src/main/java/com/minecrafttas/common/KeybindManager.java index 538a7b0b..2d187227 100644 --- a/src/main/java/com/minecrafttas/common/KeybindManager.java +++ b/src/main/java/com/minecrafttas/common/KeybindManager.java @@ -14,20 +14,21 @@ /** * Keybind manager */ -public abstract class KeybindManager implements EventClientGameLoop { +public abstract class KeybindManager implements EventClientGameLoop { public static class Keybind { - + private KeyBinding keyBinding; private String category; private Runnable onKeyDown; /** * Initialize keybind - * @param name Name of keybind - * @param category Category of keybind + * + * @param name Name of keybind + * @param category Category of keybind * @param defaultKey Default key of keybind - * @param onKeyDown Will be run when the keybind is pressed + * @param onKeyDown Will be run when the keybind is pressed */ public Keybind(String name, String category, int defaultKey, Runnable onKeyDown) { this.keyBinding = new KeyBinding(name, defaultKey, category); @@ -36,16 +37,16 @@ public Keybind(String name, String category, int defaultKey, Runnable onKeyDown) } } - + private List keybindings; - + /** * Initialize keybind manager */ public KeybindManager() { this.keybindings = new ArrayList<>(); } - + /** * Handle registered keybindings on game loop */ @@ -57,23 +58,24 @@ public void onRunClientGameLoop(Minecraft mc) { } protected abstract boolean isKeyDown(KeyBinding i); - + /** * Register new keybind + * * @param keybind Keybind */ public KeyBinding registerKeybind(Keybind keybind) { this.keybindings.add(keybind); KeyBinding keyBinding = keybind.keyBinding; - + // add category GameSettings options = Minecraft.getMinecraft().gameSettings; if (!KeyBinding.CATEGORY_ORDER.containsKey(keybind.category)) KeyBinding.CATEGORY_ORDER.put(keybind.category, KeyBinding.CATEGORY_ORDER.size() + 1); - + // add keybinding options.keyBindings = ArrayUtils.add(options.keyBindings, keyBinding); return keyBinding; } - + } \ No newline at end of file diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 242ae657..2bea98c2 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -32,21 +32,20 @@ public class Client { private Future future; private UUID clientID; - + private Side side; - - + public enum Side { - CLIENT, - SERVER; + CLIENT, SERVER; } - + /** * Create and connect socket - * @param host Host - * @param port Port + * + * @param host Host + * @param port Port * @param packetIDs A list of PacketIDs which are registered - * @param uuid The UUID of the client + * @param uuid The UUID of the client * @throws Exception Unable to connect */ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exception { @@ -56,15 +55,16 @@ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exc this.side = Side.CLIENT; this.packetIDs = packetIDs; - + this.createHandlers(); Common.LOGGER.info("Connected to server"); - + authenticate(uuid); } - + /** * Fork existing socket + * * @param socket Socket */ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs) { @@ -73,7 +73,7 @@ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs) { this.createHandlers(); this.side = Side.SERVER; } - + /** * Create read/write buffers and handlers for socket */ @@ -110,10 +110,11 @@ public void failed(Throwable exc, Object attachment) { }); } - + /** * Write packet to server - * @param id Buffer id + * + * @param id Buffer id * @param buf Buffer * @throws Exception Networking exception */ @@ -121,9 +122,9 @@ public void send(ByteBufferBuilder bufferBuilder) throws Exception { // wait for previous buffer to send if (this.future != null && !this.future.isDone()) this.future.get(); - + ByteBuffer buf = bufferBuilder.build(); - + // prepare buffer buf.flip(); this.writeBuffer.clear(); @@ -135,9 +136,10 @@ public void send(ByteBufferBuilder bufferBuilder) throws Exception { this.future = this.socket.write(this.writeBuffer); bufferBuilder.close(); } - + /** * Try to close socket + * * @throws IOException Unable to close */ public void close() throws IOException { @@ -145,107 +147,13 @@ public void close() throws IOException { Common.LOGGER.warn("Tried to close dead socket"); return; } - + this.socket.close(); } - - // move wherever you want -// public static enum ClientPackets implements Packet { -// TICK_CLIENT((pid, buf, id) -> -// TickSyncClient.onPacket()), -// CHANGE_CLIENT_TICKRATE((pid, buf, id) -> -// TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), -// ADVANCE_TICK_ON_CLIENTS((pid, buf, id) -> -// TASmodClient.tickratechanger.advanceClientTick()), -// CHANGE_TICKRATE_ON_CLIENTS((pid, buf, id) -> -// TASmodClient.tickratechanger.changeClientTickrate(buf.getFloat())), // funny duplicate please fix -// SAVESTATE_INPUTS_CLIENT((pid, buf, id) -> { -// try { -// byte[] nameBytes = new byte[buf.getInt()]; -// buf.get(nameBytes); -// String name = new String(nameBytes); -// InputSavestatesHandler.savestate(name); -// } catch (Exception e) { -// LOGGER.error("Exception occured during input savestate:", e); -// } -// }), -// CLOSE_GUISAVESTATESCREEN_ON_CLIENTS((pid, buf, id) -> { -// Minecraft mc = Minecraft.getMinecraft(); -// if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) -// mc.displayGuiScreen(new GuiSavestateSavingScreen()); -// else -// mc.displayGuiScreen(null); -// }), -// LOADSTATE_INPUTS_CLIENT((pid, buf, id) -> { -// try { -// byte[] nameBytes = new byte[buf.getInt()]; -// buf.get(nameBytes); -// String name = new String(nameBytes); -// InputSavestatesHandler.loadstate(name); -// } catch (Exception e) { -// LOGGER.error("Exception occured during input loadstate:", e); -// } -// }), -// UNLOAD_CHUNKS_ON_CLIENTS((pid, buf, id) -> -// Minecraft.getMinecraft().addScheduledTask(SavestatesChunkControl::unloadAllClientChunks)), -// REQUEST_CLIENT_MOTION((pid, buf, id) -> { -// EntityPlayerSP player = Minecraft.getMinecraft().player; -// if (player != null) { -// if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) -// Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); -// -// try { -// // send client motion to server -// int bufIndex = SecureList.POOL.available(); -// TASmodClient.client.write(bufIndex, SecureList.POOL.lock(bufIndex).putInt(ServerPackets.SEND_CLIENT_MOTION_TO_SERVER.ordinal()) -// .putDouble(player.motionX).putDouble(player.motionY).putDouble(player.motionZ) -// .putFloat(player.moveForward).putFloat(player.moveVertical).putFloat(player.moveStrafing) -// .put((byte) (player.isSprinting() ? 1 : 0)) -// .putFloat(player.jumpMovementFactor) -// ); -// } catch (Exception e) { -// LOGGER.error("Unable to send packet to server:", e); -// } -// } -// }); -// } - -// public static enum ServerPackets implements Packet { -// NOTIFY_SERVER_OF_TICK_PASS((pid, buf, id) -> -// TickSyncServer.onPacket(id)), -// REQUEST_TICKRATE_CHANGE((pid, buf, id) -> -// TASmod.tickratechanger.changeTickrate(buf.getFloat())), -// TICKRATE_ZERO_TOGGLE((pid, buf, id) -> { -// State state = TickrateChangerServer.State.fromShort(buf.getShort()); -// if (state == TickrateChangerServer.State.PAUSE) -// TASmod.tickratechanger.pauseGame(true); -// else if (state == TickrateChangerServer.State.UNPAUSE) -// TASmod.tickratechanger.pauseGame(false); -// else if (state == TickrateChangerServer.State.TOGGLE) -// TASmod.tickratechanger.togglePause(); -// }), -// REQUEST_TICK_ADVANCE((pid, buf, id) -> { -// if (TASmod.tickratechanger.ticksPerSecond == 0) -// TASmod.tickratechanger.advanceTick(); -// }), -// SEND_CLIENT_MOTION_TO_SERVER((pid, buf, id) -> -// ClientMotionServer.getMotion().put(TASmod.getServerInstance().getPlayerList().getPlayerByUUID(id), new ClientMotionServer.Saver(buf.getDouble(), buf.getDouble(), buf.getDouble(), buf.getFloat(), buf.getFloat(), buf.getFloat(), buf.get() == 1, buf.getFloat()))); -// -// -// private final PacketHandler handler; -// -// ServerPackets(PacketHandler handler) { -// this.handler = handler; -// } -// -// @Override -// public PacketHandler handler() { -// return this.handler; -// } -// } /** * Sends then authentication packet to the server + * * @param id Unique ID * @throws Exception Unable to send packet */ @@ -254,22 +162,22 @@ private void authenticate(UUID id) throws Exception { this.send(new ByteBufferBuilder(-1).writeUUID(id)); } - + private void completeAuthentication(ByteBuffer buf) throws Exception { - if(this.clientID!=null) { + if (this.clientID != null) { throw new Exception("The client tried to authenticate while being authenticated already"); } - + long mostSignificant = buf.getLong(); long leastSignificant = buf.getLong(); - + this.clientID = new UUID(mostSignificant, leastSignificant); } - + private void handle(ByteBuffer buf) { int id = buf.getInt(); try { - if(id==-1) { + if (id == -1) { completeAuthentication(buf); return; } @@ -282,15 +190,14 @@ private void handle(ByteBuffer buf) { } } - + public UUID getId() { return this.clientID; } - private PacketID getPacketFromID(int id) throws InvalidPacketException { - for(PacketID packet : packetIDs) { - if(packet.getID() == id) { + for (PacketID packet : packetIDs) { + if (packet.getID() == id) { return packet; } } diff --git a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java index e5110386..6f96e356 100644 --- a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java +++ b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java @@ -2,11 +2,10 @@ import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.UUID; -import org.apache.commons.lang3.ArrayUtils; - import com.minecrafttas.common.Common; import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -20,6 +19,9 @@ public class PacketHandlerRegistry { private static final List REGISTRY = new ArrayList<>(); public static void register(PacketHandlerBase handler) { + if(handler==null) { + throw new NullPointerException("Tried to register a handler with value null"); + } if (!REGISTRY.contains(handler)) { REGISTRY.add(handler); } else { @@ -28,6 +30,9 @@ public static void register(PacketHandlerBase handler) { } public static void unregister(PacketHandlerBase handler) { + if(handler==null) { + throw new NullPointerException("Tried to unregister a handler with value null"); + } if (REGISTRY.contains(handler)) { REGISTRY.remove(handler); } else { @@ -43,7 +48,7 @@ public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clien boolean isImplemented = false; for (PacketHandlerBase handler : REGISTRY) { - if (ArrayUtils.contains(handler.getAcceptedPacketIDs(), packet)) { // TODO Remove the third party library + if (Arrays.stream(handler.getAcceptedPacketIDs()).anyMatch(packet::equals)) { if (side == Side.CLIENT && handler instanceof ClientPacketHandler) { ClientPacketHandler clientHandler = (ClientPacketHandler) handler; clientHandler.onClientPacket(packet, buf, clientID); @@ -56,7 +61,7 @@ public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clien } } if(!isImplemented) { - throw new PacketNotImplementedException(packet); + throw new PacketNotImplementedException(packet, side); } } } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 9deff9d1..17b596ad 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -23,9 +23,10 @@ public class Server { private final AsynchronousServerSocketChannel socket; private final List clients; - + /** * Create and bind socket + * * @param port Port * @throws Exception Unable to bind */ @@ -34,7 +35,7 @@ public Server(int port, PacketID[] packetIDs) throws Exception { Common.LOGGER.info("Creating server on port {}", port); this.socket = AsynchronousServerSocketChannel.open(); this.socket.bind(new InetSocketAddress(port)); - + // create connection handler this.clients = new ArrayList<>(); this.socket.accept(null, new CompletionHandler() { @@ -50,12 +51,13 @@ public void failed(Throwable exc, Object attachment) { Common.LOGGER.error("Unable to accept client!", exc); } }); - + Common.LOGGER.info("Server created"); } - + /** * Write packet to all clients + * * @param builder The packet contents * @throws Exception Networking exception */ @@ -65,33 +67,35 @@ public void sendToAll(ByteBufferBuilder builder) throws Exception { } builder.close(); } - + /** * Send a packet to the specified uuid - * @param uuid The UUID to send to + * + * @param uuid The UUID to send to * @param builder The packet contents * @throws Exception Networking exception */ - public void sendTo(UUID uuid, ByteBufferBuilder builder) throws Exception{ + public void sendTo(UUID uuid, ByteBufferBuilder builder) throws Exception { Client client = getClient(uuid); client.send(builder); } - + /** * Send a packet to a specified player * * Similar to {@link #sendTo(UUID, ByteBufferBuilder)} * - * @param player The player to send to + * @param player The player to send to * @param builder The packet contents * @throws Exception Networking exception */ - public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Exception{ + public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Exception { sendTo(player.getUniqueID(), builder); } - + /** * Try to close socket + * * @throws IOException Unable to close */ public void close() throws IOException { @@ -99,32 +103,33 @@ public void close() throws IOException { Common.LOGGER.warn("Tried to close dead socket"); return; } - + this.socket.close(); } public boolean isClosed() { return this.socket == null || !this.socket.isOpen(); } - + /** * Get client from UUID + * * @param uniqueID UUID */ private Client getClient(UUID uniqueID) { for (Client client : this.clients) if (client.getId().equals(uniqueID)) return client; - + return null; } - - public List getClients(){ + + public List getClients() { return this.clients; } - + public AsynchronousServerSocketChannel getAsynchronousSocketChannel() { return this.socket; } - + } diff --git a/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java index 3b00ca4c..21d583dc 100644 --- a/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java +++ b/src/main/java/com/minecrafttas/common/server/exception/PacketNotImplementedException.java @@ -1,5 +1,6 @@ package com.minecrafttas.common.server.exception; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.interfaces.PacketHandlerBase; import com.minecrafttas.common.server.interfaces.PacketID; @@ -10,12 +11,12 @@ public PacketNotImplementedException(String msg) { super(msg); } - public PacketNotImplementedException(PacketID packet, Class clazz) { - super(String.format("The packet %s is not implemented in %s", packet.getName(), clazz.getCanonicalName())); + public PacketNotImplementedException(PacketID packet, Class clazz, Side side) { + super(String.format("The packet %s is not implemented in %s on the %s-Side", packet.getName(), clazz.getCanonicalName(), side)); } - public PacketNotImplementedException(PacketID packet) { - super(String.format("The packet %s is not implemented or not registered in getAssociatedPacketIDs", packet.getName())); + public PacketNotImplementedException(PacketID packet, Side side) { + super(String.format("The packet %s is not implemented or not registered in getAssociatedPacketIDs on the %s-Side", packet.getName(), side)); } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 5d49f574..e8d05e1e 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -52,7 +52,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static TASstateServer containerStateServer; - public static SavestateHandlerServer savestateHandler; + public static SavestateHandlerServer savestateHandlerServer; public static KillTheRNGHandler ktrngHandler; @@ -93,7 +93,8 @@ public void onServerInit(MinecraftServer server) { e.printStackTrace(); } - savestateHandler=new SavestateHandlerServer(server, LOGGER); + savestateHandlerServer=new SavestateHandlerServer(server, LOGGER); + PacketHandlerRegistry.register(savestateHandlerServer); if(!server.isDedicatedServer()) { TASmod.tickratechanger.ticksPerSecond=0F; @@ -139,38 +140,6 @@ public void onInitialize() { // Networking LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); -// // Savestates -// PacketSerializer.registerPacket(SavestatePacket.class); -// PacketSerializer.registerPacket(LoadstatePacket.class); -// -// PacketSerializer.registerPacket(InputSavestatesPacket.class); -// PacketSerializer.registerPacket(SavestatePlayerLoadingPacket.class); -// -// // KillTheRNG -// PacketSerializer.registerPacket(KTRNGSeedPacket.class); -// PacketSerializer.registerPacket(KTRNGStartSeedPacket.class); -// -// // Recording/Playback -// PacketSerializer.registerPacket(SyncStatePacket.class); -// PacketSerializer.registerPacket(InitialSyncStatePacket.class); -// -// PacketSerializer.registerPacket(ClearInputsPacket.class); -// -// PacketSerializer.registerPacket(FullRecordPacket.class); -// PacketSerializer.registerPacket(FullPlayPacket.class); -// -// PacketSerializer.registerPacket(RestartAndPlayPacket.class); -// -// // Storing -// PacketSerializer.registerPacket(SaveTASPacket.class); -// PacketSerializer.registerPacket(LoadTASPacket.class); -// -// // Misc -// PacketSerializer.registerPacket(PlaybackController.TeleportPlayerPacket.class); -// PacketSerializer.registerPacket(FolderPacket.class); -// -// PacketSerializer.registerPacket(PlayUntilPacket.class); - try { server = new Server(networkingport, TASmodPackets.values()); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index ba556ca7..baafcde1 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -27,6 +27,7 @@ import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.savestates.SavestateHandlerClient; import com.minecrafttas.tasmod.playback.PlaybackSerialiser; import com.minecrafttas.tasmod.playback.TASstateClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerClient; @@ -78,6 +79,8 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, Even public static InterpolationHandler interpolation = new InterpolationHandler(); + public static SavestateHandlerClient savestateHandlerClient = new SavestateHandlerClient(); + public static Client client; public static void createTASDir() { @@ -128,6 +131,8 @@ public void onInitializeClient() { PacketHandlerRegistry.register(tickratechanger); + PacketHandlerRegistry.register(savestateHandlerClient); + keybindManager = new KeybindManager() { protected boolean isKeyDown(KeyBinding i) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index b6e29238..a0ddad75 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -29,7 +29,7 @@ public String getUsage(ICommandSender sender) { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { try { - TASmod.savestateHandler.loadState(0, false, false); + TASmod.savestateHandlerServer.loadState(0, false, false); } catch (LoadstateException e) { sender.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to load a savestate: "+e.getMessage())); return; @@ -38,7 +38,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args e.printStackTrace(); return; } finally { - TASmod.savestateHandler.state=SavestateState.NONE; + TASmod.savestateHandlerServer.state=SavestateState.NONE; } TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); try { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index 907a5124..d846b166 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -29,7 +29,7 @@ public String getUsage(ICommandSender sender) { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { try { - TASmod.savestateHandler.saveState(0, false); + TASmod.savestateHandlerServer.saveState(0, false); } catch (SavestateException e) { sender.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getMessage())); return; @@ -38,7 +38,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args sender.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getCause().toString())); return; } finally { - TASmod.savestateHandler.state = SavestateState.NONE; + TASmod.savestateHandlerServer.state = SavestateState.NONE; } TASmod.containerStateServer.setServerState(TASstate.RECORDING); try { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index 668b1864..782987f8 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -48,7 +48,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args name=name.concat(args[i]+spacer); } try { - TASmod.savestateHandler.loadState(0, false); + TASmod.savestateHandlerServer.loadState(0, false); } catch (LoadstateException e) { e.printStackTrace(); } catch (IOException e) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java index bfef39ec..7aee1de1 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandSavestate.java @@ -74,8 +74,8 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args deleteMultiple(args); } } else if ("list".equals(args[0])) { - sender.sendMessage(new TextComponentString(String.format("The current savestate index is %s%s", TextFormatting.AQUA, TASmod.savestateHandler.getCurrentIndex()))); - sender.sendMessage(new TextComponentString(String.format("Available indexes are %s%s", TextFormatting.AQUA, TASmod.savestateHandler.getIndexesAsString().isEmpty() ? "None" : TASmod.savestateHandler.getIndexesAsString()))); + sender.sendMessage(new TextComponentString(String.format("The current savestate index is %s%s", TextFormatting.AQUA, TASmod.savestateHandlerServer.getCurrentIndex()))); + sender.sendMessage(new TextComponentString(String.format("Available indexes are %s%s", TextFormatting.AQUA, TASmod.savestateHandlerServer.getIndexesAsString().isEmpty() ? "None" : TASmod.savestateHandlerServer.getIndexesAsString()))); } else if ("help".equals(args[0])) { if (args.length == 1) { sendHelp(sender); @@ -100,7 +100,7 @@ private void sendHelp(ICommandSender sender) throws CommandException { } private void sendHelp(ICommandSender sender, int i) throws CommandException { - int currentIndex = TASmod.savestateHandler.getCurrentIndex(); + int currentIndex = TASmod.savestateHandlerServer.getCurrentIndex(); if (i > 3) { throw new CommandException("This help page doesn't exist (yet?)", new Object[] {}); } @@ -142,7 +142,7 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen if (args.length == 1) { return getListOfStringsMatchingLastWord(args, new String[] { "save", "load", "delete", "list", "help"}); } else if (args.length == 2 && !"list".equals(args[0])) { - sender.sendMessage(new TextComponentString("Available indexes: " + TextFormatting.AQUA + TASmod.savestateHandler.getIndexesAsString())); + sender.sendMessage(new TextComponentString("Available indexes: " + TextFormatting.AQUA + TASmod.savestateHandlerServer.getIndexesAsString())); } return super.getTabCompletions(server, sender, args, targetPos); } @@ -151,14 +151,14 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen private void saveLatest() throws CommandException { try { - TASmod.savestateHandler.saveState(); + TASmod.savestateHandlerServer.saveState(); } catch (SavestateException e) { throw new CommandException(e.getMessage(), new Object[] {}); } catch (IOException e) { e.printStackTrace(); throw new CommandException(e.getMessage(), new Object[] {}); } finally { - TASmod.savestateHandler.state = SavestateState.NONE; + TASmod.savestateHandlerServer.state = SavestateState.NONE; } } @@ -168,47 +168,47 @@ private void saveWithIndex(String[] args) throws CommandException { if (indexToSave <= 0) { // Disallow to save on Savestate 0 indexToSave = -1; } - TASmod.savestateHandler.saveState(indexToSave, true); + TASmod.savestateHandlerServer.saveState(indexToSave, true); } catch (SavestateException e) { throw new CommandException(e.getMessage(), new Object[] {}); } catch (IOException e) { e.printStackTrace(); throw new CommandException(e.getMessage(), new Object[] {}); } finally { - TASmod.savestateHandler.state = SavestateState.NONE; + TASmod.savestateHandlerServer.state = SavestateState.NONE; } } private void loadLatest() throws CommandException { try { - TASmod.savestateHandler.loadState(); + TASmod.savestateHandlerServer.loadState(); } catch (LoadstateException e) { throw new CommandException(e.getMessage(), new Object[] {}); } catch (IOException e) { e.printStackTrace(); throw new CommandException(e.getMessage(), new Object[] {}); } finally { - TASmod.savestateHandler.state = SavestateState.NONE; + TASmod.savestateHandlerServer.state = SavestateState.NONE; } } private void loadLatest(String[] args) throws CommandException { try { - TASmod.savestateHandler.loadState(processIndex(args[1]), true); + TASmod.savestateHandlerServer.loadState(processIndex(args[1]), true); } catch (LoadstateException e) { throw new CommandException(e.getMessage(), new Object[] {}); } catch (IOException e) { e.printStackTrace(); throw new CommandException(e.getMessage(), new Object[] {}); } finally { - TASmod.savestateHandler.state = SavestateState.NONE; + TASmod.savestateHandlerServer.state = SavestateState.NONE; } } private void delete(String[] args) throws CommandException { int arg1 = processIndex(args[1]); try { - TASmod.savestateHandler.deleteSavestate(arg1); + TASmod.savestateHandlerServer.deleteSavestate(arg1); } catch (SavestateDeleteException e) { throw new CommandException(e.getMessage(), new Object[] {}); } @@ -216,7 +216,7 @@ private void delete(String[] args) throws CommandException { private void deleteMultiple(String[] args) throws CommandException { try { - TASmod.savestateHandler.deleteSavestate(processIndex(args[1]), processIndex(args[2])); + TASmod.savestateHandlerServer.deleteSavestate(processIndex(args[1]), processIndex(args[2])); } catch (SavestateDeleteException e) { throw new CommandException(e.getMessage(), new Object[] {}); } @@ -226,11 +226,11 @@ private void deleteMultiple(String[] args) throws CommandException { private int processIndex(String arg) throws CommandException { if ("~".equals(arg)) { - return TASmod.savestateHandler.getCurrentIndex(); + return TASmod.savestateHandlerServer.getCurrentIndex(); } else if (arg.matches("~-?\\d")) { arg = arg.replace("~", ""); int i = Integer.parseInt(arg); - return TASmod.savestateHandler.getCurrentIndex() + i; + return TASmod.savestateHandlerServer.getCurrentIndex() + i; } else { int i = 0; try { diff --git a/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerTimeOut.java b/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerTimeOut.java index 6909adfc..a36a7c96 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerTimeOut.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerTimeOut.java @@ -8,35 +8,38 @@ import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.resources.I18n; -public class GuiMultiplayerTimeOut extends GuiScreen{ +public class GuiMultiplayerTimeOut extends GuiScreen { private GuiScreen previous; - + public GuiMultiplayerTimeOut() { - previous=new GuiMainMenu(); + previous = new GuiMainMenu(); } + @Override public void initGui() { - this.buttonList.add(new GuiButton(0, width / 2 -100, height / 2 + 70, "Continue")); + this.buttonList.add(new GuiButton(0, width / 2 - 100, height / 2 + 70, "Continue")); super.initGui(); } + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); - + ScaledResolution scaled = new ScaledResolution(Minecraft.getMinecraft()); int width = scaled.getScaledWidth(); int height = scaled.getScaledHeight(); - - drawCenteredString(fontRenderer,I18n.format("TASmod: Timed out"), width / 2, height / 4 + 50 + -16, 0xFFFFFF); - drawCenteredString(fontRenderer,I18n.format("Lost or could not make a connection to the TASmod on the server side"), width / 2, height / 4 + 50 + -6, 0xFFFFFF); - drawCenteredString(fontRenderer,I18n.format("Possible Cause:"), width / 2, height / 4 + 50 + 14, 0xFFFFFF); - drawCenteredString(fontRenderer,I18n.format("The server has no TASmod installed or the server lagged too much."), width / 2, height / 4 + 50 + 24, 0xFFFFFF); - drawCenteredString(fontRenderer,I18n.format("It's also possible to get this message in singleplayer if the integrated server stopped responding."), width / 2, height / 4 + 50 + 34, 0xFFFFFF); + + drawCenteredString(fontRenderer, I18n.format("TASmod: Timed out"), width / 2, height / 4 + 50 + -16, 0xFFFFFF); + drawCenteredString(fontRenderer, I18n.format("Lost or could not make a connection to the TASmod on the server side"), width / 2, height / 4 + 50 + -6, 0xFFFFFF); + drawCenteredString(fontRenderer, I18n.format("Possible Cause:"), width / 2, height / 4 + 50 + 14, 0xFFFFFF); + drawCenteredString(fontRenderer, I18n.format("The server has no TASmod installed or the server lagged too much."), width / 2, height / 4 + 50 + 24, 0xFFFFFF); + drawCenteredString(fontRenderer, I18n.format("It's also possible to get this message in singleplayer if the integrated server stopped responding."), width / 2, height / 4 + 50 + 34, 0xFFFFFF); super.drawScreen(mouseX, mouseY, partialTicks); } + @Override protected void actionPerformed(GuiButton button) { - if(button.id==0) { + if (button.id == 0) { Minecraft.getMinecraft().displayGuiScreen(new GuiMultiplayer(previous)); } } diff --git a/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerWarn.java b/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerWarn.java index c745f279..e079ed48 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerWarn.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/GuiMultiplayerWarn.java @@ -7,34 +7,38 @@ import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.resources.I18n; -public class GuiMultiplayerWarn extends GuiScreen{ +public class GuiMultiplayerWarn extends GuiScreen { private GuiScreen previous; + public GuiMultiplayerWarn(GuiScreen screen) { - previous=screen; + previous = screen; } + @Override public void initGui() { - this.buttonList.add(new GuiButton(0, width / 2 -100, height / 2 + 70, "Continue")); + this.buttonList.add(new GuiButton(0, width / 2 - 100, height / 2 + 70, "Continue")); super.initGui(); } + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); - + ScaledResolution scaled = new ScaledResolution(Minecraft.getMinecraft()); int width = scaled.getScaledWidth(); int height = scaled.getScaledHeight(); - - drawCenteredString(fontRenderer,I18n.format("WARNING"), width / 2, height / 4 + 50 + -16, 0xCE0000); - drawCenteredString(fontRenderer,I18n.format("Do NOT join a server that has not installed the TASmod (e.g. Hypixel)."), width / 2, height / 4 + 50 + -6, 0xFFFFFF); - drawCenteredString(fontRenderer,I18n.format("You will softlock your game for a few seconds then disconnect!"), width / 2, height / 4 + 50 + 4, 0xFFFFFF); - drawCenteredString(fontRenderer,I18n.format("This mod only works together with a server."), width / 2, height / 4 + 50 + 14, 0xFFFFFF); - + + drawCenteredString(fontRenderer, I18n.format("WARNING"), width / 2, height / 4 + 50 + -16, 0xCE0000); + drawCenteredString(fontRenderer, I18n.format("Do NOT join a server that has not installed the TASmod (e.g. Hypixel)."), width / 2, height / 4 + 50 + -6, 0xFFFFFF); + drawCenteredString(fontRenderer, I18n.format("You will softlock your game for a few seconds then disconnect!"), width / 2, height / 4 + 50 + 4, 0xFFFFFF); + drawCenteredString(fontRenderer, I18n.format("This mod only works together with a server."), width / 2, height / 4 + 50 + 14, 0xFFFFFF); + super.drawScreen(mouseX, mouseY, partialTicks); } + @Override protected void actionPerformed(GuiButton button) { - if(button.id==0) { + if (button.id == 0) { Minecraft.getMinecraft().displayGuiScreen(new GuiMultiplayer(previous)); } } diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index 44be169a..12c6b71e 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -304,23 +304,23 @@ public boolean checkInit() { lists.add(new InfoLabel(title, Integer.parseInt(configuration.getProperty(title + "_x")), Integer.parseInt(configuration.getProperty(title + "_y")), Boolean.parseBoolean(configuration.getProperty(title + "_visible")), Boolean.parseBoolean(configuration.getProperty(title + "_rect")), () -> { if (Minecraft.getMinecraft().currentScreen == this) { return "State"; - }else { - TASstate state=TASmodClient.virtual.getContainer().getState(); - ChatFormatting format=ChatFormatting.WHITE; - String out=""; - if(state==TASstate.PLAYBACK) { - out="Playback"; - format=ChatFormatting.GREEN; - }else if(state==TASstate.RECORDING){ - out="Recording"; - format=ChatFormatting.RED; - }else if(state==TASstate.PAUSED) { - out="Paused"; - format=ChatFormatting.YELLOW; - }else if(state==TASstate.NONE) { - out=""; - } - return String.format("%s%s", format, out); + } else { + TASstate state = TASmodClient.virtual.getContainer().getState(); + ChatFormatting format = ChatFormatting.WHITE; + String out = ""; + if (state == TASstate.PLAYBACK) { + out = "Playback"; + format = ChatFormatting.GREEN; + } else if (state == TASstate.RECORDING) { + out = "Recording"; + format = ChatFormatting.RED; + } else if (state == TASstate.PAUSED) { + out = "Paused"; + format = ChatFormatting.YELLOW; + } else if (state == TASstate.NONE) { + out = ""; + } + return String.format("%s%s", format, out); } })); diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java index eae90d4d..846db6ed 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java @@ -10,23 +10,25 @@ /** * Adds interpolation to the camera + * * @author Pancake * */ -public class InterpolationHandler implements EventCamera{ - +public class InterpolationHandler implements EventCamera { + public static float rotationPitch = 0f; public static float rotationYaw = 0f; - + @Override public CameraData onCameraEvent(CameraData dataIn) { if (TASmodClient.virtual.getContainer().isPlayingback() && ControlByteHandler.shouldInterpolate) { TickInputContainer input = TASmodClient.virtual.getContainer().get(); - if (input == null) return dataIn; + if (input == null) + return dataIn; float nextPitch = input.getSubticks().getPitch(); float nextYaw = input.getSubticks().getYaw(); dataIn.pitch = (float) MathHelper.clampedLerp(rotationPitch, nextPitch, Minecraft.getMinecraft().timer.renderPartialTicks); - dataIn.yaw = (float) MathHelper.clampedLerp(rotationYaw, nextYaw+180, Minecraft.getMinecraft().timer.renderPartialTicks); + dataIn.yaw = (float) MathHelper.clampedLerp(rotationYaw, nextYaw + 180, Minecraft.getMinecraft().timer.renderPartialTicks); } else { dataIn.pitch = rotationPitch; dataIn.yaw = rotationYaw; diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java index bccc9940..5e6d240d 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java @@ -14,12 +14,12 @@ /** * Handles logic during a loading screen to transition between states. + * * @author Scribble * */ -public class LoadingScreenHandler implements EventLaunchIntegratedServer, EventClientGameLoop, EventDoneLoadingWorld{ - - +public class LoadingScreenHandler implements EventLaunchIntegratedServer, EventClientGameLoop, EventDoneLoadingWorld { + private boolean waszero; private boolean isLoading; private int loadingScreenDelay = -1; @@ -28,7 +28,7 @@ public class LoadingScreenHandler implements EventLaunchIntegratedServer, EventC public void onLaunchIntegratedServer() { LOGGER.debug(LoggerMarkers.Event, "Starting the integrated server"); PlaybackController container = TASmodClient.virtual.getContainer(); - if(!container.isNothingPlaying() && !container.isPaused()) { + if (!container.isNothingPlaying() && !container.isPaused()) { container.pause(true); } if (TASmodClient.tickratechanger.ticksPerSecond == 0 || TASmodClient.tickratechanger.advanceTick) { @@ -44,7 +44,7 @@ public void onRunClientGameLoop(Minecraft mc) { LOGGER.debug(LoggerMarkers.Event, "Finished loading screen on the client"); TASmodClient.tickratechanger.joinServer(); if (!waszero) { - if(TASmod.getServerInstance()!=null) { //Check if a server is running and if it's an integrated server + if (TASmod.getServerInstance() != null) { // Check if a server is running and if it's an integrated server TASmodClient.tickratechanger.pauseClientGame(false); TASmod.tickratechanger.pauseServerGame(false); } @@ -56,15 +56,15 @@ public void onRunClientGameLoop(Minecraft mc) { loadingScreenDelay--; } } - + @Override public void onDoneLoadingWorld() { - if(TASmod.getServerInstance()!=null) { //Check if a server is running and if it's an integrated server + if (TASmod.getServerInstance() != null) { // Check if a server is running and if it's an integrated server LOGGER.debug(LoggerMarkers.Event, "Finished loading the world on the client"); loadingScreenDelay = 1; } } - + public boolean isLoading() { return isLoading; } diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index f70fb1ed..dab9c7b2 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -7,6 +7,7 @@ import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventServer.EventServerTick; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; @@ -31,64 +32,65 @@ * @author Scribble * */ -public class KillTheRNGHandler implements EventServerTick, EventPlayerJoinedClientSide, ClientPacketHandler, ServerPacketHandler{ - +public class KillTheRNGHandler implements EventServerTick, EventPlayerJoinedClientSide, ClientPacketHandler, ServerPacketHandler { + private boolean isLoaded; - + /** * Instantiates a KillTheRNGHandler instance + * * @param isLoaded If the KillTheRNG mod is loaded */ public KillTheRNGHandler(boolean isLoaded) { - - this.isLoaded=isLoaded; - + + this.isLoaded = isLoaded; + if (isLoaded) { KillTheRNG.LOGGER.info("Connection established with TASmod"); - KillTheRNG.isLibrary=true; - KillTheRNG.mode=SeedingModes.TickChange; - + KillTheRNG.isLibrary = true; + KillTheRNG.mode = SeedingModes.TickChange; + KillTheRNG.annotations.register(new KTRNGMonitor()); - }else { + } else { LOGGER.info("KillTheRNG doesn't appear to be loaded"); } } - + public long advanceGlobalSeedServer() { - if(isLoaded()) { + if (isLoaded()) { return KillTheRNG.commonRandom.nextSeed(); } else { return 0; } } - + public long getGlobalSeedServer() { - if(isLoaded()) { + if (isLoaded()) { return KillTheRNG.commonRandom.GlobalServer.getSeed(); } else { return 0; } } - + public boolean isLoaded() { return isLoaded; } - - - //=================================================Setting the seed + + // =================================================Setting the seed /** * @return The global seed of the client */ @Environment(EnvType.CLIENT) public long getGlobalSeedClient() { - if(isLoaded()) + if (isLoaded()) return KillTheRNG.clientRandom.GlobalClient.getSeed(); else return 0; } - + /** * Set the global seed on the client + * * @param seedIn The seed on the client */ @Environment(EnvType.CLIENT) @@ -97,21 +99,22 @@ public void setGlobalSeedClient(long seedIn) { KillTheRNG.clientRandom.setSeedAll(seedIn); } } - - + public void setGlobalSeedServer(long seedIn) { if (isLoaded()) { KillTheRNG.commonRandom.setSeedAll(seedIn); } } + /** * Sends a packet to the server, setting the global seed + * * @param seedIn The seed on the server */ @Environment(EnvType.CLIENT) public void sendGlobalSeedToServer(long seedIn) { - if(isLoaded()) { - if(TASmodClient.client != null) + if (isLoaded()) { + if (TASmodClient.client != null) try { TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(seedIn)); } catch (Exception e) { @@ -121,15 +124,15 @@ public void sendGlobalSeedToServer(long seedIn) { setGlobalSeedClient(seedIn); } } - //=================================================TASmod integration - + // =================================================TASmod integration + /** * Executed every tick on the server */ @Override public void onServerTick(MinecraftServer server) { - if(isLoaded()) { - if(TASmod.containerStateServer.getState() != TASstate.PAUSED) + if (isLoaded()) { + if (TASmod.containerStateServer.getState() != TASstate.PAUSED) try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(advanceGlobalSeedServer())); } catch (Exception e) { @@ -137,11 +140,11 @@ public void onServerTick(MinecraftServer server) { } } } - - //================================================= Seedsync - + + // ================================================= Seedsync + public void broadcastStartSeed() { - if(isLoaded()) { + if (isLoaded()) { long seed = getGlobalSeedServer(); try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(seed)); @@ -150,13 +153,14 @@ public void broadcastStartSeed() { } } } - + @Environment(EnvType.CLIENT) public void setInitialSeed(long initialSeed) { - if(TASmodClient.client != null) { + if (TASmodClient.client != null) { LOGGER.info("Sending initial client seed: {}", initialSeed); try { - TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_STARTSEED).writeLong(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, which is BAD + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_STARTSEED).writeLong(initialSeed)); // TODO Every new player in multiplayer will currently send the initial seed, + // which is BAD } catch (Exception e) { e.printStackTrace(); } @@ -173,27 +177,27 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] {TASmodPackets.KILLTHERNG_SEED, TASmodPackets.KILLTHERNG_STARTSEED}; + return new TASmodPackets[] { TASmodPackets.KILLTHERNG_SEED, TASmodPackets.KILLTHERNG_STARTSEED }; } @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { long seed = TASmodBufferBuilder.readLong(buf); TASmodPackets packet = (TASmodPackets) id; - + switch (packet) { - case KILLTHERNG_SEED: - setGlobalSeedServer(seed); - break; - - case KILLTHERNG_STARTSEED: - TASmod.tickSchedulerServer.add(()->{ - TASmod.ktrngHandler.setGlobalSeedServer(seed); - }); - break; - - default: - throw new PacketNotImplementedException(packet, this.getClass()); + case KILLTHERNG_SEED: + setGlobalSeedServer(seed); + break; + + case KILLTHERNG_STARTSEED: + TASmod.tickSchedulerServer.add(() -> { + TASmod.ktrngHandler.setGlobalSeedServer(seed); + }); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); } } @@ -201,20 +205,19 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { long seed = TASmodBufferBuilder.readLong(buf); TASmodPackets packet = (TASmodPackets) id; - + switch (packet) { - case KILLTHERNG_SEED: - setGlobalSeedClient(seed); - break; - - case KILLTHERNG_STARTSEED: - TASmodClient.virtual.getContainer().setStartSeed(seed); - break; - - default: - throw new PacketNotImplementedException(packet, this.getClass()); + case KILLTHERNG_SEED: + setGlobalSeedClient(seed); + break; + + case KILLTHERNG_STARTSEED: + TASmodClient.virtual.getContainer().setStartSeed(seed); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); } } - - + } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java index be8f1ac8..29d4eef6 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java @@ -71,8 +71,8 @@ public void redirectThreadSleep(long msToTick) { if( (TASmod.ticksyncServer.shouldTick() && TASmod.tickratechanger.ticksPerSecond != 0) || TASmod.tickratechanger.advanceTick) { long timeBeforeTick = System.currentTimeMillis(); - if (TASmod.savestateHandler.state == SavestateState.WASLOADING) { - TASmod.savestateHandler.state = SavestateState.NONE; + if (TASmod.savestateHandlerServer.state == SavestateState.WASLOADING) { + TASmod.savestateHandlerServer.state = SavestateState.NONE; EventCompleteLoadstate.fireLoadstateComplete(); } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java index 4c0dc039..cf36a683 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java @@ -16,6 +16,6 @@ public class MixinNetHandlerPlayServer { @Redirect(method = "processPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;isInvulnerableDimensionChange()Z")) public boolean redirect_processPlayer(EntityPlayerMP parentIn) { - return !parentIn.isInvulnerableDimensionChange() && (TASmod.savestateHandler.state!=SavestateState.LOADING && TASmod.savestateHandler.state!=SavestateState.WASLOADING); + return !parentIn.isInvulnerableDimensionChange() && (TASmod.savestateHandlerServer.state!=SavestateState.LOADING && TASmod.savestateHandlerServer.state!=SavestateState.WASLOADING); } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java index 4f24ff5c..d3907bab 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java @@ -53,15 +53,15 @@ * These inputs can be played back at any time by setting * {@linkplain #setPlayback(boolean)} to true.
*
- * Information about the author etc. get stored in the playback controller too and - * will be printed out in chat when the player loads into a world
+ * Information about the author etc. get stored in the playback controller too + * and will be printed out in chat when the player loads into a world
* Inputs are saved and loaded to/from file via the * {@linkplain PlaybackSerialiser} * * @author Scribble * */ -public class PlaybackController implements ServerPacketHandler, ClientPacketHandler{ +public class PlaybackController implements ServerPacketHandler, ClientPacketHandler { /** * The current state of the controller. @@ -76,7 +76,7 @@ public class PlaybackController implements ServerPacketHandler, ClientPacketHand * The current index of the inputs */ private int index; - + private VirtualKeyboard keyboard = new VirtualKeyboard(); private VirtualMouse mouse = new VirtualMouse(); @@ -91,42 +91,44 @@ public class PlaybackController implements ServerPacketHandler, ClientPacketHand private BigArrayList inputs = new BigArrayList(directory + File.separator + "temp"); /** - * A map of control bytes. Used to change settings during playback via the playback file. + * A map of control bytes. Used to change settings during playback via the + * playback file. *

* A full list of changes can be found in {@link ControlByteHandler} *

- * The values are as follows:

+ * The values are as follows: + *

* Map(int playbackLine, List(Pair(String controlCommand, String[] arguments))" */ private Map>> controlBytes = new HashMap>>(); - + /** * The comments in the file, used to store them again later */ private Map> comments = new HashMap<>(); - + public DesyncMonitoring desyncMonitor = new DesyncMonitoring(this); - + // ===================================================================================================== private String title = "Insert TAS category here"; - + private String authors = "Insert author here"; private String playtime = "00:00.0"; - + private int rerecords = 0; private String startLocation = ""; - + private long startSeed = TASmod.ktrngHandler.getGlobalSeedClient(); // ===================================================================================================== - private boolean creditsPrinted=false; + private boolean creditsPrinted = false; private Integer playUntil = null; - + /** * Starts or stops a recording/playback * @@ -148,107 +150,107 @@ public String setTASState(TASstate stateIn, boolean verbose) { ControlByteHandler.reset(); if (state == stateIn) { switch (stateIn) { - case PLAYBACK: - return verbose ? TextFormatting.RED + "A playback is already running" : ""; - case RECORDING: - return verbose ? TextFormatting.RED + "A recording is already running" : ""; - case PAUSED: - return verbose ? TextFormatting.RED + "The game is already paused" : ""; - case NONE: - return verbose ? TextFormatting.RED + "Nothing is running" : ""; + case PLAYBACK: + return verbose ? TextFormatting.RED + "A playback is already running" : ""; + case RECORDING: + return verbose ? TextFormatting.RED + "A recording is already running" : ""; + case PAUSED: + return verbose ? TextFormatting.RED + "The game is already paused" : ""; + case NONE: + return verbose ? TextFormatting.RED + "Nothing is running" : ""; } } else if (state == TASstate.NONE) { // If the container is currently doing nothing switch (stateIn) { - case PLAYBACK: - LOGGER.debug(LoggerMarkers.Playback, "Starting playback"); - if (Minecraft.getMinecraft().player != null && !startLocation.isEmpty()) { - try { - tpPlayer(startLocation); - } catch (NumberFormatException e) { - state = TASstate.NONE; - e.printStackTrace(); - return verbose ? TextFormatting.RED + "An error occured while reading the start location of the TAS. The file might be broken" : ""; + case PLAYBACK: + LOGGER.debug(LoggerMarkers.Playback, "Starting playback"); + if (Minecraft.getMinecraft().player != null && !startLocation.isEmpty()) { + try { + tpPlayer(startLocation); + } catch (NumberFormatException e) { + state = TASstate.NONE; + e.printStackTrace(); + return verbose ? TextFormatting.RED + "An error occured while reading the start location of the TAS. The file might be broken" : ""; + } } - } - Minecraft.getMinecraft().gameSettings.chatLinks = false; // #119 - index = 0; - state = TASstate.PLAYBACK; - creditsPrinted=false; - TASmod.ktrngHandler.setInitialSeed(startSeed); - return verbose ? TextFormatting.GREEN + "Starting playback" : ""; - case RECORDING: - LOGGER.debug(LoggerMarkers.Playback, "Starting recording"); - if (Minecraft.getMinecraft().player != null && startLocation.isEmpty()) { - startLocation = getStartLocation(Minecraft.getMinecraft().player); - } - if(this.inputs.isEmpty()) { - inputs.add(new TickInputContainer(index)); - desyncMonitor.recordNull(index); - } - state = TASstate.RECORDING; - return verbose ? TextFormatting.GREEN + "Starting a recording" : ""; - case PAUSED: - return verbose ? TextFormatting.RED + "Can't pause anything because nothing is running" : ""; - case NONE: - return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: None)"; + Minecraft.getMinecraft().gameSettings.chatLinks = false; // #119 + index = 0; + state = TASstate.PLAYBACK; + creditsPrinted = false; + TASmod.ktrngHandler.setInitialSeed(startSeed); + return verbose ? TextFormatting.GREEN + "Starting playback" : ""; + case RECORDING: + LOGGER.debug(LoggerMarkers.Playback, "Starting recording"); + if (Minecraft.getMinecraft().player != null && startLocation.isEmpty()) { + startLocation = getStartLocation(Minecraft.getMinecraft().player); + } + if (this.inputs.isEmpty()) { + inputs.add(new TickInputContainer(index)); + desyncMonitor.recordNull(index); + } + state = TASstate.RECORDING; + return verbose ? TextFormatting.GREEN + "Starting a recording" : ""; + case PAUSED: + return verbose ? TextFormatting.RED + "Can't pause anything because nothing is running" : ""; + case NONE: + return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: None)"; } } else if (state == TASstate.RECORDING) { // If the container is currently recording switch (stateIn) { - case PLAYBACK: - return verbose ? TextFormatting.RED + "A recording is currently running. Please stop the recording first before starting a playback" : ""; - case RECORDING: - return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Recording)"; - case PAUSED: - LOGGER.debug(LoggerMarkers.Playback, "Pausing a recording"); - state = TASstate.PAUSED; - tempPause = TASstate.RECORDING; - return verbose ? TextFormatting.GREEN + "Pausing a recording" : ""; - case NONE: - LOGGER.debug(LoggerMarkers.Playback, "Stopping a recording"); - TASmodClient.virtual.unpressEverything(); - state = TASstate.NONE; - return verbose ? TextFormatting.GREEN + "Stopping the recording" : ""; + case PLAYBACK: + return verbose ? TextFormatting.RED + "A recording is currently running. Please stop the recording first before starting a playback" : ""; + case RECORDING: + return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Recording)"; + case PAUSED: + LOGGER.debug(LoggerMarkers.Playback, "Pausing a recording"); + state = TASstate.PAUSED; + tempPause = TASstate.RECORDING; + return verbose ? TextFormatting.GREEN + "Pausing a recording" : ""; + case NONE: + LOGGER.debug(LoggerMarkers.Playback, "Stopping a recording"); + TASmodClient.virtual.unpressEverything(); + state = TASstate.NONE; + return verbose ? TextFormatting.GREEN + "Stopping the recording" : ""; } } else if (state == TASstate.PLAYBACK) { // If the container is currently playing back switch (stateIn) { - case PLAYBACK: - return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Playback)"; - case RECORDING: - return verbose ? TextFormatting.RED + "A playback is currently running. Please stop the playback first before starting a recording" : ""; - case PAUSED: - LOGGER.debug(LoggerMarkers.Playback, "Pausing a playback"); - state = TASstate.PAUSED; - tempPause = TASstate.PLAYBACK; - TASmodClient.virtual.unpressEverything(); - return verbose ? TextFormatting.GREEN + "Pausing a playback" : ""; - case NONE: - LOGGER.debug(LoggerMarkers.Playback, "Stopping a playback"); - Minecraft.getMinecraft().gameSettings.chatLinks = true; - TASmodClient.virtual.unpressEverything(); - state = TASstate.NONE; - return verbose ? TextFormatting.GREEN + "Stopping the playback" : ""; + case PLAYBACK: + return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Playback)"; + case RECORDING: + return verbose ? TextFormatting.RED + "A playback is currently running. Please stop the playback first before starting a recording" : ""; + case PAUSED: + LOGGER.debug(LoggerMarkers.Playback, "Pausing a playback"); + state = TASstate.PAUSED; + tempPause = TASstate.PLAYBACK; + TASmodClient.virtual.unpressEverything(); + return verbose ? TextFormatting.GREEN + "Pausing a playback" : ""; + case NONE: + LOGGER.debug(LoggerMarkers.Playback, "Stopping a playback"); + Minecraft.getMinecraft().gameSettings.chatLinks = true; + TASmodClient.virtual.unpressEverything(); + state = TASstate.NONE; + return verbose ? TextFormatting.GREEN + "Stopping the playback" : ""; } } else if (state == TASstate.PAUSED) { switch (stateIn) { - case PLAYBACK: - LOGGER.debug(LoggerMarkers.Playback, "Resuming a playback"); - state=TASstate.PLAYBACK; - tempPause=TASstate.NONE; - return verbose ? TextFormatting.GREEN + "Resuming a playback" : ""; - case RECORDING: - LOGGER.debug(LoggerMarkers.Playback, "Resuming a recording"); - state=TASstate.RECORDING; - tempPause=TASstate.NONE; - return verbose ? TextFormatting.GREEN + "Resuming a recording" : ""; - case PAUSED: - return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Paused)"; - case NONE: - LOGGER.debug(LoggerMarkers.Playback, "Aborting pausing"); - state=TASstate.NONE; - TASstate statey=tempPause; - tempPause=TASstate.NONE; - return TextFormatting.GREEN + "Aborting a "+statey.toString().toLowerCase()+" that was paused"; + case PLAYBACK: + LOGGER.debug(LoggerMarkers.Playback, "Resuming a playback"); + state = TASstate.PLAYBACK; + tempPause = TASstate.NONE; + return verbose ? TextFormatting.GREEN + "Resuming a playback" : ""; + case RECORDING: + LOGGER.debug(LoggerMarkers.Playback, "Resuming a recording"); + state = TASstate.RECORDING; + tempPause = TASstate.NONE; + return verbose ? TextFormatting.GREEN + "Resuming a recording" : ""; + case PAUSED: + return TextFormatting.RED + "Please report this message to the mod author, because you should never be able to see this (Error: Paused)"; + case NONE: + LOGGER.debug(LoggerMarkers.Playback, "Aborting pausing"); + state = TASstate.NONE; + TASstate statey = tempPause; + tempPause = TASstate.NONE; + return TextFormatting.GREEN + "Aborting a " + statey.toString().toLowerCase() + " that was paused"; } } return "Something went wrong ._."; @@ -256,12 +258,13 @@ public String setTASState(TASstate stateIn, boolean verbose) { /** * Switches between the paused state and the state it was in before the pause + * * @return The new state */ public TASstate togglePause() { - if(state!=TASstate.PAUSED) { + if (state != TASstate.PAUSED) { setTASState(TASstate.PAUSED); - }else { + } else { setTASState(tempPause); } return state; @@ -269,21 +272,22 @@ public TASstate togglePause() { /** * Forces the playback to pause or unpause + * * @param pause True, if it should be paused */ public void pause(boolean pause) { LOGGER.trace(LoggerMarkers.Playback, "Pausing {}", pause); - if(pause) { - if(state!=TASstate.NONE) { + if (pause) { + if (state != TASstate.NONE) { setTASState(TASstate.PAUSED, false); } - }else { - if(state == TASstate.PAUSED) { + } else { + if (state == TASstate.PAUSED) { setTASState(tempPause, false); } } } - + public boolean isPlayingback() { return state == TASstate.PLAYBACK; } @@ -291,7 +295,7 @@ public boolean isPlayingback() { public boolean isRecording() { return state == TASstate.RECORDING; } - + public boolean isPaused() { return state == TASstate.PAUSED; } @@ -376,30 +380,30 @@ public VirtualSubticks addSubticksToContainer(VirtualSubticks subticks) { * the next inputs */ public void nextTick() { - /*Stop the playback while player is still loading*/ - EntityPlayerSP player=Minecraft.getMinecraft().player; - - if(player!=null && player.addedToChunk) { - if(isPaused() && tempPause != TASstate.NONE) { - TASstateClient.setOrSend(tempPause); // The recording is paused in LoadWorldEvents#startLaunchServer + /* Stop the playback while player is still loading */ + EntityPlayerSP player = Minecraft.getMinecraft().player; + + if (player != null && player.addedToChunk) { + if (isPaused() && tempPause != TASstate.NONE) { + TASstateClient.setOrSend(tempPause); // The recording is paused in LoadWorldEvents#startLaunchServer pause(false); printCredits(); } } - - /*Tick the next playback or recording*/ + + /* Tick the next playback or recording */ if (state == TASstate.RECORDING) { recordNextTick(); } else if (state == TASstate.PLAYBACK) { playbackNextTick(); } } - + private void recordNextTick() { index++; - if(inputs.size()<=index) { - if(inputs.size()= index; i--) { + for (long i = inputs.size() - 1; i >= index; i--) { inputs.remove(i); } index--; TASstateClient.setOrSend(TASstate.RECORDING); return; } - - /*Stop condition*/ + + /* Stop condition */ if (index == inputs.size()) { unpressContainer(); TASstateClient.setOrSend(TASstate.NONE); } - /*Continue condition*/ + /* Continue condition */ else { - TickInputContainer tickcontainer = inputs.get(index); //Loads the new inputs from the container + TickInputContainer tickcontainer = inputs.get(index); // Loads the new inputs from the container this.keyboard = tickcontainer.getKeyboard().clone(); this.mouse = tickcontainer.getMouse().clone(); this.subticks = tickcontainer.getSubticks().clone(); @@ -468,13 +473,13 @@ public BigArrayList getInputs() { public Map>> getControlBytes() { return controlBytes; } - + public Map> getComments() { return comments; } - - public void setIndex(int index) throws IndexOutOfBoundsException{ - if(index<=size()) { + + public void setIndex(int index) throws IndexOutOfBoundsException { + if (index <= size()) { this.index = index; if (state == TASstate.PLAYBACK) { TickInputContainer tickcontainer = inputs.get(index); @@ -482,7 +487,7 @@ public void setIndex(int index) throws IndexOutOfBoundsException{ this.mouse = tickcontainer.getMouse(); this.subticks = tickcontainer.getSubticks(); } - }else { + } else { throw new IndexOutOfBoundsException("Index is bigger than the container"); } } @@ -496,7 +501,7 @@ public TickInputContainer get(int index) { } return tickcontainer; } - + /** * @return The {@link TickInputContainer} at the current index */ @@ -510,13 +515,13 @@ public void clear() { controlBytes.clear(); comments.clear(); index = 0; - startLocation=""; + startLocation = ""; desyncMonitor.clear(); clearCredits(); } - + private void clearCredits() { - title="Insert Author here"; + title = "Insert Author here"; authors = "Insert author here"; playtime = "00:00.0"; rerecords = 0; @@ -581,7 +586,7 @@ public void fixTicks() { inputs.get(i).setTick(i + 1); } } - + public long getStartSeed() { return startSeed; } @@ -642,13 +647,7 @@ private void tpPlayer(String startLocation) throws NumberFormatException { float anglePitch = Float.parseFloat(section[4]); try { - TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_TELEPORT) - .writeDouble(x) - .writeDouble(y) - .writeDouble(z) - .writeFloat(angleYaw) - .writeFloat(anglePitch) - ); + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_TELEPORT).writeDouble(x).writeDouble(y).writeDouble(z).writeFloat(angleYaw).writeFloat(anglePitch)); } catch (Exception e) { e.printStackTrace(); } @@ -664,13 +663,13 @@ public void unpressContainer() { keyboard.clear(); mouse.clear(); } - + // ============================================================== public void printCredits() { LOGGER.trace(LoggerMarkers.Playback, "Printing credits"); - if (state == TASstate.PLAYBACK&&!creditsPrinted) { - creditsPrinted=true; + if (state == TASstate.PLAYBACK && !creditsPrinted) { + creditsPrinted = true; printMessage(title, ChatFormatting.GOLD); printMessage("", null); printMessage("by " + authors, ChatFormatting.AQUA); @@ -680,23 +679,24 @@ public void printCredits() { printMessage("Rerecords: " + rerecords, null); } } - + private void printMessage(String msg, ChatFormatting format) { - String formatString=""; - if(format!=null) - formatString=format.toString(); - + String formatString = ""; + if (format != null) + formatString = format.toString(); + Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(formatString + msg)); } public void setPlayUntil(int until) { - this.playUntil = until; + this.playUntil = until; } - + // ============================================================== - + /** * Storage class which stores the keyboard, mouse and subticks of a given tick. + * * @author Scribble * */ @@ -750,25 +750,28 @@ public int getTick() { public void setTick(int tick) { this.tick = tick; } - + @Override public TickInputContainer clone() { return new TickInputContainer(tick, keyboard, mouse, subticks); } } - + /** * State of the input recorder + * * @author Scribble * */ public static enum TASstate { /** - * The game is neither recording, playing back or paused, is also set when aborting all mentioned states. + * The game is neither recording, playing back or paused, is also set when + * aborting all mentioned states. */ NONE, /** - * The game plays back the inputs loaded in {@link InputContainer} and locks user interaction. + * The game plays back the inputs loaded in {@link InputContainer} and locks + * user interaction. */ PLAYBACK, /** @@ -776,37 +779,29 @@ public static enum TASstate { */ RECORDING, /** - * The playback or recording is paused and may be resumed. Note that the game isn't paused, only the playback. Useful for debugging things. + * The playback or recording is paused and may be resumed. Note that the game + * isn't paused, only the playback. Useful for debugging things. */ - PAUSED; // #124 + PAUSED; // #124 } - public void setStateWhenOpened(TASstate state) { - TASmodClient.openMainMenuScheduler.add(()->{ - PlaybackController container = TASmodClient.virtual.getContainer(); - if(state == TASstate.RECORDING) { - long seed = TASmod.ktrngHandler.getGlobalSeedClient(); - container.setStartSeed(seed); - } - TASstateClient.setOrSend(state); + TASmodClient.openMainMenuScheduler.add(() -> { + PlaybackController container = TASmodClient.virtual.getContainer(); + if (state == TASstate.RECORDING) { + long seed = TASmod.ktrngHandler.getGlobalSeedClient(); + container.setStartSeed(seed); + } + TASstateClient.setOrSend(state); }); } - + // ====================================== Networking - + @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] { - TASmodPackets.PLAYBACK_SAVE, - TASmodPackets.PLAYBACK_LOAD, - TASmodPackets.PLAYBACK_FULLPLAY, - TASmodPackets.PLAYBACK_FULLRECORD, - TASmodPackets.PLAYBACK_RESTARTANDPLAY, - TASmodPackets.PLAYBACK_PLAYUNTIL, - TASmodPackets.PLAYBACK_TELEPORT, - TASmodPackets.CLEAR_INNPUTS - + return new TASmodPackets[] { TASmodPackets.PLAYBACK_SAVE, TASmodPackets.PLAYBACK_LOAD, TASmodPackets.PLAYBACK_FULLPLAY, TASmodPackets.PLAYBACK_FULLRECORD, TASmodPackets.PLAYBACK_RESTARTANDPLAY, TASmodPackets.PLAYBACK_PLAYUNTIL, TASmodPackets.PLAYBACK_TELEPORT, TASmodPackets.CLEAR_INNPUTS + }; } @@ -817,137 +812,136 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa Minecraft mc = Minecraft.getMinecraft(); switch (packet) { - - case PLAYBACK_SAVE: - name = TASmodBufferBuilder.readString(buf); - try { - TASmodClient.virtual.saveInputs(name); - } catch (IOException e) { + + case PLAYBACK_SAVE: + name = TASmodBufferBuilder.readString(buf); + try { + TASmodClient.virtual.saveInputs(name); + } catch (IOException e) { + if (mc.world != null) + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); + else + e.printStackTrace(); + return; + } if (mc.world != null) - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Saved inputs to " + name + ".mctas")); else - e.printStackTrace(); - return; - } - if (mc.world != null) - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Saved inputs to " + name + ".mctas")); - else - LOGGER.debug(LoggerMarkers.Playback, "Saved inputs to " + name + ".mctas"); - break; - - case PLAYBACK_LOAD: - name = TASmodBufferBuilder.readString(buf); - try { - TASmodClient.virtual.loadInputs(name); - } catch (IOException e) { + LOGGER.debug(LoggerMarkers.Playback, "Saved inputs to " + name + ".mctas"); + break; + + case PLAYBACK_LOAD: + name = TASmodBufferBuilder.readString(buf); + try { + TASmodClient.virtual.loadInputs(name); + } catch (IOException e) { + if (mc.world != null) + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); + else + e.printStackTrace(); + return; + } if (mc.world != null) - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.RED + e.getMessage())); + mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Loaded inputs from " + name + ".mctas")); else + LOGGER.debug(LoggerMarkers.Playback, "Loaded inputs from " + name + ".mctas"); + break; + + case PLAYBACK_FULLPLAY: + setStateWhenOpened(TASstate.PLAYBACK); // Set the state to PLAYBACK when the main menu is opened + + TASmodClient.tickSchedulerClient.add(() -> { // Schedule code to be executed on the next tick + // Exit the server if you are in one + if (mc.world != null) { + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + } + mc.displayGuiScreen(new GuiMainMenu()); + }); + break; + + case PLAYBACK_FULLRECORD: + setStateWhenOpened(TASstate.RECORDING); // Set the state to RECORDING when the main menu is opened + + TASmodClient.virtual.getContainer().clear(); // Clear inputs + + // Schedule code to be executed on the next tick + TASmodClient.tickSchedulerClient.add(() -> { + if (mc.world != null) { // Exit the server if you are in one + mc.world.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + } + mc.displayGuiScreen(new GuiMainMenu()); + }); + break; + + case PLAYBACK_RESTARTANDPLAY: + final String finalname = ByteBufferBuilder.readString(buf); + + try { + Thread.sleep(100L); + } catch (InterruptedException e) { e.printStackTrace(); - return; - } - if (mc.world != null) - mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString(TextFormatting.GREEN + "Loaded inputs from " + name + ".mctas")); - else - LOGGER.debug(LoggerMarkers.Playback, "Loaded inputs from " + name + ".mctas"); - break; - - case PLAYBACK_FULLPLAY: - setStateWhenOpened(TASstate.PLAYBACK); // Set the state to PLAYBACK when the main menu is opened - - TASmodClient.tickSchedulerClient.add(() -> { // Schedule code to be executed on the next tick - // Exit the server if you are in one - if (mc.world != null) { - mc.world.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient) null); - } - mc.displayGuiScreen(new GuiMainMenu()); - }); - break; - - case PLAYBACK_FULLRECORD: - setStateWhenOpened(TASstate.RECORDING); // Set the state to RECORDING when the main menu is opened - - TASmodClient.virtual.getContainer().clear(); // Clear inputs - - // Schedule code to be executed on the next tick - TASmodClient.tickSchedulerClient.add(() -> { - if (mc.world != null) { // Exit the server if you are in one - mc.world.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient) null); } - mc.displayGuiScreen(new GuiMainMenu()); - }); - break; - - case PLAYBACK_RESTARTANDPLAY: - final String finalname = ByteBufferBuilder.readString(buf); - - try { - Thread.sleep(100L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Minecraft.getMinecraft().addScheduledTask(() -> { - TASmodClient.config.set(ConfigOptions.FileToOpen, finalname); - System.exit(0); - }); - break; - - case PLAYBACK_PLAYUNTIL: - int until = ByteBufferBuilder.readInt(buf); - TASmodClient.virtual.getContainer().setPlayUntil(until); - break; - - case CLEAR_INNPUTS: - TASmodClient.virtual.getContainer().clear(); - break; - - case PLAYBACK_TELEPORT: - throw new WrongSideException(packet, Side.CLIENT); - - default: - throw new PacketNotImplementedException(packet, this.getClass()); + Minecraft.getMinecraft().addScheduledTask(() -> { + TASmodClient.config.set(ConfigOptions.FileToOpen, finalname); + System.exit(0); + }); + break; + + case PLAYBACK_PLAYUNTIL: + int until = ByteBufferBuilder.readInt(buf); + TASmodClient.virtual.getContainer().setPlayUntil(until); + break; + + case CLEAR_INNPUTS: + TASmodClient.virtual.getContainer().clear(); + break; + + case PLAYBACK_TELEPORT: + throw new WrongSideException(packet, Side.CLIENT); + + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); } } @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; - - - //TODO #181 Permissions + + // TODO #181 Permissions switch (packet) { - case PLAYBACK_TELEPORT: - double x = TASmodBufferBuilder.readDouble(buf); - double y = TASmodBufferBuilder.readDouble(buf); - double z = TASmodBufferBuilder.readDouble(buf); - float angleYaw = TASmodBufferBuilder.readFloat(buf); - float anglePitch = TASmodBufferBuilder.readFloat(buf); - - EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(clientID); - player.getServerWorld().addScheduledTask(() -> { - player.rotationPitch = anglePitch; - player.rotationYaw = angleYaw; - - player.setPositionAndUpdate(x, y, z); - }); - break; - - case CLEAR_INNPUTS: - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); - - case PLAYBACK_FULLPLAY: - case PLAYBACK_FULLRECORD: - case PLAYBACK_RESTARTANDPLAY: - case PLAYBACK_PLAYUNTIL: - case PLAYBACK_SAVE: - case PLAYBACK_LOAD: - TASmod.server.sendToAll(new TASmodBufferBuilder(buf)); - break; - default: - throw new PacketNotImplementedException(packet, this.getClass()); + case PLAYBACK_TELEPORT: + double x = TASmodBufferBuilder.readDouble(buf); + double y = TASmodBufferBuilder.readDouble(buf); + double z = TASmodBufferBuilder.readDouble(buf); + float angleYaw = TASmodBufferBuilder.readFloat(buf); + float anglePitch = TASmodBufferBuilder.readFloat(buf); + + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(clientID); + player.getServerWorld().addScheduledTask(() -> { + player.rotationPitch = anglePitch; + player.rotationYaw = angleYaw; + + player.setPositionAndUpdate(x, y, z); + }); + break; + + case CLEAR_INNPUTS: + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + + case PLAYBACK_FULLPLAY: + case PLAYBACK_FULLRECORD: + case PLAYBACK_RESTARTANDPLAY: + case PLAYBACK_PLAYUNTIL: + case PLAYBACK_SAVE: + case PLAYBACK_LOAD: + TASmod.server.sendToAll(new TASmodBufferBuilder(buf)); + break; + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); } } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java index 95704561..0c0c6f43 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java @@ -80,7 +80,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; default: - throw new PacketNotImplementedException(packet, this.getClass()); + throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java index dc2f73dc..c53fe44a 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java @@ -5,6 +5,7 @@ import java.nio.ByteBuffer; import java.util.UUID; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.PacketID; @@ -68,7 +69,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; default: - throw new PacketNotImplementedException(packet, this.getClass()); + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index 53023225..d031dd6e 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -7,6 +7,7 @@ import java.nio.ByteBuffer; import java.util.UUID; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; @@ -40,16 +41,21 @@ * * @author Scribble */ -public class SavestateHandlerClient implements ClientPacketHandler{ +public class SavestateHandlerClient implements ClientPacketHandler { public final static File savestateDirectory = new File(TASmodClient.tasdirectory + File.separator + "savestates"); - + /** - * A bug occurs when unloading the client world. The client world has a "unloadedEntityList" which, as the name implies, stores all unloaded entities
+ * A bug occurs when unloading the client world. The client world has a + * "unloadedEntityList" which, as the name implies, stores all unloaded entities + *
*
- * Strange things happen, when the client player is unloaded, which is what happens when we use {@linkplain SavestateHandlerClient#unloadAllClientChunks()}.
+ * Strange things happen, when the client player is unloaded, which is what + * happens when we use + * {@linkplain SavestateHandlerClient#unloadAllClientChunks()}.
*
- * This method ensures that the player is loaded by removing the player from the unloadedEntityList.
+ * This method ensures that the player is loaded by removing the player from the + * unloadedEntityList.
*
* TLDR:
* Makes sure that the player is not removed from the loaded entity list
@@ -63,12 +69,15 @@ public static void keepPlayerInLoadedEntityList(net.minecraft.entity.player.Enti } /** - * Similar to {@linkplain keepPlayerInLoadedEntityList}, the chunks themselves have a list with loaded entities
+ * Similar to {@linkplain keepPlayerInLoadedEntityList}, the chunks themselves + * have a list with loaded entities
*
- * Even after adding the player to the world, the chunks may not load the player correctly.
+ * Even after adding the player to the world, the chunks may not load the player + * correctly.
*
* Without this, no model is shown in third person
- * This state is fixed, once the player moves into a different chunk, since the new chunk adds the player to it's list.
+ * This state is fixed, once the player moves into a different chunk, since the + * new chunk adds the player to it's list.
*
* * TLDR:
@@ -105,22 +114,22 @@ public static void savestate(String nameOfSavestate) throws SavestateException, LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); return; } - + SavestateHandlerClient.savestateDirectory.mkdir(); - + File targetfile = new File(SavestateHandlerClient.savestateDirectory, nameOfSavestate + ".mctas"); - + PlaybackController container = TASmodClient.virtual.getContainer(); if (container.isRecording()) { - TASmodClient.serialiser.saveToFileV1(targetfile, container); //If the container is recording, store it entirely - } else if(container.isPlayingback()){ - TASmodClient.serialiser.saveToFileV1Until(targetfile, container, container.index()); //If the container is playing, store it until the current index + TASmodClient.serialiser.saveToFileV1(targetfile, container); // If the container is recording, store it entirely + } else if (container.isPlayingback()) { + TASmodClient.serialiser.saveToFileV1Until(targetfile, container, container.index()); // If the container is playing, store it until the current index } } /** - * Replaces the current recording with the recording from the savestate. - * Gets triggered when a savestate is loaded on the server
+ * Replaces the current recording with the recording from the savestate. Gets + * triggered when a savestate is loaded on the server
* Side: Client * * @param nameOfSavestate coming from the server @@ -132,19 +141,19 @@ public static void loadstate(String nameOfSavestate) throws IOException { LOGGER.error(LoggerMarkers.Savestate, "No recording savestate loaded since the name of savestate is empty"); return; } - + savestateDirectory.mkdir(); - + File targetfile = new File(savestateDirectory, nameOfSavestate + ".mctas"); - + PlaybackController container = TASmodClient.virtual.getContainer(); - if (!container.isNothingPlaying()) { // If the file exists and the container is recording or playing, load the clientSavestate + if (!container.isNothingPlaying()) { // If the file exists and the container is recording or playing, load the + // clientSavestate if (targetfile.exists()) { TASmodClient.virtual.loadClientSavestate(TASmodClient.serialiser.fromEntireFileV1(targetfile)); } else { TASmodClient.virtual.getContainer().setTASState(TASstate.NONE, false); - Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW - + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); + Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); } } @@ -189,31 +198,33 @@ public static void loadPlayer(NBTTagCompound compound) { } /** - * Unloads all chunks and reloads the renderer so no chunks will be visible throughout the unloading progress
+ * Unloads all chunks and reloads the renderer so no chunks will be visible + * throughout the unloading progress
*
* Side: Client + * * @see MixinChunkProviderClient#unloadAllChunks() */ @Environment(EnvType.CLIENT) public static void unloadAllClientChunks() { LOGGER.trace(LoggerMarkers.Savestate, "Unloading All Client Chunks"); Minecraft mc = Minecraft.getMinecraft(); - - ChunkProviderClient chunkProvider=mc.world.getChunkProvider(); - - ((ChunkProviderDuck)chunkProvider).unloadAllChunks(); + + ChunkProviderClient chunkProvider = mc.world.getChunkProvider(); + + ((ChunkProviderDuck) chunkProvider).unloadAllChunks(); Minecraft.getMinecraft().renderGlobal.loadRenderers(); } @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] { - TASmodPackets.SAVESTATE_SAVE, - TASmodPackets.SAVESTATE_LOAD, - TASmodPackets.SAVESTATE_PLAYER, - TASmodPackets.SAVESTATE_SCREEN, - TASmodPackets.SAVESTATE_UNLOAD_CHUNKS - }; + return new TASmodPackets[] { + TASmodPackets.SAVESTATE_SAVE, + TASmodPackets.SAVESTATE_LOAD, + TASmodPackets.SAVESTATE_PLAYER, + TASmodPackets.SAVESTATE_SCREEN, + TASmodPackets.SAVESTATE_UNLOAD_CHUNKS + }; } @Override @@ -221,51 +232,51 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa TASmodPackets packet = (TASmodPackets) id; String name = null; Minecraft mc = Minecraft.getMinecraft(); - + switch (packet) { - case SAVESTATE_SAVE: - // Create client savestate - name = TASmodBufferBuilder.readString(buf); - try { - SavestateHandlerClient.savestate(name); - } catch (SavestateException e) { - LOGGER.error(e.getMessage()); - } catch (IOException e) { - e.printStackTrace(); - } - break; - case SAVESTATE_LOAD: - // Load client savestate - name = TASmodBufferBuilder.readString(buf); - try { - SavestateHandlerClient.loadstate(name); - } catch (IOException e) { - e.printStackTrace(); - } - break; - case SAVESTATE_PLAYER: - NBTTagCompound compound = TASmodBufferBuilder.readNBTTagCompound(buf); - SavestateHandlerClient.loadPlayer(compound); - break; - - case SAVESTATE_SCREEN: - // Open/Close Savestate screen - boolean open = TASmodBufferBuilder.readBoolean(buf); - if (open) { - mc.displayGuiScreen(new GuiSavestateSavingScreen()); - } else { - mc.displayGuiScreen(null); - } - break; - - case SAVESTATE_UNLOAD_CHUNKS: - SavestateHandlerClient.unloadAllClientChunks(); - break; - - default: - throw new PacketNotImplementedException(packet, this.getClass()); + case SAVESTATE_SAVE: + // Create client savestate + name = TASmodBufferBuilder.readString(buf); + try { + SavestateHandlerClient.savestate(name); + } catch (SavestateException e) { + LOGGER.error(e.getMessage()); + } catch (IOException e) { + e.printStackTrace(); + } + break; + case SAVESTATE_LOAD: + // Load client savestate + name = TASmodBufferBuilder.readString(buf); + try { + SavestateHandlerClient.loadstate(name); + } catch (IOException e) { + e.printStackTrace(); + } + break; + case SAVESTATE_PLAYER: + NBTTagCompound compound = TASmodBufferBuilder.readNBTTagCompound(buf); + SavestateHandlerClient.loadPlayer(compound); + break; + + case SAVESTATE_SCREEN: + // Open/Close Savestate screen + boolean open = TASmodBufferBuilder.readBoolean(buf); + if (open) { + mc.displayGuiScreen(new GuiSavestateSavingScreen()); + } else { + mc.displayGuiScreen(null); + } + break; + + case SAVESTATE_UNLOAD_CHUNKS: + SavestateHandlerClient.unloadAllClientChunks(); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); } - + } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index ee36f433..fa7031af 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -750,7 +750,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa // return; // } try { - TASmod.savestateHandler.saveState(index, true); + TASmod.savestateHandlerServer.saveState(index, true); } catch (SavestateException e) { if(player!=null) player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getMessage())); @@ -762,7 +762,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa LOGGER.error(e); } finally { - TASmod.savestateHandler.state=SavestateState.NONE; + TASmod.savestateHandlerServer.state=SavestateState.NONE; } break; @@ -783,7 +783,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa case SAVESTATE_UNLOAD_CHUNKS: throw new WrongSideException(id, Side.SERVER); default: - throw new PacketNotImplementedException(packet, this.getClass()); + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); } } @@ -935,7 +935,7 @@ public static void loadAndSendMotionToPlayer(MinecraftServer server) { if(dimensionNow!=dimensionPrev) { list.changePlayerDimension(player, dimensionNow); - }else { + } else { player.getServerWorld().unloadedEntityList.remove(player); } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index 6896d64f..ffeba278 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -5,6 +5,7 @@ import java.nio.ByteBuffer; import java.util.UUID; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; @@ -19,10 +20,11 @@ /** * Changes the {@link Minecraft#timer} variable + * * @author Scribble * */ -public class TickrateChangerClient implements ClientPacketHandler{ +public class TickrateChangerClient implements ClientPacketHandler { /** * The current tickrate of the client */ @@ -33,22 +35,22 @@ public class TickrateChangerClient implements ClientPacketHandler{ * pausing */ public float tickrateSaved = 20F; - + /** * True if the tickrate is 20 and the client should advance 1 tick */ public boolean advanceTick = false; - + public long millisecondsPerTick = 50L; public TickrateChangerClient() { this(20f); } - + public TickrateChangerClient(float initialTickrate) { ticksPerSecond = initialTickrate; } - + /** * Changes both client and server tickrates * @@ -58,7 +60,7 @@ public void changeTickrate(float tickrate) { changeClientTickrate(tickrate); changeServerTickrate(tickrate); } - + public void changeClientTickrate(float tickrate) { changeClientTickrate(tickrate, true); } @@ -78,7 +80,7 @@ public void changeClientTickrate(float tickrate, boolean log) { if (tickrate > 0) { millisecondsPerTick = (long) (1000F / tickrate); mc.timer.tickLength = millisecondsPerTick; - + } else if (tickrate == 0F) { if (ticksPerSecond != 0) { tickrateSaved = ticksPerSecond; @@ -86,8 +88,8 @@ public void changeClientTickrate(float tickrate, boolean log) { mc.timer.tickLength = Float.MAX_VALUE; } ticksPerSecond = tickrate; - if(log) - log("Setting the client tickrate to "+ ticksPerSecond); + if (log) + log("Setting the client tickrate to " + ticksPerSecond); } /** @@ -100,7 +102,7 @@ public void changeServerTickrate(float tickrate) { if (tickrate < 0) { return; } - + try { // request tickrate change TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(tickrate)); @@ -146,25 +148,27 @@ public void pauseGame(boolean pause) { if (pause) { changeTickrate(0F); } else { - advanceTick=false; + advanceTick = false; changeTickrate(tickrateSaved); } } /** * Pauses the game without sending a command to the server + * * @param pause The state of the client */ public void pauseClientGame(boolean pause) { - if(pause) { + if (pause) { changeClientTickrate(0F); - }else { + } else { changeClientTickrate(tickrateSaved); } } - + /** - * Advances the game by 1 tick. Sends a {@link AdvanceTickratePacket} to the server or calls {@link #advanceClientTick()} if the world is null + * Advances the game by 1 tick. Sends a {@link AdvanceTickratePacket} to the + * server or calls {@link #advanceClientTick()} if the world is null */ public void advanceTick() { if (Minecraft.getMinecraft().world != null) { @@ -184,7 +188,7 @@ public void advanceServerTick() { e.printStackTrace(); } } - + /** * Advances the game by 1 tick. Doesn't send a packet to the server */ @@ -194,54 +198,51 @@ public void advanceClientTick() { changeClientTickrate(tickrateSaved); } } - + public void joinServer() { changeServerTickrate(ticksPerSecond); } - + private static void log(String msg) { LOGGER.debug(LoggerMarkers.Tickrate, msg); } @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] { - TASmodPackets.TICKRATE_CHANGE, - TASmodPackets.TICKRATE_ADVANCE, - TASmodPackets.TICKRATE_ZERO, - }; + return new TASmodPackets[] { TASmodPackets.TICKRATE_CHANGE, TASmodPackets.TICKRATE_ADVANCE, TASmodPackets.TICKRATE_ZERO, }; } + @Override public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; - - switch (packet) { - case TICKRATE_CHANGE: - float tickrate = TASmodBufferBuilder.readFloat(buf); - changeClientTickrate(tickrate); - break; - case TICKRATE_ADVANCE: - advanceClientTick(); - break; - case TICKRATE_ZERO: - TickratePauseState state = TASmodBufferBuilder.readTickratePauseState(buf); - switch (state) { - case PAUSE: - pauseClientGame(true); + switch (packet) { + case TICKRATE_CHANGE: + float tickrate = TASmodBufferBuilder.readFloat(buf); + changeClientTickrate(tickrate); break; - case UNPAUSE: - pauseClientGame(false); + case TICKRATE_ADVANCE: + advanceClientTick(); break; - case TOGGLE: - togglePauseClient(); - default: + case TICKRATE_ZERO: + TickratePauseState state = TASmodBufferBuilder.readTickratePauseState(buf); + + switch (state) { + case PAUSE: + pauseClientGame(true); + break; + case UNPAUSE: + pauseClientGame(false); + break; + case TOGGLE: + togglePauseClient(); + default: + break; + } break; - } - break; - default: - throw new PacketNotImplementedException(packet, this.getClass()); + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 7a204056..666f7f82 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -7,6 +7,7 @@ import com.minecrafttas.common.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.common.events.EventServer.EventServerStop; +import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.PacketID; @@ -22,50 +23,53 @@ /** * Controls the tickrate on the server side * - * The tickrate is controlled in MinecraftServer.run() where the server is halted for 50 milliseconds minus the time the tick took to execute. + * The tickrate is controlled in MinecraftServer.run() where the server is + * halted for 50 milliseconds minus the time the tick took to execute. *

- * To change the tickrate on server and all clients use {@link #changeTickrate(float)}. + * To change the tickrate on server and all clients use + * {@link #changeTickrate(float)}. *

- * You can individually set the tickrate with {@link #changeClientTickrate(float)} and {@link #changeServerTickrate(float)}. + * You can individually set the tickrate with + * {@link #changeClientTickrate(float)} and + * {@link #changeServerTickrate(float)}. *

* * * @author Scribble * */ -public class TickrateChangerServer implements EventServerStop, EventPlayerJoinedServerSide, ServerPacketHandler{ - +public class TickrateChangerServer implements EventServerStop, EventPlayerJoinedServerSide, ServerPacketHandler { + /** * The current tickrate of the client */ - public float ticksPerSecond=20F; - + public float ticksPerSecond = 20F; + /** * How long the server should sleep */ - public long millisecondsPerTick=50L; - + public long millisecondsPerTick = 50L; + /** * The tickrate before {@link #ticksPerSecond} was changed to 0, used to toggle * pausing */ - public float tickrateSaved=20F; - + public float tickrateSaved = 20F; + /** * True if the tickrate is 20 and the server should advance 1 tick */ - public boolean advanceTick=false; - + public boolean advanceTick = false; + /** * The logger used for logging. Has to be set seperately */ public Logger logger; - - + public TickrateChangerServer(Logger logger) { this.logger = logger; } - + /** * Changes both client and server tickrates. *

@@ -77,21 +81,21 @@ public void changeTickrate(float tickrate) { changeClientTickrate(tickrate); changeServerTickrate(tickrate); } - + public void changeClientTickrate(float tickrate) { changeClientTickrate(tickrate, false); } - + /** * Changes the tickrate of all clients. Sends a {@link ChangeTickratePacket} * * @param tickrate The new tickrate of the client - * @param log If a message should logged + * @param log If a message should logged */ public void changeClientTickrate(float tickrate, boolean log) { - if(log) - log("Changing the tickrate "+ tickrate + " to all clients"); - + if (log) + log("Changing the tickrate " + tickrate + " to all clients"); + try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(tickrate)); } catch (Exception e) { @@ -107,106 +111,106 @@ public void changeClientTickrate(float tickrate, boolean log) { public void changeServerTickrate(float tickrate) { changeServerTickrate(tickrate, true); } - + /** * Changes the tickrate of the server * * @param tickrate The new tickrate of the server - * @param log If a message should logged + * @param log If a message should logged */ public void changeServerTickrate(float tickrate, boolean log) { - if(tickrate>0) { - millisecondsPerTick = (long)(1000L / tickrate); - }else if(tickrate==0) { - if(ticksPerSecond!=0) { - tickrateSaved=ticksPerSecond; - } - } - ticksPerSecond = tickrate; - if(log) { - log("Setting the server tickrate to "+ ticksPerSecond); - } + if (tickrate > 0) { + millisecondsPerTick = (long) (1000L / tickrate); + } else if (tickrate == 0) { + if (ticksPerSecond != 0) { + tickrateSaved = ticksPerSecond; + } + } + ticksPerSecond = tickrate; + if (log) { + log("Setting the server tickrate to " + ticksPerSecond); + } } - + /** * Toggles between tickrate 0 and tickrate > 0 */ public void togglePause() { - if(ticksPerSecond>0) { + if (ticksPerSecond > 0) { changeTickrate(0); - } - else if (ticksPerSecond==0) { - changeTickrate(tickrateSaved); - } - } - + } else if (ticksPerSecond == 0) { + changeTickrate(tickrateSaved); + } + } + /** * Enables tickrate 0 + * * @param pause True if the game should be paused, false if unpause */ public void pauseGame(boolean pause) { - if(pause) { + if (pause) { changeTickrate(0); - } - else { - advanceTick=false; - changeTickrate(tickrateSaved); - } + } else { + advanceTick = false; + changeTickrate(tickrateSaved); + } } - + /** * Pauses the game without sending a command to the clients + * * @param pause The state of the server */ public void pauseServerGame(boolean pause) { - if(pause) { + if (pause) { changeServerTickrate(0F); - }else { + } else { changeServerTickrate(tickrateSaved); } } - - + /** * Advances the game by 1 tick. */ - public void advanceTick() { - advanceServerTick(); - advanceClientTick(); - } - - /** - * Sends a {@link AdvanceTickratePacket} to all clients - */ - private void advanceClientTick() { - if(ticksPerSecond == 0) { - try { - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * Advances the server by 1 tick - */ + public void advanceTick() { + advanceServerTick(); + advanceClientTick(); + } + + /** + * Sends a {@link AdvanceTickratePacket} to all clients + */ + private void advanceClientTick() { + if (ticksPerSecond == 0) { + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + /** + * Advances the server by 1 tick + */ private void advanceServerTick() { - if(ticksPerSecond==0) { - advanceTick=true; - changeServerTickrate(tickrateSaved); - } + if (ticksPerSecond == 0) { + advanceTick = true; + changeServerTickrate(tickrateSaved); + } } /** - * Fired when a player joined the server - * @param player The player that joins the server - */ + * Fired when a player joined the server + * + * @param player The player that joins the server + */ @Override public void onPlayerJoinedServerSide(EntityPlayerMP player) { - if(TASmod.getServerInstance().isDedicatedServer()) { - log("Sending the current tickrate ("+ticksPerSecond+") to " +player.getName()); - + if (TASmod.getServerInstance().isDedicatedServer()) { + log("Sending the current tickrate (" + ticksPerSecond + ") to " + player.getName()); + try { TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(ticksPerSecond)); } catch (Exception e) { @@ -214,10 +218,11 @@ public void onPlayerJoinedServerSide(EntityPlayerMP player) { } } } - + /** * The message to log - * @param msg + * + * @param msg */ private void log(String msg) { logger.debug(LoggerMarkers.Tickrate, msg); @@ -229,7 +234,7 @@ public void onServerStop(MinecraftServer server) { pauseGame(false); } } - + public static enum TickratePauseState { /** * Set's the game to tickrate 0 @@ -256,57 +261,53 @@ public short toShort() { public static TickratePauseState fromShort(short i) { switch (i) { - case 1: - return PAUSE; - case 2: - return UNPAUSE; - default: - return TOGGLE; + case 1: + return PAUSE; + case 2: + return UNPAUSE; + default: + return TOGGLE; } } } @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] { - TASmodPackets.TICKRATE_CHANGE, - TASmodPackets.TICKRATE_ADVANCE, - TASmodPackets.TICKRATE_ZERO, - }; + return new TASmodPackets[] { TASmodPackets.TICKRATE_CHANGE, TASmodPackets.TICKRATE_ADVANCE, TASmodPackets.TICKRATE_ZERO, }; } @Override public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; - + switch (packet) { - case TICKRATE_CHANGE: - float tickrate = TASmodBufferBuilder.readFloat(buf); - changeTickrate(tickrate); - break; - case TICKRATE_ADVANCE: - advanceTick(); - break; - case TICKRATE_ZERO: - TickratePauseState state = TASmodBufferBuilder.readTickratePauseState(buf); - - switch (state) { - case PAUSE: - pauseGame(true); + case TICKRATE_CHANGE: + float tickrate = TASmodBufferBuilder.readFloat(buf); + changeTickrate(tickrate); break; - case UNPAUSE: - pauseGame(false); + case TICKRATE_ADVANCE: + advanceTick(); break; - case TOGGLE: - togglePause(); - default: + case TICKRATE_ZERO: + TickratePauseState state = TASmodBufferBuilder.readTickratePauseState(buf); + + switch (state) { + case PAUSE: + pauseGame(true); + break; + case UNPAUSE: + pauseGame(false); + break; + case TOGGLE: + togglePause(); + default: + break; + } break; - } - break; - default: - throw new PacketNotImplementedException(packet, this.getClass()); + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); } } - + } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index b72001b0..2f9ad55c 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -29,6 +29,10 @@ public class TickSyncServer implements ServerPacketHandler, EventServerTickPost private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[]{TASmodPackets.TICKSYNC}; + } /** * Handles incoming tick packets from the client to the server @@ -71,11 +75,6 @@ public static void clearList() { synchronizedList.clear(); } - @Override - public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[]{TASmodPackets.TICKSYNC}; - } - @Override public void onServerTickPost(MinecraftServer server) { try { diff --git a/src/test/java/common/TestConfiguration.java b/src/test/java/common/TestConfiguration.java index 8e01df55..893fcfe6 100644 --- a/src/test/java/common/TestConfiguration.java +++ b/src/test/java/common/TestConfiguration.java @@ -35,11 +35,17 @@ static void tearDownAfterClass() throws Exception { configPath.delete(); } + /** + * Test if the config is successfully initialized + */ @Test void testIfInitialized() { assertNotNull(config); } + /** + * Test if the default option is correctly set + */ @Test void testDefault() { configPath.delete(); @@ -47,6 +53,9 @@ void testDefault() { assertEquals("", config.get(ConfigOptions.FileToOpen)); } + /** + * Setting a value and recreating the config should result in the value still being set + */ @Test void testSavingAndLoading() { config.set(ConfigOptions.FileToOpen, "Test"); @@ -54,24 +63,36 @@ void testSavingAndLoading() { assertEquals("Test", config.get(ConfigOptions.FileToOpen)); } + /** + * Test if integers can be set + */ @Test void testIntegers() { config.set(ConfigOptions.FileToOpen, 3); assertEquals(3, config.getInt(ConfigOptions.FileToOpen)); } + /** + * Test if booleans can be set + */ @Test void testBooleans() { config.set(ConfigOptions.FileToOpen, true); assertEquals(true, config.getBoolean(ConfigOptions.FileToOpen)); } + /** + * Test if deleting and unsetting a config value works + */ @Test void testDeleteAndContains() { config.delete(ConfigOptions.FileToOpen); assertFalse(config.has(ConfigOptions.FileToOpen)); } + /** + * Test if resetting to default works + */ @Test void resetToDefault() { config.reset(ConfigOptions.FileToOpen); diff --git a/src/test/java/common/server/ByteBufferBuilderTest.java b/src/test/java/common/server/ByteBufferBuilderTest.java index 3edd64e9..9deb3547 100644 --- a/src/test/java/common/server/ByteBufferBuilderTest.java +++ b/src/test/java/common/server/ByteBufferBuilderTest.java @@ -55,6 +55,9 @@ public String getName() { } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting the packetid + */ @Test void testId() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -64,6 +67,9 @@ void testId() { assertEquals(0, buf.getInt()); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting the packetid + */ @Test void testId2() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_2); @@ -73,6 +79,9 @@ void testId2() { assertEquals(1, buf.getInt()); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting the packetid + */ @Test void testId3() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_3); @@ -82,6 +91,9 @@ void testId3() { assertEquals(2, buf.getInt()); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting an integer + */ @Test void testInt() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -94,6 +106,9 @@ void testInt() { assertEquals(1234, ByteBufferBuilder.readInt(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a float + */ @Test void testFloat() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -106,6 +121,9 @@ void testFloat() { assertEquals(12.2F, ByteBufferBuilder.readFloat(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a double + */ @Test void testDouble() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -118,6 +136,9 @@ void testDouble() { assertEquals(60.9D, ByteBufferBuilder.readDouble(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a long + */ @Test void testLong() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -130,6 +151,9 @@ void testLong() { assertEquals(800815L, ByteBufferBuilder.readLong(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a short + */ @Test void testShort() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -142,6 +166,9 @@ void testShort() { assertEquals(12, ByteBufferBuilder.readShort(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a boolean + */ @Test void testBoolean() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -154,6 +181,9 @@ void testBoolean() { assertEquals(true, ByteBufferBuilder.readBoolean(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a boolean + */ @Test void testBoolean2() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -166,6 +196,9 @@ void testBoolean2() { assertEquals(false, ByteBufferBuilder.readBoolean(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a string + */ @Test void testString() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -178,6 +211,9 @@ void testString() { assertEquals("Test", ByteBufferBuilder.readString(buf)); } + /** + * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a uuid + */ @Test void testUUID() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -193,6 +229,9 @@ void testUUID() { // ==================================== + /** + * Test creating a clone from an existing ByteBufferBuilder + */ @Test void testClone() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); @@ -214,6 +253,9 @@ void testClone() { // ===================================== + /** + * Test an exception for all types if a ByteBufferBuilder is already closed + */ @Test void testClosed() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index 4c098a32..d243873b 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -27,9 +27,14 @@ import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; +/** + * An integration test for the {@link Server} class by setting up a connection. + * Disabled due to gihub actions failing to execute the tests + */ @Disabled class ServerTest { + // The time to live for how long the tests should wait for the asynchronous server private static int ttl = 1; private enum TestPacketIDs implements PacketID { @@ -103,7 +108,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa latch.countDown(); break; default: - throw new PacketNotImplementedException(id, this.getClass()); + throw new PacketNotImplementedException(id, this.getClass(), Side.SERVER); } } @@ -117,7 +122,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa latch.countDown(); break; default: - throw new PacketNotImplementedException(id, this.getClass()); + throw new PacketNotImplementedException(id, this.getClass(), Side.CLIENT); } } @@ -131,6 +136,10 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa private static TestingClass clazz = new TestingClass(); + /** + * Setting up a local connection between client and server + * @throws Exception + */ @BeforeAll static void setUpBeforeClass() throws Exception { try { @@ -166,6 +175,9 @@ void tearDown() throws Exception { result = null; } + /** + * Test sending an int packet to {@link TestingClass#onServerPacket(PacketID, ByteBuffer, UUID)} + */ @Test void testSendToServerInterface() { try { @@ -184,6 +196,9 @@ void testSendToServerInterface() { assertEquals(Client.Side.SERVER, side); } + /** + * Test sending an int packet to {@link TestingClass#onClientPacket(PacketID, ByteBuffer, UUID)} to all clients currently connected + */ @Test void testSendToAllClientsInterface() { try { @@ -202,6 +217,9 @@ void testSendToAllClientsInterface() { assertEquals(Client.Side.CLIENT, side); } + /** + * Test sending an int packet to {@link TestingClass#onClientPacket(PacketID, ByteBuffer, UUID)} to only one client + */ @Test void testSendToClientInterface() { try { @@ -220,6 +238,9 @@ void testSendToClientInterface() { assertEquals(Client.Side.CLIENT, side); } + /** + * Test sending an string packet to {@link TestingClass#onClientPacket(PacketID, ByteBuffer, UUID)} to only one client + */ @Test void testSendToServerInterface2() { try { @@ -240,6 +261,9 @@ void testSendToServerInterface2() { // ============================ Lambda + /** + * Test sending an int packet to {@link TestPacketIDs#TEST_LAMBDA_SERVER} + */ @Test void testSendToServerLambda() { try { @@ -258,6 +282,9 @@ void testSendToServerLambda() { assertEquals(Client.Side.SERVER, side); } + /** + * Test sending an int packet to {@link TestPacketIDs#TEST_LAMBDA_CLIENT} to all clients + */ @Test void testSendToAllClientsLambda() { try { @@ -276,6 +303,9 @@ void testSendToAllClientsLambda() { assertEquals(Client.Side.CLIENT, side); } + /** + * Test sending an int packet to {@link TestPacketIDs#TEST_LAMBDA_CLIENT} to one client + */ @Test void testSendToClientLambda() { try { diff --git a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java index c97f0ac7..ea9e804a 100644 --- a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java +++ b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java @@ -55,7 +55,9 @@ public String getName() { } - + /** + * Test if NBTTagCompounds get correctly stored in a ByteBuffer + */ @Test void testNBT() { From a68cd0c99da5528999be9e6a3336526ed2ce9e55 Mon Sep 17 00:00:00 2001 From: Scribble Date: Fri, 1 Sep 2023 23:58:20 +0200 Subject: [PATCH 29/60] Fixed requesting motion, simplified NBTTagCompound sending --- .../common/server/ByteBufferBuilder.java | 13 ++ .../mixin/savestates/MixinEntityPlayerMP.java | 4 +- .../networking/TASmodBufferBuilder.java | 205 +++++------------- .../tasmod/networking/TASmodPackets.java | 1 + .../savestates/SavestateHandlerClient.java | 41 +++- .../savestates/SavestateHandlerServer.java | 76 +++---- 6 files changed, 142 insertions(+), 198 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 87fe2413..4945877c 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -101,6 +101,12 @@ public ByteBufferBuilder writeUUID(UUID uuid) { buffer.putLong(uuid.getLeastSignificantBits()); return this; } + + public ByteBufferBuilder writeByteArray(byte[] value) { + buffer.putInt(value.length); + buffer.put(value); + return this; + } /** * Unlocks the buffer from the pool making it available for other uses @@ -160,4 +166,11 @@ public static String readString(ByteBuffer buf) { buf.get(nameBytes); return new String(nameBytes); } + + public static byte[] readByteArray(ByteBuffer buf) { + int length = buf.getInt(); + byte[] array = new byte[length]; + buf.get(array); + return array; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java index ff17e04b..1de0ce97 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinEntityPlayerMP.java @@ -16,7 +16,7 @@ public class MixinEntityPlayerMP { @Inject(method = "writeEntityToNBT", at = @At(value = "RETURN")) public void writeClientMotion(NBTTagCompound compound, CallbackInfo ci) { NBTTagCompound nbttagcompound = new NBTTagCompound(); - PlayerHandler.Saver saver = PlayerHandler.getMotion().get((EntityPlayerMP) (Object) this); + PlayerHandler.MotionData saver = PlayerHandler.getMotion().get((EntityPlayerMP) (Object) this); if (saver != null) { nbttagcompound.setDouble("x", saver.getClientX()); nbttagcompound.setDouble("y", saver.getClientY()); @@ -51,7 +51,7 @@ public void readClientMotion(NBTTagCompound compound, CallbackInfo ci) { boolean sprinting = nbttagcompound.getBoolean("Sprinting"); float jumpVector = nbttagcompound.getFloat("JumpFactor"); - PlayerHandler.Saver saver = new PlayerHandler.Saver(clientmotionX, clientmotionY, clientmotionZ, clientmotionrX, clientmotionrY, clientmotionrZ, sprinting, jumpVector); + PlayerHandler.MotionData saver = new PlayerHandler.MotionData(clientmotionX, clientmotionY, clientmotionZ, clientmotionrX, clientmotionrY, clientmotionrZ, sprinting, jumpVector); PlayerHandler.getMotion().put((EntityPlayerMP) (Object) this, saver); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index f118c3b9..bd5a2439 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -1,13 +1,18 @@ package com.minecrafttas.tasmod.networking; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.DataInput; +import java.io.DataInputStream; import java.io.DataOutput; +import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler.MotionData; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; import net.minecraft.nbt.CompressedStreamTools; @@ -34,84 +39,26 @@ public TASmodBufferBuilder writeTASState(TASstate state) { } public TASmodBufferBuilder writeNBTTagCompound(NBTTagCompound compound) { - DataOutput out = new DataOutput() { - - @Override - public void writeUTF(String s) throws IOException { - writeString(s); - } - - @Override - public void writeShort(int v) throws IOException { - buffer.putShort((short) v); - } - - @Override - public void writeLong(long v) throws IOException { - buffer.putLong(v); - } - - @Override - public void writeInt(int v) throws IOException { - buffer.putInt(v); - } - - @Override - public void writeFloat(float v) throws IOException { - buffer.putFloat(v); - } - - @Override - public void writeDouble(double v) throws IOException { - buffer.putDouble(v); - } - - @Override - public void writeChars(String s) throws IOException { - writeString(s); - } - - @Override - public void writeChar(int v) throws IOException { - buffer.putChar((char) v); - } - - @Override - public void writeBytes(String s) throws IOException { - writeString(s); - } - - @Override - public void writeByte(int v) throws IOException { - buffer.put((byte) v); - } - - @Override - public void writeBoolean(boolean v) throws IOException { - writeBoolean(v); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - throw new IOException("Not implemented"); - } - - @Override - public void write(byte[] b) throws IOException { - buffer.put(b); - } - - @Override - public void write(int b) throws IOException { - buffer.put((byte) b); - } - }; + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + DataOutputStream dataout = new DataOutputStream(out); try { - CompressedStreamTools.write(compound, out); + CompressedStreamTools.write(compound, dataout); } catch (IOException e) { e.printStackTrace(); } + + this.writeByteArray(out.toByteArray()); + + try { + out.close(); + dataout.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return this; } @@ -120,93 +67,49 @@ public TASmodBufferBuilder writeTickratePauseState(TickratePauseState state) { return this; } + public TASmodBufferBuilder writeMotionData(MotionData data) { + writeDouble(data.getClientX()); + writeDouble(data.getClientY()); + writeDouble(data.getClientZ()); + writeFloat(data.getClientrX()); + writeFloat(data.getClientrY()); + writeFloat(data.getClientrZ()); + writeFloat(data.getJumpMovementVector()); + writeBoolean(data.isSprinting()); + return this; + } + public static TASstate readTASState(ByteBuffer buf) { return TASstate.values()[buf.getShort()]; } public static NBTTagCompound readNBTTagCompound(ByteBuffer buf) throws IOException { - DataInput input = new DataInput() { - - @Override - public int skipBytes(int n) throws IOException { - throw new IOException("Not implemented"); - } - - @Override - public int readUnsignedShort() throws IOException { - throw new IOException("Not implemented"); - } - - @Override - public int readUnsignedByte() throws IOException { - throw new IOException("Not implemented"); - } - - @Override - public String readUTF() throws IOException { - return TASmodBufferBuilder.readString(buf); - } - - @Override - public short readShort() throws IOException { - return TASmodBufferBuilder.readShort(buf); - } - - @Override - public long readLong() throws IOException { - return TASmodBufferBuilder.readLong(buf); - } - - @Override - public String readLine() throws IOException { - throw new IOException("Not implemented"); - } - - @Override - public int readInt() throws IOException { - return TASmodBufferBuilder.readInt(buf); - } - - @Override - public void readFully(byte[] b, int off, int len) throws IOException { - buf.get(b, off, len); - } - - @Override - public void readFully(byte[] b) throws IOException { - buf.get(b); - } - - @Override - public float readFloat() throws IOException { - return TASmodBufferBuilder.readFloat(buf); - } - - @Override - public double readDouble() throws IOException { - return TASmodBufferBuilder.readDouble(buf); - } - - @Override - public char readChar() throws IOException { - return buf.getChar(); - } - - @Override - public byte readByte() throws IOException { - return buf.get(); - } - - @Override - public boolean readBoolean() throws IOException { - return TASmodBufferBuilder.readBoolean(buf); - } - }; + ByteArrayInputStream input = new ByteArrayInputStream(readByteArray(buf)); + + DataInputStream datain = new DataInputStream(input); + + NBTTagCompound compound = CompressedStreamTools.read(datain, NBTSizeTracker.INFINITE); - return CompressedStreamTools.read(input, NBTSizeTracker.INFINITE); + input.close(); + datain.close(); + + return compound; } public static TickratePauseState readTickratePauseState(ByteBuffer buf) { return TickratePauseState.values()[buf.getShort()]; } + + public static MotionData readMotionData(ByteBuffer buf) { + double x = TASmodBufferBuilder.readDouble(buf); + double y = TASmodBufferBuilder.readDouble(buf); + double z = TASmodBufferBuilder.readDouble(buf); + float rx = TASmodBufferBuilder.readFloat(buf); + float ry = TASmodBufferBuilder.readFloat(buf); + float rz = TASmodBufferBuilder.readFloat(buf); + float jumpMovementVector = TASmodBufferBuilder.readFloat(buf); + boolean sprinting = TASmodBufferBuilder.readBoolean(buf); + + return new MotionData(x, y, z, rx, ry, rz, sprinting, jumpMovementVector); + } } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index 64952eea..537aa0b7 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -43,6 +43,7 @@ public enum TASmodPackets implements PacketID { */ SAVESTATE_SCREEN, SAVESTATE_PLAYER, + SAVESTATE_REQUEST_MOTION, SAVESTATE_UNLOAD_CHUNKS, CLEAR_INNPUTS, PLAYBACK_FULLRECORD, diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index d031dd6e..4d4b4f4d 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -18,6 +18,7 @@ import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackController; import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler.MotionData; import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; import com.minecrafttas.tasmod.savestates.gui.GuiSavestateSavingScreen; import com.minecrafttas.tasmod.util.Ducks.ChunkProviderDuck; @@ -221,9 +222,10 @@ public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] { TASmodPackets.SAVESTATE_SAVE, TASmodPackets.SAVESTATE_LOAD, - TASmodPackets.SAVESTATE_PLAYER, - TASmodPackets.SAVESTATE_SCREEN, - TASmodPackets.SAVESTATE_UNLOAD_CHUNKS + TASmodPackets.SAVESTATE_PLAYER, + TASmodPackets.SAVESTATE_REQUEST_MOTION, + TASmodPackets.SAVESTATE_SCREEN, + TASmodPackets.SAVESTATE_UNLOAD_CHUNKS }; } @@ -255,10 +257,39 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } break; case SAVESTATE_PLAYER: - NBTTagCompound compound = TASmodBufferBuilder.readNBTTagCompound(buf); - SavestateHandlerClient.loadPlayer(compound); + Minecraft.getMinecraft().addScheduledTask(()->{ + NBTTagCompound compound = null; + try { + compound = TASmodBufferBuilder.readNBTTagCompound(buf); + } catch (IOException e) { + e.printStackTrace(); + } + SavestateHandlerClient.loadPlayer(compound); + }); break; + case SAVESTATE_REQUEST_MOTION: + EntityPlayerSP player = Minecraft.getMinecraft().player; + if (player != null) { + if (!(Minecraft.getMinecraft().currentScreen instanceof GuiSavestateSavingScreen)) { + Minecraft.getMinecraft().displayGuiScreen(new GuiSavestateSavingScreen()); + } + TASmodClient.client.send( + new TASmodBufferBuilder(TASmodPackets.SAVESTATE_REQUEST_MOTION) + .writeMotionData( + new MotionData( + player.motionX, + player.motionY, + player.motionZ, + player.moveForward, + player.moveVertical, + player.moveStrafing, + player.isSprinting(), + player.jumpMovementFactor) + ) + ); + } + break; case SAVESTATE_SCREEN: // Open/Close Savestate screen boolean open = TASmodBufferBuilder.readBoolean(buf); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index fa7031af..2244a7f1 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -33,6 +33,7 @@ import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderServer; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler.MotionData; import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; import com.minecrafttas.tasmod.savestates.exceptions.SavestateDeleteException; import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; @@ -728,6 +729,7 @@ public PacketID[] getAcceptedPacketIDs() { TASmodPackets.SAVESTATE_SAVE, TASmodPackets.SAVESTATE_LOAD, TASmodPackets.SAVESTATE_PLAYER, + TASmodPackets.SAVESTATE_REQUEST_MOTION, TASmodPackets.SAVESTATE_SCREEN, TASmodPackets.SAVESTATE_UNLOAD_CHUNKS }; @@ -767,18 +769,37 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case SAVESTATE_LOAD: + TASmod.tickSchedulerServer.add(() -> { + int indexing = TASmodBufferBuilder.readInt(buf); + // if (player!=null && !player.canUseCommand(2, "loadstate")) { + // player.sendMessage(new TextComponentString(TextFormatting.RED+"You don't have + // permission to do that")); + // return; + // } + try { + TASmod.savestateHandlerServer.loadState(indexing, true); + } catch (LoadstateException e) { + if (player != null) + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getMessage())); + + LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: " + e.getMessage()); + } catch (Exception e) { + if (player != null) + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getCause().toString())); + + LOGGER.error(e); + } finally { + TASmod.savestateHandlerServer.state = SavestateState.NONE; + } + }); break; - case SAVESTATE_PLAYER: - double x = TASmodBufferBuilder.readDouble(buf); - double y = TASmodBufferBuilder.readDouble(buf); - double z = TASmodBufferBuilder.readDouble(buf); - float rx = TASmodBufferBuilder.readFloat(buf); - float ry = TASmodBufferBuilder.readFloat(buf); - float rz = TASmodBufferBuilder.readFloat(buf); - boolean sprinting = TASmodBufferBuilder.readBoolean(buf); - float jumpMovementVector = TASmodBufferBuilder.readFloat(buf); - PlayerHandler.getMotion().put(player, new PlayerHandler.Saver(x, y, z, rx, ry, rz, sprinting, jumpMovementVector)); + + case SAVESTATE_REQUEST_MOTION: + System.out.println("Ahh"); + MotionData data = TASmodBufferBuilder.readMotionData(buf); + PlayerHandler.getMotion().put(player, data); break; + case SAVESTATE_PLAYER: case SAVESTATE_SCREEN: case SAVESTATE_UNLOAD_CHUNKS: throw new WrongSideException(id, Side.SERVER); @@ -792,7 +813,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa */ public static class PlayerHandler { - public static class Saver { + public static class MotionData { private double clientX; private double clientY; private double clientZ; @@ -802,7 +823,7 @@ public static class Saver { private boolean sprinting; private float jumpMovementVector; - public Saver(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { + public MotionData(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { clientX = x; clientY = y; clientZ = z; @@ -954,42 +975,17 @@ public static void requestMotionFromClient() { PlayerHandler.motion.clear(); try { // request client motion - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_REQUEST_MOTION)); } catch (Exception e) { e.printStackTrace(); } - - // TODO: is this still necessary? - int i = 1; - while (PlayerHandler.motion.size() != TASmod.getServerInstance().getPlayerList().getCurrentPlayerCount()) { - i++; - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if(i % 30 == 1) { - LOGGER.debug(LoggerMarkers.Savestate, "Resending motion packet"); - try { - // request client motion - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER)); - } catch (Exception e) { - LOGGER.error("Unable to send packet to all clients:", e); - } - } - if (i == 1000) { - LOGGER.warn(LoggerMarkers.Savestate, "Client motion timed out!"); - break; - } - - } } - public static Map getMotion() { + public static Map getMotion() { return PlayerHandler.motion; } - public static Map motion = Maps.newHashMap(); + public static Map motion = Maps.newHashMap(); } From d3262e5f89aac12451a2171c58fca731ea7a3540 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sat, 2 Sep 2023 15:36:48 +0200 Subject: [PATCH 30/60] Fixing and discovering savestating issues --- src/main/java/com/minecrafttas/common/server/Client.java | 2 +- src/main/java/com/minecrafttas/tasmod/TASmodClient.java | 2 +- .../tasmod/savestates/SavestateHandlerClient.java | 4 +++- .../tasmod/savestates/SavestateHandlerServer.java | 2 ++ 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 2bea98c2..eb5f6729 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -159,7 +159,7 @@ public void close() throws IOException { */ private void authenticate(UUID id) throws Exception { this.clientID = id; - + Common.LOGGER.info("Authenticating with UUID {}", id.toString()); this.send(new ByteBufferBuilder(-1).writeUUID(id)); } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index baafcde1..0e8a1b1c 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -157,7 +157,7 @@ protected boolean isKeyDown(KeyBinding i) { try { UUID uuid = mc.getSession().getProfile().getId(); if (uuid == null) // dev environment - uuid = UUID.randomUUID(); + uuid = UUID.nameUUIDFromBytes(mc.getSession().getUsername().getBytes()); // connect to server and authenticate client = new Client("127.0.0.1", TASmod.networkingport, TASmodPackets.values(), uuid); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index 4d4b4f4d..b3f9822b 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -301,7 +301,9 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case SAVESTATE_UNLOAD_CHUNKS: - SavestateHandlerClient.unloadAllClientChunks(); + Minecraft.getMinecraft().addScheduledTask(()-> { + SavestateHandlerClient.unloadAllClientChunks(); + }); break; default: diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 2244a7f1..f4cd8615 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -962,6 +962,8 @@ public static void loadAndSendMotionToPlayer(MinecraftServer server) { player.readFromNBT(nbttagcompound); + LOGGER.debug(LoggerMarkers.Savestate, "Sending motion to {}", player.getUniqueID()); + try { TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER).writeNBTTagCompound(nbttagcompound)); } catch (Exception e) { From 41d430b277d2d90db623bb8ebae6e5e674db682b Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 3 Sep 2023 17:49:09 +0200 Subject: [PATCH 31/60] Added defaults to infohud, added reset button, switched middleclick and rightclick --- .../com/minecrafttas/tasmod/gui/InfoHud.java | 55 ++++++++++++------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index 12c6b71e..7dc3fc69 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -9,6 +9,7 @@ import java.util.Properties; import java.util.concurrent.Callable; +import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; @@ -19,8 +20,9 @@ import com.minecrafttas.tasmod.handlers.InterpolationHandler; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; import com.minecrafttas.tasmod.playback.ControlByteHandler; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.util.TrajectoriesCalculator; +import com.minecrafttas.tasmod.virtual.VirtualInput; import com.mojang.realmsclient.gui.ChatFormatting; import net.minecraft.client.Minecraft; @@ -73,12 +75,17 @@ public void tick() { private int gridSizeY=14; public Properties configuration; + private boolean resetLayout; public static List lists = new ArrayList<>(); private void setDefaults(String string, int y) { + setDefaults(string, y, false); + } + + private void setDefaults(String string, int y, boolean enabled) { configuration.setProperty(string + "_x", "0"); configuration.setProperty(string + "_y", y + ""); - configuration.setProperty(string + "_visible", "false"); + configuration.setProperty(string + "_visible", enabled?"true":"false"); configuration.setProperty(string + "_rect", "false"); saveConfig(); } @@ -116,7 +123,7 @@ public void identify(int mouseX, int mouseY) { } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { - if (mouseButton == 1) { + if (mouseButton == 2) { identify(mouseX, mouseY); if (currentlyDraggedIndex != -1) { String id = lists.get(currentlyDraggedIndex).displayName; @@ -126,7 +133,7 @@ public void identify(int mouseX, int mouseY) { currentlyDraggedIndex = -1; } return; - } else if (mouseButton == 2) { + } else if (mouseButton == 1) { identify(mouseX, mouseY); if (currentlyDraggedIndex != -1) { String id = lists.get(currentlyDraggedIndex).displayName; @@ -208,11 +215,15 @@ public boolean checkInit() { /* Check whether already rendered before */ try { configuration = new Properties(); - File tasmodDir = new File(Minecraft.getMinecraft().mcDataDir, "tasmod"); - tasmodDir.mkdir(); - File configFile = new File(tasmodDir, "infogui2.cfg"); - if (!configFile.exists()) configFile.createNewFile(); - configuration.load(new FileReader(configFile)); + if (!resetLayout) { + File tasmodDir = new File(Minecraft.getMinecraft().mcDataDir, "tasmod"); + tasmodDir.mkdir(); + File configFile = new File(tasmodDir, "infogui2.cfg"); + if (!configFile.exists()) configFile.createNewFile(); + configuration.load(new FileReader(configFile)); + }else { + resetLayout = false; + } lists = new ArrayList(); /* ====================== */ String title = "tickrate"; @@ -389,17 +400,18 @@ public boolean checkInit() { return dMonitor.getSeed(); })); - y += 14; + + y = height - 28; title = "playback_index"; - if (configuration.getProperty(title + "_x", "err").equals("err")) setDefaults(title, y); + if (configuration.getProperty(title + "_x", "err").equals("err")) setDefaults(title, y, true); lists.add(new InfoLabel(title, Integer.parseInt(configuration.getProperty(title + "_x")), Integer.parseInt(configuration.getProperty(title + "_y")), Boolean.parseBoolean(configuration.getProperty(title + "_visible")), Boolean.parseBoolean(configuration.getProperty(title + "_rect")), () -> { if (Minecraft.getMinecraft().currentScreen == this) return "PlaybackIndex"; return Integer.toString(TASmodClient.virtual.getContainer().index()); })); - y += 14; + y = height - 14; title = "keystrokes"; - if (configuration.getProperty(title + "_x", "err").equals("err")) setDefaults(title, y); + if (configuration.getProperty(title + "_x", "err").equals("err")) setDefaults(title, y, true); lists.add(new InfoLabel(title, Integer.parseInt(configuration.getProperty(title + "_x")), Integer.parseInt(configuration.getProperty(title + "_y")), Boolean.parseBoolean(configuration.getProperty(title + "_visible")), Boolean.parseBoolean(configuration.getProperty(title + "_rect")), () -> { if (Minecraft.getMinecraft().currentScreen == this) return "Keystrokes"; return keystrokes(); @@ -430,19 +442,20 @@ public void onDrawHotbar() { drawRectWithText(label.renderText, label.x, label.y, label.renderRect); } else if (Minecraft.getMinecraft().currentScreen != null) { if (Minecraft.getMinecraft().currentScreen.getClass().getSimpleName().contains("InfoHud")) { - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(770, 771); Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(label.renderText, label.x + 2, label.y + 3, 0x60FFFFFF); - GL11.glDisable(GL11.GL_BLEND); - GL11.glPopMatrix(); } } if(Minecraft.getMinecraft().currentScreen instanceof InfoHud) { Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("Leftclick to move", width-ypos, xpos- 30, 0x60FF00); - Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("Middleclick to enable", width-ypos, xpos-20, 0x60FF00); - Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("Rightclick to add black background", width-ypos, xpos-10, 0x60FF00); + Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("Rightclick to enable", width-ypos, xpos-20, 0x60FF00); + Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("Middleclick to add black background", width-ypos, xpos-10, 0x60FF00); Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("Hold Shift to snap to grid", width-ypos, xpos, 0x60FF00); + Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("CTRL+Shift+R to reset the layout", width - ypos, xpos + 10, 0xEE8100); + + if (isCtrlKeyDown() && isShiftKeyDown() && TASmodClient.virtual.isKeyDown(Keyboard.KEY_R)) { + resetLayout = true; + configuration = null; + } } } ScaledResolution scaled = new ScaledResolution(Minecraft.getMinecraft()); @@ -453,7 +466,7 @@ public void onDrawHotbar() { * Renders a Box with Text in it */ private void drawRectWithText(String text, int x, int y, boolean rect) { - if (rect) drawRect(x, y, x + Minecraft.getMinecraft().fontRenderer.getStringWidth(text) + 4, y + 14, 0x80000000); + if (rect) drawRect(x, y, x + Minecraft.getMinecraft().fontRenderer.getStringWidth(text) + 4, y + 14, 0x60000000); Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(text, x + 2, y + 3, 0xFFFFFF); GL11.glEnable(3042 /*GL_BLEND*/); } From 59ab7cae7799d0056bb1e7492fb59a38a6d527d8 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 3 Sep 2023 20:21:30 +0200 Subject: [PATCH 32/60] Changing to usernames instead off uuid, fixing BufferUnderflow crashes --- .../common/events/CompactPacketHandler.java | 3 +- .../minecrafttas/common/server/Client.java | 26 ++-- .../common/server/PacketHandlerRegistry.java | 9 +- .../minecrafttas/common/server/Server.java | 20 ++-- .../interfaces/ClientPacketHandler.java | 3 +- .../interfaces/ServerPacketHandler.java | 3 +- .../java/com/minecrafttas/tasmod/TASmod.java | 1 + .../com/minecrafttas/tasmod/TASmodClient.java | 16 +-- .../tasmod/commands/CommandFullPlay.java | 2 +- .../tasmod/commands/CommandFullRecord.java | 2 +- .../commands/CommandRestartAndPlay.java | 2 +- .../tasmod/events/OpenGuiEvents.java | 5 +- .../externalGui/InputContainerView.java | 6 +- .../tasmod/handlers/InterpolationHandler.java | 2 +- .../tasmod/handlers/LoadingScreenHandler.java | 4 +- .../tasmod/ktrng/KillTheRNGHandler.java | 7 +- .../tasmod/monitoring/DesyncMonitoring.java | 8 +- .../networking/TASmodBufferBuilder.java | 4 +- ...ler.java => PlaybackControllerClient.java} | 112 ++++++++++++++---- .../playback/PlaybackControllerServer.java | 5 + .../tasmod/playback/PlaybackSerialiser.java | 12 +- .../tasmod/playback/TASstateClient.java | 87 -------------- .../tasmod/playback/TASstateServer.java | 9 +- .../savestates/SavestateHandlerClient.java | 33 +++--- .../savestates/SavestateHandlerServer.java | 8 +- .../TickrateChangerClient.java | 3 +- .../TickrateChangerServer.java | 5 +- .../tasmod/ticksync/TickSyncClient.java | 3 +- .../tasmod/ticksync/TickSyncServer.java | 9 +- .../tasmod/virtual/VirtualInput.java | 22 ++-- .../common/server/ByteBufferBuilderTest.java | 17 ++- src/test/java/common/server/ServerTest.java | 11 +- 32 files changed, 221 insertions(+), 238 deletions(-) rename src/main/java/com/minecrafttas/tasmod/playback/{PlaybackController.java => PlaybackControllerClient.java} (87%) create mode 100644 src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java diff --git a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java index 2cf6b7e3..15f79e7c 100644 --- a/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/events/CompactPacketHandler.java @@ -1,12 +1,11 @@ package com.minecrafttas.common.events; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @FunctionalInterface public interface CompactPacketHandler { - public void onPacket(ByteBuffer buf, UUID clientID) throws PacketNotImplementedException; + public void onPacket(ByteBuffer buf, String username) throws PacketNotImplementedException; } diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index eb5f6729..64b4aade 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -7,7 +7,6 @@ import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; -import java.util.UUID; import java.util.concurrent.Future; import org.apache.logging.log4j.Level; @@ -31,7 +30,7 @@ public class Client { private final ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE); private Future future; - private UUID clientID; + private String username; private Side side; @@ -48,7 +47,7 @@ public enum Side { * @param uuid The UUID of the client * @throws Exception Unable to connect */ - public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exception { + public Client(String host, int port, PacketID[] packetIDs, String name) throws Exception { Common.LOGGER.info("Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); @@ -59,7 +58,7 @@ public Client(String host, int port, PacketID[] packetIDs, UUID uuid) throws Exc this.createHandlers(); Common.LOGGER.info("Connected to server"); - authenticate(uuid); + authenticate(name); } /** @@ -157,21 +156,18 @@ public void close() throws IOException { * @param id Unique ID * @throws Exception Unable to send packet */ - private void authenticate(UUID id) throws Exception { - this.clientID = id; + private void authenticate(String id) throws Exception { + this.username = id; Common.LOGGER.info("Authenticating with UUID {}", id.toString()); - this.send(new ByteBufferBuilder(-1).writeUUID(id)); + this.send(new ByteBufferBuilder(-1).writeString(id)); } private void completeAuthentication(ByteBuffer buf) throws Exception { - if (this.clientID != null) { + if (this.username != null) { throw new Exception("The client tried to authenticate while being authenticated already"); } - long mostSignificant = buf.getLong(); - long leastSignificant = buf.getLong(); - - this.clientID = new UUID(mostSignificant, leastSignificant); + this.username = ByteBufferBuilder.readString(buf); } private void handle(ByteBuffer buf) { @@ -182,7 +178,7 @@ private void handle(ByteBuffer buf) { return; } PacketID packet = getPacketFromID(id); - PacketHandlerRegistry.handle(side, packet, buf, this.clientID); + PacketHandlerRegistry.handle(side, packet, buf, this.username); } catch (PacketNotImplementedException | WrongSideException e) { Common.LOGGER.throwing(Level.ERROR, e); } catch (Exception e) { @@ -191,8 +187,8 @@ private void handle(ByteBuffer buf) { } - public UUID getId() { - return this.clientID; + public String getId() { + return this.username; } private PacketID getPacketFromID(int id) throws InvalidPacketException { diff --git a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java index 6f96e356..3d7e8725 100644 --- a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java +++ b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.UUID; import com.minecrafttas.common.Common; import com.minecrafttas.common.server.Client.Side; @@ -40,9 +39,9 @@ public static void unregister(PacketHandlerBase handler) { } } - public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public static void handle(Side side, PacketID packet, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { if (side != null && side == packet.getSide()) { - packet.getLambda().onPacket(buf, clientID); + packet.getLambda().onPacket(buf, username); return; } @@ -51,11 +50,11 @@ public static void handle(Side side, PacketID packet, ByteBuffer buf, UUID clien if (Arrays.stream(handler.getAcceptedPacketIDs()).anyMatch(packet::equals)) { if (side == Side.CLIENT && handler instanceof ClientPacketHandler) { ClientPacketHandler clientHandler = (ClientPacketHandler) handler; - clientHandler.onClientPacket(packet, buf, clientID); + clientHandler.onClientPacket(packet, buf, username); isImplemented = true; } else if (side == Side.SERVER && handler instanceof ServerPacketHandler) { ServerPacketHandler serverHandler = (ServerPacketHandler) handler; - serverHandler.onServerPacket(packet, buf, clientID); + serverHandler.onServerPacket(packet, buf, username); isImplemented = true; } } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 17b596ad..79163565 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -69,28 +69,28 @@ public void sendToAll(ByteBufferBuilder builder) throws Exception { } /** - * Send a packet to the specified uuid + * Send a packet to the specified username * - * @param uuid The UUID to send to + * @param username The username to send the packet to * @param builder The packet contents * @throws Exception Networking exception */ - public void sendTo(UUID uuid, ByteBufferBuilder builder) throws Exception { - Client client = getClient(uuid); + public void sendTo(String username, ByteBufferBuilder builder) throws Exception { + Client client = getClient(username); client.send(builder); } /** * Send a packet to a specified player * - * Similar to {@link #sendTo(UUID, ByteBufferBuilder)} + * Similar to {@link #sendTo(String, ByteBufferBuilder)} * * @param player The player to send to * @param builder The packet contents * @throws Exception Networking exception */ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Exception { - sendTo(player.getUniqueID(), builder); + sendTo(player.getName(), builder); } /** @@ -112,13 +112,13 @@ public boolean isClosed() { } /** - * Get client from UUID + * Get client from username * - * @param uniqueID UUID + * @param name Username */ - private Client getClient(UUID uniqueID) { + private Client getClient(String name) { for (Client client : this.clients) - if (client.getId().equals(uniqueID)) + if (client.getId().equals(name)) return client; return null; diff --git a/src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java b/src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java index 9687ce5e..0e08ae98 100644 --- a/src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/ClientPacketHandler.java @@ -1,12 +1,11 @@ package com.minecrafttas.common.server.interfaces; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; public interface ClientPacketHandler extends PacketHandlerBase{ - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception; + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception; } diff --git a/src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java b/src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java index 8037e1bf..835aac92 100644 --- a/src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/ServerPacketHandler.java @@ -1,12 +1,11 @@ package com.minecrafttas.common.server.interfaces; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; public interface ServerPacketHandler extends PacketHandlerBase{ - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception; + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception; } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index e8d05e1e..7e827819 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -70,6 +70,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public void onServerInit(MinecraftServer server) { serverInstance = server; containerStateServer=new TASstateServer(); + PacketHandlerRegistry.register(containerStateServer); // Command handling CommandRegistry.registerServerCommand(new CommandTickrate(), server); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 0e8a1b1c..cb339573 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -5,7 +5,6 @@ import java.io.File; import java.util.ArrayList; import java.util.List; -import java.util.UUID; import org.lwjgl.input.Keyboard; @@ -26,10 +25,9 @@ import com.minecrafttas.tasmod.handlers.LoadingScreenHandler; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.savestates.SavestateHandlerClient; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.playback.PlaybackSerialiser; -import com.minecrafttas.tasmod.playback.TASstateClient; +import com.minecrafttas.tasmod.savestates.SavestateHandlerClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerClient; import com.minecrafttas.tasmod.ticksync.TickSyncClient; import com.minecrafttas.tasmod.util.Scheduler; @@ -115,6 +113,7 @@ public void onInitializeClient() { virtual=new VirtualInput(fileOnStart); EventListenerRegistry.register(virtual); + PacketHandlerRegistry.register(virtual.getContainer()); hud = new InfoHud(); EventListenerRegistry.register(hud); @@ -128,7 +127,7 @@ public void onInitializeClient() { ticksyncClient = new TickSyncClient(); EventListenerRegistry.register(ticksyncClient); PacketHandlerRegistry.register(ticksyncClient); - + PacketHandlerRegistry.register(tickratechanger); PacketHandlerRegistry.register(savestateHandlerClient); @@ -155,11 +154,8 @@ protected boolean isKeyDown(KeyBinding i) { EventListenerRegistry.register(hud); try { - UUID uuid = mc.getSession().getProfile().getId(); - if (uuid == null) // dev environment - uuid = UUID.nameUUIDFromBytes(mc.getSession().getUsername().getBytes()); // connect to server and authenticate - client = new Client("127.0.0.1", TASmod.networkingport, TASmodPackets.values(), uuid); + client = new Client("127.0.0.1", TASmod.networkingport, TASmodPackets.values(), mc.getSession().getUsername()); } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); } @@ -171,7 +167,7 @@ public void onClientInit(Minecraft mc) { List blockedKeybindings = new ArrayList<>(); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Tickrate 0 Key", "TASmod", Keyboard.KEY_F8, () -> TASmodClient.tickratechanger.togglePause()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Advance Tick", "TASmod", Keyboard.KEY_F9, () -> TASmodClient.tickratechanger.advanceTick()))); - blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Recording/Playback Stop", "TASmod", Keyboard.KEY_F10, () -> TASstateClient.setOrSend(TASstate.NONE)))); + blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Recording/Playback Stop", "TASmod", Keyboard.KEY_F10, () -> TASmodClient.virtual.getContainer().setTASState(TASstate.NONE)))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Create Savestate", "TASmod", Keyboard.KEY_J, () -> { try { TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_SAVE).writeInt(-1)); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index a0ddad75..f1362920 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -3,7 +3,7 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index d846b166..f94849e6 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -3,7 +3,7 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index 782987f8..1fae5139 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -9,7 +9,7 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java index 535ef209..dce7bdb4 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java @@ -3,8 +3,7 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.playback.TASstateClient; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import net.minecraft.client.gui.GuiControls; import net.minecraft.client.gui.GuiIngameMenu; @@ -44,7 +43,7 @@ public static void openGuiControls(GuiControls guiControls) { if (TASmodClient.tickratechanger.ticksPerSecond == 0 || TASmodClient.tickratechanger.advanceTick) { LOGGER.info("Pausing game during GuiControls"); TASmodClient.tickratechanger.pauseGame(false); - TASstateClient.setOrSend(stateWhenOpened); + TASmodClient.virtual.getContainer().setTASState(stateWhenOpened); waszero = true; } } diff --git a/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java b/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java index 17f4b569..00145f78 100644 --- a/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java +++ b/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java @@ -16,8 +16,8 @@ import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; -import com.minecrafttas.tasmod.playback.PlaybackController; -import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TickInputContainer; import com.minecrafttas.tasmod.virtual.VirtualInput; @Deprecated @@ -114,7 +114,7 @@ public static void update(VirtualInput input) { if (model == null) { return; } - PlaybackController container = input.getContainer(); + PlaybackControllerClient container = input.getContainer(); if (container == null || container.isEmpty()) { return; } diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java index 846db6ed..8b03f695 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/InterpolationHandler.java @@ -3,7 +3,7 @@ import com.minecrafttas.common.events.EventClient.EventCamera; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.ControlByteHandler; -import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TickInputContainer; import net.minecraft.client.Minecraft; import net.minecraft.util.math.MathHelper; diff --git a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java index 5e6d240d..15e07110 100644 --- a/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/handlers/LoadingScreenHandler.java @@ -7,7 +7,7 @@ import com.minecrafttas.common.events.EventClient.EventLaunchIntegratedServer; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.PlaybackController; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient; import com.minecrafttas.tasmod.util.LoggerMarkers; import net.minecraft.client.Minecraft; @@ -27,7 +27,7 @@ public class LoadingScreenHandler implements EventLaunchIntegratedServer, EventC @Override public void onLaunchIntegratedServer() { LOGGER.debug(LoggerMarkers.Event, "Starting the integrated server"); - PlaybackController container = TASmodClient.virtual.getContainer(); + PlaybackControllerClient container = TASmodClient.virtual.getContainer(); if (!container.isNothingPlaying() && !container.isPaused()) { container.pause(true); } diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index dab9c7b2..eef5dffd 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -3,7 +3,6 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.common.events.EventServer.EventServerTick; @@ -19,7 +18,7 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -181,7 +180,7 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { long seed = TASmodBufferBuilder.readLong(buf); TASmodPackets packet = (TASmodPackets) id; @@ -202,7 +201,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { long seed = TASmodBufferBuilder.readLong(buf); TASmodPackets packet = (TASmodPackets) id; diff --git a/src/main/java/com/minecrafttas/tasmod/monitoring/DesyncMonitoring.java b/src/main/java/com/minecrafttas/tasmod/monitoring/DesyncMonitoring.java index 2533146a..4baeebde 100644 --- a/src/main/java/com/minecrafttas/tasmod/monitoring/DesyncMonitoring.java +++ b/src/main/java/com/minecrafttas/tasmod/monitoring/DesyncMonitoring.java @@ -8,7 +8,7 @@ import com.dselent.bigarraylist.BigArrayList; import com.minecrafttas.killtherng.custom.CustomRandom; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.playback.PlaybackController; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; @@ -27,13 +27,13 @@ public class DesyncMonitoring { private MonitorContainer currentValues; - private PlaybackController controller; + private PlaybackControllerClient controller; /** * Creates an empty desync monitor * @param playbackController */ - public DesyncMonitoring(PlaybackController playbackController) { + public DesyncMonitoring(PlaybackControllerClient playbackController) { controller = playbackController; } @@ -42,7 +42,7 @@ public DesyncMonitoring(PlaybackController playbackController) { * @param playbackController * @param monitorLines */ - public DesyncMonitoring(PlaybackController playbackController, List monitorLines) throws IOException{ + public DesyncMonitoring(PlaybackControllerClient playbackController, List monitorLines) throws IOException{ this(playbackController); container = loadFromFile(monitorLines); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index bd5a2439..95695896 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -2,16 +2,14 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.DataInput; import java.io.DataInputStream; -import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import com.minecrafttas.common.server.ByteBufferBuilder; import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler.MotionData; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java similarity index 87% rename from src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java rename to src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java index d3907bab..1f38e16f 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackController.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java @@ -1,6 +1,16 @@ package com.minecrafttas.tasmod.playback; import static com.minecrafttas.tasmod.TASmod.LOGGER; +import static com.minecrafttas.tasmod.networking.TASmodPackets.CLEAR_INNPUTS; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_FULLPLAY; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_FULLRECORD; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_LOAD; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_PLAYUNTIL; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_RESTARTANDPLAY; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_SAVE; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_TELEPORT; +import static com.minecrafttas.tasmod.networking.TASmodPackets.STATESYNC; +import static com.minecrafttas.tasmod.networking.TASmodPackets.STATESYNC_INITIAL; import java.io.File; import java.io.IOException; @@ -9,7 +19,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; import org.lwjgl.opengl.Display; @@ -28,6 +37,7 @@ import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.util.LoggerMarkers; +import com.minecrafttas.tasmod.util.Scheduler.Task; import com.minecrafttas.tasmod.virtual.VirtualInput; import com.minecrafttas.tasmod.virtual.VirtualKeyboard; import com.minecrafttas.tasmod.virtual.VirtualMouse; @@ -61,7 +71,7 @@ * @author Scribble * */ -public class PlaybackController implements ServerPacketHandler, ClientPacketHandler { +public class PlaybackControllerClient implements ServerPacketHandler, ClientPacketHandler { /** * The current state of the controller. @@ -129,14 +139,31 @@ public class PlaybackController implements ServerPacketHandler, ClientPacketHand private Integer playUntil = null; + /** + * Sets the current {@link TASstate} + * + * First sends the state to the server. + * + * To set the client state, see {@link #setTASStateClient(TASstate)} + * + * @param stateIn The new state for all players + */ + public void setTASState(TASstate stateIn) { + try { + TASmodClient.client.send(new TASmodBufferBuilder(STATESYNC).writeTASState(stateIn)); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** * Starts or stops a recording/playback * * @param stateIn stateIn The desired state of the container * @return */ - public String setTASState(TASstate stateIn) { - return setTASState(stateIn, true); + public String setTASStateClient(TASstate stateIn) { + return setTASStateClient(stateIn, true); } /** @@ -146,7 +173,7 @@ public String setTASState(TASstate stateIn) { * @param verbose Whether the output should be printed in the chat * @return The message printed in the chat */ - public String setTASState(TASstate stateIn, boolean verbose) { + public String setTASStateClient(TASstate stateIn, boolean verbose) { ControlByteHandler.reset(); if (state == stateIn) { switch (stateIn) { @@ -263,9 +290,9 @@ public String setTASState(TASstate stateIn, boolean verbose) { */ public TASstate togglePause() { if (state != TASstate.PAUSED) { - setTASState(TASstate.PAUSED); + setTASStateClient(TASstate.PAUSED); } else { - setTASState(tempPause); + setTASStateClient(tempPause); } return state; } @@ -279,11 +306,11 @@ public void pause(boolean pause) { LOGGER.trace(LoggerMarkers.Playback, "Pausing {}", pause); if (pause) { if (state != TASstate.NONE) { - setTASState(TASstate.PAUSED, false); + setTASStateClient(TASstate.PAUSED, false); } } else { if (state == TASstate.PAUSED) { - setTASState(tempPause, false); + setTASStateClient(tempPause, false); } } } @@ -385,7 +412,7 @@ public void nextTick() { if (player != null && player.addedToChunk) { if (isPaused() && tempPause != TASstate.NONE) { - TASstateClient.setOrSend(tempPause); // The recording is paused in LoadWorldEvents#startLaunchServer + setTASState(tempPause); // The recording is paused in LoadWorldEvents#startLaunchServer pause(false); printCredits(); } @@ -417,7 +444,7 @@ private void playbackNextTick() { if (!Display.isActive()) { // Stops the playback when you tab out of minecraft, for once as a failsafe, // secondly as potential exploit protection LOGGER.info(LoggerMarkers.Playback, "Stopping a {} since the user tabbed out of the game", state); - setTASState(TASstate.NONE); + setTASStateClient(TASstate.NONE); } index++; // Increase the index and load the next inputs @@ -426,19 +453,19 @@ private void playbackNextTick() { if (playUntil != null && playUntil == index) { TASmodClient.tickratechanger.pauseGame(true); playUntil = null; - TASstateClient.setOrSend(TASstate.NONE); + setTASState(TASstate.NONE); for (long i = inputs.size() - 1; i >= index; i--) { inputs.remove(i); } index--; - TASstateClient.setOrSend(TASstate.RECORDING); + setTASState(TASstate.RECORDING); return; } /* Stop condition */ if (index == inputs.size()) { unpressContainer(); - TASstateClient.setOrSend(TASstate.NONE); + setTASState(TASstate.NONE); } /* Continue condition */ else { @@ -647,7 +674,7 @@ private void tpPlayer(String startLocation) throws NumberFormatException { float anglePitch = Float.parseFloat(section[4]); try { - TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_TELEPORT).writeDouble(x).writeDouble(y).writeDouble(z).writeFloat(angleYaw).writeFloat(anglePitch)); + TASmodClient.client.send(new TASmodBufferBuilder(PLAYBACK_TELEPORT).writeDouble(x).writeDouble(y).writeDouble(z).writeFloat(angleYaw).writeFloat(anglePitch)); } catch (Exception e) { e.printStackTrace(); } @@ -787,12 +814,12 @@ public static enum TASstate { public void setStateWhenOpened(TASstate state) { TASmodClient.openMainMenuScheduler.add(() -> { - PlaybackController container = TASmodClient.virtual.getContainer(); + PlaybackControllerClient container = TASmodClient.virtual.getContainer(); if (state == TASstate.RECORDING) { long seed = TASmod.ktrngHandler.getGlobalSeedClient(); container.setStartSeed(seed); } - TASstateClient.setOrSend(state); + setTASState(state); }); } @@ -800,13 +827,22 @@ public void setStateWhenOpened(TASstate state) { @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] { TASmodPackets.PLAYBACK_SAVE, TASmodPackets.PLAYBACK_LOAD, TASmodPackets.PLAYBACK_FULLPLAY, TASmodPackets.PLAYBACK_FULLRECORD, TASmodPackets.PLAYBACK_RESTARTANDPLAY, TASmodPackets.PLAYBACK_PLAYUNTIL, TASmodPackets.PLAYBACK_TELEPORT, TASmodPackets.CLEAR_INNPUTS - + return new TASmodPackets[] { + PLAYBACK_SAVE, + PLAYBACK_LOAD, + PLAYBACK_FULLPLAY, + PLAYBACK_FULLRECORD, + PLAYBACK_RESTARTANDPLAY, + PLAYBACK_PLAYUNTIL, + PLAYBACK_TELEPORT, + CLEAR_INNPUTS, + STATESYNC_INITIAL, + STATESYNC }; } @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; String name = null; Minecraft mc = Minecraft.getMinecraft(); @@ -900,6 +936,36 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa case PLAYBACK_TELEPORT: throw new WrongSideException(packet, Side.CLIENT); + + case STATESYNC_INITIAL: + throw new WrongSideException(id, Side.CLIENT); + + case STATESYNC: + TASstate networkState = TASmodBufferBuilder.readTASState(buf); + boolean verbose = TASmodBufferBuilder.readBoolean(buf); + Task task = ()->{ + PlaybackControllerClient container = TASmodClient.virtual.getContainer(); + if (networkState != container.getState()) { + + String message = container.setTASStateClient(networkState, verbose); + + if (!message.isEmpty()) { + if(Minecraft.getMinecraft().world != null) + Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(message)); + else + LOGGER.debug(LoggerMarkers.Playback, message); + } + } + + }; + + + if((networkState == TASstate.RECORDING || networkState == TASstate.PLAYBACK) && TASmodClient.tickratechanger.ticksPerSecond != 0) { + TASmodClient.tickSchedulerClient.add(task); // Starts a recording in the next tick + } else { + TASmodClient.gameLoopSchedulerClient.add(task); // Starts a recording in the next frame + } + break; default: throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); @@ -907,7 +973,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; // TODO #181 Permissions @@ -920,7 +986,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa float angleYaw = TASmodBufferBuilder.readFloat(buf); float anglePitch = TASmodBufferBuilder.readFloat(buf); - EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(clientID); + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); player.getServerWorld().addScheduledTask(() -> { player.rotationPitch = anglePitch; player.rotationYaw = angleYaw; @@ -930,7 +996,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa break; case CLEAR_INNPUTS: - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + TASmod.server.sendToAll(new TASmodBufferBuilder(CLEAR_INNPUTS)); case PLAYBACK_FULLPLAY: case PLAYBACK_FULLRECORD: diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java new file mode 100644 index 00000000..098ce569 --- /dev/null +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java @@ -0,0 +1,5 @@ +package com.minecrafttas.tasmod.playback; + +public class PlaybackControllerServer { + +} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java index 25cbda2b..4a9ad482 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackSerialiser.java @@ -15,7 +15,7 @@ import com.dselent.bigarraylist.BigArrayList; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; -import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TickInputContainer; import com.minecrafttas.tasmod.util.FileThread; import com.minecrafttas.tasmod.util.LoggerMarkers; import com.minecrafttas.tasmod.virtual.VirtualKey; @@ -26,7 +26,7 @@ import com.mojang.realmsclient.util.Pair; /** - * Saves a given {@linkplain PlaybackController} to a file. Is also able to read an input container from a file.
+ * Saves a given {@linkplain PlaybackControllerClient} to a file. Is also able to read an input container from a file.
*
* I plan to be backwards compatible so all the save functions have a V1 in their name by the time of writing this
*
@@ -87,7 +87,7 @@ public static String getRegexString() { * @param container The container to save * @throws IOException When the input container is empty */ - public void saveToFileV1(File file, PlaybackController container) throws IOException { + public void saveToFileV1(File file, PlaybackControllerClient container) throws IOException { saveToFileV1Until(file, container, -1); } @@ -98,7 +98,7 @@ public void saveToFileV1(File file, PlaybackController container) throws IOExcep * @param index index until the inputs get saved * @throws IOException When the input container is empty */ - public void saveToFileV1Until(File file, PlaybackController container, int index) throws IOException{ + public void saveToFileV1Until(File file, PlaybackControllerClient container, int index) throws IOException{ LOGGER.debug(LoggerMarkers.Playback, "Saving playback controller to file {}", file); if (container.size() == 0) { throw new IOException("There are no inputs to save to a file"); @@ -182,7 +182,7 @@ public int getFileVersion(File file) throws IOException { return 0; } - public PlaybackController fromEntireFileV1(File file) throws IOException { + public PlaybackControllerClient fromEntireFileV1(File file) throws IOException { LOGGER.debug(LoggerMarkers.Playback, "Loading playback controller to file {}", file); List lines = FileUtils.readLines(file, StandardCharsets.UTF_8); @@ -197,7 +197,7 @@ public PlaybackController fromEntireFileV1(File file) throws IOException { } boolean oldmonfileLoaded=!monitorLines.isEmpty(); - PlaybackController controller = new PlaybackController(); + PlaybackControllerClient controller = new PlaybackControllerClient(); String author = "Insert author here"; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java deleted file mode 100644 index 0c0c6f43..00000000 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateClient.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.minecrafttas.tasmod.playback; - -import static com.minecrafttas.tasmod.TASmod.LOGGER; - -import java.nio.ByteBuffer; -import java.util.UUID; - -import com.minecrafttas.common.server.Client.Side; -import com.minecrafttas.common.server.exception.PacketNotImplementedException; -import com.minecrafttas.common.server.exception.WrongSideException; -import com.minecrafttas.common.server.interfaces.ClientPacketHandler; -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; -import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.util.LoggerMarkers; -import com.minecrafttas.tasmod.util.Scheduler.Task; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.text.TextComponentString; - -public class TASstateClient implements ClientPacketHandler{ - - public static void setStateClient(TASstate state) { - TASmodClient.virtual.getContainer().setTASState(state); - } - - public static void setOrSend(TASstate state) { - if(Minecraft.getMinecraft().player!=null) { - try { - TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(state)); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - TASmodClient.virtual.getContainer().setTASState(state); - } - } - - @Override - public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] {TASmodPackets.STATESYNC_INITIAL, TASmodPackets.STATESYNC}; - } - - @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { - TASmodPackets packet = (TASmodPackets) id; - TASstate networkState = TASmodBufferBuilder.readTASState(buf); - - switch(packet) { - case STATESYNC_INITIAL: - throw new WrongSideException(id, Side.CLIENT); - - case STATESYNC: - - boolean verbose = TASmodBufferBuilder.readBoolean(buf); - Task task = ()->{ - PlaybackController container = TASmodClient.virtual.getContainer(); - if (networkState != container.getState()) { - - String message = container.setTASState(networkState, verbose); - - if (!message.isEmpty()) { - if(Minecraft.getMinecraft().world != null) - Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(message)); - else - LOGGER.debug(LoggerMarkers.Playback, message); - } - } - - }; - - - if((networkState == TASstate.RECORDING || networkState == TASstate.PLAYBACK) && TASmodClient.tickratechanger.ticksPerSecond != 0) { - TASmodClient.tickSchedulerClient.add(task); // Starts a recording in the next tick - } else { - TASmodClient.gameLoopSchedulerClient.add(task); // Starts a recording in the next frame - } - break; - - default: - throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); - } - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java index c53fe44a..5ba61137 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java @@ -3,7 +3,6 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -13,7 +12,7 @@ import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; @@ -49,7 +48,7 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; TASstate networkState = TASmodBufferBuilder.readTASState(buf); @@ -59,7 +58,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa setState(networkState); shouldChange = false; } else { - TASmod.server.sendTo(clientID, new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(networkState)); + TASmod.server.sendTo(username, new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(networkState)); } break; @@ -97,7 +96,7 @@ public void setServerState(TASstate stateIn) { if (state != stateIn) { if (state == TASstate.RECORDING && stateIn == TASstate.PLAYBACK || state == TASstate.PLAYBACK && stateIn == TASstate.RECORDING) return; - if(state==TASstate.NONE&&state==TASstate.PAUSED) { + if (state == TASstate.NONE && state == TASstate.PAUSED) { return; } this.state = stateIn; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index b3f9822b..5ce5d9d0 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -5,7 +5,6 @@ import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -16,8 +15,8 @@ import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackController; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler.MotionData; import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; import com.minecrafttas.tasmod.savestates.gui.GuiSavestateSavingScreen; @@ -120,7 +119,7 @@ public static void savestate(String nameOfSavestate) throws SavestateException, File targetfile = new File(SavestateHandlerClient.savestateDirectory, nameOfSavestate + ".mctas"); - PlaybackController container = TASmodClient.virtual.getContainer(); + PlaybackControllerClient container = TASmodClient.virtual.getContainer(); if (container.isRecording()) { TASmodClient.serialiser.saveToFileV1(targetfile, container); // If the container is recording, store it entirely } else if (container.isPlayingback()) { @@ -147,13 +146,13 @@ public static void loadstate(String nameOfSavestate) throws IOException { File targetfile = new File(savestateDirectory, nameOfSavestate + ".mctas"); - PlaybackController container = TASmodClient.virtual.getContainer(); + PlaybackControllerClient container = TASmodClient.virtual.getContainer(); if (!container.isNothingPlaying()) { // If the file exists and the container is recording or playing, load the // clientSavestate if (targetfile.exists()) { TASmodClient.virtual.loadClientSavestate(TASmodClient.serialiser.fromEntireFileV1(targetfile)); } else { - TASmodClient.virtual.getContainer().setTASState(TASstate.NONE, false); + TASmodClient.virtual.getContainer().setTASStateClient(TASstate.NONE, false); Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); } @@ -230,7 +229,7 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; String name = null; Minecraft mc = Minecraft.getMinecraft(); @@ -246,7 +245,6 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } catch (IOException e) { e.printStackTrace(); } - break; case SAVESTATE_LOAD: // Load client savestate name = TASmodBufferBuilder.readString(buf); @@ -257,13 +255,20 @@ public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } break; case SAVESTATE_PLAYER: + NBTTagCompound compound; + try { + compound = TASmodBufferBuilder.readNBTTagCompound(buf); + } catch (IOException e) { + e.printStackTrace(); + return; + } + /* + Fair warning: Do NOT read the buffer inside an addScheduledTask. + Read it before that. The buffer will have the wrong limit, + when the task is executed. + This is probably due to the buffers being reused. + */ Minecraft.getMinecraft().addScheduledTask(()->{ - NBTTagCompound compound = null; - try { - compound = TASmodBufferBuilder.readNBTTagCompound(buf); - } catch (IOException e) { - e.printStackTrace(); - } SavestateHandlerClient.loadPlayer(compound); }); break; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index f4cd8615..892d3941 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -736,11 +736,11 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { // TODO Permissions TASmodPackets packet = (TASmodPackets) id; - EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUUID(clientID); + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); Integer index = null; @@ -962,10 +962,10 @@ public static void loadAndSendMotionToPlayer(MinecraftServer server) { player.readFromNBT(nbttagcompound); - LOGGER.debug(LoggerMarkers.Savestate, "Sending motion to {}", player.getUniqueID()); + LOGGER.debug(LoggerMarkers.Savestate, "Sending motion to {}", player.getName()); try { - TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER).writeNBTTagCompound(nbttagcompound)); + TASmod.server.sendTo(player, new TASmodBufferBuilder(TASmodPackets.SAVESTATE_PLAYER).writeNBTTagCompound(nbttagcompound)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index ffeba278..b5643ebd 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -3,7 +3,6 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.nio.ByteBuffer; -import java.util.UUID; import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -213,7 +212,7 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; switch (packet) { diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 666f7f82..36109c32 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -1,7 +1,6 @@ package com.minecrafttas.tasmod.tickratechanger; import java.nio.ByteBuffer; -import java.util.UUID; import org.apache.logging.log4j.Logger; @@ -212,7 +211,7 @@ public void onPlayerJoinedServerSide(EntityPlayerMP player) { log("Sending the current tickrate (" + ticksPerSecond + ") to " + player.getName()); try { - TASmod.server.sendTo(player.getUniqueID(), new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(ticksPerSecond)); + TASmod.server.sendTo(player, new TASmodBufferBuilder(TASmodPackets.TICKRATE_CHANGE).writeFloat(ticksPerSecond)); } catch (Exception e) { e.printStackTrace(); } @@ -277,7 +276,7 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TASmodPackets packet = (TASmodPackets) id; switch (packet) { diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index aa3d5801..f97f9892 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -3,7 +3,6 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.nio.ByteBuffer; -import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; @@ -40,7 +39,7 @@ public PacketID[] getAcceptedPacketIDs() { * @param tick Current tick of the server */ @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) { shouldTick.set(true); } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index 2f9ad55c..c227146b 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.UUID; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; @@ -27,7 +26,7 @@ */ public class TickSyncServer implements ServerPacketHandler, EventServerTickPost { - private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); + private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); @Override public PacketID[] getAcceptedPacketIDs() { @@ -43,10 +42,10 @@ public PacketID[] getAcceptedPacketIDs() { * @param tick Current tick of the player */ @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID uuid) { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) { synchronized (synchronizedList) { - if(!synchronizedList.contains(uuid)) { - synchronizedList.add(uuid); + if(!synchronizedList.contains(username)) { + synchronizedList.add(username); } } } diff --git a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java index e6bf1c5c..58faea1a 100644 --- a/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java +++ b/src/main/java/com/minecrafttas/tasmod/virtual/VirtualInput.java @@ -10,9 +10,9 @@ import com.minecrafttas.common.events.EventClient.EventPlayerJoinedClientSide; import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.PlaybackController; -import com.minecrafttas.tasmod.playback.PlaybackController.TASstate; -import com.minecrafttas.tasmod.playback.PlaybackController.TickInputContainer; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TickInputContainer; import com.minecrafttas.tasmod.util.PointerNormalizer; import net.minecraft.client.Minecraft; @@ -90,7 +90,7 @@ public class VirtualInput implements EventPlayerJoinedClientSide{ * The container where all inputs get stored during recording or stored and * ready to be played back */ - private PlaybackController container = new PlaybackController(); + private PlaybackControllerClient container = new PlaybackControllerClient(); // ===========================Keyboard================================= @@ -420,7 +420,7 @@ public float getSubtickYaw() { // =====================================Container=========================================== - public PlaybackController getContainer() { + public PlaybackControllerClient getContainer() { return container; } @@ -439,7 +439,7 @@ public void updateContainer() { * * @param container to replace the current one */ - public void setContainer(PlaybackController container) { + public void setContainer(PlaybackControllerClient container) { this.container = container; } @@ -449,11 +449,11 @@ public void setContainer(PlaybackController container) { * Loads and preloads the inputs from the new InputContainer to * {@link #container} * - * Saving a savestate is done via {@linkplain com.minecrafttas.tasmod.playback.PlaybackSerialiser#saveToFileV1(File, PlaybackController)} in {@linkplain com.minecrafttas.tasmod.savestates.SavestateHandlerClient#savestate(String)} + * Saving a savestate is done via {@linkplain com.minecrafttas.tasmod.playback.PlaybackSerialiser#saveToFileV1(File, PlaybackControllerClient)} in {@linkplain com.minecrafttas.tasmod.savestates.SavestateHandlerClient#savestate(String)} * * @param savestatecontainer The container that should be loaded. */ - public void loadClientSavestate(PlaybackController savestatecontainer) { + public void loadClientSavestate(PlaybackControllerClient savestatecontainer) { if (container.isPlayingback()) { preloadInput(container, savestatecontainer.size() - 1); // Preloading from the current container and @@ -486,7 +486,7 @@ public void loadClientSavestate(PlaybackController savestatecontainer) { } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } - savestatecontainer.setTASState(TASstate.PLAYBACK); + savestatecontainer.setTASStateClient(TASstate.PLAYBACK); savestatecontainer.setStartLocation(start); container = savestatecontainer; } @@ -506,7 +506,7 @@ public void loadClientSavestate(PlaybackController savestatecontainer) { e.printStackTrace(); } - savestatecontainer.setTASState(TASstate.RECORDING); + savestatecontainer.setTASStateClient(TASstate.RECORDING); savestatecontainer.setStartLocation(start); container = savestatecontainer; // Replace the current container with the savestated container } @@ -520,7 +520,7 @@ public void loadClientSavestate(PlaybackController savestatecontainer) { * @param index The index of the container from which the inputs should be * loaded */ - private void preloadInput(PlaybackController container, int index) { + private void preloadInput(PlaybackControllerClient container, int index) { TickInputContainer tickcontainer = container.get(index); if (tickcontainer != null) { diff --git a/src/test/java/common/server/ByteBufferBuilderTest.java b/src/test/java/common/server/ByteBufferBuilderTest.java index 9deb3547..d9b3d7fa 100644 --- a/src/test/java/common/server/ByteBufferBuilderTest.java +++ b/src/test/java/common/server/ByteBufferBuilderTest.java @@ -1,5 +1,6 @@ package common.server; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; @@ -211,6 +212,21 @@ void testString() { assertEquals("Test", ByteBufferBuilder.readString(buf)); } + /** + * Test + */ + @Test + void testByteArray() { + ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); + + builder.writeByteArray(new byte[] {1,1,0,0,1,1,0}); + + ByteBuffer buf = builder.build(); + buf.position(4); + + assertArrayEquals(new byte[] {1,1,0,0,1,1,0}, ByteBufferBuilder.readByteArray(buf)); + } + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a uuid */ @@ -226,7 +242,6 @@ void testUUID() { assertEquals("b8abdafc-5002-40df-ab68-63206ea4c7e8", ByteBufferBuilder.readUUID(buf).toString()); } - // ==================================== /** diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index d243873b..2841d1d3 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -94,7 +94,7 @@ public PacketID[] getAcceptedPacketIDs() { } @Override - public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TestPacketIDs packet = (TestPacketIDs) id; switch (packet) { case TEST_INTERFACE_INT: @@ -113,7 +113,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, UUID clientID) throws Pa } @Override - public void onClientPacket(PacketID id, ByteBuffer buf, UUID clientID) throws PacketNotImplementedException, WrongSideException, Exception { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { TestPacketIDs packet = (TestPacketIDs) id; switch (packet) { case TEST_INTERFACE_INT: @@ -147,10 +147,9 @@ static void setUpBeforeClass() throws Exception { } catch (Exception e) { e.printStackTrace(); } - UUID uuid = UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"); try { - client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), uuid); + client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot"); } catch (Exception e) { e.printStackTrace(); } @@ -223,7 +222,7 @@ void testSendToAllClientsInterface() { @Test void testSendToClientInterface() { try { - server.sendTo(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"), new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE_INT).writeInt(3)); + server.sendTo("TASBot", new ByteBufferBuilder(TestPacketIDs.TEST_INTERFACE_INT).writeInt(3)); } catch (Exception e) { fail(e); return; @@ -309,7 +308,7 @@ void testSendToAllClientsLambda() { @Test void testSendToClientLambda() { try { - server.sendTo(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"), new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_CLIENT).writeInt(6)); + server.sendTo("TASBot", new ByteBufferBuilder(TestPacketIDs.TEST_LAMBDA_CLIENT).writeInt(6)); } catch (Exception e) { fail(e); return; From 9697829a955e817760512eebd98e979d4d6a1cc4 Mon Sep 17 00:00:00 2001 From: Scribble Date: Tue, 5 Sep 2023 23:35:28 +0200 Subject: [PATCH 33/60] =?UTF-8?q?Rearranging=20registering=20in=20main=20m?= =?UTF-8?q?ethods=20and=20documentation=20=F0=9F=9A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecrafttas/common/KeybindManager.java | 3 +- .../java/com/minecrafttas/tasmod/TASmod.java | 21 +++++---- .../com/minecrafttas/tasmod/TASmodClient.java | 47 ++++++++++--------- 3 files changed, 40 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/KeybindManager.java b/src/main/java/com/minecrafttas/common/KeybindManager.java index 2d187227..9a13c9f2 100644 --- a/src/main/java/com/minecrafttas/common/KeybindManager.java +++ b/src/main/java/com/minecrafttas/common/KeybindManager.java @@ -13,6 +13,7 @@ /** * Keybind manager + * @author Pancake */ public abstract class KeybindManager implements EventClientGameLoop { @@ -62,7 +63,7 @@ public void onRunClientGameLoop(Minecraft mc) { /** * Register new keybind * - * @param keybind Keybind + * @param keybind Keybind to register */ public KeyBinding registerKeybind(Keybind keybind) { this.keybindings.add(keybind); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 7e827819..c91f76e2 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -121,26 +121,31 @@ public static MinecraftServer getServerInstance() { @Override public void onInitialize() { - // Events LOGGER.info("Initializing TASmod"); - EventListenerRegistry.register(this); + // Start ticksync ticksyncServer = new TickSyncServer(); - EventListenerRegistry.register(ticksyncServer); - PacketHandlerRegistry.register(ticksyncServer); + // Initilize KillTheRNG LOGGER.info("Testing connection with KillTheRNG"); ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); - EventListenerRegistry.register(ktrngHandler); - PacketHandlerRegistry.register(ktrngHandler); + // Initialize TickrateChanger tickratechanger = new TickrateChangerServer(LOGGER); + + // Register event listeners + EventListenerRegistry.register(this); + EventListenerRegistry.register(ticksyncServer); EventListenerRegistry.register(tickratechanger); - PacketHandlerRegistry.register(tickratechanger); + EventListenerRegistry.register(ktrngHandler); - // Networking + // Register packet handlers LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); + PacketHandlerRegistry.register(ticksyncServer); + PacketHandlerRegistry.register(tickratechanger); + PacketHandlerRegistry.register(ktrngHandler); + // Starting custom server instance try { server = new Server(networkingport, TASmodPackets.values()); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index cb339573..fc35a03d 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -30,6 +30,7 @@ import com.minecrafttas.tasmod.savestates.SavestateHandlerClient; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerClient; import com.minecrafttas.tasmod.ticksync.TickSyncClient; +import com.minecrafttas.tasmod.util.LoggerMarkers; import com.minecrafttas.tasmod.util.Scheduler; import com.minecrafttas.tasmod.util.ShieldDownloader; import com.minecrafttas.tasmod.virtual.VirtualInput; @@ -97,41 +98,32 @@ public static void createSavestatesDir() { @Override public void onInitializeClient() { - EventListenerRegistry.register(this); + + // Check if dev environment isDevEnvironment = FabricLoaderImpl.INSTANCE.isDevelopmentEnvironment(); + // Load config Minecraft mc = Minecraft.getMinecraft(); config = new Configuration("TASmod configuration", new File(mc.mcDataDir, "config/tasmod.cfg")); + // Execute /restartandplay. Load the file to start from the config. If it exists load the playback file on start. String fileOnStart = config.get(ConfigOptions.FileToOpen); - if (fileOnStart.isEmpty()) { fileOnStart = null; } else { config.reset(ConfigOptions.FileToOpen); } - virtual=new VirtualInput(fileOnStart); - EventListenerRegistry.register(virtual); - PacketHandlerRegistry.register(virtual.getContainer()); + // Initialize InfoHud hud = new InfoHud(); - EventListenerRegistry.register(hud); - + // Initialize shield downloader shieldDownloader = new ShieldDownloader(); - EventListenerRegistry.register(shieldDownloader); - + // Initialize loading screen handler loadingScreenHandler = new LoadingScreenHandler(); - EventListenerRegistry.register(loadingScreenHandler); - + // Initialize Ticksync ticksyncClient = new TickSyncClient(); - EventListenerRegistry.register(ticksyncClient); - PacketHandlerRegistry.register(ticksyncClient); - - PacketHandlerRegistry.register(tickratechanger); - - PacketHandlerRegistry.register(savestateHandlerClient); - + // Initialize keybind manager keybindManager = new KeybindManager() { protected boolean isKeyDown(KeyBinding i) { @@ -139,11 +131,16 @@ protected boolean isKeyDown(KeyBinding i) { }; }; - EventListenerRegistry.register(keybindManager); + // Register event listeners + EventListenerRegistry.register(this); + EventListenerRegistry.register(virtual); + EventListenerRegistry.register(hud); + EventListenerRegistry.register(shieldDownloader); + EventListenerRegistry.register(loadingScreenHandler); + EventListenerRegistry.register(ticksyncClient); + EventListenerRegistry.register(keybindManager); EventListenerRegistry.register(interpolation); - - EventListenerRegistry.register((EventOpenGui)(gui -> { if(gui instanceof GuiMainMenu) { openMainMenuScheduler.runAllTasks(); @@ -151,7 +148,13 @@ protected boolean isKeyDown(KeyBinding i) { return gui; })); - EventListenerRegistry.register(hud); + // Register packet handlers + LOGGER.info(LoggerMarkers.Networking, "Registering network handlers on client"); + PacketHandlerRegistry.register(virtual.getContainer()); //TODO Move container/playbackcontroller out of virtual package + PacketHandlerRegistry.register(ticksyncClient); + PacketHandlerRegistry.register(tickratechanger); + PacketHandlerRegistry.register(savestateHandlerClient); + try { // connect to server and authenticate From 8f1eb9dc0816a7512a6d08c211dd544983ebdb72 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 10 Sep 2023 17:32:56 +0200 Subject: [PATCH 34/60] Fixed labels going off screen in InfoHud --- .../com/minecrafttas/tasmod/gui/InfoHud.java | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index 7dc3fc69..138425d4 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -9,6 +9,7 @@ import java.util.Properties; import java.util.concurrent.Callable; +import org.apache.commons.lang3.tuple.Pair; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; @@ -101,6 +102,11 @@ public void identify(int mouseX, int mouseY) { try { x = Integer.parseInt(configuration.getProperty(label.displayName + "_x")); y = Integer.parseInt(configuration.getProperty(label.displayName + "_y")); + + Pair newPos = getScreenOffset(x, y, label); + + x = newPos.getLeft(); + y = newPos.getRight(); } catch (NumberFormatException e) { configuration.setProperty(label.displayName + "_x", "0"); configuration.setProperty(label.displayName + "_y", "0"); @@ -438,8 +444,17 @@ public void onDrawHotbar() { int ypos=190; for (InfoLabel label : lists) { label.tick(); + + int lx = label.x; + int ly = label.y; + + Pair newPos = getScreenOffset(lx, ly, label); + + lx = newPos.getLeft(); + ly = newPos.getRight(); + if (label.visible) { - drawRectWithText(label.renderText, label.x, label.y, label.renderRect); + drawRectWithText(label.renderText, lx, ly, label.renderRect); } else if (Minecraft.getMinecraft().currentScreen != null) { if (Minecraft.getMinecraft().currentScreen.getClass().getSimpleName().contains("InfoHud")) { Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(label.renderText, label.x + 2, label.y + 3, 0x60FFFFFF); @@ -495,4 +510,31 @@ private String keystrokes() { return ""; } + private Pair getScreenOffset(int x, int y, InfoLabel label){ + ScaledResolution scaled = new ScaledResolution(Minecraft.getMinecraft()); + + int marginX = 5; + int marginY = 5; + + if (getBBRight(x, label.renderText) > scaled.getScaledWidth()) { + int offset = getBBRight(x, label.renderText); + x = x - (offset - scaled.getScaledWidth()) - marginX; + } + + if (getBBDown(y) > scaled.getScaledHeight()) { + int offset = getBBDown(y); + y = y - (offset - scaled.getScaledHeight()) - marginY; + } + + return Pair.of(x, y); + } + + private int getBBRight(int x, String text) { + return x + Minecraft.getMinecraft().fontRenderer.getStringWidth(text); + } + + private int getBBDown(int y) { + return y + 14; + } + } \ No newline at end of file From 8f5f046b83aaa51dc2ffd93cc02489ef83553403 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 10 Sep 2023 17:59:27 +0200 Subject: [PATCH 35/60] Networking for PlaybackControllerClient and TASstateServer to PlaybackControllerServer --- .../common/events/EventListenerRegistry.java | 6 + .../java/com/minecrafttas/tasmod/TASmod.java | 78 ++++----- .../tasmod/commands/CommandFullPlay.java | 2 +- .../tasmod/commands/CommandFullRecord.java | 2 +- .../tasmod/commands/CommandPlay.java | 2 +- .../tasmod/commands/CommandRecord.java | 2 +- .../commands/CommandRestartAndPlay.java | 2 +- .../tasmod/ktrng/KillTheRNGHandler.java | 2 +- .../playback/PlaybackControllerClient.java | 41 +---- .../playback/PlaybackControllerServer.java | 150 +++++++++++++++++- .../tasmod/playback/TASstateServer.java | 119 -------------- 11 files changed, 202 insertions(+), 204 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java diff --git a/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java index 65631b90..e425d3fc 100644 --- a/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java +++ b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java @@ -8,10 +8,16 @@ public class EventListenerRegistry { public static void register(EventBase eventListener) { + if (eventListener == null) { + throw new NullPointerException("Tried to register a packethandler with value null"); + } EVENTLISTENER_REGISTRY.add(eventListener); } public static void unregister(EventBase eventListener) { + if (eventListener == null) { + throw new NullPointerException("Tried to unregister a packethandler with value null"); + } EVENTLISTENER_REGISTRY.remove(eventListener); } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index c91f76e2..4a19d3d8 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -26,7 +26,7 @@ import com.minecrafttas.tasmod.commands.CommandTickrate; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.TASstateServer; +import com.minecrafttas.tasmod.playback.PlaybackControllerServer; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; import com.minecrafttas.tasmod.savestates.files.SavestateTrackerFile; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; @@ -50,7 +50,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static final Logger LOGGER = LogManager.getLogger("TASmod"); - public static TASstateServer containerStateServer; + public static PlaybackControllerServer playbackControllerServer; public static SavestateHandlerServer savestateHandlerServer; @@ -66,11 +66,47 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static int networkingport = 8999; + @Override + public void onInitialize() { + + LOGGER.info("Initializing TASmod"); + + // Start ticksync + ticksyncServer = new TickSyncServer(); + + // Initilize KillTheRNG + LOGGER.info("Testing connection with KillTheRNG"); + ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); + + // Initialize TickrateChanger + tickratechanger = new TickrateChangerServer(LOGGER); + + // Register event listeners + EventListenerRegistry.register(this); + EventListenerRegistry.register(ticksyncServer); + EventListenerRegistry.register(tickratechanger); + EventListenerRegistry.register(ktrngHandler); + + // Register packet handlers + LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); + PacketHandlerRegistry.register(ticksyncServer); + PacketHandlerRegistry.register(tickratechanger); + PacketHandlerRegistry.register(ktrngHandler); + + // Starting custom server instance + try { + server = new Server(networkingport, TASmodPackets.values()); + } catch (Exception e) { + LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); + } + } + @Override public void onServerInit(MinecraftServer server) { serverInstance = server; - containerStateServer=new TASstateServer(); - PacketHandlerRegistry.register(containerStateServer); + playbackControllerServer=new PlaybackControllerServer(); + PacketHandlerRegistry.register(playbackControllerServer); + // Command handling CommandRegistry.registerServerCommand(new CommandTickrate(), server); @@ -118,38 +154,4 @@ public static MinecraftServer getServerInstance() { return serverInstance; } - @Override - public void onInitialize() { - - LOGGER.info("Initializing TASmod"); - - // Start ticksync - ticksyncServer = new TickSyncServer(); - - // Initilize KillTheRNG - LOGGER.info("Testing connection with KillTheRNG"); - ktrngHandler=new KillTheRNGHandler(FabricLoaderImpl.INSTANCE.isModLoaded("killtherng")); - - // Initialize TickrateChanger - tickratechanger = new TickrateChangerServer(LOGGER); - - // Register event listeners - EventListenerRegistry.register(this); - EventListenerRegistry.register(ticksyncServer); - EventListenerRegistry.register(tickratechanger); - EventListenerRegistry.register(ktrngHandler); - - // Register packet handlers - LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); - PacketHandlerRegistry.register(ticksyncServer); - PacketHandlerRegistry.register(tickratechanger); - PacketHandlerRegistry.register(ktrngHandler); - - // Starting custom server instance - try { - server = new Server(networkingport, TASmodPackets.values()); - } catch (Exception e) { - LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); - } - } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java index f1362920..d4d3f18b 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullPlay.java @@ -40,7 +40,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } finally { TASmod.savestateHandlerServer.state=SavestateState.NONE; } - TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); + TASmod.playbackControllerServer.setServerState(TASstate.PLAYBACK); try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_FULLPLAY)); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java index f94849e6..585a50d1 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandFullRecord.java @@ -40,7 +40,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } finally { TASmod.savestateHandlerServer.state = SavestateState.NONE; } - TASmod.containerStateServer.setServerState(TASstate.RECORDING); + TASmod.playbackControllerServer.setServerState(TASstate.RECORDING); try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_FULLRECORD)); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java index ea4e4dab..2f03c713 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandPlay.java @@ -42,7 +42,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args return; } if (args.length < 1) { - TASmod.containerStateServer.togglePlayback(); + TASmod.playbackControllerServer.togglePlayback(); } else if (args.length > 1) { sender.sendMessage(new TextComponentString(TextFormatting.RED + "Too many arguments. " + getUsage(sender))); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java index 63495bb3..56f58e36 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRecord.java @@ -42,7 +42,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args return; } if (args.length < 1) { - TASmod.containerStateServer.toggleRecording(); + TASmod.playbackControllerServer.toggleRecording(); TASmod.tickSchedulerServer.add(() ->{ TASmod.ktrngHandler.broadcastStartSeed(); }); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index 1fae5139..60bd5f6d 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -54,7 +54,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } catch (IOException e) { e.printStackTrace(); } - TASmod.containerStateServer.setServerState(TASstate.PLAYBACK); + TASmod.playbackControllerServer.setServerState(TASstate.PLAYBACK); try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_RESTARTANDPLAY).writeString(args[0])); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index eef5dffd..6b2cbb4b 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -131,7 +131,7 @@ public void sendGlobalSeedToServer(long seedIn) { @Override public void onServerTick(MinecraftServer server) { if (isLoaded()) { - if (TASmod.containerStateServer.getState() != TASstate.PAUSED) + if (TASmod.playbackControllerServer.getState() != TASstate.PAUSED) try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.KILLTHERNG_SEED).writeLong(advanceGlobalSeedServer())); } catch (Exception e) { diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java index 1f38e16f..13b9dd0e 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java @@ -71,7 +71,7 @@ * @author Scribble * */ -public class PlaybackControllerClient implements ServerPacketHandler, ClientPacketHandler { +public class PlaybackControllerClient implements ClientPacketHandler { /** * The current state of the controller. @@ -971,43 +971,4 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws throw new PacketNotImplementedException(packet, this.getClass(), Side.CLIENT); } } - - @Override - public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { - TASmodPackets packet = (TASmodPackets) id; - - // TODO #181 Permissions - switch (packet) { - - case PLAYBACK_TELEPORT: - double x = TASmodBufferBuilder.readDouble(buf); - double y = TASmodBufferBuilder.readDouble(buf); - double z = TASmodBufferBuilder.readDouble(buf); - float angleYaw = TASmodBufferBuilder.readFloat(buf); - float anglePitch = TASmodBufferBuilder.readFloat(buf); - - EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); - player.getServerWorld().addScheduledTask(() -> { - player.rotationPitch = anglePitch; - player.rotationYaw = angleYaw; - - player.setPositionAndUpdate(x, y, z); - }); - break; - - case CLEAR_INNPUTS: - TASmod.server.sendToAll(new TASmodBufferBuilder(CLEAR_INNPUTS)); - - case PLAYBACK_FULLPLAY: - case PLAYBACK_FULLRECORD: - case PLAYBACK_RESTARTANDPLAY: - case PLAYBACK_PLAYUNTIL: - case PLAYBACK_SAVE: - case PLAYBACK_LOAD: - TASmod.server.sendToAll(new TASmodBufferBuilder(buf)); - break; - default: - throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); - } - } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java index 098ce569..aeeb302d 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java @@ -1,5 +1,153 @@ package com.minecrafttas.tasmod.playback; -public class PlaybackControllerServer { +import static com.minecrafttas.tasmod.TASmod.LOGGER; +import static com.minecrafttas.tasmod.networking.TASmodPackets.*; + +import java.nio.ByteBuffer; + +import com.minecrafttas.common.server.Client.Side; +import com.minecrafttas.common.server.exception.PacketNotImplementedException; +import com.minecrafttas.common.server.exception.WrongSideException; +import com.minecrafttas.common.server.interfaces.PacketID; +import com.minecrafttas.common.server.interfaces.ServerPacketHandler; +import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.networking.TASmodPackets; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.MinecraftServer; + +/** + * The playback controller on the server side.
+ * Currently used sync the {@link TASstate} with all clients + * + * @author Scribble + * + */ +public class PlaybackControllerServer implements ServerPacketHandler { + + private TASstate state; + + private boolean shouldChange = true; + + public PlaybackControllerServer() { + state = TASstate.NONE; + shouldChange = true; + } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new TASmodPackets[] + { + STATESYNC_INITIAL, + STATESYNC, + PLAYBACK_TELEPORT, + CLEAR_INNPUTS, + PLAYBACK_FULLPLAY, + PLAYBACK_FULLRECORD, + PLAYBACK_RESTARTANDPLAY, + PLAYBACK_PLAYUNTIL, + PLAYBACK_SAVE, + PLAYBACK_LOAD + }; + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + + switch (packet) { + case STATESYNC_INITIAL: + TASstate networkState = TASmodBufferBuilder.readTASState(buf); + if (/* TODO Permissions && */ shouldChange) { + setState(networkState); + shouldChange = false; + } else { + TASmod.server.sendTo(username, new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(networkState)); + } + break; + + case STATESYNC: + networkState = TASmodBufferBuilder.readTASState(buf); + /* TODO Permissions */ + setState(networkState); + break; + + case PLAYBACK_TELEPORT: + double x = TASmodBufferBuilder.readDouble(buf); + double y = TASmodBufferBuilder.readDouble(buf); + double z = TASmodBufferBuilder.readDouble(buf); + float angleYaw = TASmodBufferBuilder.readFloat(buf); + float anglePitch = TASmodBufferBuilder.readFloat(buf); + + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); + player.getServerWorld().addScheduledTask(() -> { + player.rotationPitch = anglePitch; + player.rotationYaw = angleYaw; + + player.setPositionAndUpdate(x, y, z); + }); + break; + + case CLEAR_INNPUTS: + TASmod.server.sendToAll(new TASmodBufferBuilder(CLEAR_INNPUTS)); + + case PLAYBACK_FULLPLAY: + case PLAYBACK_FULLRECORD: + case PLAYBACK_RESTARTANDPLAY: + case PLAYBACK_PLAYUNTIL: + case PLAYBACK_SAVE: + case PLAYBACK_LOAD: + TASmod.server.sendToAll(new TASmodBufferBuilder(buf)); + break; + + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); + } + } + + public void leaveServer(EntityPlayerMP player) { + MinecraftServer server = TASmod.getServerInstance(); + if (server != null) { + if (server.getPlayerList().getPlayers().size() == 1) { + state = TASstate.NONE; + shouldChange = true; + } + } + } + + public void setState(TASstate stateIn) { + setServerState(stateIn); + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.STATESYNC).writeTASState(state).writeBoolean(true)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void setServerState(TASstate stateIn) { + if (state != stateIn) { + if (state == TASstate.RECORDING && stateIn == TASstate.PLAYBACK || state == TASstate.PLAYBACK && stateIn == TASstate.RECORDING) + return; + if (state == TASstate.NONE && state == TASstate.PAUSED) { + return; + } + this.state = stateIn; + LOGGER.info(String.format("Set the server state to %s", stateIn.toString())); + } + } + + public void toggleRecording() { + setState(state == TASstate.RECORDING ? TASstate.NONE : TASstate.RECORDING); + } + + public void togglePlayback() { + setState(state == TASstate.PLAYBACK ? TASstate.NONE : TASstate.PLAYBACK); + } + + public TASstate getState() { + return state; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java b/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java deleted file mode 100644 index 5ba61137..00000000 --- a/src/main/java/com/minecrafttas/tasmod/playback/TASstateServer.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.minecrafttas.tasmod.playback; - -import static com.minecrafttas.tasmod.TASmod.LOGGER; - -import java.nio.ByteBuffer; - -import com.minecrafttas.common.server.Client.Side; -import com.minecrafttas.common.server.exception.PacketNotImplementedException; -import com.minecrafttas.common.server.exception.WrongSideException; -import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.common.server.interfaces.ServerPacketHandler; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; -import com.minecrafttas.tasmod.networking.TASmodPackets; -import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; - -/** - * Stores the state of the input container on the server side.
- *
- * Since the current state, whether it's recording playing back or nothing is - * stored on the client,
- * there needs to be some form of synchronization between all clients so all - * clients have the same state.
- *
- * Additionally the client can start recording before the server is even started - * and when multiple clients still have to connect to the server. - * - * @author Scribble - * - */ -public class TASstateServer implements ServerPacketHandler{ - - private TASstate state; - - private boolean shouldChange = true; - - public TASstateServer() { - state = TASstate.NONE; - shouldChange = true; - } - - @Override - public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] {TASmodPackets.STATESYNC_INITIAL, TASmodPackets.STATESYNC}; - } - - @Override - public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { - TASmodPackets packet = (TASmodPackets) id; - TASstate networkState = TASmodBufferBuilder.readTASState(buf); - - switch (packet) { - case STATESYNC_INITIAL: - if (/* TODO Permissions && */ shouldChange) { - setState(networkState); - shouldChange = false; - } else { - TASmod.server.sendTo(username, new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(networkState)); - } - break; - - case STATESYNC: - /* TODO Permissions */ - setState(networkState); - break; - - default: - throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); - } - } - - - public void leaveServer(EntityPlayerMP player) { - MinecraftServer server = TASmod.getServerInstance(); - if (server != null) { - if (server.getPlayerList().getPlayers().size() == 1) { - state = TASstate.NONE; - shouldChange = true; - } - } - } - - public void setState(TASstate stateIn) { - setServerState(stateIn); - try { - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.STATESYNC).writeTASState(state).writeBoolean(true)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void setServerState(TASstate stateIn) { - if (state != stateIn) { - if (state == TASstate.RECORDING && stateIn == TASstate.PLAYBACK || state == TASstate.PLAYBACK && stateIn == TASstate.RECORDING) - return; - if (state == TASstate.NONE && state == TASstate.PAUSED) { - return; - } - this.state = stateIn; - LOGGER.info(String.format("Set the server state to %s", stateIn.toString())); - } - } - - public void toggleRecording() { - setState(state == TASstate.RECORDING ? TASstate.NONE : TASstate.RECORDING); - } - - public void togglePlayback() { - setState(state == TASstate.PLAYBACK ? TASstate.NONE : TASstate.PLAYBACK); - } - - public TASstate getState() { - return state; - } - -} From 54d4e0b6be3cadb74093693759f70251be813f62 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 10 Sep 2023 19:04:56 +0200 Subject: [PATCH 36/60] More documentation for packets - Fixed crash when client motion tag does not exist --- .../tasmod/networking/TASmodPackets.java | 34 +++++++++++++- .../savestates/SavestateHandlerClient.java | 47 +++++++++++-------- .../savestates/SavestateHandlerServer.java | 1 - .../TickrateChangerServer.java | 32 +++---------- 4 files changed, 67 insertions(+), 47 deletions(-) diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index 537aa0b7..c5de7ca3 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -4,6 +4,9 @@ import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.commands.CommandFolder; +import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; + +import net.minecraft.nbt.NBTTagCompound; /** * PacketIDs and handlers specifically for TASmod @@ -31,17 +34,46 @@ public enum TASmodPackets implements PacketID { /** *

Sets the tickrate to 0, pausing the game. Also unpauses the game * + *

SIDE: Both
+ * ARGS: {@link TickratePauseState} state The paused state */ TICKRATE_ZERO, + /** + *

While in tickrate 0, advances the game by one tick + * + *

SIDE: Both
+ * ARGS: None + */ TICKRATE_ADVANCE, - SAVESTATE_LOAD, + /** + *

Creates a savestate + * + *

SIDE: Both
+ * ARGS:
+ * Client->Server: int The index of the savestate that should be created. -1 to create the latest savestate, might overwrite existing savestates.
+ * Server->Client: String The name of the savestate that is created for the clientside + */ SAVESTATE_SAVE, + /** + *

Loads a savestate + * + *

SIDE: Both
+ * ARGS:
+ * Client->Server int The index of the savestate that should be loaded
+ * Server->Client String The name of the savestate that is loaded for the clientside + */ + SAVESTATE_LOAD, /** *

Opens or closes the savestate screen on the client *

SIDE: Client
* ARGS: none */ SAVESTATE_SCREEN, + /** + *

Sends the playerdata of the player to the client, inluding the motion + *

SIDE: Client
+ * ARGS: {@link NBTTagCompound} compound The playerdata + */ SAVESTATE_PLAYER, SAVESTATE_REQUEST_MOTION, SAVESTATE_UNLOAD_CHUNKS, diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index 5ce5d9d0..e9f9fced 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -160,35 +160,42 @@ public static void loadstate(String nameOfSavestate) throws IOException { } public static void loadPlayer(NBTTagCompound compound) { + LOGGER.trace(LoggerMarkers.Savestate, "Loading client player from NBT"); Minecraft mc = Minecraft.getMinecraft(); EntityPlayerSP player = mc.player; player.readFromNBT(compound); NBTTagCompound motion = compound.getCompoundTag("clientMotion"); + + if(motion.hasNoTags()) { + LOGGER.warn(LoggerMarkers.Savestate, "Could not load the motion from the savestate. Savestate seems to be created manually or by a different mod"); + } else { + LOGGER.trace(LoggerMarkers.Savestate, "Loading client motion from NBT"); + double x = motion.getDouble("x"); + double y = motion.getDouble("y"); + double z = motion.getDouble("z"); + player.motionX = x; + player.motionY = y; + player.motionZ = z; + + float rx = motion.getFloat("RelativeX"); + float ry = motion.getFloat("RelativeY"); + float rz = motion.getFloat("RelativeZ"); + player.moveForward = rx; + player.moveVertical = ry; + player.moveStrafing = rz; + + boolean sprinting = motion.getBoolean("Sprinting"); + float jumpVector = motion.getFloat("JumpFactor"); + player.setSprinting(sprinting); + player.jumpMovementFactor = jumpVector; + } - double x = motion.getDouble("x"); - double y = motion.getDouble("y"); - double z = motion.getDouble("z"); - player.motionX = x; - player.motionY = y; - player.motionZ = z; - - float rx = motion.getFloat("RelativeX"); - float ry = motion.getFloat("RelativeY"); - float rz = motion.getFloat("RelativeZ"); - player.moveForward = rx; - player.moveVertical = ry; - player.moveStrafing = rz; - - boolean sprinting = motion.getBoolean("Sprinting"); - float jumpVector = motion.getFloat("JumpFactor"); - player.setSprinting(sprinting); - player.jumpMovementFactor = jumpVector; - + LOGGER.trace(LoggerMarkers.Savestate, "Setting client gamemode"); // #86 int gamemode = compound.getInteger("playerGameType"); GameType type = GameType.getByID(gamemode); - Minecraft.getMinecraft().playerController.setGameType(type); + mc.playerController.setGameType(type); // #?? Player rotation does not change when loading a savestate // CameraInterpolationEvents.rotationPitch = player.rotationPitch; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 892d3941..406d005b 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -795,7 +795,6 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws break; case SAVESTATE_REQUEST_MOTION: - System.out.println("Ahh"); MotionData data = TASmodBufferBuilder.readMotionData(buf); PlayerHandler.getMotion().put(player, data); break; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 36109c32..a296e1a1 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -234,45 +234,27 @@ public void onServerStop(MinecraftServer server) { } } + /** + * Enum for sending paused states for the tickratechanger + */ public static enum TickratePauseState { /** * Set's the game to tickrate 0 */ - PAUSE((short) 1), + PAUSE, /** * Set's the game to "tickrate saved" */ - UNPAUSE((short) 2), + UNPAUSE, /** * Toggles between {@link #PAUSE} and {@link #UNPAUSE} */ - TOGGLE((short) 0); - - private short id; - - TickratePauseState(short i) { - id = i; - } - - public short toShort() { - return id; - } - - public static TickratePauseState fromShort(short i) { - switch (i) { - case 1: - return PAUSE; - case 2: - return UNPAUSE; - default: - return TOGGLE; - } - } + TOGGLE; } @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[] { TASmodPackets.TICKRATE_CHANGE, TASmodPackets.TICKRATE_ADVANCE, TASmodPackets.TICKRATE_ZERO, }; + return new TASmodPackets[] { TASmodPackets.TICKRATE_CHANGE, TASmodPackets.TICKRATE_ADVANCE, TASmodPackets.TICKRATE_ZERO }; } @Override From 55ae4a6721765caac4489f609274ab9ba396be50 Mon Sep 17 00:00:00 2001 From: Scribble Date: Thu, 5 Oct 2023 21:32:10 +0200 Subject: [PATCH 37/60] Updating loader version to 0.14.23 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index b4c2796e..4b1eced2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx3G # Fabric properties minecraft_version=1.12.2 -loader_version=0.14.21 +loader_version=0.14.23 loom_version=1.3-SNAPSHOT # Mod properties From 6ec4a45118bb1acf5b0006151e8cf52b04cb67cc Mon Sep 17 00:00:00 2001 From: Scribble Date: Thu, 5 Oct 2023 21:33:12 +0200 Subject: [PATCH 38/60] Adding log4j config to server console --- src/main/resources/log4j.xml | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml index bad101f8..36586568 100644 --- a/src/main/resources/log4j.xml +++ b/src/main/resources/log4j.xml @@ -18,16 +18,29 @@ %style{[%d{HH:mm:ss}]}{blue} %highlight{[%t/%level]}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=green, TRACE=blue} %style{(%logger{1}%notEmpty{/%marker})}{cyan} %highlight{%msg%n}{FATAL=red, ERROR=red, WARN=normal, INFO=normal, DEBUG=normal, TRACE=normal} + + + + + + + + + + + + - + + \ No newline at end of file From 8b30d81bfe7113ec8d6fecfb88e2512a971e3bc8 Mon Sep 17 00:00:00 2001 From: Scribble Date: Thu, 5 Oct 2023 21:33:47 +0200 Subject: [PATCH 39/60] Testing multiplayer connections --- .../minecrafttas/common/server/Client.java | 10 +++++ .../minecrafttas/common/server/Server.java | 1 - .../java/com/minecrafttas/tasmod/TASmod.java | 19 +++++--- .../com/minecrafttas/tasmod/TASmodClient.java | 43 ++++++++++++++++--- 4 files changed, 59 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 64b4aade..c22bcd27 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -31,6 +31,8 @@ public class Client { private Future future; private String username; + private String ip; + private int port; private Side side; @@ -52,6 +54,9 @@ public Client(String host, int port, PacketID[] packetIDs, String name) throws E this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); + ip = host; + this.port = port; + this.side = Side.CLIENT; this.packetIDs = packetIDs; @@ -203,4 +208,9 @@ private PacketID getPacketFromID(int id) throws InvalidPacketException { public boolean isClosed() { return this.socket == null || !this.socket.isOpen(); } + + public String getRemote() throws IOException { + return ip+":"+port; + } + } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 79163565..37597003 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -7,7 +7,6 @@ import java.nio.channels.CompletionHandler; import java.util.ArrayList; import java.util.List; -import java.util.UUID; import com.minecrafttas.common.Common; import com.minecrafttas.common.server.interfaces.PacketID; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 4a19d3d8..217468da 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -64,13 +64,16 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static Server server; - public static int networkingport = 8999; + public static final int networkingport = 8999; + + public static final boolean isDevEnvironment = FabricLoaderImpl.INSTANCE.isDevelopmentEnvironment(); @Override public void onInitialize() { LOGGER.info("Initializing TASmod"); + // Start ticksync ticksyncServer = new TickSyncServer(); @@ -93,16 +96,11 @@ public void onInitialize() { PacketHandlerRegistry.register(tickratechanger); PacketHandlerRegistry.register(ktrngHandler); - // Starting custom server instance - try { - server = new Server(networkingport, TASmodPackets.values()); - } catch (Exception e) { - LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); - } } @Override public void onServerInit(MinecraftServer server) { + LOGGER.info("Initializing server"); serverInstance = server; playbackControllerServer=new PlaybackControllerServer(); PacketHandlerRegistry.register(playbackControllerServer); @@ -136,6 +134,13 @@ public void onServerInit(MinecraftServer server) { if(!server.isDedicatedServer()) { TASmod.tickratechanger.ticksPerSecond=0F; TASmod.tickratechanger.tickrateSaved=20F; + } else { + // Starting custom server instance + try { + TASmod.server = new Server(networkingport, TASmodPackets.values()); + } catch (Exception e) { + LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); + } } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index fc35a03d..cab47a1c 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -3,6 +3,7 @@ import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -19,6 +20,7 @@ import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.common.server.Client; import com.minecrafttas.common.server.PacketHandlerRegistry; +import com.minecrafttas.common.server.Server; import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.gui.InfoHud; import com.minecrafttas.tasmod.handlers.InterpolationHandler; @@ -46,8 +48,6 @@ public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide{ - public static boolean isDevEnvironment; - public static VirtualInput virtual; public static TickSyncClient ticksyncClient; @@ -99,9 +99,6 @@ public static void createSavestatesDir() { @Override public void onInitializeClient() { - // Check if dev environment - isDevEnvironment = FabricLoaderImpl.INSTANCE.isDevelopmentEnvironment(); - // Load config Minecraft mc = Minecraft.getMinecraft(); config = new Configuration("TASmod configuration", new File(mc.mcDataDir, "config/tasmod.cfg")); @@ -155,10 +152,17 @@ protected boolean isKeyDown(KeyBinding i) { PacketHandlerRegistry.register(tickratechanger); PacketHandlerRegistry.register(savestateHandlerClient); + // Starting local server instance + try { + TASmod.server = new Server(TASmod.networkingport-1, TASmodPackets.values()); + } catch (Exception e) { + LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); + } + // Connecting to local server instance try { // connect to server and authenticate - client = new Client("127.0.0.1", TASmod.networkingport, TASmodPackets.values(), mc.getSession().getUsername()); + client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername()); } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); } @@ -220,6 +224,33 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { * Will be obsolete once we have a networking system that starts in the main menu. Then we can sync the state from there */ // TASmodClient.packetClient.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); + Minecraft mc = Minecraft.getMinecraft(); + String full = mc.getCurrentServerData().serverIP; + String ip = full.split(":")[0]; + + String connectedIP = null; + try { + connectedIP = client.getRemote(); + } catch (IOException e) { + e.printStackTrace(); + } + + System.out.println(full); + System.out.println(connectedIP); + + if(!(ip+TASmod.networkingport).equals(full)) { + try { + client.close(); + } catch (IOException e) { + e.printStackTrace(); + } + try { + // connect to server and authenticate + client = new Client(ip, TASmod.networkingport, TASmodPackets.values(), mc.getSession().getUsername()); + } catch (Exception e) { + LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); + } + } } @Override From eaefa654dc7c00569b51f144094cc8ab3a259141 Mon Sep 17 00:00:00 2001 From: Scribble Date: Mon, 9 Oct 2023 21:36:38 +0200 Subject: [PATCH 40/60] Rewriting connection things --- .../java/com/minecrafttas/common/Common.java | 4 +++ .../common/server/ByteBufferBuilder.java | 6 ++++ .../minecrafttas/common/server/Client.java | 20 +++++++---- .../minecrafttas/common/server/Server.java | 22 ++++++++++--- .../com/minecrafttas/tasmod/TASmodClient.java | 33 +++++++++---------- .../networking/TASmodBufferBuilder.java | 1 + 6 files changed, 58 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/Common.java b/src/main/java/com/minecrafttas/common/Common.java index 70c25759..f806e618 100644 --- a/src/main/java/com/minecrafttas/common/Common.java +++ b/src/main/java/com/minecrafttas/common/Common.java @@ -9,4 +9,8 @@ public class Common { public static final Logger LOGGER = LogManager.getLogger("Common"); public static final Marker Event = MarkerManager.getMarker("Event"); + + public static final Marker Server = MarkerManager.getMarker("Server"); + + public static final Marker Client = MarkerManager.getMarker("Client"); } diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 4945877c..591388fa 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -13,10 +13,12 @@ */ public class ByteBufferBuilder { + private int bufferId; private int bufferIndex; protected ByteBuffer buffer; public ByteBufferBuilder(int id) { + bufferId = id; bufferIndex = SecureList.POOL.available(); buffer = SecureList.POOL.lock(bufferIndex); buffer.putInt(id); @@ -173,4 +175,8 @@ public static byte[] readByteArray(ByteBuffer buf) { buf.get(array); return array; } + + public int getId(){ + return bufferId; + } } diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index c22bcd27..2434b6e3 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -1,10 +1,14 @@ package com.minecrafttas.common.server; import static com.minecrafttas.common.server.SecureList.BUFFER_SIZE; +import static com.minecrafttas.common.Common.LOGGER; +import static com.minecrafttas.common.Common.Client; +import static com.minecrafttas.common.Common.Server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.Future; @@ -50,7 +54,7 @@ public enum Side { * @throws Exception Unable to connect */ public Client(String host, int port, PacketID[] packetIDs, String name) throws Exception { - Common.LOGGER.info("Connecting server to {}:{}", host, port); + LOGGER.info(Client, "Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); @@ -61,7 +65,7 @@ public Client(String host, int port, PacketID[] packetIDs, String name) throws E this.packetIDs = packetIDs; this.createHandlers(); - Common.LOGGER.info("Connected to server"); + LOGGER.info(Client, "Connected to server"); authenticate(name); } @@ -103,13 +107,17 @@ public void completed(Integer result, Object attachment) { readBuffer.clear().limit(4); socket.read(readBuffer, null, this); } catch (Throwable exc) { - Common.LOGGER.error("Unable to read packet!", exc); + LOGGER.error("Unable to read packet!", exc); } } @Override public void failed(Throwable exc, Object attachment) { - Common.LOGGER.error("Unable to read packet!", exc); + if(exc instanceof AsynchronousCloseException) { + LOGGER.warn(side==Side.CLIENT? Client:Server, "Connection was closed"); + } else { + LOGGER.error(side==Side.CLIENT? Client:Server, "Unable to read packet!", exc); + } } }); @@ -148,7 +156,7 @@ public void send(ByteBufferBuilder bufferBuilder) throws Exception { */ public void close() throws IOException { if (this.socket == null || !this.socket.isOpen()) { - Common.LOGGER.warn("Tried to close dead socket"); + Common.LOGGER.warn(side==Side.CLIENT? Client:Server, "Tried to close dead socket"); return; } @@ -163,7 +171,7 @@ public void close() throws IOException { */ private void authenticate(String id) throws Exception { this.username = id; - Common.LOGGER.info("Authenticating with UUID {}", id.toString()); + Common.LOGGER.info(side==Side.CLIENT? Client:Server, "Authenticating with UUID {}", id.toString()); this.send(new ByteBufferBuilder(-1).writeString(id)); } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 37597003..521a71a6 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -1,7 +1,11 @@ package com.minecrafttas.common.server; +import static com.minecrafttas.common.Common.LOGGER; +import static com.minecrafttas.common.Common.Server; + import java.io.IOException; import java.net.InetSocketAddress; +import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; @@ -31,7 +35,7 @@ public class Server { */ public Server(int port, PacketID[] packetIDs) throws Exception { // create connection - Common.LOGGER.info("Creating server on port {}", port); + LOGGER.info(Server, "Creating server on port {}", port); this.socket = AsynchronousServerSocketChannel.open(); this.socket.bind(new InetSocketAddress(port)); @@ -47,11 +51,15 @@ public void completed(AsynchronousSocketChannel clientSocket, Object attachment) @Override public void failed(Throwable exc, Object attachment) { - Common.LOGGER.error("Unable to accept client!", exc); + if(exc instanceof AsynchronousCloseException) { + LOGGER.info(Server, "Connection to the player was closed!"); + } else { + Common.LOGGER.error(Server, "Unable to accept client!", exc); + } } }); - Common.LOGGER.info("Server created"); + Common.LOGGER.info(Server, "Server created"); } /** @@ -76,7 +84,11 @@ public void sendToAll(ByteBufferBuilder builder) throws Exception { */ public void sendTo(String username, ByteBufferBuilder builder) throws Exception { Client client = getClient(username); - client.send(builder); + if(client != null && !client.isClosed()) { + client.send(builder); + } else { + Common.LOGGER.warn(Server, "Buffer with id {} could not be sent to the client {}: The client is closed", builder.getId(), username); + } } /** @@ -99,7 +111,7 @@ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Except */ public void close() throws IOException { if (this.socket == null || !this.socket.isOpen()) { - Common.LOGGER.warn("Tried to close dead socket"); + Common.LOGGER.warn(Server, "Tried to close dead socket on server"); return; } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index cab47a1c..6661e1ec 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -43,6 +43,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.settings.KeyBinding; public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide{ @@ -212,21 +213,20 @@ public void onClientInit(Minecraft mc) { @Override public void onPlayerJoinedClientSide(EntityPlayerSP player) { - // FIXME: ask how this works - - /* == Scribble == - * The playback state (Playing, Recording, Paused, None) of the client may be different from the server state, - * since we allow the fact that the player can start a playback in the main menu. - * - * So when joining the world, the player sends their current state over to the server. If another player is already on the server, - * then the server sends back the current server state, so everyone has the same playback state. - * - * Will be obsolete once we have a networking system that starts in the main menu. Then we can sync the state from there - */ // TASmodClient.packetClient.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); Minecraft mc = Minecraft.getMinecraft(); - String full = mc.getCurrentServerData().serverIP; - String ip = full.split(":")[0]; + ServerData data = mc.getCurrentServerData(); + + String ip = null; + int port; + + if(data==null) { + ip = "localhost"; + port = TASmod.networkingport-1; + } else { + ip = data.serverIP.split(":")[0]; + port = TASmod.networkingport; + } String connectedIP = null; try { @@ -235,18 +235,17 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { e.printStackTrace(); } - System.out.println(full); - System.out.println(connectedIP); - if(!(ip+TASmod.networkingport).equals(full)) { + if(!(ip+":"+port).equals(connectedIP)) { try { + LOGGER.info("Closing current client connection!"); client.close(); } catch (IOException e) { e.printStackTrace(); } try { // connect to server and authenticate - client = new Client(ip, TASmod.networkingport, TASmodPackets.values(), mc.getSession().getUsername()); + client = new Client(ip, port, TASmodPackets.values(), mc.getSession().getUsername()); } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index 95695896..e4f64e1e 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -110,4 +110,5 @@ public static MotionData readMotionData(ByteBuffer buf) { return new MotionData(x, y, z, rx, ry, rz, sprinting, jumpMovementVector); } + } From 5a502a2e50060f9d0b04a86cc455f3266a13f525 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 15 Oct 2023 16:58:34 +0200 Subject: [PATCH 41/60] Fixing server closing - Fixed local server closing when leaving the singeplayer world - Fixed client being unresponsive in main menu when not connected to a custom server - Various logging changes - Add testing keybinds for connecting and disconnecting from the custom server --- .../common/events/EventServer.java | 18 +++++++++ .../minecrafttas/common/server/Client.java | 17 +++++++-- .../minecrafttas/common/server/Server.java | 31 +++++++++------ .../java/com/minecrafttas/tasmod/TASmod.java | 12 +++--- .../com/minecrafttas/tasmod/TASmodClient.java | 38 ++++++++++++------- .../com/minecrafttas/tasmod/gui/InfoHud.java | 3 ++ .../minecrafttas/tasmod/mixin/MixinTimer.java | 2 +- .../tasmod/ticksync/TickSyncClient.java | 2 +- .../tasmod/ticksync/TickSyncServer.java | 23 ++++++----- 9 files changed, 102 insertions(+), 44 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/events/EventServer.java b/src/main/java/com/minecrafttas/common/events/EventServer.java index a44ab51a..aeedcf15 100644 --- a/src/main/java/com/minecrafttas/common/events/EventServer.java +++ b/src/main/java/com/minecrafttas/common/events/EventServer.java @@ -140,4 +140,22 @@ public static void firePlayerLeaveServerSide(EntityPlayerMP player) { } } } + + public static interface EventClientCompleteAuthentication extends EventBase { + + /** + * Fired when authentication was successful on the server side + */ + public void onClientCompleteAuthentication(String username); + + public static void fireClientCompleteAuthentication(String username) { + Common.LOGGER.trace(Common.Event, "Firing ClientCompleteAuthenticationEvent"); + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if (eventListener instanceof EventClientCompleteAuthentication) { + EventClientCompleteAuthentication event = (EventClientCompleteAuthentication) eventListener; + event.onClientCompleteAuthentication(username); + } + } + } + } } diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 2434b6e3..f82fc184 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -16,6 +16,7 @@ import org.apache.logging.log4j.Level; import com.minecrafttas.common.Common; +import com.minecrafttas.common.events.EventServer.EventClientCompleteAuthentication; import com.minecrafttas.common.server.exception.InvalidPacketException; import com.minecrafttas.common.server.exception.PacketNotImplementedException; import com.minecrafttas.common.server.exception.WrongSideException; @@ -88,10 +89,18 @@ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs) { private void createHandlers() { // create input handler this.readBuffer.limit(4); + if(socket == null || !socket.isOpen()) { + LOGGER.info(side==Side.CLIENT? Client:Server, "Connection was closed"); + return; + } this.socket.read(this.readBuffer, null, new CompletionHandler() { @Override public void completed(Integer result, Object attachment) { + if(result == -1) { + LOGGER.info(side==Side.CLIENT? Client:Server, "Stream was closed"); + return; + } try { // read rest of packet readBuffer.flip(); @@ -113,10 +122,10 @@ public void completed(Integer result, Object attachment) { @Override public void failed(Throwable exc, Object attachment) { - if(exc instanceof AsynchronousCloseException) { - LOGGER.warn(side==Side.CLIENT? Client:Server, "Connection was closed"); + if(exc instanceof AsynchronousCloseException || exc instanceof IOException) { + LOGGER.warn(side==Side.CLIENT? Client:Server, "Connection was closed!"); } else { - LOGGER.error(side==Side.CLIENT? Client:Server, "Unable to read packet!", exc); + LOGGER.error(side==Side.CLIENT? Client:Server, "Something went wrong!", exc); } } @@ -159,6 +168,7 @@ public void close() throws IOException { Common.LOGGER.warn(side==Side.CLIENT? Client:Server, "Tried to close dead socket"); return; } + this.future=null; this.socket.close(); } @@ -181,6 +191,7 @@ private void completeAuthentication(ByteBuffer buf) throws Exception { } this.username = ByteBufferBuilder.readString(buf); + EventClientCompleteAuthentication.fireClientCompleteAuthentication(username); } private void handle(ByteBuffer buf) { diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 521a71a6..49888894 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -24,7 +24,7 @@ */ public class Server { - private final AsynchronousServerSocketChannel socket; + private final AsynchronousServerSocketChannel serverSocket; private final List clients; /** @@ -36,17 +36,26 @@ public class Server { public Server(int port, PacketID[] packetIDs) throws Exception { // create connection LOGGER.info(Server, "Creating server on port {}", port); - this.socket = AsynchronousServerSocketChannel.open(); - this.socket.bind(new InetSocketAddress(port)); + this.serverSocket = AsynchronousServerSocketChannel.open(); + this.serverSocket.bind(new InetSocketAddress(port)); // create connection handler this.clients = new ArrayList<>(); - this.socket.accept(null, new CompletionHandler() { + this.serverSocket.accept(null, new CompletionHandler() { @Override public void completed(AsynchronousSocketChannel clientSocket, Object attachment) { + cleanClients(); clients.add(new Client(clientSocket, packetIDs)); - socket.accept(null, this); + serverSocket.accept(null, this); + } + + private void cleanClients() { + for(Client client : clients) { + if(client.isClosed()) { + clients.remove(client); + } + } } @Override @@ -54,12 +63,12 @@ public void failed(Throwable exc, Object attachment) { if(exc instanceof AsynchronousCloseException) { LOGGER.info(Server, "Connection to the player was closed!"); } else { - Common.LOGGER.error(Server, "Unable to accept client!", exc); + LOGGER.error(Server, "Unable to accept client!", exc); } } }); - Common.LOGGER.info(Server, "Server created"); + LOGGER.info(Server, "Server created"); } /** @@ -110,16 +119,16 @@ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Except * @throws IOException Unable to close */ public void close() throws IOException { - if (this.socket == null || !this.socket.isOpen()) { + if (this.serverSocket == null || !this.serverSocket.isOpen()) { Common.LOGGER.warn(Server, "Tried to close dead socket on server"); return; } - this.socket.close(); + this.serverSocket.close(); } public boolean isClosed() { - return this.socket == null || !this.socket.isOpen(); + return this.serverSocket == null || !this.serverSocket.isOpen(); } /** @@ -140,7 +149,7 @@ public List getClients() { } public AsynchronousServerSocketChannel getAsynchronousSocketChannel() { - return this.socket; + return this.serverSocket; } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 217468da..22d174ad 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -147,11 +147,13 @@ public void onServerInit(MinecraftServer server) { @Override public void onServerStop(MinecraftServer mcserver) { serverInstance=null; - try { - if (server != null) server.close(); - } catch (IOException e) { - LOGGER.error("Unable to close TASmod server: {}", e); - e.printStackTrace(); + if(mcserver.isDedicatedServer()) { + try { + if (server != null) server.close(); + } catch (IOException e) { + LOGGER.error("Unable to close TASmod server: {}", e); + e.printStackTrace(); + } } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 6661e1ec..defb3236 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -193,13 +193,18 @@ public void onClientInit(Minecraft mc) { blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Open InfoGui Editor", "TASmod", Keyboard.KEY_F6, () -> Minecraft.getMinecraft().displayGuiScreen(TASmodClient.hud)))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Buffer View", "TASmod", Keyboard.KEY_NUMPAD0, () -> InputContainerView.startBufferView()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing", "TASmod", Keyboard.KEY_F12, () -> { - TASmod.tickSchedulerServer.add(() -> { - try { - Thread.sleep(1000L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); + try { + TASmodClient.client.close(); + } catch (IOException e) { + e.printStackTrace(); + } + }))); + blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing2", "TASmod", Keyboard.KEY_F7, () -> { + try { + TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName()); + } catch (Exception e) { + e.printStackTrace(); + } }))); blockedKeybindings.forEach(VirtualKeybindings::registerBlockedKeyBinding); @@ -238,17 +243,22 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { if(!(ip+":"+port).equals(connectedIP)) { try { - LOGGER.info("Closing current client connection!"); + LOGGER.info("Closing client connection: {}", client.getRemote()); client.close(); } catch (IOException e) { e.printStackTrace(); } - try { - // connect to server and authenticate - client = new Client(ip, port, TASmodPackets.values(), mc.getSession().getUsername()); - } catch (Exception e) { - LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); - } + final String IP = ip; + final int PORT = port; + gameLoopSchedulerClient.add(()->{ + try { + // connect to server and authenticate + client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername()); + } catch (Exception e) { + LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); + e.printStackTrace(); + } + }); } } diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index 138425d4..b5639709 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -195,6 +195,9 @@ private int snapToGridY(int y) { * Saves the Configuration */ private void saveConfig() { + if(!(Minecraft.getMinecraft().currentScreen instanceof InfoHud) || configuration == null) { + return; + } try { File tasmodDir = new File(Minecraft.getMinecraft().mcDataDir, "tasmod"); tasmodDir.mkdir(); diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java index 1b1d3ac8..b240b069 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java @@ -42,7 +42,7 @@ public class MixinTimer { @Inject(method = "updateTimer", at = @At("HEAD"), cancellable = true) public void inject_tick(CallbackInfo ci) { - if (Minecraft.getMinecraft().getConnection() != null) { + if (TASmodClient.client != null && !TASmodClient.client.isClosed()) { lastSyncSysClock = Minecraft.getSystemTime(); // update the tick tracker so that after returning to scheduling the client won't catch up all ticks (max 10) this.elapsedTicks = 0; // do not do any ticks long newGameLoop = Minecraft.getSystemTime(); diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index f97f9892..9afcfa10 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -52,7 +52,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) { */ @Override public void onClientTickPost(Minecraft mc) { - if (mc.player == null) { + if (TASmodClient.client == null || TASmodClient.client.isClosed()) { return; } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index c227146b..9b113b8e 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -8,6 +8,7 @@ import java.util.Collections; import java.util.List; +import com.minecrafttas.common.events.EventServer.EventClientCompleteAuthentication; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; @@ -24,7 +25,7 @@ * * @author Pancake */ -public class TickSyncServer implements ServerPacketHandler, EventServerTickPost { +public class TickSyncServer implements ServerPacketHandler, EventServerTickPost, EventClientCompleteAuthentication { private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); @@ -48,6 +49,9 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) { synchronizedList.add(username); } } + if(TASmod.getServerInstance()==null) { // If the server is null, keep the clients ticking + sendToClients(); + } } public boolean shouldTick() { @@ -62,20 +66,21 @@ public boolean shouldTick() { } } - /** - * Called after a server tick. This will send a packet - * to all clients making them tick - */ - public void serverPostTick() { - - } - public static void clearList() { synchronizedList.clear(); } @Override public void onServerTickPost(MinecraftServer server) { + sendToClients(); + } + + @Override + public void onClientCompleteAuthentication(String username) { + sendToClients(); + } + + private void sendToClients() { try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { From 55b3e19e94c8c0008f804949a9952c15381bd725 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 15 Oct 2023 20:03:43 +0200 Subject: [PATCH 42/60] Fixed connecting to the wrong server Crash fix --- src/main/java/com/minecrafttas/tasmod/TASmodClient.java | 6 ++++-- src/main/resources/tasmod.mixin.json | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index defb3236..339e0ac7 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -45,6 +45,7 @@ import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.settings.KeyBinding; +import net.minecraft.server.MinecraftServer; public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide{ @@ -218,14 +219,14 @@ public void onClientInit(Minecraft mc) { @Override public void onPlayerJoinedClientSide(EntityPlayerSP player) { - // TASmodClient.packetClient.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); Minecraft mc = Minecraft.getMinecraft(); ServerData data = mc.getCurrentServerData(); + MinecraftServer server = TASmod.getServerInstance(); String ip = null; int port; - if(data==null) { + if(server!=null) { ip = "localhost"; port = TASmod.networkingport-1; } else { @@ -260,6 +261,7 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { } }); } +// TASmod.server.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); } @Override diff --git a/src/main/resources/tasmod.mixin.json b/src/main/resources/tasmod.mixin.json index b0e76918..11b70b45 100644 --- a/src/main/resources/tasmod.mixin.json +++ b/src/main/resources/tasmod.mixin.json @@ -20,8 +20,7 @@ //Events //Fixing forge and vanilla stuff - "fixes.MixinDragonFightManager", - "fixes.MixinNetworkManager" + "fixes.MixinDragonFightManager" ], "client": [ @@ -61,6 +60,9 @@ //Shields "shields.MixinRenderItem", - "shields.MixinTileEntityItemStackRenderer" + "shields.MixinTileEntityItemStackRenderer", + + //Fixes + "fixes.MixinNetworkManager" ] } \ No newline at end of file From 22ce325af95996dbb28fcac4b0a5801ac2ab2387 Mon Sep 17 00:00:00 2001 From: Scribble Date: Fri, 20 Oct 2023 21:54:43 +0200 Subject: [PATCH 43/60] Fixed tickadvance not working as intended --- .gitignore | 3 ++- .../java/com/minecrafttas/common/server/Client.java | 9 +++++++++ .../java/com/minecrafttas/common/server/Server.java | 13 ++++--------- .../java/com/minecrafttas/tasmod/TASmodClient.java | 1 - .../tasmod/externalGui/InputContainerView.java | 11 ++++++++++- .../java/com/minecrafttas/tasmod/gui/InfoHud.java | 1 + .../minecrafttas/tasmod/mixin/MixinMinecraft.java | 2 -- .../tasmod/playback/PlaybackControllerClient.java | 2 -- .../tickratechanger/TickrateChangerServer.java | 11 +++++------ 9 files changed, 31 insertions(+), 22 deletions(-) diff --git a/.gitignore b/.gitignore index b96c7fb2..b4e87106 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ build # other eclipse run/ -logs/ \ No newline at end of file +logs/ +/.apt_generated_tests/ diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index f82fc184..4bce2139 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.net.InetSocketAddress; +import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousSocketChannel; @@ -58,6 +59,8 @@ public Client(String host, int port, PacketID[] packetIDs, String name) throws E LOGGER.info(Client, "Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); + this.socket.setOption(StandardSocketOptions.SO_KEEPALIVE, true); + this.socket.setOption(StandardSocketOptions.TCP_NODELAY, true); ip = host; this.port = port; @@ -78,6 +81,12 @@ public Client(String host, int port, PacketID[] packetIDs, String name) throws E */ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs) { this.socket = socket; + try { + this.socket.setOption(StandardSocketOptions.SO_KEEPALIVE, true); + this.socket.setOption(StandardSocketOptions.TCP_NODELAY, true); + } catch (IOException e) { + e.printStackTrace(); + } this.packetIDs = packetIDs; this.createHandlers(); this.side = Side.SERVER; diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 49888894..a8f8bad7 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -45,19 +45,10 @@ public Server(int port, PacketID[] packetIDs) throws Exception { @Override public void completed(AsynchronousSocketChannel clientSocket, Object attachment) { - cleanClients(); clients.add(new Client(clientSocket, packetIDs)); serverSocket.accept(null, this); } - private void cleanClients() { - for(Client client : clients) { - if(client.isClosed()) { - clients.remove(client); - } - } - } - @Override public void failed(Throwable exc, Object attachment) { if(exc instanceof AsynchronousCloseException) { @@ -97,6 +88,7 @@ public void sendTo(String username, ByteBufferBuilder builder) throws Exception client.send(builder); } else { Common.LOGGER.warn(Server, "Buffer with id {} could not be sent to the client {}: The client is closed", builder.getId(), username); + removeClient(client); } } @@ -152,4 +144,7 @@ public AsynchronousServerSocketChannel getAsynchronousSocketChannel() { return this.serverSocket; } + private void removeClient(Client client) { + getClients().remove(client); + } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 339e0ac7..3d6df354 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -39,7 +39,6 @@ import com.minecrafttas.tasmod.virtual.VirtualKeybindings; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.loader.impl.FabricLoaderImpl; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; diff --git a/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java b/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java index 00145f78..c6bd87f3 100644 --- a/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java +++ b/src/main/java/com/minecrafttas/tasmod/externalGui/InputContainerView.java @@ -16,12 +16,16 @@ import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; +import com.minecrafttas.common.events.EventClient.EventClientTick; +import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.playback.PlaybackControllerClient; import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TickInputContainer; import com.minecrafttas.tasmod.virtual.VirtualInput; +import net.minecraft.client.Minecraft; + @Deprecated -public class InputContainerView extends JFrame { +public class InputContainerView extends JFrame implements EventClientTick{ private static final long serialVersionUID = -1823965270972132025L; private JPanel contentPane; @@ -175,4 +179,9 @@ public void run() { } }); } + + @Override + public void onClientTick(Minecraft mc) { + update(TASmodClient.virtual); + } } diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index b5639709..b0f182e4 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -478,6 +478,7 @@ public void onDrawHotbar() { } ScaledResolution scaled = new ScaledResolution(Minecraft.getMinecraft()); drawCenteredString(Minecraft.getMinecraft().fontRenderer, "TASmod is still in development! Major issues may arise!", scaled.getScaledWidth() / 2, scaled.getScaledHeight() - 50, 0xFF8400); +// drawCenteredString(Minecraft.getMinecraft().fontRenderer, Float.toString(TASmod.tickratechanger.ticksPerSecond), scaled.getScaledWidth() / 2, scaled.getScaledHeight() - 36, 0xFFFFFF); } /** diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java index 11421e49..4f0b0ab0 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java @@ -97,8 +97,6 @@ public void inject_shutdownMinecraftApplet(CallbackInfo ci) { @Inject(method = "runTick", at = @At(value = "HEAD")) public void injectRunTick(CallbackInfo ci) throws IOException { - - InputContainerView.update(TASmodClient.virtual); if (SavestateHandlerServer.wasLoading) { SavestateHandlerServer.wasLoading = false; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java index 13b9dd0e..9e5903d5 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java @@ -30,7 +30,6 @@ import com.minecrafttas.common.server.exception.WrongSideException; import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; -import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.monitoring.DesyncMonitoring; @@ -49,7 +48,6 @@ import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index a296e1a1..46c68b4a 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -181,12 +181,11 @@ public void advanceTick() { * Sends a {@link AdvanceTickratePacket} to all clients */ private void advanceClientTick() { - if (ticksPerSecond == 0) { - try { - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); - } catch (Exception e) { - e.printStackTrace(); - } + // Do not check for ticksPerSecond==0 here, because at this point, ticksPerSecond is 20 for one tick! + try { + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ADVANCE)); + } catch (Exception e) { + e.printStackTrace(); } } From 95c706523628919dd72e3984627ee72a1c2c81be Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 22 Oct 2023 14:42:11 +0200 Subject: [PATCH 44/60] Added disconnect packet and check for timeout - Fixed EventOpenGuiScreen not firing --- .../java/com/minecrafttas/common/Common.java | 2 + .../common/events/EventClient.java | 22 ++- .../common/events/EventServer.java | 20 +++ .../common/mixin/MixinMinecraft.java | 12 +- .../minecrafttas/common/server/Client.java | 142 ++++++++++++++++-- .../minecrafttas/common/server/Server.java | 29 +++- .../com/minecrafttas/tasmod/TASmodClient.java | 36 +++-- .../tasmod/mixin/MixinMinecraft.java | 2 +- src/test/java/common/server/ServerTest.java | 2 +- 9 files changed, 231 insertions(+), 36 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/Common.java b/src/main/java/com/minecrafttas/common/Common.java index f806e618..283640ce 100644 --- a/src/main/java/com/minecrafttas/common/Common.java +++ b/src/main/java/com/minecrafttas/common/Common.java @@ -13,4 +13,6 @@ public class Common { public static final Marker Server = MarkerManager.getMarker("Server"); public static final Marker Client = MarkerManager.getMarker("Client"); + + public static final Marker Timeout = MarkerManager.getMarker("Timeout"); } diff --git a/src/main/java/com/minecrafttas/common/events/EventClient.java b/src/main/java/com/minecrafttas/common/events/EventClient.java index f7dab234..724af00a 100644 --- a/src/main/java/com/minecrafttas/common/events/EventClient.java +++ b/src/main/java/com/minecrafttas/common/events/EventClient.java @@ -2,6 +2,7 @@ import com.minecrafttas.common.Common; import com.minecrafttas.common.events.EventListenerRegistry.EventBase; +import com.minecrafttas.common.server.Client; import com.mojang.authlib.GameProfile; import net.minecraft.client.Minecraft; @@ -279,6 +280,25 @@ public static void fireOtherPlayerJoinedClientSide(GameProfile profile) { } } } - + + } + + public static interface EventDisconnectClient extends EventBase { + + public void onDisconnectClient(Client client); + + /** + * Fired when the connection to the custom server was closed on the client side. + * @param client The client that is disconnecting + */ + public static void fireDisconnectClient(Client client) { + Common.LOGGER.trace(Common.Event, "Firing EventDisconnectClient"); + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if(eventListener instanceof EventDisconnectClient) { + EventDisconnectClient event = (EventDisconnectClient) eventListener; + event.onDisconnectClient(client); + } + } + } } } diff --git a/src/main/java/com/minecrafttas/common/events/EventServer.java b/src/main/java/com/minecrafttas/common/events/EventServer.java index aeedcf15..3ca02151 100644 --- a/src/main/java/com/minecrafttas/common/events/EventServer.java +++ b/src/main/java/com/minecrafttas/common/events/EventServer.java @@ -2,6 +2,7 @@ import com.minecrafttas.common.Common; import com.minecrafttas.common.events.EventListenerRegistry.EventBase; +import com.minecrafttas.common.server.Client; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; @@ -158,4 +159,23 @@ public static void fireClientCompleteAuthentication(String username) { } } } + + public static interface EventDisconnectServer extends EventBase { + + public void onDisconnectServer(Client client); + + /** + * Fired when the connection to the custom server was closed on the server side. + * @param client The client that is disconnecting + */ + public static void fireDisconnectServer(Client client) { + Common.LOGGER.trace(Common.Event, "Firing CustomServerClientDisconnect"); + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if(eventListener instanceof EventDisconnectServer) { + EventDisconnectServer event = (EventDisconnectServer) eventListener; + event.onDisconnectServer(client); + } + } + } + } } diff --git a/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java index af5cfbe3..e19c68af 100644 --- a/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java @@ -1,9 +1,12 @@ package com.minecrafttas.common.mixin; +import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.minecrafttas.common.events.EventClient.EventClientGameLoop; @@ -44,9 +47,12 @@ public void inject_loadWorld(CallbackInfo ci) { EventDoneLoadingWorld.fireOnDoneLoadingWorld(); } - @ModifyVariable(method = "displayGuiScreen", at = @At(value = "STORE")) - public GuiScreen inject_displayGuiScreen(GuiScreen guiScreen) { + @Shadow + private GuiScreen currentScreen; + + @Redirect(method = "displayGuiScreen", at = @At(value = "FIELD", target = "currentScreen:Lnet/minecraft/client/gui/GuiScreen;", opcode = Opcodes.PUTFIELD)) + public void modify_displayGuiScreen(Minecraft mc, GuiScreen guiScreen) { guiScreen = EventOpenGui.fireOpenGuiEvent(guiScreen); - return guiScreen; + currentScreen = guiScreen; } } diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 4bce2139..4df1af64 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -1,9 +1,9 @@ package com.minecrafttas.common.server; -import static com.minecrafttas.common.server.SecureList.BUFFER_SIZE; -import static com.minecrafttas.common.Common.LOGGER; import static com.minecrafttas.common.Common.Client; +import static com.minecrafttas.common.Common.LOGGER; import static com.minecrafttas.common.Common.Server; +import static com.minecrafttas.common.server.SecureList.BUFFER_SIZE; import java.io.IOException; import java.net.InetSocketAddress; @@ -12,11 +12,15 @@ import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; +import java.util.Timer; +import java.util.TimerTask; import java.util.concurrent.Future; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Marker; import com.minecrafttas.common.Common; +import com.minecrafttas.common.events.EventClient.EventDisconnectClient; import com.minecrafttas.common.events.EventServer.EventClientCompleteAuthentication; import com.minecrafttas.common.server.exception.InvalidPacketException; import com.minecrafttas.common.server.exception.PacketNotImplementedException; @@ -41,6 +45,17 @@ public class Client { private int port; private Side side; + + /*=Timeout checking=*/ + private long timeout; + private TimerTask timertask; + /** + * Timestamp of the last packet that was received + */ + private long timeAtLastPacket; + private ClientCallback callback; + + private static Timer timeoutTimer = new Timer("Timeout Timer", true); public enum Side { CLIENT, SERVER; @@ -53,9 +68,10 @@ public enum Side { * @param port Port * @param packetIDs A list of PacketIDs which are registered * @param uuid The UUID of the client + * @param timout Time since last packet when the client should disconnect * @throws Exception Unable to connect */ - public Client(String host, int port, PacketID[] packetIDs, String name) throws Exception { + public Client(String host, int port, PacketID[] packetIDs, String name, long timeout) throws Exception { LOGGER.info(Client, "Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); @@ -69,8 +85,16 @@ public Client(String host, int port, PacketID[] packetIDs, String name) throws E this.packetIDs = packetIDs; this.createHandlers(); + + this.timeout = timeout; + this.callback = (client)-> { + EventDisconnectClient.fireDisconnectClient(client); + }; + this.registerTimeoutTask(100); LOGGER.info(Client, "Connected to server"); + username = name; + authenticate(name); } @@ -79,19 +103,46 @@ public Client(String host, int port, PacketID[] packetIDs, String name) throws E * * @param socket Socket */ - public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs) { + public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, long timeout, ClientCallback callback) { this.socket = socket; + this.callback = callback; + this.timeout = timeout; try { this.socket.setOption(StandardSocketOptions.SO_KEEPALIVE, true); this.socket.setOption(StandardSocketOptions.TCP_NODELAY, true); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error(Server, "Unable to set socket options", e); } this.packetIDs = packetIDs; this.createHandlers(); + this.registerTimeoutTask(100); this.side = Side.SERVER; } + /** + * Disconnecting and closing the socket. Sends a disconnect packet to the other side + */ + public void disconnect() { + + if(isClosed()) { + LOGGER.warn(getLoggerMarker(), "Tried to disconnect, but client {} is already closed", getId()); + return; + } + + // Sending the disconnect packet + try { + send(new ByteBufferBuilder(-2)); + } catch (Exception e) { + LOGGER.error(getLoggerMarker(), "Tried to send disconnect packet, but failed", e); + } + + try { + this.close(); + } catch (IOException e) { + LOGGER.error(getLoggerMarker(), "Tried to close socket, but failed", e); + } + } + /** * Create read/write buffers and handlers for socket */ @@ -99,7 +150,7 @@ private void createHandlers() { // create input handler this.readBuffer.limit(4); if(socket == null || !socket.isOpen()) { - LOGGER.info(side==Side.CLIENT? Client:Server, "Connection was closed"); + LOGGER.info(getLoggerMarker(), "Connection was closed"); return; } this.socket.read(this.readBuffer, null, new CompletionHandler() { @@ -107,7 +158,7 @@ private void createHandlers() { @Override public void completed(Integer result, Object attachment) { if(result == -1) { - LOGGER.info(side==Side.CLIENT? Client:Server, "Stream was closed"); + LOGGER.info(getLoggerMarker(), "Stream was closed"); return; } try { @@ -132,9 +183,9 @@ public void completed(Integer result, Object attachment) { @Override public void failed(Throwable exc, Object attachment) { if(exc instanceof AsynchronousCloseException || exc instanceof IOException) { - LOGGER.warn(side==Side.CLIENT? Client:Server, "Connection was closed!"); + LOGGER.warn(getLoggerMarker(), "Connection was closed!"); } else { - LOGGER.error(side==Side.CLIENT? Client:Server, "Something went wrong!", exc); + LOGGER.error(getLoggerMarker(), "Something went wrong!", exc); } } @@ -172,16 +223,26 @@ public void send(ByteBufferBuilder bufferBuilder) throws Exception { * * @throws IOException Unable to close */ - public void close() throws IOException { + private void close() throws IOException { if (this.socket == null || !this.socket.isOpen()) { - Common.LOGGER.warn(side==Side.CLIENT? Client:Server, "Tried to close dead socket"); + Common.LOGGER.warn(getLoggerMarker(), "Tried to close dead socket"); return; } this.future=null; - + + //Running the callback + if(callback!=null) { + callback.onClose(this); + } + + this.timertask.cancel(); this.socket.close(); } + private Marker getLoggerMarker() { + return side==Side.CLIENT? Client:Server; + } + /** * Sends then authentication packet to the server * @@ -190,7 +251,7 @@ public void close() throws IOException { */ private void authenticate(String id) throws Exception { this.username = id; - Common.LOGGER.info(side==Side.CLIENT? Client:Server, "Authenticating with UUID {}", id.toString()); + LOGGER.debug(getLoggerMarker(), "Authenticating with UUID {}", id.toString()); this.send(new ByteBufferBuilder(-1).writeString(id)); } @@ -199,7 +260,9 @@ private void completeAuthentication(ByteBuffer buf) throws Exception { throw new Exception("The client tried to authenticate while being authenticated already"); } + this.username = ByteBufferBuilder.readString(buf); + LOGGER.debug(getLoggerMarker(), "Completing authentication for user {}", username); EventClientCompleteAuthentication.fireClientCompleteAuthentication(username); } @@ -209,7 +272,12 @@ private void handle(ByteBuffer buf) { if (id == -1) { completeAuthentication(buf); return; + }else if (id == -2){ + LOGGER.debug(getLoggerMarker(), "Disconnected by the {}", side.name(), (side==Side.CLIENT?Side.CLIENT:Side.SERVER).name()); + close(); + return; } + timeAtLastPacket = System.currentTimeMillis(); PacketID packet = getPacketFromID(id); PacketHandlerRegistry.handle(side, packet, buf, this.username); } catch (PacketNotImplementedException | WrongSideException e) { @@ -241,4 +309,52 @@ public String getRemote() throws IOException { return ip+":"+port; } + /** + * Registers a task for the timer, that checks if this socket is timed out. + * + *

The interval is 1 second + * + */ + private void registerTimeoutTask(long delay) { + TimerTask task = new TimerTask() { + + @Override + public void run() { + if(checkTimeout()) { + disconnect(); + } + } + + }; + this.timertask = task; + timeAtLastPacket = System.currentTimeMillis(); + timeoutTimer.scheduleAtFixedRate(task, delay, 1000); + } + + private boolean checkTimeout() { + long timeSinceLastPacket = System.currentTimeMillis() - timeAtLastPacket; + + if(timeSinceLastPacket > timeout) { + LOGGER.warn(getLoggerMarker(), "Client {} timed out after {}ms", getId(), timeSinceLastPacket); + return true; + }else if(timeSinceLastPacket < 0) { + LOGGER.error(getLoggerMarker(), "Time ran backwards? Timing out client {}: {}ms", getId(), timeSinceLastPacket); + return true; + } + + return false; + } + + public void setTimeoutTime(long timeout) { + this.timeout = timeout; + } + + public long getTimeoutTime() { + return this.timeout; + } + + @FunctionalInterface + public interface ClientCallback{ + public void onClose(Client client); + } } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index a8f8bad7..10537c5e 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -13,6 +13,8 @@ import java.util.List; import com.minecrafttas.common.Common; +import com.minecrafttas.common.events.EventServer.EventDisconnectServer; +import com.minecrafttas.common.server.Client.ClientCallback; import com.minecrafttas.common.server.interfaces.PacketID; import net.minecraft.entity.player.EntityPlayer; @@ -45,7 +47,16 @@ public Server(int port, PacketID[] packetIDs) throws Exception { @Override public void completed(AsynchronousSocketChannel clientSocket, Object attachment) { - clients.add(new Client(clientSocket, packetIDs)); + + ClientCallback callback = (client) -> { + EventDisconnectServer.fireDisconnectServer(client); + clients.remove(client); + LOGGER.debug(Server, "Disconnecting player from server. Server now has {} connections", getClients().size()); + }; + + Client newclient = new Client(clientSocket, packetIDs, 10000, callback); + clients.add(newclient); + serverSocket.accept(null, this); } @@ -105,6 +116,22 @@ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Except sendTo(player.getName(), builder); } + + public void disconnect(String username) { + Client client = getClient(username); + client.disconnect(); + } + + public void disconnect(EntityPlayer player) { + disconnect(player.getName()); + } + + public void disconnectAll() { + for (Client client : getClients()) { + client.disconnect(); + } + } + /** * Try to close socket * diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 3d6df354..fd96cf9d 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -42,11 +42,12 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.settings.KeyBinding; import net.minecraft.server.MinecraftServer; -public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide{ +public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide, EventOpenGui{ public static VirtualInput virtual; @@ -160,13 +161,6 @@ protected boolean isKeyDown(KeyBinding i) { LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); } - // Connecting to local server instance - try { - // connect to server and authenticate - client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername()); - } catch (Exception e) { - LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); - } } @Override @@ -193,15 +187,11 @@ public void onClientInit(Minecraft mc) { blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Open InfoGui Editor", "TASmod", Keyboard.KEY_F6, () -> Minecraft.getMinecraft().displayGuiScreen(TASmodClient.hud)))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Buffer View", "TASmod", Keyboard.KEY_NUMPAD0, () -> InputContainerView.startBufferView()))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing", "TASmod", Keyboard.KEY_F12, () -> { - try { - TASmodClient.client.close(); - } catch (IOException e) { - e.printStackTrace(); - } + TASmodClient.client.disconnect(); }))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing2", "TASmod", Keyboard.KEY_F7, () -> { try { - TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName()); + TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), 10000); } catch (Exception e) { e.printStackTrace(); } @@ -244,7 +234,7 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { if(!(ip+":"+port).equals(connectedIP)) { try { LOGGER.info("Closing client connection: {}", client.getRemote()); - client.close(); + client.disconnect(); } catch (IOException e) { e.printStackTrace(); } @@ -253,7 +243,7 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { gameLoopSchedulerClient.add(()->{ try { // connect to server and authenticate - client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername()); + client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), 10000); //TODO set timeout by tickrate } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); e.printStackTrace(); @@ -267,5 +257,19 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { public void onPlayerLeaveClientSide(EntityPlayerSP player) { } + + @Override + public GuiScreen onOpenGui(GuiScreen gui) { + if(gui instanceof GuiMainMenu && client == null) { + Minecraft mc = Minecraft.getMinecraft(); + try { + // connect to server and authenticate + client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000); + } catch (Exception e) { + LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); + } + } + return gui; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java index 4f0b0ab0..c13e550f 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java @@ -86,7 +86,7 @@ public void inject_shutdownMinecraftApplet(CallbackInfo ci) { try { if (TASmodClient.client != null) { TASmodClient.tickratechanger.changeTickrate(20); - TASmodClient.client.close(); + TASmodClient.client.disconnect(); } } catch (Exception e) { e.printStackTrace(); diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index 2841d1d3..347f2891 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -149,7 +149,7 @@ static void setUpBeforeClass() throws Exception { } try { - client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot"); + client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", 3000); } catch (Exception e) { e.printStackTrace(); } From 64555512abcf2b31ec0393f9e8451e9f27779f72 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 22 Oct 2023 14:53:29 +0200 Subject: [PATCH 45/60] Fixed Redirect throwing errors --- .../java/com/minecrafttas/common/mixin/MixinMinecraft.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java index e19c68af..8a93b27b 100644 --- a/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/common/mixin/MixinMinecraft.java @@ -5,7 +5,6 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -50,7 +49,7 @@ public void inject_loadWorld(CallbackInfo ci) { @Shadow private GuiScreen currentScreen; - @Redirect(method = "displayGuiScreen", at = @At(value = "FIELD", target = "currentScreen:Lnet/minecraft/client/gui/GuiScreen;", opcode = Opcodes.PUTFIELD)) + @Redirect(method = "displayGuiScreen", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;currentScreen:Lnet/minecraft/client/gui/GuiScreen;", opcode = Opcodes.PUTFIELD)) public void modify_displayGuiScreen(Minecraft mc, GuiScreen guiScreen) { guiScreen = EventOpenGui.fireOpenGuiEvent(guiScreen); currentScreen = guiScreen; From 38eb555313debd2f29b8e3aff888dc6a3d31de22 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 22 Oct 2023 22:28:09 +0200 Subject: [PATCH 46/60] Fixed client and server timing out in tickrate 0 --- .../minecrafttas/common/server/Client.java | 1 + .../minecrafttas/common/server/Server.java | 6 +++ .../java/com/minecrafttas/tasmod/TASmod.java | 4 ++ .../com/minecrafttas/tasmod/TASmodClient.java | 16 ++++---- .../tasmod/events/EventClient.java | 22 +++++++++++ .../tasmod/events/EventServer.java | 23 +++++++++++ .../networking/ServerModifications.java | 38 +++++++++++++++++++ .../TickrateChangerClient.java | 16 ++++---- .../TickrateChangerServer.java | 2 + 9 files changed, 112 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 4df1af64..1892a08e 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -346,6 +346,7 @@ private boolean checkTimeout() { } public void setTimeoutTime(long timeout) { + this.timeAtLastPacket = System.currentTimeMillis(); this.timeout = timeout; } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 10537c5e..a3b419cf 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -132,6 +132,12 @@ public void disconnectAll() { } } + public void setTimeoutTime(long timeout) { + for (Client client : getClients()) { + client.setTimeoutTime(timeout); + } + } + /** * Try to close socket * diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 22d174ad..95a3416c 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -25,6 +25,7 @@ import com.minecrafttas.tasmod.commands.CommandSavestate; import com.minecrafttas.tasmod.commands.CommandTickrate; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; +import com.minecrafttas.tasmod.networking.ServerModifications; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackControllerServer; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; @@ -62,6 +63,8 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static final Scheduler tickSchedulerServer = new Scheduler(); + public static final ServerModifications servermod = new ServerModifications(); + public static Server server; public static final int networkingport = 8999; @@ -89,6 +92,7 @@ public void onInitialize() { EventListenerRegistry.register(ticksyncServer); EventListenerRegistry.register(tickratechanger); EventListenerRegistry.register(ktrngHandler); + EventListenerRegistry.register(servermod); // Register packet handlers LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index fd96cf9d..5190eba5 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -260,13 +260,15 @@ public void onPlayerLeaveClientSide(EntityPlayerSP player) { @Override public GuiScreen onOpenGui(GuiScreen gui) { - if(gui instanceof GuiMainMenu && client == null) { - Minecraft mc = Minecraft.getMinecraft(); - try { - // connect to server and authenticate - client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000); - } catch (Exception e) { - LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); + if(gui instanceof GuiMainMenu) { + if(client == null) { + Minecraft mc = Minecraft.getMinecraft(); + try { + // connect to server and authenticate + client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000); + } catch (Exception e) { + LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); + } } } return gui; diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventClient.java b/src/main/java/com/minecrafttas/tasmod/events/EventClient.java index 096e9fbe..a22d3359 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventClient.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventClient.java @@ -49,4 +49,26 @@ public static void fireOnClientPostTick(Minecraft mc) { } } } + + /** + * Fired when the tickrate changes on the client side + * @author Scribble + * + */ + public static interface EventClientTickrateChange extends EventBase{ + + /** + * Fired at the end of a client tick + */ + public void onClientTickrateChange(float tickrate); + + public static void fireOnClientTickrateChange(float tickrate) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if(eventListener instanceof EventClientTickrateChange) { + EventClientTickrateChange event = (EventClientTickrateChange) eventListener; + event.onClientTickrateChange(tickrate); + } + } + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java index 9d115509..d552f882 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java @@ -4,6 +4,7 @@ import java.io.File; +import com.minecrafttas.common.events.EventListenerRegistry; import com.minecrafttas.common.events.EventListenerRegistry.EventBase; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -110,4 +111,26 @@ public static void fireServerTickPost(MinecraftServer minecraftServer) { } } + + /** + * Fired when the tickrate changes on the server side + * @author Scribble + * + */ + public static interface EventServerTickrateChange extends EventBase{ + + /** + * Fired at the end of a client tick + */ + public void onServerTickrateChange(float tickrate); + + public static void fireOnServerTickrateChange(float tickrate) { + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if(eventListener instanceof EventServerTickrateChange) { + EventServerTickrateChange event = (EventServerTickrateChange) eventListener; + event.onServerTickrateChange(tickrate); + } + } + } + } } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java b/src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java new file mode 100644 index 00000000..20db6600 --- /dev/null +++ b/src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java @@ -0,0 +1,38 @@ +package com.minecrafttas.tasmod.networking; + +import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.events.EventClient.EventClientTickrateChange; +import com.minecrafttas.tasmod.events.EventServer.EventServerTickrateChange; + +public class ServerModifications implements EventClientTickrateChange, EventServerTickrateChange{ + + @Override + public void onServerTickrateChange(float tickrate) { + long timeout; + if(tickrate>0) { + long millisecondsPerTick = (long) (1000L / tickrate); + timeout = millisecondsPerTick * 10 * 20; + + } else { + timeout = Long.MAX_VALUE; + } + TASmod.LOGGER.debug("Setting server timeout to {}", timeout); + TASmod.server.setTimeoutTime(timeout); + } + + @Override + public void onClientTickrateChange(float tickrate) { + long timeout; + if(tickrate>0) { + long millisecondsPerTick = (long) (1000L / tickrate); + timeout = millisecondsPerTick * 10 * 20; + + } else { + timeout = Long.MAX_VALUE; + } + TASmod.LOGGER.debug("Setting client timeout to {}", timeout); + TASmodClient.client.setTimeoutTime(timeout); + } + +} diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java index b5643ebd..b42ab8b1 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerClient.java @@ -10,6 +10,7 @@ import com.minecrafttas.common.server.interfaces.ClientPacketHandler; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.events.EventClient.EventClientTickrateChange; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; @@ -87,6 +88,7 @@ public void changeClientTickrate(float tickrate, boolean log) { mc.timer.tickLength = Float.MAX_VALUE; } ticksPerSecond = tickrate; + EventClientTickrateChange.fireOnClientTickrateChange(tickrate); if (log) log("Setting the client tickrate to " + ticksPerSecond); } @@ -114,15 +116,11 @@ public void changeServerTickrate(float tickrate) { * Toggles between tickrate 0 and tickrate > 0 */ public void togglePause() { - if (Minecraft.getMinecraft().world != null) { - try { - // request tickrate change - TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ZERO).writeTickratePauseState(TickratePauseState.TOGGLE)); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - togglePauseClient(); + try { + // request tickrate change + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.TICKRATE_ZERO).writeTickratePauseState(TickratePauseState.TOGGLE)); + } catch (Exception e) { + e.printStackTrace(); } } diff --git a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java index 46c68b4a..eb0686a9 100644 --- a/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/tickratechanger/TickrateChangerServer.java @@ -12,6 +12,7 @@ import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.common.server.interfaces.ServerPacketHandler; import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.events.EventServer.EventServerTickrateChange; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -126,6 +127,7 @@ public void changeServerTickrate(float tickrate, boolean log) { } } ticksPerSecond = tickrate; + EventServerTickrateChange.fireOnServerTickrateChange(tickrate); if (log) { log("Setting the server tickrate to " + ticksPerSecond); } From 8e235d08683416a85f1447b81f8af570d57ce17f Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 22 Oct 2023 22:29:12 +0200 Subject: [PATCH 47/60] Fixed gui controls crashing in tr 0 --- .../com/minecrafttas/tasmod/TASmodClient.java | 14 ++++ .../tasmod/events/OpenGuiEvents.java | 64 ------------------- .../tasmod/mixin/events/MixinGuiControls.java | 25 -------- src/main/resources/tasmod.mixin.json | 1 - 4 files changed, 14 insertions(+), 90 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java delete mode 100644 src/main/java/com/minecrafttas/tasmod/mixin/events/MixinGuiControls.java diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 5190eba5..23538ce8 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -41,6 +41,7 @@ import net.fabricmc.api.ClientModInitializer; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.GuiControls; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.ServerData; @@ -271,6 +272,19 @@ public GuiScreen onOpenGui(GuiScreen gui) { } } } + else if(gui instanceof GuiControls) { + TASmodClient.virtual.getContainer().setTASState(TASstate.NONE); // Set the TASState to nothing to avoid collisions + if(TASmodClient.tickratechanger.ticksPerSecond==0) { + TASmodClient.tickratechanger.pauseClientGame(false); // Unpause the game + waszero = true; + } + } + else if(!(gui instanceof GuiControls)) { + if(waszero) { + waszero = false; + TASmodClient.tickratechanger.pauseClientGame(true); + } + } return gui; } diff --git a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java b/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java deleted file mode 100644 index dce7bdb4..00000000 --- a/src/main/java/com/minecrafttas/tasmod/events/OpenGuiEvents.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.minecrafttas.tasmod.events; - -import static com.minecrafttas.tasmod.TASmod.LOGGER; - -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; - -import net.minecraft.client.gui.GuiControls; -import net.minecraft.client.gui.GuiIngameMenu; -import net.minecraft.client.gui.GuiMainMenu; - -@Deprecated -public class OpenGuiEvents { - /** - * The state that should be used when the main menu opens - */ - public static TASstate stateWhenOpened = null; - - /** - * Called when the main menu opens - * - * @param guiMainMenu The menu that was opened - */ - public static void openGuiMainMenu(GuiMainMenu guiMainMenu) { - } - - /** - * Called when the Ingame Menu opens - * - * @param guiIngameMenu The menu that was opened - */ - public static void openGuiIngameMenu(GuiIngameMenu guiIngameMenu) { - } - - public static boolean waszero; - - /** - * Called then the Controls Gui opens - * - * @param guiControls The gui that was opened - */ - public static void openGuiControls(GuiControls guiControls) { - if (TASmodClient.tickratechanger.ticksPerSecond == 0 || TASmodClient.tickratechanger.advanceTick) { - LOGGER.info("Pausing game during GuiControls"); - TASmodClient.tickratechanger.pauseGame(false); - TASmodClient.virtual.getContainer().setTASState(stateWhenOpened); - waszero = true; - } - } - - /** - * Called then the Controls Gui closes - * - * @param guiControls The gui that was opened - */ - public static void closeGuiControls(GuiControls guiControls) { - if (waszero) { - LOGGER.info("Unpausing the game again"); - waszero = false; - TASmodClient.tickratechanger.pauseGame(true); - } - } - -} diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinGuiControls.java b/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinGuiControls.java deleted file mode 100644 index 4f6e496d..00000000 --- a/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinGuiControls.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.minecrafttas.tasmod.mixin.events; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.minecrafttas.tasmod.events.OpenGuiEvents; - -import net.minecraft.client.gui.GuiControls; -import net.minecraft.client.gui.GuiScreen; - -@Mixin(GuiControls.class) -public class MixinGuiControls extends GuiScreen{ - - @Inject(method = "initGui", at = @At("HEAD")) - public void inject_initGui(CallbackInfo ci) { - OpenGuiEvents.openGuiControls((GuiControls)(Object)this); - } - - @Override - public void onGuiClosed() { - OpenGuiEvents.closeGuiControls((GuiControls)(Object)this); - } -} diff --git a/src/main/resources/tasmod.mixin.json b/src/main/resources/tasmod.mixin.json index 11b70b45..b91afa5c 100644 --- a/src/main/resources/tasmod.mixin.json +++ b/src/main/resources/tasmod.mixin.json @@ -44,7 +44,6 @@ //Join and leave game event on the client "events.MixinGuiMainMenu", - "events.MixinGuiControls", "events.MixinGuiIngame", //Playbackhooks From 9b7fcca35e2ec0374dd3caa046354786404d931b Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 22 Oct 2023 22:29:25 +0200 Subject: [PATCH 48/60] Updated junit --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 5c41a5a6..f2cf6ac8 100644 --- a/build.gradle +++ b/build.gradle @@ -51,7 +51,7 @@ dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.legacyfabric:yarn:${project.minecraft_version}+build.mcp" modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3' + testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0' } // task for downloading KillTheRng From 9e4ab6dd0d592964b0f1f3f453808bfbc78225e5 Mon Sep 17 00:00:00 2001 From: Scribble Date: Tue, 24 Oct 2023 21:08:17 +0200 Subject: [PATCH 49/60] Add property for "integrated" server --- .../minecrafttas/common/server/Client.java | 123 +++++++++++------- .../com/minecrafttas/tasmod/TASmodClient.java | 12 +- .../minecrafttas/tasmod/mixin/MixinTimer.java | 2 +- .../tasmod/ticksync/TickSyncClient.java | 12 +- .../tasmod/ticksync/TickSyncServer.java | 9 ++ src/test/java/common/server/ServerTest.java | 2 +- 6 files changed, 105 insertions(+), 55 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 1892a08e..fa080180 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -45,8 +45,8 @@ public class Client { private int port; private Side side; - - /*=Timeout checking=*/ + + /* =Timeout checking= */ private long timeout; private TimerTask timertask; /** @@ -54,7 +54,12 @@ public class Client { */ private long timeAtLastPacket; private ClientCallback callback; - + /** + * True, if the client is connected to a local "integrated" server. Special + * conditions may apply + */ + private boolean local = false; + private static Timer timeoutTimer = new Timer("Timeout Timer", true); public enum Side { @@ -68,10 +73,12 @@ public enum Side { * @param port Port * @param packetIDs A list of PacketIDs which are registered * @param uuid The UUID of the client - * @param timout Time since last packet when the client should disconnect + * @param timout Time since last packet when the client should disconnect + * @param local Property to check, if the server is a local server. If yes, + * special conditions may apply * @throws Exception Unable to connect */ - public Client(String host, int port, PacketID[] packetIDs, String name, long timeout) throws Exception { + public Client(String host, int port, PacketID[] packetIDs, String name, long timeout, boolean local) throws Exception { LOGGER.info(Client, "Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); @@ -80,21 +87,24 @@ public Client(String host, int port, PacketID[] packetIDs, String name, long tim ip = host; this.port = port; - + this.side = Side.CLIENT; this.packetIDs = packetIDs; this.createHandlers(); - + this.timeout = timeout; - this.callback = (client)-> { + this.callback = (client) -> { EventDisconnectClient.fireDisconnectClient(client); }; - this.registerTimeoutTask(100); + + this.local = local; + +// this.registerTimeoutTask(100); LOGGER.info(Client, "Connected to server"); username = name; - + authenticate(name); } @@ -115,41 +125,42 @@ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, long timeo } this.packetIDs = packetIDs; this.createHandlers(); - this.registerTimeoutTask(100); +// this.registerTimeoutTask(100); this.side = Side.SERVER; } /** - * Disconnecting and closing the socket. Sends a disconnect packet to the other side + * Disconnecting and closing the socket. Sends a disconnect packet to the other + * side */ public void disconnect() { - - if(isClosed()) { + + if (isClosed()) { LOGGER.warn(getLoggerMarker(), "Tried to disconnect, but client {} is already closed", getId()); return; } - + // Sending the disconnect packet try { send(new ByteBufferBuilder(-2)); } catch (Exception e) { LOGGER.error(getLoggerMarker(), "Tried to send disconnect packet, but failed", e); } - + try { this.close(); } catch (IOException e) { LOGGER.error(getLoggerMarker(), "Tried to close socket, but failed", e); } } - + /** * Create read/write buffers and handlers for socket */ private void createHandlers() { // create input handler this.readBuffer.limit(4); - if(socket == null || !socket.isOpen()) { + if (socket == null || !socket.isOpen()) { LOGGER.info(getLoggerMarker(), "Connection was closed"); return; } @@ -157,7 +168,7 @@ private void createHandlers() { @Override public void completed(Integer result, Object attachment) { - if(result == -1) { + if (result == -1) { LOGGER.info(getLoggerMarker(), "Stream was closed"); return; } @@ -182,10 +193,20 @@ public void completed(Integer result, Object attachment) { @Override public void failed(Throwable exc, Object attachment) { - if(exc instanceof AsynchronousCloseException || exc instanceof IOException) { - LOGGER.warn(getLoggerMarker(), "Connection was closed!"); + if (exc instanceof AsynchronousCloseException || exc instanceof IOException) { + LOGGER.warn(getLoggerMarker(), "{} terminated the connection!", (side == Side.CLIENT ? Side.CLIENT : Side.SERVER).name()); + try { + close(); + } catch (IOException e) { + LOGGER.error(getLoggerMarker(), "Attempted to close connection but failed", e); + } } else { - LOGGER.error(getLoggerMarker(), "Something went wrong!", exc); + LOGGER.error(getLoggerMarker(), "Something went wrong, terminating connection!", exc); + try { + close(); + } catch (IOException e) { + LOGGER.error(getLoggerMarker(), "Attempted to close connection but failed", e); + } } } @@ -228,21 +249,21 @@ private void close() throws IOException { Common.LOGGER.warn(getLoggerMarker(), "Tried to close dead socket"); return; } - this.future=null; - - //Running the callback - if(callback!=null) { + this.future = null; + + // Running the callback + if (callback != null) { callback.onClose(this); } - + this.timertask.cancel(); this.socket.close(); } private Marker getLoggerMarker() { - return side==Side.CLIENT? Client:Server; + return side == Side.CLIENT ? Client : Server; } - + /** * Sends then authentication packet to the server * @@ -260,7 +281,6 @@ private void completeAuthentication(ByteBuffer buf) throws Exception { throw new Exception("The client tried to authenticate while being authenticated already"); } - this.username = ByteBufferBuilder.readString(buf); LOGGER.debug(getLoggerMarker(), "Completing authentication for user {}", username); EventClientCompleteAuthentication.fireClientCompleteAuthentication(username); @@ -272,8 +292,8 @@ private void handle(ByteBuffer buf) { if (id == -1) { completeAuthentication(buf); return; - }else if (id == -2){ - LOGGER.debug(getLoggerMarker(), "Disconnected by the {}", side.name(), (side==Side.CLIENT?Side.CLIENT:Side.SERVER).name()); + } else if (id == -2) { + LOGGER.debug(getLoggerMarker(), "Disconnected by the {}", side.name(), (side == Side.CLIENT ? Side.CLIENT : Side.SERVER).name()); close(); return; } @@ -304,23 +324,24 @@ private PacketID getPacketFromID(int id) throws InvalidPacketException { public boolean isClosed() { return this.socket == null || !this.socket.isOpen(); } - + public String getRemote() throws IOException { - return ip+":"+port; + return ip + ":" + port; } - + /** * Registers a task for the timer, that checks if this socket is timed out. * - *

The interval is 1 second + *

+ * The interval is 1 second * */ private void registerTimeoutTask(long delay) { TimerTask task = new TimerTask() { - + @Override public void run() { - if(checkTimeout()) { + if (checkTimeout()) { disconnect(); } } @@ -330,32 +351,38 @@ public void run() { timeAtLastPacket = System.currentTimeMillis(); timeoutTimer.scheduleAtFixedRate(task, delay, 1000); } - + private boolean checkTimeout() { long timeSinceLastPacket = System.currentTimeMillis() - timeAtLastPacket; - - if(timeSinceLastPacket > timeout) { + + System.out.println(timeSinceLastPacket); + + if (timeSinceLastPacket > timeout) { LOGGER.warn(getLoggerMarker(), "Client {} timed out after {}ms", getId(), timeSinceLastPacket); return true; - }else if(timeSinceLastPacket < 0) { + } else if (timeSinceLastPacket < 0) { LOGGER.error(getLoggerMarker(), "Time ran backwards? Timing out client {}: {}ms", getId(), timeSinceLastPacket); return true; } - + return false; } - + public void setTimeoutTime(long timeout) { this.timeAtLastPacket = System.currentTimeMillis(); this.timeout = timeout; } - + public long getTimeoutTime() { return this.timeout; } - + + public boolean isLocal() { + return this.local; + } + @FunctionalInterface - public interface ClientCallback{ - public void onClose(Client client); + public interface ClientCallback { + public void onClose(Client client); } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 23538ce8..bb35fff1 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -192,7 +192,7 @@ public void onClientInit(Minecraft mc) { }))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing2", "TASmod", Keyboard.KEY_F7, () -> { try { - TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), 10000); + TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), 10000, true); } catch (Exception e) { e.printStackTrace(); } @@ -215,13 +215,15 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { String ip = null; int port; - + boolean local; if(server!=null) { ip = "localhost"; port = TASmod.networkingport-1; + local = true; } else { ip = data.serverIP.split(":")[0]; port = TASmod.networkingport; + local = false; } String connectedIP = null; @@ -244,11 +246,12 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { gameLoopSchedulerClient.add(()->{ try { // connect to server and authenticate - client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), 10000); //TODO set timeout by tickrate + client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), 10000, local); //TODO set timeout by tickrate } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); e.printStackTrace(); } + ticksyncClient.setEnabled(true); }); } // TASmod.server.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); @@ -266,10 +269,11 @@ public GuiScreen onOpenGui(GuiScreen gui) { Minecraft mc = Minecraft.getMinecraft(); try { // connect to server and authenticate - client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000); + client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000, true); } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); } + ticksyncClient.setEnabled(false); } } else if(gui instanceof GuiControls) { diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java index b240b069..9462ad79 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinTimer.java @@ -42,7 +42,7 @@ public class MixinTimer { @Inject(method = "updateTimer", at = @At("HEAD"), cancellable = true) public void inject_tick(CallbackInfo ci) { - if (TASmodClient.client != null && !TASmodClient.client.isClosed()) { + if (TASmodClient.client != null && !TASmodClient.client.isClosed() && TASmodClient.ticksyncClient.isEnabled()) { lastSyncSysClock = Minecraft.getSystemTime(); // update the tick tracker so that after returning to scheduling the client won't catch up all ticks (max 10) this.elapsedTicks = 0; // do not do any ticks long newGameLoop = Minecraft.getSystemTime(); diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index 9afcfa10..b0c8c252 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -25,6 +25,8 @@ public class TickSyncClient implements ClientPacketHandler, EventClientTickPost{ public static final AtomicBoolean shouldTick = new AtomicBoolean(true); + private boolean enabled = true; + @Override public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] {TASmodPackets.TICKSYNC}; @@ -52,7 +54,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) { */ @Override public void onClientTickPost(Minecraft mc) { - if (TASmodClient.client == null || TASmodClient.client.isClosed()) { + if (TASmodClient.client == null || TASmodClient.client.isClosed() || !enabled) { return; } @@ -62,4 +64,12 @@ public void onClientTickPost(Minecraft mc) { LOGGER.error("Unable to send packet to server:", e); } } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index 9b113b8e..b206492e 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -28,6 +28,8 @@ public class TickSyncServer implements ServerPacketHandler, EventServerTickPost, EventClientCompleteAuthentication { private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); + + private boolean enabled = true; @Override public PacketID[] getAcceptedPacketIDs() { @@ -90,4 +92,11 @@ private void sendToClients() { synchronizedList.clear(); } + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } } diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index 347f2891..cdee7217 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -149,7 +149,7 @@ static void setUpBeforeClass() throws Exception { } try { - client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", 3000); + client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", 3000, true); } catch (Exception e) { e.printStackTrace(); } From 149dc1b5e5e8387e5543649341a42a9b98cf9a91 Mon Sep 17 00:00:00 2001 From: Scribble Date: Tue, 24 Oct 2023 21:34:17 +0200 Subject: [PATCH 50/60] Removed timeout system --- .../minecrafttas/common/server/Client.java | 92 +++++-------------- .../minecrafttas/common/server/Server.java | 8 +- .../java/com/minecrafttas/tasmod/TASmod.java | 4 - .../com/minecrafttas/tasmod/TASmodClient.java | 6 +- .../networking/ServerModifications.java | 38 -------- src/test/java/common/server/ServerTest.java | 2 +- 6 files changed, 30 insertions(+), 120 deletions(-) delete mode 100644 src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index fa080180..0261cebc 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -14,6 +14,7 @@ import java.nio.channels.CompletionHandler; import java.util.Timer; import java.util.TimerTask; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.logging.log4j.Level; @@ -46,13 +47,6 @@ public class Client { private Side side; - /* =Timeout checking= */ - private long timeout; - private TimerTask timertask; - /** - * Timestamp of the last packet that was received - */ - private long timeAtLastPacket; private ClientCallback callback; /** * True, if the client is connected to a local "integrated" server. Special @@ -72,13 +66,11 @@ public enum Side { * @param host Host * @param port Port * @param packetIDs A list of PacketIDs which are registered - * @param uuid The UUID of the client - * @param timout Time since last packet when the client should disconnect * @param local Property to check, if the server is a local server. If yes, * special conditions may apply * @throws Exception Unable to connect */ - public Client(String host, int port, PacketID[] packetIDs, String name, long timeout, boolean local) throws Exception { + public Client(String host, int port, PacketID[] packetIDs, String name, boolean local) throws Exception { LOGGER.info(Client, "Connecting server to {}:{}", host, port); this.socket = AsynchronousSocketChannel.open(); this.socket.connect(new InetSocketAddress(host, port)).get(); @@ -93,7 +85,6 @@ public Client(String host, int port, PacketID[] packetIDs, String name, long tim this.createHandlers(); - this.timeout = timeout; this.callback = (client) -> { EventDisconnectClient.fireDisconnectClient(client); }; @@ -113,10 +104,9 @@ public Client(String host, int port, PacketID[] packetIDs, String name, long tim * * @param socket Socket */ - public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, long timeout, ClientCallback callback) { + public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, ClientCallback callback) { this.socket = socket; this.callback = callback; - this.timeout = timeout; try { this.socket.setOption(StandardSocketOptions.SO_KEEPALIVE, true); this.socket.setOption(StandardSocketOptions.TCP_NODELAY, true); @@ -125,7 +115,6 @@ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, long timeo } this.packetIDs = packetIDs; this.createHandlers(); -// this.registerTimeoutTask(100); this.side = Side.SERVER; } @@ -187,20 +176,35 @@ public void completed(Integer result, Object attachment) { readBuffer.clear().limit(4); socket.read(readBuffer, null, this); } catch (Throwable exc) { - LOGGER.error("Unable to read packet!", exc); + if(exc instanceof ExecutionException && !isClosed()) { + LOGGER.debug(getLoggerMarker(), "{} terminated the connection!", getOppositeSide().name()); + try { + close(); + } catch (IOException e) { + e.printStackTrace(); + } + return; + } + LOGGER.error(getLoggerMarker(), "Unable to read packet!", exc); } } @Override public void failed(Throwable exc, Object attachment) { if (exc instanceof AsynchronousCloseException || exc instanceof IOException) { - LOGGER.warn(getLoggerMarker(), "{} terminated the connection!", (side == Side.CLIENT ? Side.CLIENT : Side.SERVER).name()); + if(isClosed()) { + return; + } + LOGGER.debug(getLoggerMarker(), "{} terminated the connection!", getOppositeSide().name()); try { close(); } catch (IOException e) { LOGGER.error(getLoggerMarker(), "Attempted to close connection but failed", e); } } else { + if(isClosed()) { + return; + } LOGGER.error(getLoggerMarker(), "Something went wrong, terminating connection!", exc); try { close(); @@ -256,13 +260,16 @@ private void close() throws IOException { callback.onClose(this); } - this.timertask.cancel(); this.socket.close(); } private Marker getLoggerMarker() { return side == Side.CLIENT ? Client : Server; } + + private Side getOppositeSide() { + return side == Side.CLIENT ? Side.SERVER : Side.CLIENT; + } /** * Sends then authentication packet to the server @@ -293,11 +300,10 @@ private void handle(ByteBuffer buf) { completeAuthentication(buf); return; } else if (id == -2) { - LOGGER.debug(getLoggerMarker(), "Disconnected by the {}", side.name(), (side == Side.CLIENT ? Side.CLIENT : Side.SERVER).name()); + LOGGER.info(getLoggerMarker(), "Disconnected by the {}", getOppositeSide().name()); close(); return; } - timeAtLastPacket = System.currentTimeMillis(); PacketID packet = getPacketFromID(id); PacketHandlerRegistry.handle(side, packet, buf, this.username); } catch (PacketNotImplementedException | WrongSideException e) { @@ -329,54 +335,6 @@ public String getRemote() throws IOException { return ip + ":" + port; } - /** - * Registers a task for the timer, that checks if this socket is timed out. - * - *

- * The interval is 1 second - * - */ - private void registerTimeoutTask(long delay) { - TimerTask task = new TimerTask() { - - @Override - public void run() { - if (checkTimeout()) { - disconnect(); - } - } - - }; - this.timertask = task; - timeAtLastPacket = System.currentTimeMillis(); - timeoutTimer.scheduleAtFixedRate(task, delay, 1000); - } - - private boolean checkTimeout() { - long timeSinceLastPacket = System.currentTimeMillis() - timeAtLastPacket; - - System.out.println(timeSinceLastPacket); - - if (timeSinceLastPacket > timeout) { - LOGGER.warn(getLoggerMarker(), "Client {} timed out after {}ms", getId(), timeSinceLastPacket); - return true; - } else if (timeSinceLastPacket < 0) { - LOGGER.error(getLoggerMarker(), "Time ran backwards? Timing out client {}: {}ms", getId(), timeSinceLastPacket); - return true; - } - - return false; - } - - public void setTimeoutTime(long timeout) { - this.timeAtLastPacket = System.currentTimeMillis(); - this.timeout = timeout; - } - - public long getTimeoutTime() { - return this.timeout; - } - public boolean isLocal() { return this.local; } diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index a3b419cf..2827cde8 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -54,7 +54,7 @@ public void completed(AsynchronousSocketChannel clientSocket, Object attachment) LOGGER.debug(Server, "Disconnecting player from server. Server now has {} connections", getClients().size()); }; - Client newclient = new Client(clientSocket, packetIDs, 10000, callback); + Client newclient = new Client(clientSocket, packetIDs, callback); clients.add(newclient); serverSocket.accept(null, this); @@ -132,12 +132,6 @@ public void disconnectAll() { } } - public void setTimeoutTime(long timeout) { - for (Client client : getClients()) { - client.setTimeoutTime(timeout); - } - } - /** * Try to close socket * diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 95a3416c..22d174ad 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -25,7 +25,6 @@ import com.minecrafttas.tasmod.commands.CommandSavestate; import com.minecrafttas.tasmod.commands.CommandTickrate; import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler; -import com.minecrafttas.tasmod.networking.ServerModifications; import com.minecrafttas.tasmod.networking.TASmodPackets; import com.minecrafttas.tasmod.playback.PlaybackControllerServer; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; @@ -63,8 +62,6 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static final Scheduler tickSchedulerServer = new Scheduler(); - public static final ServerModifications servermod = new ServerModifications(); - public static Server server; public static final int networkingport = 8999; @@ -92,7 +89,6 @@ public void onInitialize() { EventListenerRegistry.register(ticksyncServer); EventListenerRegistry.register(tickratechanger); EventListenerRegistry.register(ktrngHandler); - EventListenerRegistry.register(servermod); // Register packet handlers LOGGER.info(LoggerMarkers.Networking, "Registering network handlers"); diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index bb35fff1..8af1a628 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -192,7 +192,7 @@ public void onClientInit(Minecraft mc) { }))); blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing2", "TASmod", Keyboard.KEY_F7, () -> { try { - TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), 10000, true); + TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), true); } catch (Exception e) { e.printStackTrace(); } @@ -246,7 +246,7 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { gameLoopSchedulerClient.add(()->{ try { // connect to server and authenticate - client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), 10000, local); //TODO set timeout by tickrate + client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), local); //TODO set timeout by tickrate } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); e.printStackTrace(); @@ -269,7 +269,7 @@ public GuiScreen onOpenGui(GuiScreen gui) { Minecraft mc = Minecraft.getMinecraft(); try { // connect to server and authenticate - client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000, true); + client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), true); } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java b/src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java deleted file mode 100644 index 20db6600..00000000 --- a/src/main/java/com/minecrafttas/tasmod/networking/ServerModifications.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.minecrafttas.tasmod.networking; - -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.events.EventClient.EventClientTickrateChange; -import com.minecrafttas.tasmod.events.EventServer.EventServerTickrateChange; - -public class ServerModifications implements EventClientTickrateChange, EventServerTickrateChange{ - - @Override - public void onServerTickrateChange(float tickrate) { - long timeout; - if(tickrate>0) { - long millisecondsPerTick = (long) (1000L / tickrate); - timeout = millisecondsPerTick * 10 * 20; - - } else { - timeout = Long.MAX_VALUE; - } - TASmod.LOGGER.debug("Setting server timeout to {}", timeout); - TASmod.server.setTimeoutTime(timeout); - } - - @Override - public void onClientTickrateChange(float tickrate) { - long timeout; - if(tickrate>0) { - long millisecondsPerTick = (long) (1000L / tickrate); - timeout = millisecondsPerTick * 10 * 20; - - } else { - timeout = Long.MAX_VALUE; - } - TASmod.LOGGER.debug("Setting client timeout to {}", timeout); - TASmodClient.client.setTimeoutTime(timeout); - } - -} diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index cdee7217..00e49033 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -149,7 +149,7 @@ static void setUpBeforeClass() throws Exception { } try { - client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", 3000, true); + client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", true); } catch (Exception e) { e.printStackTrace(); } From 24739c2e21aa8d7c53db9c176b2b633d05a3ba58 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 12 Nov 2023 16:34:55 +0100 Subject: [PATCH 51/60] Added a trace statement for network packets and it's contents - Added an option to packets (In this case TASmodPackets) to be turned off for this trace view --- .../common/server/ByteBufferBuilder.java | 61 ++++++++++++++----- .../minecrafttas/common/server/Client.java | 2 + .../minecrafttas/common/server/Server.java | 4 +- .../server/interfaces/PacketHandlerBase.java | 2 +- .../common/server/interfaces/PacketID.java | 2 + .../tasmod/networking/TASmodPackets.java | 16 ++++- .../common/server/ByteBufferBuilderTest.java | 5 ++ src/test/java/common/server/ServerTest.java | 5 ++ .../TASmodByteBufferBuilderTest.java | 5 ++ 9 files changed, 83 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 591388fa..31d77c97 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -1,6 +1,7 @@ package com.minecrafttas.common.server; import java.nio.ByteBuffer; +import java.util.ArrayList; import java.util.UUID; import com.minecrafttas.common.server.interfaces.PacketID; @@ -13,12 +14,15 @@ */ public class ByteBufferBuilder { - private int bufferId; private int bufferIndex; protected ByteBuffer buffer; + /* Debug PacketName */ + private PacketID bufferPacketId; + /* Debug PacketContent */ + private ArrayList bufferContent = new ArrayList<>(); + public ByteBufferBuilder(int id) { - bufferId = id; bufferIndex = SecureList.POOL.available(); buffer = SecureList.POOL.lock(bufferIndex); buffer.putInt(id); @@ -26,17 +30,20 @@ public ByteBufferBuilder(int id) { public ByteBufferBuilder(PacketID packet) { this(packet.getID()); + this.bufferPacketId = packet; } - + public ByteBufferBuilder(ByteBuffer buf) { bufferIndex = SecureList.POOL.available(); buffer = SecureList.POOL.lock(bufferIndex); buffer.put(buf); } - private ByteBufferBuilder(int bufferIndex, ByteBuffer buffer) { + private ByteBufferBuilder(int bufferIndex, ByteBuffer buffer, PacketID bufferName, ArrayList bufferContent) { this.bufferIndex = bufferIndex; this.buffer = buffer; + this.bufferPacketId = bufferName; + this.bufferContent = new ArrayList<>(bufferContent); } public ByteBuffer build() { @@ -49,6 +56,7 @@ public ByteBufferBuilder writeInt(int value) { if (buffer == null) throw new IllegalStateException("This buffer is already closed"); buffer.putInt(value); + bufferContent.add("int " + value); return this; } @@ -56,6 +64,7 @@ public ByteBufferBuilder writeDouble(double value) { if (buffer == null) throw new IllegalStateException("This buffer is already closed"); buffer.putDouble(value); + bufferContent.add("double " + value); return this; } @@ -63,6 +72,7 @@ public ByteBufferBuilder writeFloat(float value) { if (buffer == null) throw new IllegalStateException("This buffer is already closed"); buffer.putFloat(value); + bufferContent.add("float " + value); return this; } @@ -70,6 +80,7 @@ public ByteBufferBuilder writeLong(long value) { if (buffer == null) throw new IllegalStateException("This buffer is already closed"); buffer.putLong(value); + bufferContent.add("long " + value); return this; } @@ -77,6 +88,7 @@ public ByteBufferBuilder writeShort(short value) { if (buffer == null) throw new IllegalStateException("This buffer is already closed"); buffer.putShort(value); + bufferContent.add("short " + value); return this; } @@ -84,6 +96,7 @@ public ByteBufferBuilder writeBoolean(boolean value) { if (buffer == null) throw new IllegalStateException("This buffer is already closed"); buffer.put((byte) (value ? 1 : 0)); + bufferContent.add("boolean " + value); return this; } @@ -93,6 +106,7 @@ public ByteBufferBuilder writeString(String value) { byte[] stringbytes = value.getBytes(); buffer.putInt(stringbytes.length); buffer.put(stringbytes); + bufferContent.add("String " + value); return this; } @@ -101,12 +115,15 @@ public ByteBufferBuilder writeUUID(UUID uuid) { throw new IllegalStateException("This buffer is already closed"); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); + bufferContent.add("UUID " + uuid); return this; } - + public ByteBufferBuilder writeByteArray(byte[] value) { buffer.putInt(value.length); buffer.put(value); + + bufferContent.add("ByteArray length(" + value.length + ")"); return this; } @@ -125,14 +142,14 @@ public ByteBufferBuilder clone() throws CloneNotSupportedException { int current = this.buffer.position(); int sid = SecureList.POOL.available(); ByteBuffer clone = SecureList.POOL.lock(sid); - + this.buffer.limit(current).position(0); - + clone.put(this.buffer); - + this.buffer.position(current); - - return new ByteBufferBuilder(sid, clone); + + return new ByteBufferBuilder(sid, clone, this.bufferPacketId, this.bufferContent); } public static int readInt(ByteBuffer buf) { @@ -158,7 +175,7 @@ public static short readShort(ByteBuffer buf) { public static boolean readBoolean(ByteBuffer buf) { return buf.get() == 1 ? true : false; } - + public static UUID readUUID(ByteBuffer buf) { return new UUID(buf.getLong(), buf.getLong()); } @@ -168,15 +185,29 @@ public static String readString(ByteBuffer buf) { buf.get(nameBytes); return new String(nameBytes); } - + public static byte[] readByteArray(ByteBuffer buf) { int length = buf.getInt(); byte[] array = new byte[length]; buf.get(array); return array; } - - public int getId(){ - return bufferId; + + /** + * Debug packetname + * + * @return + */ + public PacketID getPacketID() { + return bufferPacketId; + } + + public String getPacketContent() { + return String.join("\n", this.bufferContent); + } + + @Override + public String toString() { + return getPacketID().getName() + getPacketContent(); } } diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 0261cebc..3d555f9a 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -225,6 +225,8 @@ public void failed(Throwable exc, Object attachment) { * @throws Exception Networking exception */ public void send(ByteBufferBuilder bufferBuilder) throws Exception { + if(bufferBuilder.getPacketID() != null && bufferBuilder.getPacketID().shouldTrace()) + LOGGER.trace(getLoggerMarker(), "Sending a {} packet to the {} with content:\n{}", bufferBuilder.getPacketID(), getOppositeSide(), bufferBuilder.getPacketContent()); // wait for previous buffer to send if (this.future != null && !this.future.isDone()) this.future.get(); diff --git a/src/main/java/com/minecrafttas/common/server/Server.java b/src/main/java/com/minecrafttas/common/server/Server.java index 2827cde8..63ebe6f7 100644 --- a/src/main/java/com/minecrafttas/common/server/Server.java +++ b/src/main/java/com/minecrafttas/common/server/Server.java @@ -51,7 +51,7 @@ public void completed(AsynchronousSocketChannel clientSocket, Object attachment) ClientCallback callback = (client) -> { EventDisconnectServer.fireDisconnectServer(client); clients.remove(client); - LOGGER.debug(Server, "Disconnecting player from server. Server now has {} connections", getClients().size()); + LOGGER.debug(Server, "Disconnecting player from server"); }; Client newclient = new Client(clientSocket, packetIDs, callback); @@ -98,7 +98,7 @@ public void sendTo(String username, ByteBufferBuilder builder) throws Exception if(client != null && !client.isClosed()) { client.send(builder); } else { - Common.LOGGER.warn(Server, "Buffer with id {} could not be sent to the client {}: The client is closed", builder.getId(), username); + Common.LOGGER.warn(Server, "Buffer with id {} could not be sent to the client {}: The client is closed", builder.getPacketID(), username); removeClient(client); } } diff --git a/src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java b/src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java index a8663271..9c65996d 100644 --- a/src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/PacketHandlerBase.java @@ -7,5 +7,5 @@ public interface PacketHandlerBase { * or {@link ServerPacketHandler#onServerPacket(PacketID, java.nio.ByteBuffer, java.util.UUID)} methods. */ public PacketID[] getAcceptedPacketIDs(); - + } diff --git a/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java b/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java index 62070642..acd7eea2 100644 --- a/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java @@ -11,4 +11,6 @@ public interface PacketID { public Side getSide(); public String getName(); + + public boolean shouldTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index c5de7ca3..072e0873 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -23,7 +23,7 @@ public enum TASmodPackets implements PacketID { *

SIDE: Both
* ARGS: None */ - TICKSYNC, + TICKSYNC(false), /** *

Sets the tickrate/gamespeed * @@ -115,13 +115,23 @@ public enum TASmodPackets implements PacketID { private Side side; private CompactPacketHandler lambda; + private boolean shouldTrace = true; private TASmodPackets() { } + private TASmodPackets(boolean shouldTrace) { + this.shouldTrace = shouldTrace; + } + private TASmodPackets(Side side, CompactPacketHandler lambda) { + this(side, lambda, true); + } + + private TASmodPackets(Side side, CompactPacketHandler lambda, boolean shouldTrace) { this.side = side; this.lambda = lambda; + this.shouldTrace = shouldTrace; } @Override @@ -144,4 +154,8 @@ public String getName() { return this.name(); } + @Override + public boolean shouldTrace() { + return shouldTrace; + } } diff --git a/src/test/java/common/server/ByteBufferBuilderTest.java b/src/test/java/common/server/ByteBufferBuilderTest.java index d9b3d7fa..f602cb7a 100644 --- a/src/test/java/common/server/ByteBufferBuilderTest.java +++ b/src/test/java/common/server/ByteBufferBuilderTest.java @@ -53,6 +53,11 @@ public Side getSide() { public String getName() { return this.name(); } + + @Override + public boolean shouldTrace() { + return false; + } } diff --git a/src/test/java/common/server/ServerTest.java b/src/test/java/common/server/ServerTest.java index 00e49033..def5dc43 100644 --- a/src/test/java/common/server/ServerTest.java +++ b/src/test/java/common/server/ServerTest.java @@ -82,6 +82,11 @@ public String getName() { return this.name(); } + @Override + public boolean shouldTrace() { + return false; + } + } private static Client.Side side = null; diff --git a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java index ea9e804a..273bcfc0 100644 --- a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java +++ b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java @@ -52,6 +52,11 @@ public Side getSide() { public String getName() { return this.name(); } + + @Override + public boolean shouldTrace() { + return false; + } } From e8a7dc298836ac9897308574f4e2976e20cc4813 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 12 Nov 2023 16:39:52 +0100 Subject: [PATCH 52/60] Networking fixes - Fixed the ability to register 2 instances of packet handlers with the same class - Removed STATESYNC_INITIAL - [Savestates] Fixed unexpected behaviour - [PlaybackController] Fixed errors in console --- .../common/events/EventServer.java | 3 ++ .../common/server/PacketHandlerRegistry.java | 15 +++++++++ .../java/com/minecrafttas/tasmod/TASmod.java | 16 +++++---- .../com/minecrafttas/tasmod/TASmodClient.java | 12 ++----- .../tasmod/mixin/MixinMinecraft.java | 1 - .../tasmod/networking/TASmodPackets.java | 1 - .../playback/PlaybackControllerClient.java | 7 +--- .../playback/PlaybackControllerServer.java | 33 ++----------------- .../savestates/SavestateHandlerClient.java | 12 +++---- .../savestates/SavestateHandlerServer.java | 16 ++++----- .../tasmod/ticksync/TickSyncClient.java | 2 +- 11 files changed, 50 insertions(+), 68 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/events/EventServer.java b/src/main/java/com/minecrafttas/common/events/EventServer.java index 3ca02151..c4da5942 100644 --- a/src/main/java/com/minecrafttas/common/events/EventServer.java +++ b/src/main/java/com/minecrafttas/common/events/EventServer.java @@ -65,6 +65,9 @@ public static interface EventServerStop extends EventBase { /** * Fired when the server is about to stop + *

WARNING!

+ * This method may run twice!

+ * * @param server The stopping server */ public void onServerStop(MinecraftServer server); diff --git a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java index 3d7e8725..8c60685a 100644 --- a/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java +++ b/src/main/java/com/minecrafttas/common/server/PacketHandlerRegistry.java @@ -21,6 +21,12 @@ public static void register(PacketHandlerBase handler) { if(handler==null) { throw new NullPointerException("Tried to register a handler with value null"); } + + if(containsClass(handler)) { + Common.LOGGER.warn("Trying to register packet handler {}, but another instance of this class is already registered!", handler.getClass().getName()); + return; + } + if (!REGISTRY.contains(handler)) { REGISTRY.add(handler); } else { @@ -63,4 +69,13 @@ public static void handle(Side side, PacketID packet, ByteBuffer buf, String use throw new PacketNotImplementedException(packet, side); } } + + private static boolean containsClass(PacketHandlerBase handler) { + for(PacketHandlerBase packethandler : REGISTRY) { + if(packethandler.getClass().equals(handler.getClass())) { + return true; + } + } + return false; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 22d174ad..8fb47b22 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -50,7 +50,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{ public static final Logger LOGGER = LogManager.getLogger("TASmod"); - public static PlaybackControllerServer playbackControllerServer; + public static PlaybackControllerServer playbackControllerServer=new PlaybackControllerServer();; public static SavestateHandlerServer savestateHandlerServer; @@ -95,15 +95,13 @@ public void onInitialize() { PacketHandlerRegistry.register(ticksyncServer); PacketHandlerRegistry.register(tickratechanger); PacketHandlerRegistry.register(ktrngHandler); - + PacketHandlerRegistry.register(playbackControllerServer); } @Override public void onServerInit(MinecraftServer server) { LOGGER.info("Initializing server"); serverInstance = server; - playbackControllerServer=new PlaybackControllerServer(); - PacketHandlerRegistry.register(playbackControllerServer); // Command handling @@ -127,8 +125,8 @@ public void onServerInit(MinecraftServer server) { } catch (IOException e) { e.printStackTrace(); } - - savestateHandlerServer=new SavestateHandlerServer(server, LOGGER); + + savestateHandlerServer = new SavestateHandlerServer(server, LOGGER); PacketHandlerRegistry.register(savestateHandlerServer); if(!server.isDedicatedServer()) { @@ -147,6 +145,7 @@ public void onServerInit(MinecraftServer server) { @Override public void onServerStop(MinecraftServer mcserver) { serverInstance=null; + if(mcserver.isDedicatedServer()) { try { if (server != null) server.close(); @@ -155,6 +154,11 @@ public void onServerStop(MinecraftServer mcserver) { e.printStackTrace(); } } + + if(savestateHandlerServer != null) { + PacketHandlerRegistry.unregister(savestateHandlerServer); // Unregistering the savestatehandler, as a new instance is registered in onServerStart() + savestateHandlerServer = null; + } } public static MinecraftServer getServerInstance() { diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 8af1a628..a63e6d7f 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -48,7 +48,7 @@ import net.minecraft.client.settings.KeyBinding; import net.minecraft.server.MinecraftServer; -public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventPlayerLeaveClientSide, EventOpenGui{ +public class TASmodClient implements ClientModInitializer, EventClientInit, EventPlayerJoinedClientSide, EventOpenGui{ public static VirtualInput virtual; @@ -254,12 +254,6 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { ticksyncClient.setEnabled(true); }); } -// TASmod.server.sendToServer(new InitialSyncStatePacket(TASmodClient.virtual.getContainer().getState())); - } - - @Override - public void onPlayerLeaveClientSide(EntityPlayerSP player) { - } @Override @@ -271,9 +265,9 @@ public GuiScreen onOpenGui(GuiScreen gui) { // connect to server and authenticate client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), true); } catch (Exception e) { - LOGGER.error("Unable to connect TASmod client: {}", e.getMessage()); + LOGGER.error("Unable to connect TASmod client: {}", e); } - ticksyncClient.setEnabled(false); + ticksyncClient.setEnabled(true); } } else if(gui instanceof GuiControls) { diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java index c13e550f..4401621c 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraft.java @@ -15,7 +15,6 @@ import com.minecrafttas.tasmod.TASmodClient; import com.minecrafttas.tasmod.events.EventClient.EventClientTickPost; -import com.minecrafttas.tasmod.externalGui.InputContainerView; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; import com.minecrafttas.tasmod.util.Ducks.GuiScreenDuck; import com.minecrafttas.tasmod.util.Ducks.SubtickDuck; diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index 072e0873..ae960af2 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -85,7 +85,6 @@ public enum TASmodPackets implements PacketID { PLAYBACK_LOAD, PLAYBACK_PLAYUNTIL, PLAYBACK_TELEPORT, - STATESYNC_INITIAL, STATESYNC, /** *

Opens a TASmod related folder on the file system diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java index 9e5903d5..0e53fdea 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java @@ -10,7 +10,6 @@ import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_SAVE; import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_TELEPORT; import static com.minecrafttas.tasmod.networking.TASmodPackets.STATESYNC; -import static com.minecrafttas.tasmod.networking.TASmodPackets.STATESYNC_INITIAL; import java.io.File; import java.io.IOException; @@ -442,7 +441,7 @@ private void playbackNextTick() { if (!Display.isActive()) { // Stops the playback when you tab out of minecraft, for once as a failsafe, // secondly as potential exploit protection LOGGER.info(LoggerMarkers.Playback, "Stopping a {} since the user tabbed out of the game", state); - setTASStateClient(TASstate.NONE); + setTASState(TASstate.NONE); } index++; // Increase the index and load the next inputs @@ -834,7 +833,6 @@ public PacketID[] getAcceptedPacketIDs() { PLAYBACK_PLAYUNTIL, PLAYBACK_TELEPORT, CLEAR_INNPUTS, - STATESYNC_INITIAL, STATESYNC }; } @@ -935,9 +933,6 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws case PLAYBACK_TELEPORT: throw new WrongSideException(packet, Side.CLIENT); - case STATESYNC_INITIAL: - throw new WrongSideException(id, Side.CLIENT); - case STATESYNC: TASstate networkState = TASmodBufferBuilder.readTASState(buf); boolean verbose = TASmodBufferBuilder.readBoolean(buf); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java index aeeb302d..ffe6729e 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java @@ -1,6 +1,7 @@ package com.minecrafttas.tasmod.playback; import static com.minecrafttas.tasmod.TASmod.LOGGER; +import static com.minecrafttas.tasmod.util.LoggerMarkers.*; import static com.minecrafttas.tasmod.networking.TASmodPackets.*; import java.nio.ByteBuffer; @@ -16,7 +17,6 @@ import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; /** * The playback controller on the server side.
@@ -29,18 +29,10 @@ public class PlaybackControllerServer implements ServerPacketHandler { private TASstate state; - private boolean shouldChange = true; - - public PlaybackControllerServer() { - state = TASstate.NONE; - shouldChange = true; - } - @Override public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] { - STATESYNC_INITIAL, STATESYNC, PLAYBACK_TELEPORT, CLEAR_INNPUTS, @@ -58,18 +50,9 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws TASmodPackets packet = (TASmodPackets) id; switch (packet) { - case STATESYNC_INITIAL: - TASstate networkState = TASmodBufferBuilder.readTASState(buf); - if (/* TODO Permissions && */ shouldChange) { - setState(networkState); - shouldChange = false; - } else { - TASmod.server.sendTo(username, new TASmodBufferBuilder(TASmodPackets.STATESYNC_INITIAL).writeTASState(networkState)); - } - break; case STATESYNC: - networkState = TASmodBufferBuilder.readTASState(buf); + TASstate networkState = TASmodBufferBuilder.readTASState(buf); /* TODO Permissions */ setState(networkState); break; @@ -107,16 +90,6 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws } } - public void leaveServer(EntityPlayerMP player) { - MinecraftServer server = TASmod.getServerInstance(); - if (server != null) { - if (server.getPlayerList().getPlayers().size() == 1) { - state = TASstate.NONE; - shouldChange = true; - } - } - } - public void setState(TASstate stateIn) { setServerState(stateIn); try { @@ -134,7 +107,7 @@ public void setServerState(TASstate stateIn) { return; } this.state = stateIn; - LOGGER.info(String.format("Set the server state to %s", stateIn.toString())); + LOGGER.info(Playback, "Set the server state to {}", stateIn.toString()); } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index e9f9fced..fe8a1e35 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -252,6 +252,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws } catch (IOException e) { e.printStackTrace(); } + break; case SAVESTATE_LOAD: // Load client savestate name = TASmodBufferBuilder.readString(buf); @@ -270,12 +271,11 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws return; } /* - Fair warning: Do NOT read the buffer inside an addScheduledTask. - Read it before that. The buffer will have the wrong limit, - when the task is executed. - This is probably due to the buffers being reused. + * Fair warning: Do NOT read the buffer inside an addScheduledTask. Read it + * before that. The buffer will have the wrong limit, when the task is executed. + * This is probably due to the buffers being reused. */ - Minecraft.getMinecraft().addScheduledTask(()->{ + Minecraft.getMinecraft().addScheduledTask(() -> { SavestateHandlerClient.loadPlayer(compound); }); break; @@ -313,7 +313,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws break; case SAVESTATE_UNLOAD_CHUNKS: - Minecraft.getMinecraft().addScheduledTask(()-> { + Minecraft.getMinecraft().addScheduledTask(() -> { SavestateHandlerClient.unloadAllClientChunks(); }); break; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 406d005b..8cbddcf4 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -754,23 +754,23 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws try { TASmod.savestateHandlerServer.saveState(index, true); } catch (SavestateException e) { - if(player!=null) - player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getMessage())); + if (player != null) + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getMessage())); - LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: "+ e.getMessage()); + LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: " + e.getMessage()); } catch (Exception e) { - if(player!=null) - player.sendMessage(new TextComponentString(TextFormatting.RED+"Failed to create a savestate: "+ e.getCause().toString())); - + if (player != null) + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getCause().toString())); + LOGGER.error(e); } finally { - TASmod.savestateHandlerServer.state=SavestateState.NONE; + TASmod.savestateHandlerServer.state = SavestateState.NONE; } break; case SAVESTATE_LOAD: + int indexing = TASmodBufferBuilder.readInt(buf); TASmod.tickSchedulerServer.add(() -> { - int indexing = TASmodBufferBuilder.readInt(buf); // if (player!=null && !player.canUseCommand(2, "loadstate")) { // player.sendMessage(new TextComponentString(TextFormatting.RED+"You don't have // permission to do that")); diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java index b0c8c252..1a88da35 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncClient.java @@ -25,7 +25,7 @@ public class TickSyncClient implements ClientPacketHandler, EventClientTickPost{ public static final AtomicBoolean shouldTick = new AtomicBoolean(true); - private boolean enabled = true; + private boolean enabled = false; @Override public PacketID[] getAcceptedPacketIDs() { From 7fd795b2b52bbdd78a55566d60a56b54bab47782 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 12 Nov 2023 16:40:22 +0100 Subject: [PATCH 53/60] [Savestates] Fixed a rare crash with gui screens --- .../tasmod/savestates/gui/GuiSavestateLoadingScreen.java | 4 ++++ .../tasmod/savestates/gui/GuiSavestateSavingScreen.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java index a1ec7ed7..d0619aaa 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java @@ -7,6 +7,10 @@ public class GuiSavestateLoadingScreen extends GuiScreen { + public GuiSavestateLoadingScreen() { + this.mc=Minecraft.getMinecraft(); + } + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java index 5fc851d0..92f16863 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java @@ -7,6 +7,10 @@ public class GuiSavestateSavingScreen extends GuiScreen { + public GuiSavestateSavingScreen() { + this.mc = Minecraft.getMinecraft(); + } + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); From c60195e944f0adb3b77ffafb17538edae22b2733 Mon Sep 17 00:00:00 2001 From: Scribble Date: Sun, 12 Nov 2023 20:03:13 +0100 Subject: [PATCH 54/60] Trying to fix savestates --- .../minecrafttas/common/server/Client.java | 4 - .../com/minecrafttas/tasmod/gui/InfoHud.java | 1 - .../tasmod/mixin/MixinMinecraftServer.java | 7 -- .../savestates/SavestateHandlerClient.java | 3 +- .../savestates/SavestateHandlerServer.java | 100 +++++++++--------- 5 files changed, 50 insertions(+), 65 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/Client.java b/src/main/java/com/minecrafttas/common/server/Client.java index 3d555f9a..fedfbcd2 100644 --- a/src/main/java/com/minecrafttas/common/server/Client.java +++ b/src/main/java/com/minecrafttas/common/server/Client.java @@ -12,8 +12,6 @@ import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; -import java.util.Timer; -import java.util.TimerTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -54,7 +52,6 @@ public class Client { */ private boolean local = false; - private static Timer timeoutTimer = new Timer("Timeout Timer", true); public enum Side { CLIENT, SERVER; @@ -91,7 +88,6 @@ public Client(String host, int port, PacketID[] packetIDs, String name, boolean this.local = local; -// this.registerTimeoutTask(100); LOGGER.info(Client, "Connected to server"); username = name; diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index b0f182e4..b1bcd126 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -23,7 +23,6 @@ import com.minecrafttas.tasmod.playback.ControlByteHandler; import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.util.TrajectoriesCalculator; -import com.minecrafttas.tasmod.virtual.VirtualInput; import com.mojang.realmsclient.gui.ChatFormatting; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java index 29d4eef6..11b8e8ed 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinMinecraftServer.java @@ -11,9 +11,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.events.EventServer.EventCompleteLoadstate; import com.minecrafttas.tasmod.events.EventServer.EventServerTickPost; -import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.SavestateState; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -71,11 +69,6 @@ public void redirectThreadSleep(long msToTick) { if( (TASmod.ticksyncServer.shouldTick() && TASmod.tickratechanger.ticksPerSecond != 0) || TASmod.tickratechanger.advanceTick) { long timeBeforeTick = System.currentTimeMillis(); - if (TASmod.savestateHandlerServer.state == SavestateState.WASLOADING) { - TASmod.savestateHandlerServer.state = SavestateState.NONE; - EventCompleteLoadstate.fireLoadstateComplete(); - } - this.tick(); TASmod.tickSchedulerServer.runAllTasks(); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index fe8a1e35..5b34a2d9 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -153,7 +153,8 @@ public static void loadstate(String nameOfSavestate) throws IOException { TASmodClient.virtual.loadClientSavestate(TASmodClient.serialiser.fromEntireFileV1(targetfile)); } else { TASmodClient.virtual.getContainer().setTASStateClient(TASstate.NONE, false); - Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate, since the file doesn't exist. Stopping!")); + Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "Inputs could not be loaded for this savestate,")); + Minecraft.getMinecraft().player.sendMessage(new TextComponentString(ChatFormatting.YELLOW + "since the file doesn't exist. Stopping!")); LOGGER.warn(LoggerMarkers.Savestate, "Inputs could not be loaded for this savestate, since the file doesn't exist."); } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 8cbddcf4..315d857f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -349,7 +349,7 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex if (savestateIndex != 0) { try { // loadstate inputs client - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_LOAD).writeString(getSavestateName(savestateIndex))); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_LOAD).writeString(getSavestateName(indexToLoad))); } catch (Exception e) { e.printStackTrace(); } @@ -416,6 +416,12 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex TASmod.tickratechanger.pauseGame(false); } + + TASmod.tickSchedulerServer.add(()->{ + EventCompleteLoadstate.fireLoadstateComplete(); + state = SavestateState.NONE; + }); + // Unlock loadstating state = SavestateState.WASLOADING; } @@ -739,71 +745,61 @@ public PacketID[] getAcceptedPacketIDs() { public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { // TODO Permissions TASmodPackets packet = (TASmodPackets) id; - + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); Integer index = null; - - - switch (packet) { - case SAVESTATE_SAVE: - index = TASmodBufferBuilder.readInt(buf); -// if (player!=null && !player.canUseCommand(2, "savestate")) { -// player.sendMessage(new TextComponentString(TextFormatting.RED+"You don't have permission to do that")); -// return; -// } - try { - TASmod.savestateHandlerServer.saveState(index, true); - } catch (SavestateException e) { - if (player != null) - player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getMessage())); - LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: " + e.getMessage()); - } catch (Exception e) { - if (player != null) - player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getCause().toString())); - - LOGGER.error(e); - } finally { - TASmod.savestateHandlerServer.state = SavestateState.NONE; - } - break; - - case SAVESTATE_LOAD: - int indexing = TASmodBufferBuilder.readInt(buf); - TASmod.tickSchedulerServer.add(() -> { - // if (player!=null && !player.canUseCommand(2, "loadstate")) { - // player.sendMessage(new TextComponentString(TextFormatting.RED+"You don't have - // permission to do that")); - // return; - // } + switch (packet) { + case SAVESTATE_SAVE: + index = TASmodBufferBuilder.readInt(buf); try { - TASmod.savestateHandlerServer.loadState(indexing, true); - } catch (LoadstateException e) { + TASmod.savestateHandlerServer.saveState(index, true); + } catch (SavestateException e) { if (player != null) - player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getMessage())); + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getMessage())); LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: " + e.getMessage()); } catch (Exception e) { if (player != null) - player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getCause().toString())); + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to create a savestate: " + e.getCause().toString())); LOGGER.error(e); } finally { TASmod.savestateHandlerServer.state = SavestateState.NONE; } - }); - break; - - case SAVESTATE_REQUEST_MOTION: - MotionData data = TASmodBufferBuilder.readMotionData(buf); - PlayerHandler.getMotion().put(player, data); - break; - case SAVESTATE_PLAYER: - case SAVESTATE_SCREEN: - case SAVESTATE_UNLOAD_CHUNKS: - throw new WrongSideException(id, Side.SERVER); - default: - throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); + break; + + case SAVESTATE_LOAD: + int indexing = TASmodBufferBuilder.readInt(buf); + player.getServerWorld().addScheduledTask(() -> { + try { + TASmod.savestateHandlerServer.loadState(indexing, true); + } catch (LoadstateException e) { + if (player != null) + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getMessage())); + + LOGGER.error(LoggerMarkers.Savestate, "Failed to create a savestate: " + e.getMessage()); + TASmod.savestateHandlerServer.state = SavestateState.NONE; + } catch (Exception e) { + if (player != null) + player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to load a savestate: " + e.getCause().toString())); + + LOGGER.error(e); + TASmod.savestateHandlerServer.state = SavestateState.NONE; + } + }); + break; + + case SAVESTATE_REQUEST_MOTION: + MotionData data = TASmodBufferBuilder.readMotionData(buf); + PlayerHandler.getMotion().put(player, data); + break; + case SAVESTATE_PLAYER: + case SAVESTATE_SCREEN: + case SAVESTATE_UNLOAD_CHUNKS: + throw new WrongSideException(id, Side.SERVER); + default: + throw new PacketNotImplementedException(packet, this.getClass(), Side.SERVER); } } From 2cb0fdcd8746cbfd099afd758794babcb139d819 Mon Sep 17 00:00:00 2001 From: Scribble Date: Mon, 13 Nov 2023 18:36:45 +0100 Subject: [PATCH 55/60] [Savestates] Remove WASLOADING state --- .../minecrafttas/tasmod/events/EventServer.java | 2 +- .../savestates/MixinNetHandlerPlayServer.java | 2 +- .../savestates/SavestateHandlerServer.java | 16 ++++++---------- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java index d552f882..6b591dda 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java @@ -101,7 +101,7 @@ public static interface EventServerTickPost extends EventBase{ public void onServerTickPost(MinecraftServer minecraftServer); public static void fireServerTickPost(MinecraftServer minecraftServer) { - LOGGER.trace(LoggerMarkers.Event, "ServerTickPostEvent"); +// LOGGER.trace(LoggerMarkers.Event, "ServerTickPostEvent"); for (EventBase eventListener : TASmodEventListener.getEventListeners()) { if(eventListener instanceof EventServerTickPost) { EventServerTickPost event = (EventServerTickPost) eventListener; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java index cf36a683..00641961 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinNetHandlerPlayServer.java @@ -16,6 +16,6 @@ public class MixinNetHandlerPlayServer { @Redirect(method = "processPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;isInvulnerableDimensionChange()Z")) public boolean redirect_processPlayer(EntityPlayerMP parentIn) { - return !parentIn.isInvulnerableDimensionChange() && (TASmod.savestateHandlerServer.state!=SavestateState.LOADING && TASmod.savestateHandlerServer.state!=SavestateState.WASLOADING); + return !parentIn.isInvulnerableDimensionChange() && TASmod.savestateHandlerServer.state!=SavestateState.LOADING; } } diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java index 315d857f..c77c7ea4 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerServer.java @@ -75,7 +75,7 @@ * @author Scribble * */ -public class SavestateHandlerServer implements EventCompleteLoadstate, ServerPacketHandler { +public class SavestateHandlerServer implements ServerPacketHandler { private MinecraftServer server; private File savestateDirectory; @@ -419,12 +419,13 @@ public void loadState(int savestateIndex, boolean tickrate0, boolean changeIndex TASmod.tickSchedulerServer.add(()->{ EventCompleteLoadstate.fireLoadstateComplete(); + onLoadstateComplete(); + + // Unlock savestating state = SavestateState.NONE; }); - - // Unlock loadstating - state = SavestateState.WASLOADING; } + /** * Creates the savestate directory in case the user deletes it between @@ -683,9 +684,8 @@ public int getCurrentIndex() { return currentIndex; } - @Override public void onLoadstateComplete() { - logger.trace(LoggerMarkers.Event, "Running loadstate complete event"); + logger.trace(LoggerMarkers.Savestate, "Running loadstate complete event"); PlayerList playerList = TASmod.getServerInstance().getPlayerList(); for (EntityPlayerMP player : playerList.getPlayers()) { NBTTagCompound nbttagcompound = playerList.readPlayerDataFromFile(player); @@ -725,7 +725,6 @@ private int legacyIndexFile(File savestateDat) { public static enum SavestateState { SAVING, LOADING, - WASLOADING, NONE } @@ -1070,7 +1069,6 @@ public static void flushSaveHandler(MinecraftServer server) { */ public static void addPlayersToChunkMap(MinecraftServer server) { List players=server.getPlayerList().getPlayers(); - //Vanilla WorldServer[] worlds=server.worlds; for (EntityPlayerMP player : players) { LOGGER.trace(LoggerMarkers.Savestate, "Add player {} to the chunk map", player.getName()); @@ -1100,7 +1098,6 @@ public static void addPlayersToChunkMap(MinecraftServer server) { */ public static void disconnectPlayersFromChunkMap(MinecraftServer server) { List players=server.getPlayerList().getPlayers(); - //Vanilla WorldServer[] worlds=server.worlds; for (WorldServer world : worlds) { for (EntityPlayerMP player : players) { @@ -1118,7 +1115,6 @@ public static void disconnectPlayersFromChunkMap(MinecraftServer server) { */ public static void unloadAllServerChunks(MinecraftServer server) { LOGGER.trace(LoggerMarkers.Savestate, "Unloading all server chunks"); - //Vanilla WorldServer[] worlds=server.worlds; for (WorldServer world:worlds) { From 8614dbb4ed0b467586e7b7d572d20edfdb4c4111 Mon Sep 17 00:00:00 2001 From: Scribble Date: Mon, 13 Nov 2023 22:40:24 +0100 Subject: [PATCH 56/60] [Event] Drafting new event firing --- .../common/events/EventClient.java | 13 +---- .../common/events/EventListenerRegistry.java | 53 ++++++++++++++++++- 2 files changed, 54 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/events/EventClient.java b/src/main/java/com/minecrafttas/common/events/EventClient.java index 724af00a..80b74e57 100644 --- a/src/main/java/com/minecrafttas/common/events/EventClient.java +++ b/src/main/java/com/minecrafttas/common/events/EventClient.java @@ -26,17 +26,8 @@ public static interface EventOpenGui extends EventBase { public GuiScreen onOpenGui(GuiScreen gui); public static GuiScreen fireOpenGuiEvent(GuiScreen gui) { - Common.LOGGER.trace(Common.Event, "Firing OpenGuiEvent"); - for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { - if(eventListener instanceof EventOpenGui) { - EventOpenGui event = (EventOpenGui) eventListener; - GuiScreen newGui = event.onOpenGui(gui); - if(newGui != gui) { - return newGui; - } - } - } - return gui; + Common.LOGGER.trace(Common.Event, "Firing LaunchIntegratedServer"); + return (GuiScreen) EventBase.fireEvent(EventOpenGui.class, gui); } } diff --git a/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java index e425d3fc..b000334d 100644 --- a/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java +++ b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java @@ -1,6 +1,11 @@ package com.minecrafttas.common.events; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; public class EventListenerRegistry { @@ -21,12 +26,58 @@ public static void unregister(EventBase eventListener) { EVENTLISTENER_REGISTRY.remove(eventListener); } - public static ArrayList getEventListeners(){ return EVENTLISTENER_REGISTRY; } public static interface EventBase { + /** + * Fires the event specified in eventClass + * @param eventClass The event handler class + * @param eventParams The parameters for this event + * @return The return value of the event + */ + public static Object fireEvent(Class eventClass, Object... eventParams) { + + Method methodToFire = null; + + for(Method method : eventClass.getMethods()) { + if(Modifier.isAbstract(method.getModifiers())) { + methodToFire = method; + break; + } + } + + for(EventListenerRegistry.EventBase eventListener : EventListenerRegistry.EVENTLISTENER_REGISTRY) { + Class[] interfaces = eventListener.getClass().getInterfaces(); + for(Class interfaze : interfaces) { + if(interfaze.equals(eventClass)) { + Method methodInClass = null; + Method[] methods = eventListener.getClass().getMethods(); + for(Method method : methods) { + if(method.getName().equals(methodToFire.getName())) { + methodInClass = method; + break; + } + } + + try { + return methodInClass.invoke(eventListener, eventParams); + } catch (IllegalAccessException e) { + e.printStackTrace(); + return null; + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return null; + } catch (InvocationTargetException e) { + e.printStackTrace(); + return null; + } + } + } + } + return null; + } } } From d2bfe4b76ff269d1986d5515eaafd6490831581f Mon Sep 17 00:00:00 2001 From: Scribble Date: Wed, 15 Nov 2023 19:27:24 +0100 Subject: [PATCH 57/60] Revert "[Event] Drafting new event firing" This reverts commit 8614dbb4ed0b467586e7b7d572d20edfdb4c4111. --- .../common/events/EventClient.java | 13 ++++- .../common/events/EventListenerRegistry.java | 53 +------------------ 2 files changed, 12 insertions(+), 54 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/events/EventClient.java b/src/main/java/com/minecrafttas/common/events/EventClient.java index 80b74e57..724af00a 100644 --- a/src/main/java/com/minecrafttas/common/events/EventClient.java +++ b/src/main/java/com/minecrafttas/common/events/EventClient.java @@ -26,8 +26,17 @@ public static interface EventOpenGui extends EventBase { public GuiScreen onOpenGui(GuiScreen gui); public static GuiScreen fireOpenGuiEvent(GuiScreen gui) { - Common.LOGGER.trace(Common.Event, "Firing LaunchIntegratedServer"); - return (GuiScreen) EventBase.fireEvent(EventOpenGui.class, gui); + Common.LOGGER.trace(Common.Event, "Firing OpenGuiEvent"); + for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { + if(eventListener instanceof EventOpenGui) { + EventOpenGui event = (EventOpenGui) eventListener; + GuiScreen newGui = event.onOpenGui(gui); + if(newGui != gui) { + return newGui; + } + } + } + return gui; } } diff --git a/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java index b000334d..e425d3fc 100644 --- a/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java +++ b/src/main/java/com/minecrafttas/common/events/EventListenerRegistry.java @@ -1,11 +1,6 @@ package com.minecrafttas.common.events; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; public class EventListenerRegistry { @@ -26,58 +21,12 @@ public static void unregister(EventBase eventListener) { EVENTLISTENER_REGISTRY.remove(eventListener); } + public static ArrayList getEventListeners(){ return EVENTLISTENER_REGISTRY; } public static interface EventBase { - /** - * Fires the event specified in eventClass - * @param eventClass The event handler class - * @param eventParams The parameters for this event - * @return The return value of the event - */ - public static Object fireEvent(Class eventClass, Object... eventParams) { - - Method methodToFire = null; - - for(Method method : eventClass.getMethods()) { - if(Modifier.isAbstract(method.getModifiers())) { - methodToFire = method; - break; - } - } - - for(EventListenerRegistry.EventBase eventListener : EventListenerRegistry.EVENTLISTENER_REGISTRY) { - Class[] interfaces = eventListener.getClass().getInterfaces(); - for(Class interfaze : interfaces) { - if(interfaze.equals(eventClass)) { - Method methodInClass = null; - Method[] methods = eventListener.getClass().getMethods(); - for(Method method : methods) { - if(method.getName().equals(methodToFire.getName())) { - methodInClass = method; - break; - } - } - - try { - return methodInClass.invoke(eventListener, eventParams); - } catch (IllegalAccessException e) { - e.printStackTrace(); - return null; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - return null; - } catch (InvocationTargetException e) { - e.printStackTrace(); - return null; - } - } - } - } - return null; - } } } From e85bc87c469dcaa824cedfde6ee6a37d51791555 Mon Sep 17 00:00:00 2001 From: Scribble Date: Wed, 15 Nov 2023 20:00:48 +0100 Subject: [PATCH 58/60] [Networking] Added config option for automatically connecting to a custom server on startup --- .../minecrafttas/common/Configuration.java | 3 +- .../com/minecrafttas/tasmod/TASmodClient.java | 35 ++++++++++++++----- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/Configuration.java b/src/main/java/com/minecrafttas/common/Configuration.java index 17c6420a..6fd879d9 100644 --- a/src/main/java/com/minecrafttas/common/Configuration.java +++ b/src/main/java/com/minecrafttas/common/Configuration.java @@ -118,7 +118,8 @@ public void delete(ConfigOptions configOption) { } public static enum ConfigOptions{ - FileToOpen("fileToOpen", ""); + FileToOpen("fileToOpen", ""), + ServerConnection("serverConnection", ""); private String configKey; private String defaultValue; diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index a63e6d7f..9ee3c417 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; +import org.apache.logging.log4j.Level; import org.lwjgl.input.Keyboard; import com.minecrafttas.common.Configuration; @@ -258,27 +259,43 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { @Override public GuiScreen onOpenGui(GuiScreen gui) { - if(gui instanceof GuiMainMenu) { - if(client == null) { + if (gui instanceof GuiMainMenu) { + if (client == null) { Minecraft mc = Minecraft.getMinecraft(); + + String IP = "localhost"; + int PORT = TASmod.networkingport - 1; + + // Get the connection on startup from config + String configAddress = config.get(ConfigOptions.ServerConnection); + if(configAddress != null && !configAddress.isEmpty()) { + String[] ipSplit = configAddress.split(":"); + IP = ipSplit[0]; + try { + PORT = Integer.parseInt(ipSplit[1]); + } catch (Exception e) { + LOGGER.catching(Level.ERROR, e); + IP = "localhost"; + PORT = TASmod.networkingport - 1; + } + } + try { // connect to server and authenticate - client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), true); + client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), true); } catch (Exception e) { LOGGER.error("Unable to connect TASmod client: {}", e); } ticksyncClient.setEnabled(true); } - } - else if(gui instanceof GuiControls) { + } else if (gui instanceof GuiControls) { TASmodClient.virtual.getContainer().setTASState(TASstate.NONE); // Set the TASState to nothing to avoid collisions - if(TASmodClient.tickratechanger.ticksPerSecond==0) { + if (TASmodClient.tickratechanger.ticksPerSecond == 0) { TASmodClient.tickratechanger.pauseClientGame(false); // Unpause the game waszero = true; } - } - else if(!(gui instanceof GuiControls)) { - if(waszero) { + } else if (!(gui instanceof GuiControls)) { + if (waszero) { waszero = false; TASmodClient.tickratechanger.pauseClientGame(true); } From e01363404db11a358ea342d307796224d840732b Mon Sep 17 00:00:00 2001 From: Scribble Date: Wed, 15 Nov 2023 20:39:21 +0100 Subject: [PATCH 59/60] =?UTF-8?q?[Networking]=20Documentation=20fixes=20?= =?UTF-8?q?=F0=9F=9A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/minecrafttas/common/events/EventClient.java | 12 ++++++++---- .../com/minecrafttas/common/events/EventServer.java | 11 +++++++++-- .../common/server/ByteBufferBuilder.java | 8 ++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/events/EventClient.java b/src/main/java/com/minecrafttas/common/events/EventClient.java index 724af00a..c789148c 100644 --- a/src/main/java/com/minecrafttas/common/events/EventClient.java +++ b/src/main/java/com/minecrafttas/common/events/EventClient.java @@ -265,12 +265,13 @@ public static void firePlayerJoinedClientSide(EntityPlayerSP player) { */ public static interface EventOtherPlayerJoinedClientSide extends EventBase { - public void onOtherPlayerJoinedClientSide(GameProfile profile); - /** * Fired when a different player other than yourself joins a server or a world * @param player The game profile of the player that joins the server or the world */ + public void onOtherPlayerJoinedClientSide(GameProfile profile); + + public static void fireOtherPlayerJoinedClientSide(GameProfile profile) { Common.LOGGER.trace(Common.Event, "Firing OtherPlayerJoinedClientSide"); for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { @@ -283,14 +284,17 @@ public static void fireOtherPlayerJoinedClientSide(GameProfile profile) { } + /** + * Fired when the connection to the custom server was closed on the client side. + */ public static interface EventDisconnectClient extends EventBase { - public void onDisconnectClient(Client client); - /** * Fired when the connection to the custom server was closed on the client side. * @param client The client that is disconnecting */ + public void onDisconnectClient(Client client); + public static void fireDisconnectClient(Client client) { Common.LOGGER.trace(Common.Event, "Firing EventDisconnectClient"); for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { diff --git a/src/main/java/com/minecrafttas/common/events/EventServer.java b/src/main/java/com/minecrafttas/common/events/EventServer.java index c4da5942..852d05aa 100644 --- a/src/main/java/com/minecrafttas/common/events/EventServer.java +++ b/src/main/java/com/minecrafttas/common/events/EventServer.java @@ -145,10 +145,14 @@ public static void firePlayerLeaveServerSide(EntityPlayerMP player) { } } + /** + * Fired when authentication was successful on the server side + */ public static interface EventClientCompleteAuthentication extends EventBase { /** * Fired when authentication was successful on the server side + * @param username The username of the client that is connecting */ public void onClientCompleteAuthentication(String username); @@ -163,14 +167,17 @@ public static void fireClientCompleteAuthentication(String username) { } } + /** + * Fired when the connection to the custom server was closed on the server side. + */ public static interface EventDisconnectServer extends EventBase { - public void onDisconnectServer(Client client); - /** * Fired when the connection to the custom server was closed on the server side. * @param client The client that is disconnecting */ + public void onDisconnectServer(Client client); + public static void fireDisconnectServer(Client client) { Common.LOGGER.trace(Common.Event, "Firing CustomServerClientDisconnect"); for (EventBase eventListener : EventListenerRegistry.getEventListeners()) { diff --git a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java index 31d77c97..fedfc8a7 100644 --- a/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java +++ b/src/main/java/com/minecrafttas/common/server/ByteBufferBuilder.java @@ -28,11 +28,19 @@ public ByteBufferBuilder(int id) { buffer.putInt(id); } + /** + * Creates a new ByteBufferBuilder with a packetId + * @param packet The address to which the packet is sent. Usually an enum. + */ public ByteBufferBuilder(PacketID packet) { this(packet.getID()); this.bufferPacketId = packet; } + /** + * Creates a ByteBufferBuilder from an existing buffer. Useful for sending the same buffer back. + * @param buf + */ public ByteBufferBuilder(ByteBuffer buf) { bufferIndex = SecureList.POOL.available(); buffer = SecureList.POOL.lock(bufferIndex); From f69a6f2c7203d2c28a32a4b8b73e301d7d64db45 Mon Sep 17 00:00:00 2001 From: Scribble Date: Thu, 16 Nov 2023 22:36:08 +0100 Subject: [PATCH 60/60] =?UTF-8?q?[Networking]=20Finishing=20documentation?= =?UTF-8?q?=20=F0=9F=9A=82=20for=20packet=20ids=20-=20Fixed=20clearinputs?= =?UTF-8?q?=20packet=20being=20sent=20twice=20-=20Renamed=20SYNCSTATE=20pa?= =?UTF-8?q?cket=20to=20PLAYBACK=5FSTATE=20-=20Renamed=20CLEAR=5FINPUTS=20t?= =?UTF-8?q?o=20PLAYBACK=5FCLEAR=5FINPUTS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/server/interfaces/PacketID.java | 22 +++- .../tasmod/commands/CommandClearInputs.java | 2 +- .../tasmod/networking/TASmodPackets.java | 101 ++++++++++++++++-- .../playback/PlaybackControllerClient.java | 16 +-- .../playback/PlaybackControllerServer.java | 14 +-- 5 files changed, 126 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java b/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java index acd7eea2..522cd42b 100644 --- a/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java +++ b/src/main/java/com/minecrafttas/common/server/interfaces/PacketID.java @@ -4,13 +4,27 @@ import com.minecrafttas.common.server.Client.Side; public interface PacketID { + /** + * @return The numerical ID of the packet + */ public int getID(); - - public CompactPacketHandler getLambda(); - + /** + * Only used in combination with {@link #getLambda()} + * @return The side of the packet this is registered to + */ public Side getSide(); - + /** + * Used for compact small lambda packet handlers + * @return The lamda to run when receiving a packet + */ + public CompactPacketHandler getLambda(); + /** + * @return The name of the packet + */ public String getName(); + /** + * @return Whether the packet should be used in trace messages + */ public boolean shouldTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java index ab6fcc5b..b93ac489 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java @@ -26,7 +26,7 @@ public String getUsage(ICommandSender sender) { public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if(sender instanceof EntityPlayer) { try { - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.CLEAR_INNPUTS)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_CLEAR_INPUTS)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java index ae960af2..d62135e0 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodPackets.java @@ -4,6 +4,10 @@ import com.minecrafttas.common.server.Client.Side; import com.minecrafttas.common.server.interfaces.PacketID; import com.minecrafttas.tasmod.commands.CommandFolder; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; +import com.minecrafttas.tasmod.playback.PlaybackSerialiser; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer.PlayerHandler.MotionData; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; import net.minecraft.nbt.NBTTagCompound; @@ -17,37 +21,31 @@ public enum TASmodPackets implements PacketID { /** *

Ticksync is a system to sync the tick execution between client and server. * Both can tick independent from each other causing issues with playback. - * *

This is used to notify the other to start ticking and shouldn't be used otherwise. - * *

SIDE: Both
* ARGS: None */ TICKSYNC(false), /** *

Sets the tickrate/gamespeed - * *

SIDE: Both
* ARGS: int tickrate */ TICKRATE_CHANGE, /** *

Sets the tickrate to 0, pausing the game. Also unpauses the game - * *

SIDE: Both
* ARGS: {@link TickratePauseState} state The paused state */ TICKRATE_ZERO, /** *

While in tickrate 0, advances the game by one tick - * *

SIDE: Both
* ARGS: None */ TICKRATE_ADVANCE, /** *

Creates a savestate - * *

SIDE: Both
* ARGS:
* Client->Server: int The index of the savestate that should be created. -1 to create the latest savestate, might overwrite existing savestates.
@@ -56,7 +54,6 @@ public enum TASmodPackets implements PacketID { SAVESTATE_SAVE, /** *

Loads a savestate - * *

SIDE: Both
* ARGS:
* Client->Server int The index of the savestate that should be loaded
@@ -75,17 +72,91 @@ public enum TASmodPackets implements PacketID { * ARGS: {@link NBTTagCompound} compound The playerdata */ SAVESTATE_PLAYER, + /** + *

Used for storing the client motion data on the server. + *

SIDE: BOTH
+ * ARGS:
+ * Server->ClientNone
+ * Client->Server {@link MotionData} motionData An Object containing all necessary motion data
+ */ SAVESTATE_REQUEST_MOTION, + /** + *

Unloads the chunks on the client side + *

SIDE: Client
+ * ARGS: none + */ SAVESTATE_UNLOAD_CHUNKS, - CLEAR_INNPUTS, + /** + *

Notifies the client to clear all inputs from the input buffer in {@link PlaybackControllerClient} + *

SIDE: Both
+ * ARGS: none + */ + PLAYBACK_CLEAR_INPUTS, + /** + *

Notifies the client to quit to the main menu and start recording inputs in {@link PlaybackControllerClient} + *

SIDE: Both
+ * ARGS: none + */ PLAYBACK_FULLRECORD, + /** + *

Notifies the client to quit to the main menu and start playing back inputs in {@link PlaybackControllerClient} + *

SIDE: Both
+ * ARGS: none + */ PLAYBACK_FULLPLAY, + /** + *

Notifies the client to quit the game. Upon restarting the game, the specified tasfile will be loaded and played back in {@link PlaybackControllerClient} + *

SIDE: Both
+ * ARGS:
+ * Client->Server None
+ * Server->Client String filename The TASfile name to load on restart + */ PLAYBACK_RESTARTANDPLAY, + /** + *

Notifies the client to store the current inputs to a file in {@link PlaybackControllerClient}. This is done using {@link PlaybackSerialiser} + *

SIDE: Both
+ * ARGS:
+ * Client->Server None
+ * Server->Client String filename The TASfile name to store + */ PLAYBACK_SAVE, + /** + *

Notifies the client to load the inputs from a file in {@link PlaybackControllerClient}. This is done using {@link PlaybackSerialiser} + *

SIDE: Both
+ * ARGS:
+ * Client->Server None
+ * Server->Client String filename The TASfile name to load + */ PLAYBACK_LOAD, + /** + *

Notifies the client activate "playuntil" in {@link PlaybackControllerClient}. The next playback will stop at the specified tick and the client will enter recording mode + *

SIDE: Both
+ * ARGS:
+ * Client->Server None
+ * Server->Client int tick The tick when to stop playing back and start recording + */ PLAYBACK_PLAYUNTIL, + /** + *

A permissionless teleport packet, used for setting the playerdata on the server. Used for teleporting the player back to the start of the TAS when using /play + *

SIDE: Server
+ * ARGS:
+ * double x The x value
+ * double y etc...
+ * double z
+ * float angleYaw
+ * float anglePitch
+ */ PLAYBACK_TELEPORT, - STATESYNC, + /** + *

Notifies the players to change the {@link TASstate} + *

SIDE: Both
+ * ARGS:
+ * Client->Server {@link TASstate} state The new state everyone should adapt + * Server->Client + * {@link TASstate} state The new state everyone should adapt
+ * boolean verbose If a chat message should be printed + */ + PLAYBACK_STATE, /** *

Opens a TASmod related folder on the file system *

The action describes which folder to open: @@ -109,7 +180,19 @@ public enum TASmodPackets implements PacketID { break; } }), + /** + *

Sets the KillTheRNG seed + *

SIDE: Both
+ * ARGS:
+ * long seed The new KillTheRNG seed + */ KILLTHERNG_SEED, + /** + *

Sets the KillTheRNG start seed when starting recording + *

SIDE: Both
+ * ARGS:
+ * long seed The new KillTheRNG seed + */ KILLTHERNG_STARTSEED; private Side side; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java index 0e53fdea..c00a5aa3 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerClient.java @@ -1,7 +1,7 @@ package com.minecrafttas.tasmod.playback; import static com.minecrafttas.tasmod.TASmod.LOGGER; -import static com.minecrafttas.tasmod.networking.TASmodPackets.CLEAR_INNPUTS; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_CLEAR_INPUTS; import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_FULLPLAY; import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_FULLRECORD; import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_LOAD; @@ -9,7 +9,7 @@ import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_RESTARTANDPLAY; import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_SAVE; import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_TELEPORT; -import static com.minecrafttas.tasmod.networking.TASmodPackets.STATESYNC; +import static com.minecrafttas.tasmod.networking.TASmodPackets.PLAYBACK_STATE; import java.io.File; import java.io.IOException; @@ -147,7 +147,7 @@ public class PlaybackControllerClient implements ClientPacketHandler { */ public void setTASState(TASstate stateIn) { try { - TASmodClient.client.send(new TASmodBufferBuilder(STATESYNC).writeTASState(stateIn)); + TASmodClient.client.send(new TASmodBufferBuilder(PLAYBACK_STATE).writeTASState(stateIn)); } catch (Exception e) { e.printStackTrace(); } @@ -171,7 +171,7 @@ public String setTASStateClient(TASstate stateIn) { * @return The message printed in the chat */ public String setTASStateClient(TASstate stateIn, boolean verbose) { - ControlByteHandler.reset(); + ControlByteHandler.reset(); // FIXME Controlbytes are resetting when loading a world, due to "Paused" state being active during loading... Fix Paused state shenanigans? if (state == stateIn) { switch (stateIn) { case PLAYBACK: @@ -832,8 +832,8 @@ public PacketID[] getAcceptedPacketIDs() { PLAYBACK_RESTARTANDPLAY, PLAYBACK_PLAYUNTIL, PLAYBACK_TELEPORT, - CLEAR_INNPUTS, - STATESYNC + PLAYBACK_CLEAR_INPUTS, + PLAYBACK_STATE }; } @@ -926,14 +926,14 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws TASmodClient.virtual.getContainer().setPlayUntil(until); break; - case CLEAR_INNPUTS: + case PLAYBACK_CLEAR_INPUTS: TASmodClient.virtual.getContainer().clear(); break; case PLAYBACK_TELEPORT: throw new WrongSideException(packet, Side.CLIENT); - case STATESYNC: + case PLAYBACK_STATE: TASstate networkState = TASmodBufferBuilder.readTASState(buf); boolean verbose = TASmodBufferBuilder.readBoolean(buf); Task task = ()->{ diff --git a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java index ffe6729e..98fd36f5 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/PlaybackControllerServer.java @@ -33,9 +33,9 @@ public class PlaybackControllerServer implements ServerPacketHandler { public PacketID[] getAcceptedPacketIDs() { return new TASmodPackets[] { - STATESYNC, + PLAYBACK_STATE, PLAYBACK_TELEPORT, - CLEAR_INNPUTS, + PLAYBACK_CLEAR_INPUTS, PLAYBACK_FULLPLAY, PLAYBACK_FULLRECORD, PLAYBACK_RESTARTANDPLAY, @@ -51,7 +51,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws switch (packet) { - case STATESYNC: + case PLAYBACK_STATE: TASstate networkState = TASmodBufferBuilder.readTASState(buf); /* TODO Permissions */ setState(networkState); @@ -73,9 +73,9 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws }); break; - case CLEAR_INNPUTS: - TASmod.server.sendToAll(new TASmodBufferBuilder(CLEAR_INNPUTS)); - + case PLAYBACK_CLEAR_INPUTS: + TASmod.server.sendToAll(new TASmodBufferBuilder(PLAYBACK_CLEAR_INPUTS)); + break; case PLAYBACK_FULLPLAY: case PLAYBACK_FULLRECORD: case PLAYBACK_RESTARTANDPLAY: @@ -93,7 +93,7 @@ public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws public void setState(TASstate stateIn) { setServerState(stateIn); try { - TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.STATESYNC).writeTASState(state).writeBoolean(true)); + TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_STATE).writeTASState(state).writeBoolean(true)); } catch (Exception e) { e.printStackTrace(); }