From bb60ad979a79da5510b2bad3eb1e569f7e36bf61 Mon Sep 17 00:00:00 2001 From: Hilligans Date: Tue, 2 Jan 2024 12:30:37 -0600 Subject: [PATCH] Fixed some server stuff and added thread tracking --- .../dev/hilligans/ourcraft/ClientMain.java | 12 +++--- .../dev/hilligans/ourcraft/GameInstance.java | 7 ++- .../java/dev/hilligans/ourcraft/Ourcraft.java | 6 ++- .../dev/hilligans/ourcraft/ServerMain.java | 2 + .../dev/hilligans/ourcraft/client/Client.java | 2 - .../ourcraft/client/ClientPlayerData.java | 5 ++- .../graphics/opengl/OpenGLEngine.java | 2 +- .../graphics/opengl/OpenGLWindow.java | 8 ++-- .../graphics/opengl/OpenglDefaultImpl.java | 5 +++ .../graphics/tasks/ChunkDebugRenderTask.java | 8 ++-- .../vulkan/boilerplate/LogicalDevice.java | 3 +- .../client/rendering/newrenderer/Image.java | 2 +- .../rendering/newrenderer/TextAtlas.java | 2 +- .../rendering/newrenderer/TextureAtlas.java | 43 ++++++++++++++----- .../widgets/ServerSelectorWidget.java | 1 + .../rendering/world/StringRenderer.java | 16 ++++--- .../ourcraft/network/ClientNetwork.java | 4 +- .../network/ClientNetworkHandler.java | 8 ++-- .../hilligans/ourcraft/network/Network.java | 2 +- .../ourcraft/network/NetworkHandler.java | 8 ++-- .../ourcraft/network/PacketByteArray.java | 9 +++- .../ourcraft/network/PacketData.java | 39 ----------------- .../ourcraft/network/ServerNetwork.java | 3 +- .../network/ServerNetworkHandler.java | 2 +- .../network/debug/PacketTraceByteArray.java | 24 ----------- .../packet/client/CHandshakePacket.java | 2 + .../ourcraft/resource/ResourceManager.java | 8 +++- .../ourcraft/server/MultiPlayerServer.java | 6 +-- .../ourcraft/util/NamedThreadFactory.java | 11 ++--- .../ourcraft/util/ThreadProvider.java | 10 ++++- .../ourcraft/util/TrackedThread.java | 17 ++++++++ 31 files changed, 145 insertions(+), 132 deletions(-) delete mode 100644 src/main/java/dev/hilligans/ourcraft/network/PacketData.java create mode 100644 src/main/java/dev/hilligans/ourcraft/util/TrackedThread.java diff --git a/src/main/java/dev/hilligans/ourcraft/ClientMain.java b/src/main/java/dev/hilligans/ourcraft/ClientMain.java index fd7f57ff..ae1d995a 100644 --- a/src/main/java/dev/hilligans/ourcraft/ClientMain.java +++ b/src/main/java/dev/hilligans/ourcraft/ClientMain.java @@ -14,8 +14,6 @@ public class ClientMain { - //public static GameInstance gameInstance = Ourcraft.GAME_INSTANCE; - public static ArgumentContainer argumentContainer; public static long start = System.currentTimeMillis(); @@ -32,6 +30,7 @@ public static void main(String[] args) throws IOException { gameInstance.handleArgs(args); gameInstance.side = Side.CLIENT; gameInstance.loadContent(); + gameInstance.THREAD_PROVIDER.map(); Thread serverThread = null; if(argumentContainer.getBoolean("--integratedServer", false)) { @@ -46,17 +45,18 @@ public static void main(String[] args) throws IOException { } Client client = new Client(gameInstance, argumentContainer); - // Client client1 = new Client(gameInstance, argumentContainer); + Client client1 = new Client(gameInstance, argumentContainer); String graphicsEngine = argumentContainer.getString("--graphicsEngine", null); if(graphicsEngine != null) { System.out.println(graphicsEngine); client.setGraphicsEngine(gameInstance.GRAPHICS_ENGINES.get(graphicsEngine)); - // client1.setGraphicsEngine(gameInstance.GRAPHICS_ENGINES.get(graphicsEngine)); + client1.setGraphicsEngine(gameInstance.GRAPHICS_ENGINES.get(graphicsEngine)); } - //client1.setupClient(); + client1.setupClient(); client.startClient(); + + gameInstance.THREAD_PROVIDER.EXECUTOR.shutdownNow(); - Ourcraft.EXECUTOR.shutdownNow(); if(argumentContainer.getBoolean("--integratedServer", false)) { ServerMain.getServer().stop(); } diff --git a/src/main/java/dev/hilligans/ourcraft/GameInstance.java b/src/main/java/dev/hilligans/ourcraft/GameInstance.java index 104b41c5..0e748d30 100644 --- a/src/main/java/dev/hilligans/ourcraft/GameInstance.java +++ b/src/main/java/dev/hilligans/ourcraft/GameInstance.java @@ -59,8 +59,7 @@ public class GameInstance { public final EventBus EVENT_BUS = new EventBus(); public final ModLoader MOD_LOADER = new ModLoader(this); public final Logger LOGGER = new Logger("", ""); - public final ExecutorService EXECUTOR = Executors.newFixedThreadPool(2,new NamedThreadFactory("random_executor")); - public final ResourceManager RESOURCE_MANAGER = new ResourceManager(); + public final ResourceManager RESOURCE_MANAGER = new ResourceManager(this); public final ModContent OURCRAFT = new ModContent("ourcraft",this).addClassLoader(new URLClassLoader(new URL[]{Ourcraft.class.getProtectionDomain().getCodeSource().getLocation()})).addMainClass(Ourcraft.class); public final ContentPack CONTENT_PACK = new ContentPack(this); public final AtomicBoolean REBUILDING = new AtomicBoolean(false); @@ -332,6 +331,10 @@ public void registerLayoutEngine(ILayoutEngine... layoutEngines) { LAYOUT_ENGINES.putAll(layoutEngines); } + public void register(IRegistryElement registryElement) { + register(registryElement.getIdentifierName(), registryElement); + } + public void register(String name, Object o) { boolean put = false; for(Registry registry : REGISTRIES.ELEMENTS) { diff --git a/src/main/java/dev/hilligans/ourcraft/Ourcraft.java b/src/main/java/dev/hilligans/ourcraft/Ourcraft.java index f71bdb98..b5419fcb 100644 --- a/src/main/java/dev/hilligans/ourcraft/Ourcraft.java +++ b/src/main/java/dev/hilligans/ourcraft/Ourcraft.java @@ -31,6 +31,7 @@ import dev.hilligans.ourcraft.resource.loaders.JsonLoader; import dev.hilligans.ourcraft.resource.ResourceManager; import dev.hilligans.ourcraft.schematic.LitematicaSchematicLoader; +import dev.hilligans.ourcraft.util.ArgumentContainer; import dev.hilligans.ourcraft.util.NamedThreadFactory; import at.favre.lib.crypto.bcrypt.BCrypt; import dev.hilligans.ourcraft.util.Side; @@ -55,8 +56,9 @@ public class Ourcraft { public static final GameInstance GAME_INSTANCE = new GameInstance(); - public static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(2,new NamedThreadFactory("random_executor")); - + public static final ArgumentContainer getArgumentContainer() { + return ClientMain.argumentContainer; + } public static String path = System.getProperty("user.dir"); public static String hashString(String password, String salt) { diff --git a/src/main/java/dev/hilligans/ourcraft/ServerMain.java b/src/main/java/dev/hilligans/ourcraft/ServerMain.java index b07260f4..3baf5b88 100644 --- a/src/main/java/dev/hilligans/ourcraft/ServerMain.java +++ b/src/main/java/dev/hilligans/ourcraft/ServerMain.java @@ -36,6 +36,7 @@ public static void main(String[] args) { public static IServer server(GameInstance gameInstance, ArgumentContainer argumentContainer) { ServerMain.argumentContainer = argumentContainer; + gameInstance.THREAD_PROVIDER.map(); //ServerWorld world = new ServerWorld(gameInstance); //world.worldBuilders.add(new OreBuilder("ore", Blocks.GRASS,Blocks.STONE).setFrequency(20)); @@ -56,6 +57,7 @@ public static IServer server(GameInstance gameInstance, ArgumentContainer argume server.addWorld(world1); System.out.println("starting server"); server.startServer("25588"); + gameInstance.THREAD_PROVIDER.unmap(); return server; } diff --git a/src/main/java/dev/hilligans/ourcraft/client/Client.java b/src/main/java/dev/hilligans/ourcraft/client/Client.java index 52fb729e..8c297831 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/Client.java +++ b/src/main/java/dev/hilligans/ourcraft/client/Client.java @@ -57,7 +57,6 @@ public class Client implements IClientPacketHandler { public int playerId; - public boolean joinServer = true; public boolean valid = false; public boolean screenShot = false; public boolean renderWorld = false; @@ -73,7 +72,6 @@ public class Client implements IClientPacketHandler { public SoundEngine soundEngine; public ClientPlayerData playerData = new ClientPlayerData(); - //public IWorld newClientWorld = new SimpleWorld(0,""); public IWorld newClientWorld; public MultiPlayerServer multiPlayerServer; diff --git a/src/main/java/dev/hilligans/ourcraft/client/ClientPlayerData.java b/src/main/java/dev/hilligans/ourcraft/client/ClientPlayerData.java index 5f4199e8..2898d6e2 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/ClientPlayerData.java +++ b/src/main/java/dev/hilligans/ourcraft/client/ClientPlayerData.java @@ -6,6 +6,7 @@ import dev.hilligans.ourcraft.util.Settings; import java.util.HashMap; +import java.util.concurrent.atomic.AtomicInteger; public class ClientPlayerData { @@ -20,7 +21,7 @@ public class ClientPlayerData { public boolean spectator = true; public String authToken = ""; - public String userName = ""; + public String userName = "" + x.getAndIncrement(); public String email = ""; public String login_token = ""; public boolean valid_account = false; @@ -40,4 +41,6 @@ public T get(String key, T clazz) { public T set(String key, T newValue) { return (T) arbDataMap.put(key, newValue); } + + public static AtomicInteger x = new AtomicInteger(); } diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLEngine.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLEngine.java index 9345887d..cf152794 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLEngine.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLEngine.java @@ -48,7 +48,7 @@ public OpenGLWindow createWindow() { renderWindow.setRenderPipeline(gameInstance.ARGUMENTS.getString("--renderPipeline", "ourcraft:menu_pipeline")); windows.add(renderWindow); renderWindow.setup(); - GL.createCapabilities(); + //GL.createCapabilities(); glEnable(GL_DEBUG_OUTPUT); glEnable(GL_BLEND); diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLWindow.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLWindow.java index 93717d59..556bde62 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLWindow.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenGLWindow.java @@ -78,10 +78,10 @@ public void swapBuffers(GraphicsContext graphicsContext) { } client.rendering = false; client.soundEngine.tick(); - if(client.screenShot) { - client.screenShot = false; - ScreenShot.takeScreenShot(this); - } +// if(client.screenShot) { +// client.screenShot = false; +// ScreenShot.takeScreenShot(this); +// } glfwPollEvents(); tick(); } diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenglDefaultImpl.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenglDefaultImpl.java index 4db188e4..a042af3e 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenglDefaultImpl.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/opengl/OpenglDefaultImpl.java @@ -201,6 +201,11 @@ public void bindTexture(GraphicsContext graphicsContext, long texture) { if(texture == 0) { throw new NullPointerException(); } + if(trackingResourceAllocations) { + if(textureAllocationTracker.get((int)texture) == null) { + throw new RuntimeException("Unknown texture with texture id " + texture); + } + } if(texture != boundTexture) { GL20.glBindTexture(textureTypes.get((int)texture), (int)texture); boundTexture = texture; diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/tasks/ChunkDebugRenderTask.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/tasks/ChunkDebugRenderTask.java index 9041cfe0..e649077a 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/tasks/ChunkDebugRenderTask.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/tasks/ChunkDebugRenderTask.java @@ -60,14 +60,16 @@ public void draw(RenderWindow window, GraphicsContext graphicsContext, IGraphics worldStack.push(); worldStack.translate((chunkX) * chunkWidth, (chunkY) * chunkHeight, (chunkZ) * chunkWidth); if (chunk != null) { - if(chunkX-playerChunkPos.x == 0 && chunkY-playerChunkPos.y == 0 && chunkZ-playerChunkPos.z == 0) { + if (chunkX - playerChunkPos.x == 0 && chunkY - playerChunkPos.y == 0 && chunkZ - playerChunkPos.z == 0) { worldStack.setColor(0, 255, 0, 255); } else { worldStack.setColor(255, 255, 0, 255); } - impl.uploadMatrix(graphicsContext, worldStack, shaderSource); - impl.drawMesh(graphicsContext, worldStack, mesh, 0, meshBuilder.indices.size()); + } else { + worldStack.setColor(255, 0, 0, 255); } + impl.uploadMatrix(graphicsContext, worldStack, shaderSource); + impl.drawMesh(graphicsContext, worldStack, mesh, 0, meshBuilder.indices.size()); worldStack.pop(); }); impl.destroyMesh(graphicsContext, mesh); diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/vulkan/boilerplate/LogicalDevice.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/vulkan/boilerplate/LogicalDevice.java index 3b280e23..06c41ce9 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/vulkan/boilerplate/LogicalDevice.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/graphics/vulkan/boilerplate/LogicalDevice.java @@ -26,12 +26,13 @@ public class LogicalDevice { public VulkanQueueFamilyManager queueFamilyManager; public VkDeviceQueueCreateInfo.Buffer buffer; public VertexBufferManager bufferManager = new VertexBufferManager(this); - public final ExecutorService cleanup = Executors.newSingleThreadExecutor(new NamedThreadFactory("Vulkan cleanup")); + public final ExecutorService cleanup; public AtomicBoolean alive = new AtomicBoolean(true); public LogicalDevice(PhysicalDevice physicalDevice) { this.vulkanInstance = physicalDevice.vulkanInstance; this.physicalDevice = physicalDevice; + this.cleanup = Executors.newSingleThreadExecutor(new NamedThreadFactory("Vulkan cleanup", physicalDevice.vulkanInstance.engine.getGameInstance())); memoryManager = new VulkanMemoryManager(this); getMemoryAllocations(); diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/Image.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/Image.java index 37bc360c..a6bfc735 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/Image.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/Image.java @@ -23,7 +23,7 @@ public Image(int width, int height) { } public Image(int width, int height, int format) { - this(width,height,format,ByteBuffer.allocateDirect(width * height * format)); + this(width,height,format, ByteBuffer.allocateDirect(width * height * format)); } public Image(int width, int height, int format, ByteBuffer byteBuffer) { diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextAtlas.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextAtlas.java index 2b77ef98..ed9514cf 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextAtlas.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextAtlas.java @@ -66,7 +66,7 @@ private long getLong(long size, int x, int y) { public void assemble(GameInstance gameInstance) { long start = System.currentTimeMillis(); - executorService = Executors.newFixedThreadPool(4,new NamedThreadFactory("texture_atlas_builder")); + executorService = Executors.newFixedThreadPool(4, new NamedThreadFactory("texture_atlas_builder", gameInstance)); time = 0; count = 0; for(ImageLocation imageLocation : images) { diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextureAtlas.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextureAtlas.java index 1b5b6968..47859bfa 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextureAtlas.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/newrenderer/TextureAtlas.java @@ -56,7 +56,7 @@ public synchronized int addImage(BufferedImage img, int width) { TextureAtlas.ImageHolder imageHolder = new TextureAtlas.ImageHolder(width,imageHolders.size(), this); Triplet val = imageHolder.getNextID(); - gameInstance.THREAD_PROVIDER.submit(() -> imageHolder.addTexture(img, val.typeB, val.typeC)); + gameInstance.THREAD_PROVIDER.execute(() -> imageHolder.addTexture(img, val.typeB, val.typeC)); imageHolders.add(imageHolder); id = val.typeA; imageMap.put(id,imageHolder); @@ -65,13 +65,13 @@ public synchronized int addImage(BufferedImage img, int width) { } public dev.hilligans.ourcraft.client.rendering.newrenderer.Image toImage() { - BufferedImage img; + Image img; if(imageHolders.size() != 0) { - img = imageHolders.get(0).bufferedImage; + img = imageHolders.get(0).image; for (int x = 1; x < imageHolders.size(); x++) { - img = joinImage(img, imageHolders.get(x).bufferedImage); + img = joinImage(img, imageHolders.get(x).image=null); } - return new Image(img); + return img; } return null; } @@ -129,12 +129,29 @@ public static BufferedImage joinImage(BufferedImage img1, BufferedImage img2) { return img; } + public static Image joinImage(Image img1, Image img2) { + int width = img1.getWidth() + img2.getWidth(); + int height = Math.max(img1.getHeight(),img2.getHeight()); + Image img = new Image(width,height,4); + for(int x = 0; x < img1.getWidth(); x++) { + for(int y = 0; y < img1.getHeight(); y++) { + img.putPixel(x,y,img1.getPixel(x,y)); + } + } + for(int x = 0; x < img2.getWidth(); x++) { + for(int y = 0; y < img2.getHeight(); y++) { + img.putPixel(x + img1.getWidth(),y,img2.getPixel(x,y)); + } + } + return img; + } + public static class ImageHolder { public double imageSize; int count; - public BufferedImage bufferedImage; + public Image image; int width = 0; int height = 0; @@ -148,10 +165,13 @@ public ImageHolder(int imageSize, int id, TextureAtlas textureAtlas) { this.imageSize = imageSize; this.id = id; this.textureAtlas = textureAtlas; - bufferedImage = new BufferedImage(textureAtlas.maxTextureSize,textureAtlas.maxTextureSize,BufferedImage.TYPE_INT_ARGB); - for(int y = 0; y < bufferedImage.getHeight(); y++) { - for(int x = 0; x < bufferedImage.getWidth(); x++) { - bufferedImage.setRGB(x,y,new Color(255,255,255,127).getRGB()); + image = new Image(textureAtlas.maxTextureSize, textureAtlas.maxTextureSize, 4); + //bufferedImage = new BufferedImage(textureAtlas.maxTextureSize,textureAtlas.maxTextureSize,BufferedImage.TYPE_INT_ARGB); + int color = new Color(255,255,255,127).getRGB(); + for(int y = 0; y < image.getHeight(); y++) { + for(int x = 0; x < image.getWidth(); x++) { + image.putPixel(x, y, color); + //bufferedImage.setRGB(x,y,); } } count = textureAtlas.maxTextureSize / imageSize; @@ -160,7 +180,8 @@ public ImageHolder(int imageSize, int id, TextureAtlas textureAtlas) { public void addTexture(BufferedImage img, int width, int height) { for(int y = 0; y < Math.min(img.getHeight(),imageSize); y++) { for(int x = 0; x < Math.min(img.getWidth(),64); x++) { - bufferedImage.setRGB(x + width * (int)imageSize, y + height * (int)imageSize, img.getRGB(x,y)); + //bufferedImage.setRGB(x + width * (int)imageSize, y + height * (int)imageSize, img.getRGB(x,y)); + image.putPixel((int) (x + width * imageSize), (int) (y + height * imageSize), img.getRGB(x,y)); } } } diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/widgets/ServerSelectorWidget.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/widgets/ServerSelectorWidget.java index cab9a7bd..d0f14ae9 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/widgets/ServerSelectorWidget.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/widgets/ServerSelectorWidget.java @@ -34,6 +34,7 @@ public void render(RenderWindow window, GraphicsContext graphicsContext, MatrixS public void joinServer() { try { screenBase.getClient().network.joinServer(ip,port, screenBase.getClient()); + Thread.sleep(1000); screenBase.getClient().closeScreen(); screenBase.getClient().serverIP = ip + ":" + port; screenBase.window.queueRenderPipeline("ourcraft:new_world_pipeline"); diff --git a/src/main/java/dev/hilligans/ourcraft/client/rendering/world/StringRenderer.java b/src/main/java/dev/hilligans/ourcraft/client/rendering/world/StringRenderer.java index e353b1e0..ced2588d 100644 --- a/src/main/java/dev/hilligans/ourcraft/client/rendering/world/StringRenderer.java +++ b/src/main/java/dev/hilligans/ourcraft/client/rendering/world/StringRenderer.java @@ -154,14 +154,16 @@ public void draw1(RenderWindow window, GraphicsContext graphicsContext, MatrixSt PrimitiveBuilder primitiveBuilder = primitiveBuilders.get(val); primitiveBuilder.translate(1.0f,0,1.0f); IDefaultEngineImpl impl = window.getEngineImpl(); - impl.uploadMatrix(graphicsContext,matrixStack,shaderSource); - impl.bindPipeline(graphicsContext,shaderSource.program); - impl.bindTexture(graphicsContext,textureAtlas.glTextureId); - impl.drawAndDestroyMesh(graphicsContext,matrixStack,primitiveBuilder.toVertexMesh()); + if(textureAtlas.glTextureId != -1) { + impl.uploadMatrix(graphicsContext, matrixStack, shaderSource); + impl.bindPipeline(graphicsContext, shaderSource.program); + impl.bindTexture(graphicsContext, textureAtlas.glTextureId); + impl.drawAndDestroyMesh(graphicsContext, matrixStack, primitiveBuilder.toVertexMesh()); + } }); } - public Int2ObjectOpenHashMap textureAtlases = new Int2ObjectOpenHashMap<>(); + public final Int2ObjectOpenHashMap textureAtlases = new Int2ObjectOpenHashMap<>(); public Char2IntOpenHashMap charMap = new Char2IntOpenHashMap(); public Char2IntOpenHashMap idMap = new Char2IntOpenHashMap(); public Int2BooleanArrayMap texturesBuilt = new Int2BooleanArrayMap(); @@ -172,7 +174,9 @@ public void buildChars() { int finalX = x; gameInstance.THREAD_PROVIDER.execute(() -> { TextureAtlas textureAtlas = buildTextureAtlas(gameInstance, finalX); - textureAtlases.put(finalX,textureAtlas); + synchronized (textureAtlases) { + textureAtlases.put(finalX, textureAtlas); + } }); } } diff --git a/src/main/java/dev/hilligans/ourcraft/network/ClientNetwork.java b/src/main/java/dev/hilligans/ourcraft/network/ClientNetwork.java index 2e8de4bb..b7a7503b 100644 --- a/src/main/java/dev/hilligans/ourcraft/network/ClientNetwork.java +++ b/src/main/java/dev/hilligans/ourcraft/network/ClientNetwork.java @@ -40,7 +40,8 @@ public void joinServer(String ip, String port, Client client) throws Exception { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(this); ((NetworkHandler) networkHandler).setData(b.connect(HOST, PORT).sync().channel(), group, ip, port); - } finally { + } catch (Exception e) { + e.printStackTrace(); } flush(); } @@ -53,6 +54,7 @@ public ClientNetwork debug(boolean debug) { @Override public void sendPacket(PacketBase packetBase) { + System.out.println("Sending packet:" + packetBase.getClass()); if(networkHandler != null && ((ClientNetworkHandler)networkHandler).enabled) { packetBase.packetId = sendProtocol.packetMap.get(packetBase.getClass()); sendPacketDirect(packetBase); diff --git a/src/main/java/dev/hilligans/ourcraft/network/ClientNetworkHandler.java b/src/main/java/dev/hilligans/ourcraft/network/ClientNetworkHandler.java index ff110eac..3ced3af5 100644 --- a/src/main/java/dev/hilligans/ourcraft/network/ClientNetworkHandler.java +++ b/src/main/java/dev/hilligans/ourcraft/network/ClientNetworkHandler.java @@ -9,8 +9,6 @@ public class ClientNetworkHandler extends NetworkHandler { - public static ClientNetworkHandler clientNetworkHandler; - public ClientNetwork network; public ConcurrentLinkedQueue packets = new ConcurrentLinkedQueue<>(); @@ -27,7 +25,8 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { - System.out.println("DISCONNECTED FROM SERVER"); + System.out.println(STR."CLIENT \{network.client.rWindow.getWindowName()} DISCONNECTED FROM SERVER"); + //System.out.println(channel.closeFuture().sync().exceptionNow().getMessage()); network.client.renderWorld = false; network.client.valid = false; //network.client.clientWorld = new ClientWorld(network.client); @@ -41,9 +40,8 @@ protected void channelRead0(ChannelHandlerContext ctx, IPacketByteArray msg) thr } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - ctx.close(); cause.printStackTrace(); - //network.client.clientWorld = new ClientWorld(network.client); + ctx.close(); network.client.openScreen(new DisconnectScreen(network.client,cause.getMessage())); } diff --git a/src/main/java/dev/hilligans/ourcraft/network/Network.java b/src/main/java/dev/hilligans/ourcraft/network/Network.java index cdeb91fd..24248c23 100644 --- a/src/main/java/dev/hilligans/ourcraft/network/Network.java +++ b/src/main/java/dev/hilligans/ourcraft/network/Network.java @@ -39,7 +39,7 @@ public Network(Protocol sendProtocol, Protocol receiveProtocol, int packetIdWidt protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc())); - if(debug) { + if(!debug) { pipeline.addLast(new PacketEncoder(packetIdWidth, compressed)); pipeline.addLast(new PacketDecoder(packetIdWidth, compressed)); } else { diff --git a/src/main/java/dev/hilligans/ourcraft/network/NetworkHandler.java b/src/main/java/dev/hilligans/ourcraft/network/NetworkHandler.java index 7a3d1b82..1cbe032d 100644 --- a/src/main/java/dev/hilligans/ourcraft/network/NetworkHandler.java +++ b/src/main/java/dev/hilligans/ourcraft/network/NetworkHandler.java @@ -1,11 +1,9 @@ package dev.hilligans.ourcraft.network; +import dev.hilligans.ourcraft.Ourcraft; import dev.hilligans.ourcraft.network.debug.PacketTraceByteArray; import dev.hilligans.ourcraft.ServerMain; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.channel.*; public abstract class NetworkHandler extends SimpleChannelInboundHandler { @@ -14,7 +12,7 @@ public abstract class NetworkHandler extends SimpleChannelInboundHandler implements IServerPacketHandler { - static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); + final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); public ArrayList channelIds = new ArrayList<>(); public HashMap mappedPlayerData = new HashMap<>(); public HashMap nameToPlayerData = new HashMap<>(); diff --git a/src/main/java/dev/hilligans/ourcraft/network/debug/PacketTraceByteArray.java b/src/main/java/dev/hilligans/ourcraft/network/debug/PacketTraceByteArray.java index 42bf4925..c9120208 100644 --- a/src/main/java/dev/hilligans/ourcraft/network/debug/PacketTraceByteArray.java +++ b/src/main/java/dev/hilligans/ourcraft/network/debug/PacketTraceByteArray.java @@ -121,20 +121,6 @@ public double readDouble() { return packetTrace.get(byteBuf.readDouble()); } - @Override - public String readUTF8() { - return byteBuf.readCharSequence(readVarInt(), StandardCharsets.UTF_8).toString(); - } - - @Override - public String readUTF16() { - int length = readVarInt(); - //System.out.print("read length:" + length + " "); - String s = byteBuf.readCharSequence(length, StandardCharsets.UTF_16).toString(); - //System.out.println(s); - return s; - } - @Override public void writeByte(byte val) { index += 1; @@ -177,16 +163,6 @@ public void writeDouble(double val) { packetTrace.put(val); } - @Override - public void writeUTF8(String val) { - writeBytes(val.getBytes(StandardCharsets.UTF_8)); - } - - @Override - public void writeUTF16(String val) { - writeBytes(val.getBytes(StandardCharsets.UTF_16)); - } - @Override public ByteBuf getByteBuf() { return byteBuf; diff --git a/src/main/java/dev/hilligans/ourcraft/network/packet/client/CHandshakePacket.java b/src/main/java/dev/hilligans/ourcraft/network/packet/client/CHandshakePacket.java index 8c20c9f8..04eea45c 100644 --- a/src/main/java/dev/hilligans/ourcraft/network/packet/client/CHandshakePacket.java +++ b/src/main/java/dev/hilligans/ourcraft/network/packet/client/CHandshakePacket.java @@ -82,6 +82,8 @@ public static synchronized void handlePlayer(String name, long version, ChannelH serverPlayerData.setServer(serverPacketHandler.getServer()).setNetworkHandler(serverPacketHandler.getServerNetworkHandler()).setName(name); serverPlayerData.setPlayerID(new UUID(playerId, 0)).setChannelID(ctx.channel().id()); + System.out.println("Handling player"); + serverPacketHandler.getServerNetworkHandler().mappedPlayerData.put(ctx.channel().id(), serverPlayerData); //ServerNetworkHandler.mappedName.put(ctx.channel().id(),name); serverPacketHandler.getServerNetworkHandler().nameToPlayerData.put(name, serverPlayerData); diff --git a/src/main/java/dev/hilligans/ourcraft/resource/ResourceManager.java b/src/main/java/dev/hilligans/ourcraft/resource/ResourceManager.java index bc2031d9..d2d29beb 100644 --- a/src/main/java/dev/hilligans/ourcraft/resource/ResourceManager.java +++ b/src/main/java/dev/hilligans/ourcraft/resource/ResourceManager.java @@ -26,10 +26,16 @@ public class ResourceManager { public HashMap> models = new HashMap<>(); public ArrayList classLoaders = new ArrayList<>(); + public GameInstance gameInstance; + + + public ResourceManager(GameInstance gameInstance) { + this.gameInstance = gameInstance; + } public void setLanguageFile(String languageFile) { Languages.switchingLanguage.set(true); - Future languageFuture = Ourcraft.EXECUTOR.submit(() -> { + Future languageFuture = gameInstance.THREAD_PROVIDER.submit(() -> { Language language = new Language(languageFile + ".txt"); ArrayList languageData = languageFiles.get(languageFile); if(languageData != null) { diff --git a/src/main/java/dev/hilligans/ourcraft/server/MultiPlayerServer.java b/src/main/java/dev/hilligans/ourcraft/server/MultiPlayerServer.java index 5ed8a4cb..aa2062bf 100644 --- a/src/main/java/dev/hilligans/ourcraft/server/MultiPlayerServer.java +++ b/src/main/java/dev/hilligans/ourcraft/server/MultiPlayerServer.java @@ -46,13 +46,13 @@ public MultiPlayerServer(GameInstance gameInstance) { public void startServer(String port) { gameInstance.EVENT_BUS.postEvent(new MultiPlayerServerStartEvent(this,port)); Server server = new Server(this); - tick = Executors.newScheduledThreadPool(1, new NamedThreadFactory("server_tick")); + tick = Executors.newScheduledThreadPool(1, new NamedThreadFactory("server_tick", gameInstance)); tick.scheduleAtFixedRate(server, 0, 40, TimeUnit.MILLISECONDS); - playerHandler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("server_player_handler")); + playerHandler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("server_player_handler", gameInstance)); playerHandler.scheduleAtFixedRate(new PlayerHandler(this), 0, 10, TimeUnit.MILLISECONDS); // ConsoleReader consoleReader = new ConsoleReader(this::executeCommand); - serverNetwork = new ServerNetwork(gameInstance.PROTOCOLS.get("Play"), this).debug(ServerMain.argumentContainer.getBoolean("--packetTrace", false)); + serverNetwork = new ServerNetwork(gameInstance.PROTOCOLS.get("Play"), this).debug(Ourcraft.getArgumentContainer().getBoolean("--packetTrace", false)); try { serverNetwork.startServer(port); } catch (Exception e) { diff --git a/src/main/java/dev/hilligans/ourcraft/util/NamedThreadFactory.java b/src/main/java/dev/hilligans/ourcraft/util/NamedThreadFactory.java index 99e3951d..36c9f165 100644 --- a/src/main/java/dev/hilligans/ourcraft/util/NamedThreadFactory.java +++ b/src/main/java/dev/hilligans/ourcraft/util/NamedThreadFactory.java @@ -13,10 +13,9 @@ public class NamedThreadFactory implements ThreadFactory { private final GameInstance gameInstance; public NamedThreadFactory(String name) { - SecurityManager s = System.getSecurityManager(); this.gameInstance = null; - group = (s != null) ? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); + Thread.currentThread().getThreadGroup(); + group = Thread.currentThread().getThreadGroup(); namePrefix = name + "-pool-" + poolNumber.getAndIncrement() + "-thread"; @@ -24,16 +23,14 @@ public NamedThreadFactory(String name) { public NamedThreadFactory(String name, GameInstance gameInstance) { this.gameInstance = gameInstance; - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); + group = Thread.currentThread().getThreadGroup(); namePrefix = name + "-pool-" + poolNumber.getAndIncrement() + "-thread"; } public Thread newThread(Runnable r) { - Thread t = new Thread(group, r, + Thread t = new TrackedThread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if(gameInstance != null) { diff --git a/src/main/java/dev/hilligans/ourcraft/util/ThreadProvider.java b/src/main/java/dev/hilligans/ourcraft/util/ThreadProvider.java index bfc318fc..8b282815 100644 --- a/src/main/java/dev/hilligans/ourcraft/util/ThreadProvider.java +++ b/src/main/java/dev/hilligans/ourcraft/util/ThreadProvider.java @@ -36,13 +36,21 @@ public void execute(Runnable runnable) { } } - public Future submit(Runnable runnable) { + public Future submit(Callable runnable) { if(!EXECUTOR.isShutdown()) { return EXECUTOR.submit(runnable); } return null; } + public void map() { + mapThread(Thread.currentThread(), gameInstance); + } + + public void unmap() { + unmapThread(Thread.currentThread()); + } + public synchronized void addThread(Thread thread) { while (stopped) {} threadCount++; diff --git a/src/main/java/dev/hilligans/ourcraft/util/TrackedThread.java b/src/main/java/dev/hilligans/ourcraft/util/TrackedThread.java new file mode 100644 index 00000000..ab92c3f0 --- /dev/null +++ b/src/main/java/dev/hilligans/ourcraft/util/TrackedThread.java @@ -0,0 +1,17 @@ +package dev.hilligans.ourcraft.util; + +import dev.hilligans.ourcraft.GameInstance; +import dev.hilligans.ourcraft.util.ThreadProvider; + +public class TrackedThread extends Thread { + + public TrackedThread(ThreadGroup group, Runnable task, String name, long stackSize) { + super(group, task, name, stackSize); + } + + @Override + public void run() { + super.run(); + ThreadProvider.unmapThread(this); + } +}