From a776879eeddcb4a350728d2f5162b399d367859f Mon Sep 17 00:00:00 2001 From: Richard Freimer Date: Wed, 10 Apr 2019 15:12:12 -0400 Subject: [PATCH] Readd voice server (#5374) * Add back the voice server defaulted to disabled * Port 098472a make voice output properly sleepy * Cleanup some of the voice server code * Keep track of UUID in VoiceConnection instead of username * Collapse a few missed error logging into stack trace printing * Add tooltip to walkie talkie when voice server is disabled * Fix single player crash if voice server is enabled after launch before world start --- .../client/ClientConnectionHandler.java | 37 ++++ .../java/mekanism/client/ClientProxy.java | 10 ++ .../java/mekanism/client/MekanismClient.java | 10 ++ .../mekanism/client/MekanismKeyHandler.java | 7 +- .../mekanism/client/voice/VoiceClient.java | 98 +++++++++++ .../mekanism/client/voice/VoiceInput.java | 92 ++++++++++ .../mekanism/client/voice/VoiceOutput.java | 75 ++++++++ .../java/mekanism/common/CommonProxy.java | 16 +- src/main/java/mekanism/common/Mekanism.java | 17 ++ .../common/config/MekanismConfig.java | 2 + .../common/item/ItemWalkieTalkie.java | 4 + .../common/network/PacketConfigSync.java | 4 + .../common/voice/VoiceConnection.java | 163 ++++++++++++++++++ .../common/voice/VoiceServerManager.java | 107 ++++++++++++ .../resources/assets/mekanism/lang/en_us.lang | 1 + .../assets/mekanism/recipes/walkietalkie.json | 24 +++ 16 files changed, 661 insertions(+), 6 deletions(-) create mode 100644 src/main/java/mekanism/client/ClientConnectionHandler.java create mode 100644 src/main/java/mekanism/client/voice/VoiceClient.java create mode 100644 src/main/java/mekanism/client/voice/VoiceInput.java create mode 100644 src/main/java/mekanism/client/voice/VoiceOutput.java create mode 100644 src/main/java/mekanism/common/voice/VoiceConnection.java create mode 100644 src/main/java/mekanism/common/voice/VoiceServerManager.java create mode 100644 src/main/resources/assets/mekanism/recipes/walkietalkie.json diff --git a/src/main/java/mekanism/client/ClientConnectionHandler.java b/src/main/java/mekanism/client/ClientConnectionHandler.java new file mode 100644 index 000000000..fe606b21f --- /dev/null +++ b/src/main/java/mekanism/client/ClientConnectionHandler.java @@ -0,0 +1,37 @@ +package mekanism.client; + +import java.net.InetSocketAddress; +import mekanism.client.voice.VoiceClient; +import mekanism.common.Mekanism; +import mekanism.common.config.MekanismConfig.general; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class ClientConnectionHandler { + + @SubscribeEvent + public void onConnection(ClientConnectedToServerEvent event) { + if (general.voiceServerEnabled) { + if (event.isLocal()) { + // If the client is connecting to its own corresponding integrated server. + try { + MekanismClient.voiceClient = new VoiceClient("127.0.0.1"); + // Will probably not work when multiple integrateds are running on one computer + } catch (Throwable e) { + Mekanism.logger.error("Unable to establish VoiceClient on local connection.", e); + } + } else { + // If the client is connecting to a foreign integrated or dedicated server. + try { + MekanismClient.voiceClient = new VoiceClient( + ((InetSocketAddress) event.getManager().getRemoteAddress()).getHostString()); + } catch (Throwable e) { + Mekanism.logger.error("Unable to establish VoiceClient on remote connection.", e); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/mekanism/client/ClientProxy.java b/src/main/java/mekanism/client/ClientProxy.java index 9f71f216c..b81964657 100644 --- a/src/main/java/mekanism/client/ClientProxy.java +++ b/src/main/java/mekanism/client/ClientProxy.java @@ -131,6 +131,7 @@ import mekanism.common.block.states.BlockStatePlastic.PlasticBlockStateMapper; import mekanism.common.block.states.BlockStateTransmitter.TransmitterStateMapper; import mekanism.common.block.states.BlockStateTransmitter.TransmitterType; import mekanism.common.config.MekanismConfig.client; +import mekanism.common.config.MekanismConfig.general; import mekanism.common.entity.EntityBabySkeleton; import mekanism.common.entity.EntityBalloon; import mekanism.common.entity.EntityFlame; @@ -1079,6 +1080,7 @@ public class ClientProxy extends CommonProxy { * 255); }, MekanismItems.Balloon); + MinecraftForge.EVENT_BUS.register(new ClientConnectionHandler()); MinecraftForge.EVENT_BUS.register(new ClientPlayerTracker()); MinecraftForge.EVENT_BUS.register(new ClientTickHandler()); MinecraftForge.EVENT_BUS.register(new RenderTickHandler()); @@ -1089,6 +1091,14 @@ public class ClientProxy extends CommonProxy { HolidayManager.init(); } + @Override + public void onConfigSync(boolean fromPacket) { + super.onConfigSync(fromPacket); + if (fromPacket && general.voiceServerEnabled && MekanismClient.voiceClient != null) { + MekanismClient.voiceClient.start(); + } + } + @SubscribeEvent public void onModelBake(ModelBakeEvent event) { IRegistry modelRegistry = event.getModelRegistry(); diff --git a/src/main/java/mekanism/client/MekanismClient.java b/src/main/java/mekanism/client/MekanismClient.java index b8205b924..8afe3f4c2 100644 --- a/src/main/java/mekanism/client/MekanismClient.java +++ b/src/main/java/mekanism/client/MekanismClient.java @@ -6,8 +6,10 @@ import java.util.UUID; import mekanism.api.MekanismAPI; import mekanism.api.MekanismAPI.BoxBlacklistEvent; import mekanism.client.render.obj.TransmitterModel; +import mekanism.client.voice.VoiceClient; import mekanism.common.Mekanism; import mekanism.common.base.IModule; +import mekanism.common.config.MekanismConfig.general; import mekanism.common.content.boiler.SynchronizedBoilerData; import mekanism.common.network.PacketKey.KeyMessage; import mekanism.common.security.SecurityData; @@ -20,6 +22,7 @@ public class MekanismClient extends Mekanism { public static Map clientSecurityMap = new HashMap<>(); public static Map clientUUIDMap = new HashMap<>(); + public static VoiceClient voiceClient; public static long ticksPassed = 0; public static void updateKey(KeyBinding key, int type) { @@ -35,6 +38,13 @@ public class MekanismClient extends Mekanism { clientSecurityMap.clear(); clientUUIDMap.clear(); + if (general.voiceServerEnabled) { + if (MekanismClient.voiceClient != null) { + MekanismClient.voiceClient.disconnect(); + MekanismClient.voiceClient = null; + } + } + ClientTickHandler.tickingSet.clear(); ClientTickHandler.portableTeleports.clear(); diff --git a/src/main/java/mekanism/client/MekanismKeyHandler.java b/src/main/java/mekanism/client/MekanismKeyHandler.java index af6d2541a..7db3411a9 100644 --- a/src/main/java/mekanism/client/MekanismKeyHandler.java +++ b/src/main/java/mekanism/client/MekanismKeyHandler.java @@ -47,18 +47,21 @@ public class MekanismKeyHandler extends MekKeyHandler { Keyboard.KEY_M, keybindCategory); public static KeyBinding armorModeSwitchKey = new KeyBinding("Mekanism " + LangUtils.localize("key.armorMode"), Keyboard.KEY_G, keybindCategory); + public static KeyBinding voiceKey = new KeyBinding("Mekanism " + LangUtils.localize("key.voice"), Keyboard.KEY_U, + keybindCategory); public static KeyBinding freeRunnerModeSwitchKey = new KeyBinding("Mekanism " + LangUtils.localize("key.feetMode"), Keyboard.KEY_H, keybindCategory); public static KeyBinding sneakKey = Minecraft.getMinecraft().gameSettings.keyBindSneak; public static KeyBinding jumpKey = Minecraft.getMinecraft().gameSettings.keyBindJump; public MekanismKeyHandler() { - super(new KeyBinding[]{modeSwitchKey, armorModeSwitchKey, freeRunnerModeSwitchKey}, - new boolean[]{false, false, false}); + super(new KeyBinding[]{modeSwitchKey, armorModeSwitchKey, freeRunnerModeSwitchKey, voiceKey}, + new boolean[]{false, false, false, true}); ClientRegistry.registerKeyBinding(modeSwitchKey); ClientRegistry.registerKeyBinding(armorModeSwitchKey); ClientRegistry.registerKeyBinding(freeRunnerModeSwitchKey); + ClientRegistry.registerKeyBinding(voiceKey); MinecraftForge.EVENT_BUS.register(this); } diff --git a/src/main/java/mekanism/client/voice/VoiceClient.java b/src/main/java/mekanism/client/voice/VoiceClient.java new file mode 100644 index 000000000..fcaa2454e --- /dev/null +++ b/src/main/java/mekanism/client/voice/VoiceClient.java @@ -0,0 +1,98 @@ +package mekanism.client.voice; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.net.ConnectException; +import java.net.Socket; +import javax.sound.sampled.AudioFormat; +import mekanism.common.Mekanism; +import mekanism.common.config.MekanismConfig.general; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class VoiceClient extends Thread { + + private AudioFormat format = new AudioFormat(16000F, 16, 1, true, true); + private VoiceOutput outputThread; + private VoiceInput inputThread; + private DataOutputStream output; + private DataInputStream input; + private boolean running; + private Socket socket; + private String ip; + + public VoiceClient(String s) { + ip = s; + } + + @Override + public void run() { + Mekanism.logger.info("VoiceServer: Starting client connection..."); + + try { + socket = new Socket(ip, general.VOICE_PORT); + running = true; + + input = new DataInputStream(new BufferedInputStream(socket.getInputStream())); + output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); + + (outputThread = new VoiceOutput(this)).start(); + (inputThread = new VoiceInput(this)).start(); + + Mekanism.logger.info("VoiceServer: Successfully connected to server."); + } catch (ConnectException e) { + Mekanism.logger.error("VoiceServer: Server's VoiceServer is disabled."); + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while starting client connection.", e); + } + } + + public void disconnect() { + Mekanism.logger.info("VoiceServer: Stopping client connection..."); + + try { + if (inputThread != null) { + inputThread.interrupt(); + inputThread.close(); + } + if (outputThread != null) { + outputThread.interrupt(); + outputThread.close(); + } + if (output != null) { + output.close(); + } + if (input != null) { + input.close(); + } + if (socket != null) { + socket.close(); + } + + interrupt(); + + running = false; + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while stopping client connection.", e); + } + } + + public boolean isRunning() { + return running; + } + + public DataOutputStream getOutputStream() { + return output; + } + + public DataInputStream getInputStream() { + return input; + } + + public AudioFormat getAudioFormat() { + return format; + } +} \ No newline at end of file diff --git a/src/main/java/mekanism/client/voice/VoiceInput.java b/src/main/java/mekanism/client/voice/VoiceInput.java new file mode 100644 index 000000000..ffe7054cd --- /dev/null +++ b/src/main/java/mekanism/client/voice/VoiceInput.java @@ -0,0 +1,92 @@ +package mekanism.client.voice; + +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.TargetDataLine; +import mekanism.client.MekanismKeyHandler; +import mekanism.common.Mekanism; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class VoiceInput extends Thread { + + private VoiceClient voiceClient; + private DataLine.Info microphone; + private TargetDataLine targetLine; + + public VoiceInput(VoiceClient client) { + voiceClient = client; + microphone = new DataLine.Info(TargetDataLine.class, voiceClient.getAudioFormat(), 2200); + + setDaemon(true); + setName("VoiceServer Client Input Thread"); + } + + @Override + public void run() { + try { + if (!AudioSystem.isLineSupported(microphone)) { + Mekanism.logger.info("No audio system available."); + return; + } + targetLine = ((TargetDataLine) AudioSystem.getLine(microphone)); + targetLine.open(voiceClient.getAudioFormat(), 2200); + targetLine.start(); + AudioInputStream audioInput = new AudioInputStream(targetLine); + + boolean doFlush = false; + + while (voiceClient.isRunning()) { + if (MekanismKeyHandler.voiceKey.isPressed()) { + targetLine.flush(); + + while (voiceClient.isRunning() && MekanismKeyHandler.voiceKey.isPressed()) { + try { + int availableBytes = audioInput.available(); + byte[] audioData = new byte[availableBytes > 2200 ? 2200 : availableBytes]; + int bytesRead = audioInput.read(audioData, 0, audioData.length); + + if (bytesRead > 0) { + voiceClient.getOutputStream().writeShort(audioData.length); + voiceClient.getOutputStream().write(audioData); + } + } catch (Exception ignored) { + } + } + + try { + Thread.sleep(200L); + } catch (Exception ignored) { + } + + doFlush = true; + } else if (doFlush) { + try { + voiceClient.getOutputStream().flush(); + } catch (Exception ignored) { + } + + doFlush = false; + } + + try { + Thread.sleep(20L); + } catch (Exception ignored) { + } + } + + audioInput.close(); + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while running client input thread.", e); + } + } + + public void close() { + if (targetLine != null) { + targetLine.flush(); + targetLine.close(); + } + } +} \ No newline at end of file diff --git a/src/main/java/mekanism/client/voice/VoiceOutput.java b/src/main/java/mekanism/client/voice/VoiceOutput.java new file mode 100644 index 000000000..729a0571c --- /dev/null +++ b/src/main/java/mekanism/client/voice/VoiceOutput.java @@ -0,0 +1,75 @@ +package mekanism.client.voice; + +import java.io.EOFException; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.SourceDataLine; +import mekanism.common.Mekanism; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class VoiceOutput extends Thread { + + private VoiceClient voiceClient; + private DataLine.Info speaker; + private SourceDataLine sourceLine; + + public VoiceOutput(VoiceClient client) { + voiceClient = client; + speaker = new DataLine.Info(SourceDataLine.class, voiceClient.getAudioFormat(), 2200); + + setDaemon(true); + setName("VoiceServer Client Output Thread"); + } + + @Override + public void run() { + try { + sourceLine = ((SourceDataLine) AudioSystem.getLine(speaker)); + sourceLine.open(voiceClient.getAudioFormat(), 2200); + sourceLine.start(); + byte[] audioData = new byte[4096]; //less allocation/gc (if done outside the loop) + int byteCount; + int length; + while (voiceClient.isRunning()) { + try { + if (voiceClient.getInputStream().available() > 0) { + //Why would we only read signed shorts? negative amount of waiting data doesn't make sense anyway :D + byteCount = voiceClient.getInputStream().readUnsignedShort(); + while (byteCount > 0 && voiceClient.isRunning()) { + length = audioData.length; + if (length > byteCount) { + length = byteCount; + } + //That one returns the actual read amount of data (we can begin transferring even if input + // is waiting/incomplete) + length = voiceClient.getInputStream().read(audioData, 0, length); + if (length < 0) { + throw new EOFException(); + } + sourceLine.write(audioData, 0, length); + byteCount -= length; + } + } else { + Thread.sleep(20); + } + } catch (EOFException eof) { + Mekanism.logger.error("VoiceServer: Unexpected input EOF Exception occurred."); + break; // voiceClient.input will continue throwing EOFs -> no need to go on checking + } catch (InterruptedException e) { + break; + } catch (Exception e) { + Mekanism.logger.error(e); + } + } + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while running client output thread.", e); + } + } + + public void close() { + sourceLine.flush(); + sourceLine.close(); + } +} \ No newline at end of file diff --git a/src/main/java/mekanism/common/CommonProxy.java b/src/main/java/mekanism/common/CommonProxy.java index 33fd2e251..0748b0304 100644 --- a/src/main/java/mekanism/common/CommonProxy.java +++ b/src/main/java/mekanism/common/CommonProxy.java @@ -57,7 +57,6 @@ import mekanism.common.inventory.container.robit.ContainerRobitMain; import mekanism.common.inventory.container.robit.ContainerRobitRepair; import mekanism.common.inventory.container.robit.ContainerRobitSmelting; import mekanism.common.item.ItemPortableTeleporter; -import mekanism.common.multiblock.UpdateProtocol.NodeChecker; import mekanism.common.network.PacketPortableTeleporter.PortableTeleporterMessage; import mekanism.common.tile.TileEntityChanceMachine; import mekanism.common.tile.TileEntityChemicalCrystallizer; @@ -80,7 +79,6 @@ import mekanism.common.tile.TileEntityInductionCasing; import mekanism.common.tile.TileEntityLaserAmplifier; import mekanism.common.tile.TileEntityLaserTractorBeam; import mekanism.common.tile.TileEntityMetallurgicInfuser; -import mekanism.common.tile.TileEntityMultiblock; import mekanism.common.tile.TileEntityOredictionificator; import mekanism.common.tile.TileEntityPRC; import mekanism.common.tile.TileEntityQuantumEntangloporter; @@ -97,6 +95,7 @@ import mekanism.common.tile.prefab.TileEntityDoubleElectricMachine; import mekanism.common.tile.prefab.TileEntityElectricMachine; import mekanism.common.util.UnitDisplayUtils.EnergyType; import mekanism.common.util.UnitDisplayUtils.TempType; +import mekanism.common.voice.VoiceServerManager; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -173,6 +172,8 @@ public class CommonProxy implements IGuiProvider { .getBoolean(); general.dynamicTankEasterEgg = Mekanism.configuration .get(Configuration.CATEGORY_GENERAL, "DynamicTankEasterEgg", false, "Audible sparkles.").getBoolean(); + general.voiceServerEnabled = Mekanism.configuration + .get(Configuration.CATEGORY_GENERAL, "WalkieTalkieServerEnabled", false).getBoolean(); general.cardboardSpawners = Mekanism.configuration .get(Configuration.CATEGORY_GENERAL, "AllowSpawnerBoxPickup", true, "Allows vanilla spawners to be moved with a Cardboard Box.").getBoolean(); @@ -253,6 +254,8 @@ public class CommonProxy implements IGuiProvider { general.DISASSEMBLER_USAGE = Mekanism.configuration .get(Configuration.CATEGORY_GENERAL, "DisassemblerEnergyUsage", 10, "Base Energy (Joules) usage of the Atomic Disassembler.").getInt(); + general.VOICE_PORT = Mekanism.configuration + .get(Configuration.CATEGORY_GENERAL, "VoicePort", 36123, null, 1, 65535).getInt(); //If this is less than 1, upgrades make machines worse. If less than 0, I don't even know. general.maxUpgradeMultiplier = Mekanism.configuration .get(Configuration.CATEGORY_GENERAL, "UpgradeModifier", 10, @@ -514,13 +517,15 @@ public class CommonProxy implements IGuiProvider { /** * Does the multiblock creation animation, starting from the rendering block. */ - public void doMultiblockSparkle(TileEntity tileEntity, BlockPos corner1, BlockPos corner2, INodeChecker checker) {} + public void doMultiblockSparkle(TileEntity tileEntity, BlockPos corner1, BlockPos corner2, INodeChecker checker) { + } /** * Does the multiblock creation animation, starting from the rendering block. */ public void doMultiblockSparkle(TileEntity tileEntity, BlockPos renderLoc, int length, int width, int height, - INodeChecker checker) {} + INodeChecker checker) { + } @Override public Object getClientGui(int ID, EntityPlayer player, World world, BlockPos pos) { @@ -723,6 +728,9 @@ public class CommonProxy implements IGuiProvider { BlockStateMachine.MachineType.updateAllUsages(); + if (general.voiceServerEnabled && Mekanism.voiceManager == null) { + Mekanism.voiceManager = new VoiceServerManager(); + } if (fromPacket) { Mekanism.logger.info("Received config from server."); } diff --git a/src/main/java/mekanism/common/Mekanism.java b/src/main/java/mekanism/common/Mekanism.java index 988b78201..d34d14051 100644 --- a/src/main/java/mekanism/common/Mekanism.java +++ b/src/main/java/mekanism/common/Mekanism.java @@ -137,6 +137,7 @@ import mekanism.common.transmitters.grid.EnergyNetwork.EnergyTransferEvent; import mekanism.common.transmitters.grid.FluidNetwork.FluidTransferEvent; import mekanism.common.transmitters.grid.GasNetwork.GasTransferEvent; import mekanism.common.util.MekanismUtils; +import mekanism.common.voice.VoiceServerManager; import mekanism.common.world.GenHandler; import net.minecraft.block.Block; import net.minecraft.entity.EnumCreatureType; @@ -267,6 +268,10 @@ public class Mekanism { * changes. */ public static int baseWorldGenVersion = 0; + /** + * The VoiceServer manager for walkie talkies + */ + public static VoiceServerManager voiceManager; /** * The GameProfile used by the dummy Mekanism player */ @@ -864,11 +869,18 @@ public class Mekanism { @EventHandler public void serverStarting(FMLServerStartingEvent event) { + if (general.voiceServerEnabled) { + voiceManager.start(); + } CommandMek.register(event); } @EventHandler public void serverStopping(FMLServerStoppingEvent event) { + if (general.voiceServerEnabled) { + voiceManager.stop(); + } + //Clear all cache data playerState.clear(); activeVibrators.clear(); @@ -979,6 +991,11 @@ public class Mekanism { //Register this module's GUI handler in the simple packet protocol PacketSimpleGui.handlers.add(0, proxy); + //Set up VoiceServerManager + if (general.voiceServerEnabled) { + voiceManager = new VoiceServerManager(); + } + //Register with TransmitterNetworkRegistry TransmitterNetworkRegistry.initiate(); diff --git a/src/main/java/mekanism/common/config/MekanismConfig.java b/src/main/java/mekanism/common/config/MekanismConfig.java index ca12b6a7d..f1b8869aa 100644 --- a/src/main/java/mekanism/common/config/MekanismConfig.java +++ b/src/main/java/mekanism/common/config/MekanismConfig.java @@ -13,6 +13,7 @@ public class MekanismConfig { public static boolean controlCircuitOreDict = true; public static boolean logPackets = false; public static boolean dynamicTankEasterEgg = false; + public static boolean voiceServerEnabled = false; public static boolean cardboardSpawners = true; public static boolean enableWorldRegeneration = true; public static boolean spawnBabySkeletons = true; @@ -27,6 +28,7 @@ public class MekanismConfig { public static int saltMaxVeinSize = 6; public static int obsidianTNTDelay = 100; public static int UPDATE_DELAY = 10; + public static int VOICE_PORT = 36123; public static int maxUpgradeMultiplier = 10; public static int userWorldGenVersion = 0; public static double ENERGY_PER_REDSTONE = 10000; diff --git a/src/main/java/mekanism/common/item/ItemWalkieTalkie.java b/src/main/java/mekanism/common/item/ItemWalkieTalkie.java index c3cdd9e9f..64811c917 100644 --- a/src/main/java/mekanism/common/item/ItemWalkieTalkie.java +++ b/src/main/java/mekanism/common/item/ItemWalkieTalkie.java @@ -7,6 +7,7 @@ import java.util.Map; import javax.annotation.Nonnull; import mekanism.api.EnumColor; import mekanism.common.base.IItemNetwork; +import mekanism.common.config.MekanismConfig.general; import mekanism.common.util.ItemDataUtils; import mekanism.common.util.LangUtils; import net.minecraft.client.renderer.block.model.ModelResourceLocation; @@ -48,6 +49,9 @@ public class ItemWalkieTalkie extends ItemMekanism implements IItemNetwork { .localize("gui." + (getOn(itemstack) ? "on" : "off"))); list.add(EnumColor.DARK_AQUA + LangUtils.localize("tooltip.channel") + ": " + EnumColor.GREY + getChannel( itemstack)); + if (!general.voiceServerEnabled) { + list.add(EnumColor.DARK_RED + LangUtils.localize("tooltip.walkie_disabled")); + } } @Nonnull diff --git a/src/main/java/mekanism/common/network/PacketConfigSync.java b/src/main/java/mekanism/common/network/PacketConfigSync.java index b7d7a3ad3..f40db44fd 100644 --- a/src/main/java/mekanism/common/network/PacketConfigSync.java +++ b/src/main/java/mekanism/common/network/PacketConfigSync.java @@ -31,6 +31,7 @@ public class PacketConfigSync implements IMessageHandler l = Collections + .synchronizedList(new ArrayList<>(server.getPlayerList().getPlayers())); + + for (EntityPlayerMP playerMP : l) { + String playerIP = playerMP.getPlayerIP(); + + if (!server.isDedicatedServer() && playerIP.equals("local") && !Mekanism.voiceManager + .isFoundLocal()) { + Mekanism.voiceManager.setFoundLocal(true); + uuid = playerMP.getUniqueID(); + break; + } else if (playerIP.equals(socket.getInetAddress().getHostAddress())) { + uuid = playerMP.getUniqueID(); + break; + } + } + + retryCount++; + Thread.sleep(50); + } catch (Exception ignored) { + } + } + + if (uuid == null) { + Mekanism.logger.error("VoiceServer: Unable to trace connection's IP address."); + kill(); + return; + } else { + Mekanism.logger.info("VoiceServer: Traced IP in " + retryCount + " attempts."); + } + } + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while starting server-based connection.", e); + open = false; + } + + // Main client listen thread + new Thread(() -> { + while (open) { + try { + short byteCount = VoiceConnection.this.input.readShort(); + byte[] audioData = new byte[byteCount]; + VoiceConnection.this.input.readFully(audioData); + + if (byteCount > 0) { + Mekanism.voiceManager.sendToPlayers(byteCount, audioData, VoiceConnection.this); + } + } catch (Exception e) { + open = false; + } + } + + if (!open) { + kill(); + } + }).start(); + } + + private void kill() { + try { + if (input != null) { + input.close(); + } + if (output != null) { + output.close(); + } + if (socket != null) { + socket.close(); + } + Mekanism.voiceManager.removeConnection(this); + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while stopping server-based connection.", e); + } + } + + public void sendToPlayer(short byteCount, byte[] audioData, VoiceConnection connection) { + if (!open) { + kill(); + } + + try { + output.writeShort(byteCount); + output.write(audioData); + + output.flush(); + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while sending data to player.", e); + } + } + + public boolean canListen(int channel) { + return getPlayer().inventory.mainInventory.stream().anyMatch(itemStack -> canListen(channel, itemStack)) + || getPlayer().inventory.offHandInventory.stream().anyMatch(itemStack -> canListen(channel, itemStack)); + } + + private boolean canListen(int channel, ItemStack itemStack) { + if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemWalkieTalkie) { + ItemWalkieTalkie walkieTalkie = (ItemWalkieTalkie) itemStack.getItem(); + return walkieTalkie.getOn(itemStack) && walkieTalkie.getChannel(itemStack) == channel; + } + + return false; + } + + public int getCurrentChannel() { + ItemStack itemStack = getPlayer().inventory.getCurrentItem(); + + if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemWalkieTalkie) { + ItemWalkieTalkie walkieTalkie = (ItemWalkieTalkie) itemStack.getItem(); + if (walkieTalkie.getOn(itemStack)) { + return walkieTalkie.getChannel(itemStack); + } + } + + return 0; + } + + public EntityPlayerMP getPlayer() { + return server.getPlayerList().getPlayerByUUID(uuid); + } +} \ No newline at end of file diff --git a/src/main/java/mekanism/common/voice/VoiceServerManager.java b/src/main/java/mekanism/common/voice/VoiceServerManager.java new file mode 100644 index 000000000..cc8a62b16 --- /dev/null +++ b/src/main/java/mekanism/common/voice/VoiceServerManager.java @@ -0,0 +1,107 @@ +package mekanism.common.voice; + +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; +import java.util.HashSet; +import java.util.Set; +import mekanism.common.Mekanism; +import mekanism.common.config.MekanismConfig.general; + +public class VoiceServerManager { + + private Set connections = new HashSet<>(); + private ServerSocket serverSocket; + private Thread listenThread; + private boolean foundLocal = false; + private boolean running; + + public void start() { + Mekanism.logger.info("VoiceServer: Starting up server..."); + + try { + running = true; + serverSocket = new ServerSocket(general.VOICE_PORT); + (listenThread = new ListenThread()).start(); + } catch (Exception ignored) { + } + } + + public void stop() { + try { + Mekanism.logger.info("VoiceServer: Shutting down server..."); + + try { + listenThread.interrupt(); + } catch (Exception ignored) { + } + + foundLocal = false; + + try { + serverSocket.close(); + serverSocket = null; + } catch (Exception ignored) { + } + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while shutting down server.", e); + } + + running = false; + } + + public void removeConnection(VoiceConnection connection) { + connections.remove(connection); + } + + public boolean isFoundLocal() { + return foundLocal; + } + + public void setFoundLocal(boolean found) { + foundLocal = found; + } + + public void sendToPlayers(short byteCount, byte[] audioData, VoiceConnection connection) { + if (connection.getPlayer() == null) { + return; + } + + int channel = connection.getCurrentChannel(); + + if (channel == 0) { + return; + } + + for (VoiceConnection iterConn : connections) { + if (iterConn.getPlayer() != null && iterConn != connection && iterConn.canListen(channel)) { + iterConn.sendToPlayer(byteCount, audioData, connection); + } + } + } + + private class ListenThread extends Thread { + + private ListenThread() { + setDaemon(true); + setName("VoiceServer Listen Thread"); + } + + @Override + public void run() { + while (running) { + try { + Socket s = serverSocket.accept(); + VoiceConnection connection = new VoiceConnection(s); + connection.start(); + connections.add(connection); + + Mekanism.logger.info("VoiceServer: Accepted new connection."); + } catch (SocketException | NullPointerException ignored) { + } catch (Exception e) { + Mekanism.logger.error("VoiceServer: Error while accepting connection.", e); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/resources/assets/mekanism/lang/en_us.lang b/src/main/resources/assets/mekanism/lang/en_us.lang index fd0476ca9..f4a61019d 100644 --- a/src/main/resources/assets/mekanism/lang/en_us.lang +++ b/src/main/resources/assets/mekanism/lang/en_us.lang @@ -757,6 +757,7 @@ tooltip.diversionDesc=Controllable by redstone tooltip.noGas=No gas stored tooltip.stored=Stored tooltip.channel=Channel +tooltip.walkie_disabled=Voice server disabled. tooltip.mode=Mode tooltip.efficiency=Efficiency tooltip.modeToggle=Mode toggled to diff --git a/src/main/resources/assets/mekanism/recipes/walkietalkie.json b/src/main/resources/assets/mekanism/recipes/walkietalkie.json new file mode 100644 index 000000000..7b7446ac1 --- /dev/null +++ b/src/main/resources/assets/mekanism/recipes/walkietalkie.json @@ -0,0 +1,24 @@ +{ + "result": { + "item": "mekanism:walkietalkie" + }, + "pattern": [ + " O", + "SCS", + " S " + ], + "type": "forge:ore_shaped", + "key": { + "S": { + "ore": "ingotSteel", + "type": "forge:ore_dict" + }, + "C": { + "item": "#CIRCUITBASIC" + }, + "O": { + "ore": "ingotOsmium", + "type": "forge:ore_dict" + } + } +} \ No newline at end of file