From d07a151926dcdac51dd72ecd1c0a7f65df6682eb Mon Sep 17 00:00:00 2001 From: MelonHell Date: Mon, 29 Jan 2024 01:53:45 +0300 Subject: [PATCH 01/16] started rewriting --- .../src/main/java/net/minestom/demo/Main.java | 20 +- .../java/net/minestom/demo/PlayerInit.java | 260 +++++++++--------- .../demo/commands/ShutdownCommand.java | 7 +- .../net/minestom/server/MinecraftServer.java | 148 +++------- .../net/minestom/server/ServerProcess.java | 36 +-- .../minestom/server/ServerProcessImpl.java | 60 ++-- .../audience/PacketGroupingAudience.java | 4 +- .../net/minestom/server/entity/Entity.java | 2 +- .../net/minestom/server/entity/Player.java | 49 ++-- .../server/entity/fakeplayer/FakePlayer.java | 32 ++- .../minestom/server/extras/query/Query.java | 43 +-- .../extras/query/event/FullQueryEvent.java | 10 +- .../query/response/FullQueryResponse.java | 17 +- .../extras/query/response/QueryKey.java | 29 +- .../minestom/server/instance/AnvilLoader.java | 33 ++- .../minestom/server/instance/Instance.java | 2 +- .../server/network/ConnectionManager.java | 24 +- .../server/common/PluginMessagePacket.java | 4 +- .../server/thread/TickSchedulerThread.java | 2 +- .../minestom/server/ServerProcessTest.java | 5 +- .../AdvancementIntegrationTest.java | 6 +- .../CommandSuggestionIntegrationTest.java | 4 +- .../entity/EntityRemovalIntegrationTest.java | 2 +- .../entity/player/PlayerIntegrationTest.java | 8 +- .../server/event/EventNodeMapTest.java | 4 +- .../instance/ChunkViewerIntegrationTest.java | 2 +- .../EntityTrackerIntegrationTest.java | 4 +- .../GeneratorForkConsumerIntegrationTest.java | 14 +- .../GeneratorForkIntegrationTest.java | 12 +- .../instance/GeneratorIntegrationTest.java | 14 +- .../InstanceEventsIntegrationTest.java | 2 +- .../InstanceUnregisterIntegrationTest.java | 14 +- .../light/WorldRelightIntegrationTest.java | 2 +- .../main/java/net/minestom/testing/Env.java | 4 +- .../java/net/minestom/testing/EnvImpl.java | 6 +- .../java/net/minestom/testing/EnvTest.java | 2 +- .../minestom/testing/TestConnectionImpl.java | 10 +- 37 files changed, 432 insertions(+), 465 deletions(-) diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index 255bc525bf7..27424dbc15e 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -25,21 +25,23 @@ public class Main { public static void main(String[] args) { System.setProperty("minestom.experiment.pose-updates", "true"); - MinecraftServer.setCompressionThreshold(0); + MinecraftServer minecraftServer = new MinecraftServer(); - MinecraftServer minecraftServer = MinecraftServer.init(); + minecraftServer.setCompressionThreshold(0); - BlockManager blockManager = MinecraftServer.getBlockManager(); + minecraftServer.init(); + + BlockManager blockManager = minecraftServer.getBlockManager(); blockManager.registerBlockPlacementRule(new DripstonePlacementRule()); blockManager.registerHandler(TestBlockHandler.INSTANCE.getNamespaceId(), () -> TestBlockHandler.INSTANCE); - CommandManager commandManager = MinecraftServer.getCommandManager(); + CommandManager commandManager = minecraftServer.getCommandManager(); commandManager.register(new TestCommand()); commandManager.register(new EntitySelectorCommand()); commandManager.register(new HealthCommand()); commandManager.register(new LegacyCommand()); commandManager.register(new DimensionCommand()); - commandManager.register(new ShutdownCommand()); + commandManager.register(new ShutdownCommand(minecraftServer)); commandManager.register(new TeleportCommand()); commandManager.register(new PlayersCommand()); commandManager.register(new FindCommand()); @@ -65,11 +67,11 @@ public static void main(String[] args) { commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED))); - MinecraftServer.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); + minecraftServer.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); - MinecraftServer.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); + minecraftServer.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); - MinecraftServer.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { + minecraftServer.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { ResponseData responseData = event.getResponseData(); responseData.addEntry(NamedAndIdentified.named("The first line is separated from the others")); responseData.addEntry(NamedAndIdentified.named("Could be a name, or a message")); @@ -103,7 +105,7 @@ public static void main(String[] args) { //responseData.setPlayersHidden(true); }); - PlayerInit.init(); + new PlayerInit(minecraftServer).init(); // VelocityProxy.enable("abcdef"); //BungeeCordProxy.enable(); diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index 68c54e190ac..ef55dc59753 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.advancements.FrameType; import net.minestom.server.advancements.notifications.Notification; import net.minestom.server.advancements.notifications.NotificationCenter; @@ -47,127 +48,13 @@ public class PlayerInit { - private static final Inventory inventory; - - private static final EventNode DEMO_NODE = EventNode.all("demo") - .addListener(EntityAttackEvent.class, event -> { - final Entity source = event.getEntity(); - final Entity entity = event.getTarget(); - - entity.takeKnockback(0.4f, Math.sin(source.getPosition().yaw() * 0.017453292), -Math.cos(source.getPosition().yaw() * 0.017453292)); - - if (entity instanceof Player) { - Player target = (Player) entity; - target.damage(Damage.fromEntity(source, 5)); - } - - if (source instanceof Player) { - ((Player) source).sendMessage("You attacked something!"); - } - }) - .addListener(PlayerDeathEvent.class, event -> event.setChatMessage(Component.text("custom death message"))) - .addListener(PickupItemEvent.class, event -> { - final Entity entity = event.getLivingEntity(); - if (entity instanceof Player) { - // Cancel event if player does not have enough inventory space - final ItemStack itemStack = event.getItemEntity().getItemStack(); - event.setCancelled(!((Player) entity).getInventory().addItemStack(itemStack)); - } - }) - .addListener(ItemDropEvent.class, event -> { - final Player player = event.getPlayer(); - ItemStack droppedItem = event.getItemStack(); - - Pos playerPos = player.getPosition(); - ItemEntity itemEntity = new ItemEntity(droppedItem); - itemEntity.setPickupDelay(Duration.of(500, TimeUnit.MILLISECOND)); - itemEntity.setInstance(player.getInstance(), playerPos.withY(y -> y + 1.5)); - Vec velocity = playerPos.direction().mul(6); - itemEntity.setVelocity(velocity); - - FakePlayer.initPlayer(UUID.randomUUID(), "fake123", fp -> { - System.out.println("fp = " + fp); - }); - }) - .addListener(PlayerDisconnectEvent.class, event -> System.out.println("DISCONNECTION " + event.getPlayer().getUsername())) - .addListener(AsyncPlayerConfigurationEvent.class, event -> { - final Player player = event.getPlayer(); - - var instances = MinecraftServer.getInstanceManager().getInstances(); - Instance instance = instances.stream().skip(new Random().nextInt(instances.size())).findFirst().orElse(null); - event.setSpawningInstance(instance); - int x = Math.abs(ThreadLocalRandom.current().nextInt()) % 500 - 250; - int z = Math.abs(ThreadLocalRandom.current().nextInt()) % 500 - 250; - player.setRespawnPoint(new Pos(0, 40f, 0)); - }) - .addListener(PlayerSpawnEvent.class, event -> { - final Player player = event.getPlayer(); - player.setGameMode(GameMode.CREATIVE); - player.setPermissionLevel(4); - ItemStack itemStack = ItemStack.builder(Material.STONE) - .amount(64) - .meta(itemMetaBuilder -> - itemMetaBuilder.canPlaceOn(Set.of(Block.STONE)) - .canDestroy(Set.of(Block.DIAMOND_ORE))) - .build(); - player.getInventory().addItemStack(itemStack); - - ItemStack bundle = ItemStack.builder(Material.BUNDLE) - .meta(BundleMeta.class, bundleMetaBuilder -> { - bundleMetaBuilder.addItem(ItemStack.of(Material.DIAMOND, 5)); - bundleMetaBuilder.addItem(ItemStack.of(Material.RABBIT_FOOT, 5)); - }) - .build(); - player.getInventory().addItemStack(bundle); - - if (event.isFirstSpawn()) { - Notification notification = new Notification( - Component.text("Welcome!"), - FrameType.TASK, - Material.IRON_SWORD - ); - NotificationCenter.send(notification, event.getPlayer()); - } - }) - .addListener(PlayerPacketOutEvent.class, event -> { - //System.out.println("out " + event.getPacket().getClass().getSimpleName()); - }) - .addListener(PlayerPacketEvent.class, event -> { - //System.out.println("in " + event.getPacket().getClass().getSimpleName()); - }) - .addListener(PlayerUseItemOnBlockEvent.class, event -> { - if (event.getHand() != Player.Hand.MAIN) return; - - var itemStack = event.getItemStack(); - var block = event.getInstance().getBlock(event.getPosition()); - - event.getPlayer().sendMessage("MESSAGE " + ThreadLocalRandom.current().nextDouble()); - - if ("false" .equals(block.getProperty("waterlogged")) && itemStack.material().equals(Material.WATER_BUCKET)) { - block = block.withProperty("waterlogged", "true"); - System.out.println("SET WATERLOGGER"); - } else if ("true" .equals(block.getProperty("waterlogged")) && itemStack.material().equals(Material.BUCKET)) { - block = block.withProperty("waterlogged", "false"); - System.out.println("SET NOT WATERLOGGED"); - } else return; - - event.getInstance().setBlock(event.getPosition(), block); - - }) - .addListener(PlayerBlockPlaceEvent.class, event -> { -// event.setDoBlockUpdates(false); - }) - .addListener(PlayerBlockInteractEvent.class, event -> { - var block = event.getBlock(); - var rawOpenProp = block.getProperty("open"); - if (rawOpenProp == null) return; + private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - block = block.withProperty("open", String.valueOf(!Boolean.parseBoolean(rawOpenProp))); - event.getInstance().setBlock(event.getBlockPosition(), block); - }); - - static { - InstanceManager instanceManager = MinecraftServer.getInstanceManager(); + public PlayerInit(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); + InstanceManager instanceManager = serverProcess.getInstanceManager(); InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); instanceContainer.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); @@ -189,12 +76,133 @@ public class PlayerInit { inventory = new Inventory(InventoryType.CHEST_1_ROW, Component.text("Test inventory")); inventory.setItemStack(3, ItemStack.of(Material.DIAMOND, 34)); + + DEMO_NODE = EventNode.all("demo") + .addListener(EntityAttackEvent.class, event -> { + final Entity source = event.getEntity(); + final Entity entity = event.getTarget(); + + entity.takeKnockback(0.4f, Math.sin(source.getPosition().yaw() * 0.017453292), -Math.cos(source.getPosition().yaw() * 0.017453292)); + + if (entity instanceof Player) { + Player target = (Player) entity; + target.damage(Damage.fromEntity(source, 5)); + } + + if (source instanceof Player) { + ((Player) source).sendMessage("You attacked something!"); + } + }) + .addListener(PlayerDeathEvent.class, event -> event.setChatMessage(Component.text("custom death message"))) + .addListener(PickupItemEvent.class, event -> { + final Entity entity = event.getLivingEntity(); + if (entity instanceof Player) { + // Cancel event if player does not have enough inventory space + final ItemStack itemStack = event.getItemEntity().getItemStack(); + event.setCancelled(!((Player) entity).getInventory().addItemStack(itemStack)); + } + }) + .addListener(ItemDropEvent.class, event -> { + final Player player = event.getPlayer(); + ItemStack droppedItem = event.getItemStack(); + + Pos playerPos = player.getPosition(); + ItemEntity itemEntity = new ItemEntity(droppedItem); + itemEntity.setPickupDelay(Duration.of(500, TimeUnit.MILLISECOND)); + itemEntity.setInstance(player.getInstance(), playerPos.withY(y -> y + 1.5)); + Vec velocity = playerPos.direction().mul(6); + itemEntity.setVelocity(velocity); + + FakePlayer.initPlayer(minecraftServer, UUID.randomUUID(), "fake123", fp -> { + System.out.println("fp = " + fp); + }); + }) + .addListener(PlayerDisconnectEvent.class, event -> System.out.println("DISCONNECTION " + event.getPlayer().getUsername())) + .addListener(AsyncPlayerConfigurationEvent.class, event -> { + final Player player = event.getPlayer(); + + var instances = serverProcess.getInstanceManager().getInstances(); + Instance instance = instances.stream().skip(new Random().nextInt(instances.size())).findFirst().orElse(null); + event.setSpawningInstance(instance); + int x = Math.abs(ThreadLocalRandom.current().nextInt()) % 500 - 250; + int z = Math.abs(ThreadLocalRandom.current().nextInt()) % 500 - 250; + player.setRespawnPoint(new Pos(0, 40f, 0)); + }) + .addListener(PlayerSpawnEvent.class, event -> { + final Player player = event.getPlayer(); + player.setGameMode(GameMode.CREATIVE); + player.setPermissionLevel(4); + ItemStack itemStack = ItemStack.builder(Material.STONE) + .amount(64) + .meta(itemMetaBuilder -> + itemMetaBuilder.canPlaceOn(Set.of(Block.STONE)) + .canDestroy(Set.of(Block.DIAMOND_ORE))) + .build(); + player.getInventory().addItemStack(itemStack); + + ItemStack bundle = ItemStack.builder(Material.BUNDLE) + .meta(BundleMeta.class, bundleMetaBuilder -> { + bundleMetaBuilder.addItem(ItemStack.of(Material.DIAMOND, 5)); + bundleMetaBuilder.addItem(ItemStack.of(Material.RABBIT_FOOT, 5)); + }) + .build(); + player.getInventory().addItemStack(bundle); + + if (event.isFirstSpawn()) { + Notification notification = new Notification( + Component.text("Welcome!"), + FrameType.TASK, + Material.IRON_SWORD + ); + NotificationCenter.send(notification, event.getPlayer()); + } + }) + .addListener(PlayerPacketOutEvent.class, event -> { + //System.out.println("out " + event.getPacket().getClass().getSimpleName()); + }) + .addListener(PlayerPacketEvent.class, event -> { + //System.out.println("in " + event.getPacket().getClass().getSimpleName()); + }) + .addListener(PlayerUseItemOnBlockEvent.class, event -> { + if (event.getHand() != Player.Hand.MAIN) return; + + var itemStack = event.getItemStack(); + var block = event.getInstance().getBlock(event.getPosition()); + + event.getPlayer().sendMessage("MESSAGE " + ThreadLocalRandom.current().nextDouble()); + + if ("false" .equals(block.getProperty("waterlogged")) && itemStack.material().equals(Material.WATER_BUCKET)) { + block = block.withProperty("waterlogged", "true"); + System.out.println("SET WATERLOGGER"); + } else if ("true" .equals(block.getProperty("waterlogged")) && itemStack.material().equals(Material.BUCKET)) { + block = block.withProperty("waterlogged", "false"); + System.out.println("SET NOT WATERLOGGED"); + } else return; + + event.getInstance().setBlock(event.getPosition(), block); + + }) + .addListener(PlayerBlockPlaceEvent.class, event -> { +// event.setDoBlockUpdates(false); + }) + .addListener(PlayerBlockInteractEvent.class, event -> { + var block = event.getBlock(); + var rawOpenProp = block.getProperty("open"); + if (rawOpenProp == null) return; + + block = block.withProperty("open", String.valueOf(!Boolean.parseBoolean(rawOpenProp))); + event.getInstance().setBlock(event.getBlockPosition(), block); + }); } - private static final AtomicReference LAST_TICK = new AtomicReference<>(); + private final Inventory inventory; + + private final EventNode DEMO_NODE; + + private final AtomicReference LAST_TICK = new AtomicReference<>(); - public static void init() { - var eventHandler = MinecraftServer.getGlobalEventHandler(); + public void init() { + var eventHandler = serverProcess.getGlobalEventHandler(); eventHandler.addChild(DEMO_NODE); MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; @@ -202,9 +210,9 @@ public static void init() { eventHandler.addListener(ServerTickMonitorEvent.class, event -> LAST_TICK.set(event.getTickMonitor())); - BenchmarkManager benchmarkManager = MinecraftServer.getBenchmarkManager(); - MinecraftServer.getSchedulerManager().buildTask(() -> { - if (MinecraftServer.getConnectionManager().getOnlinePlayerCount() != 0) + BenchmarkManager benchmarkManager = serverProcess.getBenchmarkManager(); + serverProcess.getSchedulerManager().buildTask(() -> { + if (serverProcess.getConnectionManager().getOnlinePlayerCount() != 0) return; long ramUsage = benchmarkManager.getUsedMemory(); diff --git a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java index 288c314ee1b..99f5bf357cb 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java @@ -11,12 +11,15 @@ */ public class ShutdownCommand extends Command { - public ShutdownCommand() { + private final MinecraftServer minecraftServer; + + public ShutdownCommand(MinecraftServer minecraftServer) { super("shutdown"); + this.minecraftServer = minecraftServer; addSyntax(this::execute); } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - MinecraftServer.stopCleanly(); + minecraftServer.stopCleanly(); } } diff --git a/src/main/java/net/minestom/server/MinecraftServer.java b/src/main/java/net/minestom/server/MinecraftServer.java index 8a62c19ac59..7edeba96096 100644 --- a/src/main/java/net/minestom/server/MinecraftServer.java +++ b/src/main/java/net/minestom/server/MinecraftServer.java @@ -59,25 +59,24 @@ public final class MinecraftServer { public static final int TICK_MS = 1000 / TICK_PER_SECOND; // In-Game Manager - private static volatile ServerProcess serverProcess; + private volatile ServerProcess serverProcess; - private static int chunkViewDistance = Integer.getInteger("minestom.chunk-view-distance", 8); - private static int entityViewDistance = Integer.getInteger("minestom.entity-view-distance", 5); - private static int compressionThreshold = 256; - private static boolean terminalEnabled = System.getProperty("minestom.terminal.disabled") == null; - private static String brandName = "Minestom"; - private static Difficulty difficulty = Difficulty.NORMAL; + private int chunkViewDistance = Integer.getInteger("minestom.chunk-view-distance", 8); + private int entityViewDistance = Integer.getInteger("minestom.entity-view-distance", 5); + private int compressionThreshold = 256; + private boolean terminalEnabled = System.getProperty("minestom.terminal.disabled") == null; + private String brandName = "Minestom"; + private Difficulty difficulty = Difficulty.NORMAL; - public static MinecraftServer init() { + public void init() { updateProcess(); - return new MinecraftServer(); } @ApiStatus.Internal - public static ServerProcess updateProcess() { + public ServerProcess updateProcess() { ServerProcess process; try { - process = new ServerProcessImpl(); + process = new ServerProcessImpl(this); serverProcess = process; } catch (IOException e) { throw new RuntimeException(e); @@ -91,7 +90,7 @@ public static ServerProcess updateProcess() { * @return the server brand name */ @NotNull - public static String getBrandName() { + public String getBrandName() { return brandName; } @@ -101,9 +100,9 @@ public static String getBrandName() { * @param brandName the server brand name * @throws NullPointerException if {@code brandName} is null */ - public static void setBrandName(@NotNull String brandName) { - MinecraftServer.brandName = brandName; - PacketUtils.broadcastPlayPacket(PluginMessagePacket.getBrandPacket()); + public void setBrandName(@NotNull String brandName) { + this.brandName = brandName; + PacketUtils.broadcastPlayPacket(PluginMessagePacket.getBrandPacket(this)); } /** @@ -112,7 +111,7 @@ public static void setBrandName(@NotNull String brandName) { * @return the server difficulty */ @NotNull - public static Difficulty getDifficulty() { + public Difficulty getDifficulty() { return difficulty; } @@ -121,87 +120,22 @@ public static Difficulty getDifficulty() { * * @param difficulty the new server difficulty */ - public static void setDifficulty(@NotNull Difficulty difficulty) { - MinecraftServer.difficulty = difficulty; + public void setDifficulty(@NotNull Difficulty difficulty) { + this.difficulty = difficulty; PacketUtils.broadcastPlayPacket(new ServerDifficultyPacket(difficulty, true)); } @ApiStatus.Experimental - public static @UnknownNullability ServerProcess process() { + public @UnknownNullability ServerProcess process() { return serverProcess; } - public static @NotNull GlobalEventHandler getGlobalEventHandler() { - return serverProcess.eventHandler(); - } - - public static @NotNull PacketListenerManager getPacketListenerManager() { - return serverProcess.packetListener(); - } - - public static @NotNull InstanceManager getInstanceManager() { - return serverProcess.instance(); - } - - public static @NotNull BlockManager getBlockManager() { - return serverProcess.block(); - } - - public static @NotNull CommandManager getCommandManager() { - return serverProcess.command(); - } - - public static @NotNull RecipeManager getRecipeManager() { - return serverProcess.recipe(); - } - - public static @NotNull TeamManager getTeamManager() { - return serverProcess.team(); - } - - public static @NotNull SchedulerManager getSchedulerManager() { - return serverProcess.scheduler(); - } - - /** - * Gets the manager handling server monitoring. - * - * @return the benchmark manager - */ - public static @NotNull BenchmarkManager getBenchmarkManager() { - return serverProcess.benchmark(); - } - - public static @NotNull ExceptionManager getExceptionManager() { - return serverProcess.exception(); - } - - public static @NotNull ConnectionManager getConnectionManager() { - return serverProcess.connection(); - } - - public static @NotNull BossBarManager getBossBarManager() { - return serverProcess.bossBar(); - } - - public static @NotNull PacketProcessor getPacketProcessor() { - return serverProcess.packetProcessor(); - } - - public static boolean isStarted() { - return serverProcess.isAlive(); - } - - public static boolean isStopping() { - return !isStarted(); - } - /** * Gets the chunk view distance of the server. * * @return the chunk view distance */ - public static int getChunkViewDistance() { + public int getChunkViewDistance() { return chunkViewDistance; } @@ -213,11 +147,11 @@ public static int getChunkViewDistance() { * @deprecated should instead be defined with a java property */ @Deprecated - public static void setChunkViewDistance(int chunkViewDistance) { + public void setChunkViewDistance(int chunkViewDistance) { Check.stateCondition(serverProcess.isAlive(), "You cannot change the chunk view distance after the server has been started."); Check.argCondition(!MathUtils.isBetween(chunkViewDistance, 2, 32), "The chunk view distance must be between 2 and 32"); - MinecraftServer.chunkViewDistance = chunkViewDistance; + this.chunkViewDistance = chunkViewDistance; } /** @@ -225,7 +159,7 @@ public static void setChunkViewDistance(int chunkViewDistance) { * * @return the entity view distance */ - public static int getEntityViewDistance() { + public int getEntityViewDistance() { return entityViewDistance; } @@ -237,11 +171,11 @@ public static int getEntityViewDistance() { * @deprecated should instead be defined with a java property */ @Deprecated - public static void setEntityViewDistance(int entityViewDistance) { + public void setEntityViewDistance(int entityViewDistance) { Check.stateCondition(serverProcess.isAlive(), "You cannot change the entity view distance after the server has been started."); Check.argCondition(!MathUtils.isBetween(entityViewDistance, 0, 32), "The entity view distance must be between 0 and 32"); - MinecraftServer.entityViewDistance = entityViewDistance; + this.entityViewDistance = entityViewDistance; } /** @@ -249,7 +183,7 @@ public static void setEntityViewDistance(int entityViewDistance) { * * @return the compression threshold, 0 means that compression is disabled */ - public static int getCompressionThreshold() { + public int getCompressionThreshold() { return compressionThreshold; } @@ -261,9 +195,9 @@ public static int getCompressionThreshold() { * @param compressionThreshold the new compression threshold, 0 to disable compression * @throws IllegalStateException if this is called after the server started */ - public static void setCompressionThreshold(int compressionThreshold) { + public void setCompressionThreshold(int compressionThreshold) { Check.stateCondition(serverProcess != null && serverProcess.isAlive(), "The compression threshold cannot be changed after the server has been started."); - MinecraftServer.compressionThreshold = compressionThreshold; + this.compressionThreshold = compressionThreshold; } /** @@ -271,7 +205,7 @@ public static void setCompressionThreshold(int compressionThreshold) { * * @return true if the terminal is enabled */ - public static boolean isTerminalEnabled() { + public boolean isTerminalEnabled() { return terminalEnabled; } @@ -280,29 +214,9 @@ public static boolean isTerminalEnabled() { * * @param enabled true to enable, false to disable */ - public static void setTerminalEnabled(boolean enabled) { + public void setTerminalEnabled(boolean enabled) { Check.stateCondition(serverProcess.isAlive(), "Terminal settings may not be changed after starting the server."); - MinecraftServer.terminalEnabled = enabled; - } - - public static DimensionTypeManager getDimensionTypeManager() { - return serverProcess.dimension(); - } - - public static BiomeManager getBiomeManager() { - return serverProcess.biome(); - } - - public static AdvancementManager getAdvancementManager() { - return serverProcess.advancement(); - } - - public static TagManager getTagManager() { - return serverProcess.tag(); - } - - public static Server getServer() { - return serverProcess.server(); + terminalEnabled = enabled; } /** @@ -325,7 +239,7 @@ public void start(@NotNull String address, int port) { /** * Stops this server properly (saves if needed, kicking players, etc.) */ - public static void stopCleanly() { + public void stopCleanly() { serverProcess.stop(); } } diff --git a/src/main/java/net/minestom/server/ServerProcess.java b/src/main/java/net/minestom/server/ServerProcess.java index bf677eafb99..edebd3341d1 100644 --- a/src/main/java/net/minestom/server/ServerProcess.java +++ b/src/main/java/net/minestom/server/ServerProcess.java @@ -33,94 +33,94 @@ public interface ServerProcess extends Snapshotable { /** * Handles incoming connections/players. */ - @NotNull ConnectionManager connection(); + @NotNull ConnectionManager getConnectionManager(); /** * Handles registered instances. */ - @NotNull InstanceManager instance(); + @NotNull InstanceManager getInstanceManager(); /** * Handles {@link net.minestom.server.instance.block.BlockHandler block handlers} * and {@link BlockPlacementRule placement rules}. */ - @NotNull BlockManager block(); + @NotNull BlockManager getBlockManager(); /** * Handles registered commands. */ - @NotNull CommandManager command(); + @NotNull CommandManager getCommandManager(); /** * Handles registered recipes shown to clients. */ - @NotNull RecipeManager recipe(); + @NotNull RecipeManager getRecipeManager(); /** * Handles registered teams. */ - @NotNull TeamManager team(); + @NotNull TeamManager getTeamManager(); /** * Gets the global event handler. *

* Used to register event callback at a global scale. */ - @NotNull GlobalEventHandler eventHandler(); + @NotNull GlobalEventHandler getGlobalEventHandler(); /** * Main scheduler ticked at the server rate. */ - @NotNull SchedulerManager scheduler(); + @NotNull SchedulerManager getSchedulerManager(); - @NotNull BenchmarkManager benchmark(); + @NotNull BenchmarkManager getBenchmarkManager(); /** * Handles registered dimensions. */ - @NotNull DimensionTypeManager dimension(); + @NotNull DimensionTypeManager getDimensionTypeManager(); /** * Handles registered biomes. */ - @NotNull BiomeManager biome(); + @NotNull BiomeManager getBiomeManager(); /** * Handles registered advancements. */ - @NotNull AdvancementManager advancement(); + @NotNull AdvancementManager getAdvancementManager(); /** * Handles registered boss bars. */ - @NotNull BossBarManager bossBar(); + @NotNull BossBarManager getBossBarManager(); /** * Handles registry tags. */ - @NotNull TagManager tag(); + @NotNull TagManager getTagManager(); /** * Handles all thrown exceptions from the server. */ - @NotNull ExceptionManager exception(); + @NotNull ExceptionManager getExceptionManager(); /** * Handles incoming packets. */ - @NotNull PacketListenerManager packetListener(); + @NotNull PacketListenerManager getPacketListenerManager(); /** * Gets the object handling the client packets processing. *

* Can be used if you want to convert a buffer to a client packet object. */ - @NotNull PacketProcessor packetProcessor(); + @NotNull PacketProcessor getPacketProcessor(); /** * Exposed socket server. */ - @NotNull Server server(); + @NotNull Server getServer(); /** * Dispatcher for tickable game objects. diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java index 01f581378d4..c66bc546771 100644 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -70,10 +70,12 @@ final class ServerProcessImpl implements ServerProcess { private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); + private final MinecraftServer minecraftServer; - public ServerProcessImpl() throws IOException { + public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { + this.minecraftServer = minecraftServer; this.exception = new ExceptionManager(); - this.connection = new ConnectionManager(); + this.connection = new ConnectionManager(minecraftServer); this.packetListener = new PacketListenerManager(); this.packetProcessor = new PacketProcessor(packetListener); this.instance = new InstanceManager(); @@ -96,92 +98,92 @@ public ServerProcessImpl() throws IOException { } @Override - public @NotNull ConnectionManager connection() { + public @NotNull ConnectionManager getConnectionManager() { return connection; } @Override - public @NotNull InstanceManager instance() { + public @NotNull InstanceManager getInstanceManager() { return instance; } @Override - public @NotNull BlockManager block() { + public @NotNull BlockManager getBlockManager() { return block; } @Override - public @NotNull CommandManager command() { + public @NotNull CommandManager getCommandManager() { return command; } @Override - public @NotNull RecipeManager recipe() { + public @NotNull RecipeManager getRecipeManager() { return recipe; } @Override - public @NotNull TeamManager team() { + public @NotNull TeamManager getTeamManager() { return team; } @Override - public @NotNull GlobalEventHandler eventHandler() { + public @NotNull GlobalEventHandler getGlobalEventHandler() { return eventHandler; } @Override - public @NotNull SchedulerManager scheduler() { + public @NotNull SchedulerManager getSchedulerManager() { return scheduler; } @Override - public @NotNull BenchmarkManager benchmark() { + public @NotNull BenchmarkManager getBenchmarkManager() { return benchmark; } @Override - public @NotNull DimensionTypeManager dimension() { + public @NotNull DimensionTypeManager getDimensionTypeManager() { return dimension; } @Override - public @NotNull BiomeManager biome() { + public @NotNull BiomeManager getBiomeManager() { return biome; } @Override - public @NotNull AdvancementManager advancement() { + public @NotNull AdvancementManager getAdvancementManager() { return advancement; } @Override - public @NotNull BossBarManager bossBar() { + public @NotNull BossBarManager getBossBarManager() { return bossBar; } @Override - public @NotNull TagManager tag() { + public @NotNull TagManager getTagManager() { return tag; } @Override - public @NotNull ExceptionManager exception() { + public @NotNull ExceptionManager getExceptionManager() { return exception; } @Override - public @NotNull PacketListenerManager packetListener() { + public @NotNull PacketListenerManager getPacketListenerManager() { return packetListener; } @Override - public @NotNull PacketProcessor packetProcessor() { + public @NotNull PacketProcessor getPacketProcessor() { return packetProcessor; } @Override - public @NotNull Server server() { + public @NotNull Server getServer() { return server; } @@ -201,7 +203,7 @@ public void start(@NotNull SocketAddress socketAddress) { throw new IllegalStateException("Server already started"); } - LOGGER.info("Starting " + MinecraftServer.getBrandName() + " server."); + LOGGER.info("Starting " + minecraftServer.getBrandName() + " server."); // Init server try { @@ -214,7 +216,7 @@ public void start(@NotNull SocketAddress socketAddress) { // Start server server.start(); - LOGGER.info(MinecraftServer.getBrandName() + " server started successfully."); + LOGGER.info(minecraftServer.getBrandName() + " server started successfully."); // Stop the server on SIGINT if (SHUTDOWN_ON_SIGNAL) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); @@ -224,14 +226,14 @@ public void start(@NotNull SocketAddress socketAddress) { public void stop() { if (!stopped.compareAndSet(false, true)) return; - LOGGER.info("Stopping " + MinecraftServer.getBrandName() + " server."); + LOGGER.info("Stopping " + minecraftServer.getBrandName() + " server."); scheduler.shutdown(); connection.shutdown(); server.stop(); LOGGER.info("Shutting down all thread pools."); benchmark.disable(); dispatcher.shutdown(); - LOGGER.info(MinecraftServer.getBrandName() + " server stopped successfully."); + LOGGER.info(minecraftServer.getBrandName() + " server stopped successfully."); } @Override @@ -257,10 +259,10 @@ private final class TickerImpl implements Ticker { public void tick(long nanoTime) { final long msTime = System.currentTimeMillis(); - scheduler().processTick(); + getSchedulerManager().processTick(); // Connection tick (let waiting clients in, send keep alives, handle configuration players packets) - connection().tick(msTime); + getConnectionManager().tick(msTime); // Server tick (chunks/entities) serverTick(msTime); @@ -269,7 +271,7 @@ public void tick(long nanoTime) { PacketUtils.flush(); // Server connection tick - server().tick(); + getServer().tick(); // Monitoring { @@ -282,11 +284,11 @@ public void tick(long nanoTime) { private void serverTick(long tickStart) { // Tick all instances - for (Instance instance : instance().getInstances()) { + for (Instance instance : getInstanceManager().getInstances()) { try { instance.tick(tickStart); } catch (Exception e) { - exception().handleException(e); + getExceptionManager().handleException(e); } } // Tick all chunks (and entities inside) diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index d164ff23158..70a99c3d51e 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -89,12 +89,12 @@ default void resetTitle() { @Override default void showBossBar(@NotNull BossBar bar) { - MinecraftServer.getBossBarManager().addBossBar(this.getPlayers(), bar); + this.getPlayers().stream().findAny().ifPresent((p) -> p.minecraftServer.process().getBossBarManager().addBossBar(this.getPlayers(), bar)); } @Override default void hideBossBar(@NotNull BossBar bar) { - MinecraftServer.getBossBarManager().removeBossBar(this.getPlayers(), bar); + this.getPlayers().stream().findAny().ifPresent((p) -> p.minecraftServer.process().getBossBarManager().removeBossBar(this.getPlayers(), bar)); } /** diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index db957dbf7a6..e35d65462bb 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -200,7 +200,7 @@ public Entity(@NotNull EntityType entityType, @NotNull UUID uuid) { final ServerProcess process = MinecraftServer.process(); if (process != null) { - this.eventNode = process.eventHandler().map(this, EventFilter.ENTITY); + this.eventNode = process.getGlobalEventHandler().map(this, EventFilter.ENTITY); } else { // Local nodes require a server process this.eventNode = null; diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index c440f3d1797..11c554d3c53 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -20,6 +20,7 @@ import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.title.TitlePart; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; @@ -71,6 +72,7 @@ import net.minestom.server.recipe.RecipeManager; import net.minestom.server.scoreboard.BelowNameTag; import net.minestom.server.scoreboard.Team; +import net.minestom.server.scoreboard.TeamManager; import net.minestom.server.snapshot.EntitySnapshot; import net.minestom.server.snapshot.PlayerSnapshot; import net.minestom.server.snapshot.SnapshotImpl; @@ -228,8 +230,13 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // The future is non-null when a resource pack is in-flight, and completed when all statuses have been received. private CompletableFuture resourcePackFuture = null; - public Player(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { + public final MinecraftServer minecraftServer; + protected final ServerProcess serverProcess; + + public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { super(EntityType.PLAYER, uuid); + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); this.username = username; this.usernameComponent = Component.text(username); this.playerConnection = playerConnection; @@ -288,13 +295,13 @@ public CompletableFuture UNSAFE_init() { final JoinGamePacket joinGamePacket = new JoinGamePacket( getEntityId(), this.hardcore, List.of(), 0, - MinecraftServer.getChunkViewDistance(), MinecraftServer.getChunkViewDistance(), + minecraftServer.getChunkViewDistance(), minecraftServer.getChunkViewDistance(), false, true, false, dimensionType.toString(), spawnInstance.getDimensionName(), 0, gameMode, null, false, levelFlat, deathLocation, portalCooldown); sendPacket(joinGamePacket); // Difficulty - sendPacket(new ServerDifficultyPacket(MinecraftServer.getDifficulty(), true)); + sendPacket(new ServerDifficultyPacket(minecraftServer.getDifficulty(), true)); sendPacket(new SpawnPositionPacket(respawnPoint, 0)); @@ -321,7 +328,7 @@ public CompletableFuture UNSAFE_init() { // FIXME: when using Geyser, this line remove the skin of the client PacketUtils.broadcastPlayPacket(getAddPlayerToList()); - var connectionManager = MinecraftServer.getConnectionManager(); + var connectionManager = serverProcess.getConnectionManager(); for (var player : connectionManager.getOnlinePlayers()) { if (player != this) { sendPacket(player.getAddPlayerToList()); @@ -332,7 +339,7 @@ public CompletableFuture UNSAFE_init() { } //Teams - for (Team team : MinecraftServer.getTeamManager().getTeams()) { + for (Team team : serverProcess.getTeamManager().getTeams()) { sendPacket(team.createTeamsCreationPacket()); } @@ -341,7 +348,7 @@ public CompletableFuture UNSAFE_init() { // Recipes start { - RecipeManager recipeManager = MinecraftServer.getRecipeManager(); + RecipeManager recipeManager = serverProcess.getRecipeManager(); sendPacket(recipeManager.getDeclareRecipesPacket()); List recipesIdentifier = new ArrayList<>(); @@ -385,7 +392,7 @@ public void startConfigurationPhase() { // Remove the player, then send them back to configuration remove(false); - var connectionManager = MinecraftServer.getConnectionManager(); + var connectionManager = serverProcess.getConnectionManager(); connectionManager.transitionPlayToConfig(this); } @@ -532,7 +539,7 @@ public void respawn() { ChunkUtils.forChunksInRange(respawnPosition, settings.getEffectiveViewDistance(), chunkAdder); chunksLoadedByClient = new Vec(respawnPosition.chunkX(), respawnPosition.chunkZ()); // Client also needs all entities resent to them, since those are unloaded as well - this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(MinecraftServer.getChunkViewDistance(), settings.getViewDistance()), + this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(minecraftServer.getChunkViewDistance(), settings.getViewDistance()), EntityTracker.Target.ENTITIES, entity -> { // Skip refreshing self with a new viewer if (!entity.getUuid().equals(uuid) && entity.isViewer(this)) { @@ -547,7 +554,7 @@ public void respawn() { */ private void refreshClientStateAfterRespawn() { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); - sendPacket(new ServerDifficultyPacket(MinecraftServer.getDifficulty(), false)); + sendPacket(new ServerDifficultyPacket(minecraftServer.getDifficulty(), false)); sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation)); sendPacket(new SetExperiencePacket(exp, level, 0)); triggerStatus((byte) (24 + permissionLevel)); // Set permission level @@ -560,7 +567,7 @@ private void refreshClientStateAfterRespawn() { * again, and any changes will be visible to the player. */ public void refreshCommands() { - sendPacket(MinecraftServer.getCommandManager().createDeclareCommandsPacket(this)); + sendPacket(serverProcess.getCommandManager().createDeclareCommandsPacket(this)); } @Override @@ -581,7 +588,7 @@ public void remove(boolean permanent) { final Inventory currentInventory = getOpenInventory(); if (currentInventory != null) currentInventory.removeViewer(this); - MinecraftServer.getBossBarManager().removeAllBossBars(this); + serverProcess.getBossBarManager().removeAllBossBars(this); // Advancement tabs cache { Set advancementTabs = AdvancementTab.getTabs(this); @@ -595,7 +602,7 @@ public void remove(boolean permanent) { final int chunkX = position.chunkX(); final int chunkZ = position.chunkZ(); // Clear all viewable chunks - ChunkUtils.forChunksInRange(chunkX, chunkZ, MinecraftServer.getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(chunkX, chunkZ, minecraftServer.getChunkViewDistance(), chunkRemover); // Remove from the tab-list PacketUtils.broadcastPlayPacket(getRemovePlayerToList()); @@ -647,7 +654,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Ensure that surrounding chunks are loaded List> futures = new ArrayList<>(); - ChunkUtils.forChunksInRange(spawnPosition, MinecraftServer.getChunkViewDistance(), (chunkX, chunkZ) -> { + ChunkUtils.forChunksInRange(spawnPosition, minecraftServer.getChunkViewDistance(), (chunkX, chunkZ) -> { final CompletableFuture future = instance.loadOptionalChunk(chunkX, chunkZ); if (!future.isDone()) futures.add(future); }); @@ -660,7 +667,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // One or more chunks need to be loaded final Thread runThread = Thread.currentThread(); CountDownLatch latch = new CountDownLatch(1); - Scheduler scheduler = MinecraftServer.getSchedulerManager(); + Scheduler scheduler = serverProcess.getSchedulerManager(); CompletableFuture future = new CompletableFuture<>() { @Override public Void join() { @@ -720,7 +727,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, if (!firstSpawn && !dimensionChange) { // Player instance changed, clear current viewable collections if (updateChunks) - ChunkUtils.forChunksInRange(spawnPosition, MinecraftServer.getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(spawnPosition, minecraftServer.getChunkViewDistance(), chunkRemover); } if (dimensionChange) sendDimension(instance.getDimensionType(), instance.getDimensionName()); @@ -735,7 +742,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new UpdateViewPositionPacket(chunkX, chunkZ)); // Load the nearby chunks and queue them to be sent to them - ChunkUtils.forChunksInRange(spawnPosition, MinecraftServer.getChunkViewDistance(), chunkAdder); + ChunkUtils.forChunksInRange(spawnPosition, minecraftServer.getChunkViewDistance(), chunkAdder); } synchronizePosition(true); // So the player doesn't get stuck @@ -976,12 +983,12 @@ public void clearTitle() { @Override public void showBossBar(@NotNull BossBar bar) { - MinecraftServer.getBossBarManager().addBossBar(this, bar); + serverProcess.getBossBarManager().addBossBar(this, bar); } @Override public void hideBossBar(@NotNull BossBar bar) { - MinecraftServer.getBossBarManager().removeBossBar(this, bar); + serverProcess.getBossBarManager().removeBossBar(this, bar); } @Override @@ -2053,7 +2060,7 @@ public void interpretPacketQueue() { kick(Component.text("Too Many Packets", NamedTextColor.RED)); return; } - final PacketListenerManager manager = MinecraftServer.getPacketListenerManager(); + final PacketListenerManager manager = serverProcess.getPacketListenerManager(); // This method is NOT thread-safe this.packets.drain(packet -> manager.processClientPacket(packet, playerConnection), PACKET_PER_TICK); } @@ -2347,7 +2354,7 @@ protected void sendChunkUpdates(Chunk newChunk) { final Vec old = chunksLoadedByClient; sendPacket(new UpdateViewPositionPacket(newX, newZ)); ChunkUtils.forDifferingChunksInRange(newX, newZ, (int) old.x(), (int) old.z(), - MinecraftServer.getChunkViewDistance(), chunkAdder, chunkRemover); + minecraftServer.getChunkViewDistance(), chunkAdder, chunkRemover); this.chunksLoadedByClient = new Vec(newX, newZ); } } @@ -2415,7 +2422,7 @@ public byte getViewDistance() { } public int getEffectiveViewDistance() { - return Math.min(getViewDistance(), MinecraftServer.getChunkViewDistance()); + return Math.min(getViewDistance(), minecraftServer.getChunkViewDistance()); } /** diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index d7487a4f4e3..9ce34f07583 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -28,13 +28,13 @@ * (events, velocity, gravity, player list, etc...) with the exception that you need to control it server-side * using a {@link FakePlayerController} (see {@link #getController()}). *

- * You can create one using {@link #initPlayer(UUID, String, Consumer)}. Be aware that this really behave exactly like a player + * You can create one using {@link #initPlayer(MinecraftServer, UUID, String, Consumer)}. Be aware that this really behave exactly like a player * and this is a feature not a bug, you will need to check at some place if the player is a fake one or not (instanceof) if you want to change it. */ public class FakePlayer extends Player implements NavigableEntity { - private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); - private static final PacketListenerManager PACKET_LISTENER_MANAGER = MinecraftServer.getPacketListenerManager(); + private final ConnectionManager connectionManager; + private final PacketListenerManager packetListenerManager; private final FakePlayerOption option; private final FakePlayerController fakePlayerController; @@ -50,10 +50,12 @@ public class FakePlayer extends Player implements NavigableEntity { * @param username The username for the fake player. * @param option Any option for the fake player. */ - protected FakePlayer(@NotNull UUID uuid, @NotNull String username, + protected FakePlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - super(uuid, username, new FakePlayerConnection()); + super(minecraftServer, uuid, username, new FakePlayerConnection()); + this.connectionManager = serverProcess.getConnectionManager(); + this.packetListenerManager = serverProcess.getPacketListenerManager(); this.option = option; @@ -66,16 +68,16 @@ protected FakePlayer(@NotNull UUID uuid, @NotNull String username, if (event.getPlayer().equals(this)) if (event.isFirstSpawn()) { spawnCallback.accept(this); - MinecraftServer.getGlobalEventHandler().removeListener(spawnListener); + serverProcess.getGlobalEventHandler().removeListener(spawnListener); } }).build(); - MinecraftServer.getGlobalEventHandler().addListener(spawnListener); + serverProcess.getGlobalEventHandler().addListener(spawnListener); } playerConnection.setConnectionState(ConnectionState.LOGIN); - CONNECTION_MANAGER.transitionLoginToConfig(this).thenRun(() -> { + connectionManager.transitionLoginToConfig(this).thenRun(() -> { // Need to immediately reply with login acknowledged for the player to enter config. - PACKET_LISTENER_MANAGER.processClientPacket(new ClientLoginAcknowledgedPacket(), getPlayerConnection()); + packetListenerManager.processClientPacket(new ClientLoginAcknowledgedPacket(), getPlayerConnection()); }); } @@ -86,23 +88,23 @@ protected FakePlayer(@NotNull UUID uuid, @NotNull String username, * @param username the FakePlayer username * @param spawnCallback the optional callback called when the fake player first spawn */ - public static void initPlayer(@NotNull UUID uuid, @NotNull String username, + public static void initPlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - new FakePlayer(uuid, username, option, spawnCallback); + new FakePlayer(minecraftServer, uuid, username, option, spawnCallback); } /** * Initializes a new {@link FakePlayer} without adding it in cache. *

* If you want the fake player to be obtainable with the {@link net.minestom.server.network.ConnectionManager} - * you need to specify it in a {@link FakePlayerOption} and use {@link #initPlayer(UUID, String, FakePlayerOption, Consumer)}. + * you need to specify it in a {@link FakePlayerOption} and use {@link #initPlayer(MinecraftServer, UUID, String, FakePlayerOption, Consumer)}. * * @param uuid the FakePlayer uuid * @param username the FakePlayer username * @param spawnCallback the optional callback called when the fake player first spawn */ - public static void initPlayer(@NotNull UUID uuid, @NotNull String username, @Nullable Consumer spawnCallback) { - initPlayer(uuid, username, new FakePlayerOption(), spawnCallback); + public static void initPlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @Nullable Consumer spawnCallback) { + initPlayer(minecraftServer, uuid, username, new FakePlayerOption(), spawnCallback); } /** @@ -164,7 +166,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - MinecraftServer.getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.SERVER_TICK).schedule(); + serverProcess.getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.SERVER_TICK).schedule(); } } } diff --git a/src/main/java/net/minestom/server/extras/query/Query.java b/src/main/java/net/minestom/server/extras/query/Query.java index 34087ced132..964b7ccbb3e 100644 --- a/src/main/java/net/minestom/server/extras/query/Query.java +++ b/src/main/java/net/minestom/server/extras/query/Query.java @@ -4,6 +4,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.event.EventDispatcher; import net.minestom.server.extras.query.event.BasicQueryEvent; import net.minestom.server.extras.query.event.FullQueryEvent; @@ -32,16 +33,20 @@ */ public class Query { public static final Charset CHARSET = StandardCharsets.ISO_8859_1; - private static final Logger LOGGER = LoggerFactory.getLogger(Query.class); - private static final Random RANDOM = new Random(); - private static final Int2ObjectMap CHALLENGE_TOKENS = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>()); - - private static volatile boolean started; - private static volatile DatagramSocket socket; - private static volatile Thread thread; - private static volatile Task task; - - private Query() { + private final Logger LOGGER = LoggerFactory.getLogger(Query.class); + private final Random RANDOM = new Random(); + private final Int2ObjectMap CHALLENGE_TOKENS = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>()); + + private volatile boolean started; + private volatile DatagramSocket socket; + private volatile Thread thread; + private volatile Task task; + private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; + + public Query(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); } /** @@ -50,7 +55,7 @@ private Query() { * @return the port * @throws IllegalArgumentException if the system was already running */ - public static int start() { + public int start() { if (socket != null) { throw new IllegalArgumentException("System is already running"); } else { @@ -66,7 +71,7 @@ public static int start() { * @param port the port * @return {@code true} if the query system started successfully, {@code false} otherwise */ - public static boolean start(int port) { + public boolean start(int port) { if (socket != null) { return false; } else { @@ -77,11 +82,11 @@ public static boolean start(int port) { return false; } - thread = new Thread(Query::run); + thread = new Thread(this::run); thread.start(); started = true; - task = MinecraftServer.getSchedulerManager() + task = serverProcess.getSchedulerManager() .buildTask(CHALLENGE_TOKENS::clear) .repeat(30, TimeUnit.SECOND) .schedule(); @@ -95,7 +100,7 @@ public static boolean start(int port) { * * @return {@code true} if the query system was stopped, {@code false} if it was not running */ - public static boolean stop() { + public boolean stop() { if (!started) { return false; } else { @@ -118,11 +123,11 @@ public static boolean stop() { * * @return {@code true} if it has been started, {@code false} otherwise */ - public static boolean isStarted() { + public boolean isStarted() { return started; } - private static void run() { + private void run() { final byte[] buffer = new byte[16]; while (started) { @@ -186,7 +191,7 @@ private static void run() { EventDispatcher.callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } else if (remaining == 5) { // full - FullQueryEvent event = new FullQueryEvent(sender, sessionID); + FullQueryEvent event = new FullQueryEvent(minecraftServer, sender, sessionID); EventDispatcher.callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } @@ -195,7 +200,7 @@ private static void run() { } } - private static void sendResponse(@NotNull Writeable queryResponse, int sessionID, @NotNull SocketAddress sender) { + private void sendResponse(@NotNull Writeable queryResponse, int sessionID, @NotNull SocketAddress sender) { // header BinaryWriter response = new BinaryWriter(); response.writeByte((byte) 0); diff --git a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java index 0b0ba2e52d5..80f82d32264 100644 --- a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java @@ -1,5 +1,6 @@ package net.minestom.server.extras.query.event; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.response.FullQueryResponse; import org.jetbrains.annotations.NotNull; @@ -13,10 +14,11 @@ public class FullQueryEvent extends QueryEvent { /** * Creates a new full query event. * - * @param sender the sender - * @param sessionID the sessionID + * @param minecraftServer + * @param sender the sender + * @param sessionID the sessionID */ - public FullQueryEvent(@NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new FullQueryResponse()); + public FullQueryEvent(MinecraftServer minecraftServer, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new FullQueryResponse(minecraftServer)); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java index aa9743d8f35..ef614a1cb6c 100644 --- a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java @@ -1,10 +1,9 @@ package net.minestom.server.extras.query.response; -import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.extras.query.Query; -import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.Writeable; import org.jetbrains.annotations.NotNull; @@ -18,6 +17,8 @@ public class FullQueryResponse implements Writeable { private static final PlainTextComponentSerializer PLAIN = PlainTextComponentSerializer.plainText(); private static final byte[] PADDING_10 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, PADDING_11 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private Map kv; private List players; @@ -25,15 +26,17 @@ public class FullQueryResponse implements Writeable { /** * Creates a new full query response with default values set. */ - public FullQueryResponse() { + public FullQueryResponse(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); this.kv = new HashMap<>(); // populate defaults for (QueryKey key : QueryKey.VALUES) { - this.kv.put(key.getKey(), key.getValue()); + this.kv.put(key.getKey(), key.getValue(minecraftServer)); } - this.players = MinecraftServer.getConnectionManager().getOnlinePlayers() + this.players = serverProcess.getConnectionManager().getOnlinePlayers() .stream() .map(player -> PLAIN.serialize(player.getName())) .toList(); @@ -119,8 +122,8 @@ public void setPlayers(@NotNull List players) { * * @return the string result */ - public static String generatePluginsValue() { - StringBuilder builder = new StringBuilder(MinecraftServer.getBrandName()) + public static String generatePluginsValue(MinecraftServer minecraftServer) { + StringBuilder builder = new StringBuilder(minecraftServer.getBrandName()) .append(' ') .append(MinecraftServer.VERSION_NAME); diff --git a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java index f5d1ed40993..6a8d1f093cb 100644 --- a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java +++ b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java @@ -7,33 +7,34 @@ import java.util.Locale; import java.util.Objects; +import java.util.function.Function; import java.util.function.Supplier; /** * An enum of default query keys. */ public enum QueryKey { - HOSTNAME(() -> "A Minestom Server"), - GAME_TYPE(() -> "SMP"), - GAME_ID("game_id", () -> "MINECRAFT"), - VERSION(() -> MinecraftServer.VERSION_NAME), + HOSTNAME((minecraftServer) -> "A Minestom Server"), + GAME_TYPE((minecraftServer) -> "SMP"), + GAME_ID("game_id", (minecraftServer) -> "MINECRAFT"), + VERSION((minecraftServer) -> MinecraftServer.VERSION_NAME), PLUGINS(FullQueryResponse::generatePluginsValue), - MAP(() -> "world"), - NUM_PLAYERS("numplayers", () -> String.valueOf(MinecraftServer.getConnectionManager().getOnlinePlayerCount())), - MAX_PLAYERS("maxplayers", () -> String.valueOf(MinecraftServer.getConnectionManager().getOnlinePlayerCount() + 1)), - HOST_PORT("hostport", () -> String.valueOf(MinecraftServer.getServer().getPort())), - HOST_IP("hostip", () -> Objects.requireNonNullElse(MinecraftServer.getServer().getAddress(), "localhost")); + MAP((minecraftServer) -> "world"), + NUM_PLAYERS("numplayers", (minecraftServer) -> String.valueOf(minecraftServer.process().getConnectionManager().getOnlinePlayerCount())), + MAX_PLAYERS("maxplayers", (minecraftServer) -> String.valueOf(minecraftServer.process().getConnectionManager().getOnlinePlayerCount() + 1)), + HOST_PORT("hostport", (minecraftServer) -> String.valueOf(minecraftServer.process().getServer().getPort())), + HOST_IP("hostip", (minecraftServer) -> Objects.requireNonNullElse(minecraftServer.process().getServer().getAddress(), "localhost")); static QueryKey[] VALUES = QueryKey.values(); private final String key; - private final Supplier value; + private final Function value; - QueryKey(@NotNull Supplier value) { + QueryKey(@NotNull Function value) { this(null, value); } - QueryKey(@Nullable String key, @NotNull Supplier value) { + QueryKey(@Nullable String key, @NotNull Function value) { this.key = Objects.requireNonNullElse(key, this.name().toLowerCase(Locale.ROOT).replace('_', ' ')); this.value = value; } @@ -52,7 +53,7 @@ public enum QueryKey { * * @return the value */ - public @NotNull String getValue() { - return this.value.get(); + public @NotNull String getValue(MinecraftServer minecraftServer) { + return this.value.apply(minecraftServer); } } diff --git a/src/main/java/net/minestom/server/instance/AnvilLoader.java b/src/main/java/net/minestom/server/instance/AnvilLoader.java index e7af40f3e0a..110d5c994a1 100644 --- a/src/main/java/net/minestom/server/instance/AnvilLoader.java +++ b/src/main/java/net/minestom/server/instance/AnvilLoader.java @@ -4,6 +4,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.IntIntImmutablePair; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockHandler; import net.minestom.server.utils.NamespaceID; @@ -37,6 +38,8 @@ public class AnvilLoader implements IChunkLoader { private static final Biome BIOME = Biome.PLAINS; private final Map alreadyLoaded = new ConcurrentHashMap<>(); + private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final Path path; private final Path levelPath; private final Path regionPath; @@ -52,14 +55,16 @@ private static class RegionCache extends ConcurrentHashMap> blockStateId2ObjectCacheTLS = ThreadLocal.withInitial(Int2ObjectArrayMap::new); - public AnvilLoader(@NotNull Path path) { + public AnvilLoader(@NotNull MinecraftServer minecraftServer, @NotNull Path path) { + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); this.path = path; this.levelPath = path.resolve("level.dat"); this.regionPath = path.resolve("region"); } - public AnvilLoader(@NotNull String path) { - this(Path.of(path)); + public AnvilLoader(@NotNull MinecraftServer minecraftServer, @NotNull String path) { + this(minecraftServer, Path.of(path)); } @Override @@ -72,7 +77,7 @@ public void loadInstance(@NotNull Instance instance) { Files.copy(levelPath, path.resolve("level.dat_old"), StandardCopyOption.REPLACE_EXISTING); instance.tagHandler().updateContent(tag); } catch (IOException | NBTException e) { - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } @@ -85,7 +90,7 @@ public void loadInstance(@NotNull Instance instance) { try { return loadMCA(instance, chunkX, chunkZ); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } return CompletableFuture.completedFuture(null); } @@ -151,7 +156,7 @@ public void loadInstance(@NotNull Instance instance) { } return new RegionFile(new RandomAccessFile(regionPath.toFile(), "rw"), regionX, regionZ, instance.getDimensionType().getMinY(), instance.getDimensionType().getMaxY() - 1); } catch (IOException | AnvilException e) { - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); return null; } }); @@ -189,7 +194,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { int finalY = sectionY * Chunk.CHUNK_SECTION_SIZE + y; String biomeName = sectionBiomeInformation.getBaseBiome(); Biome biome = biomeCache.computeIfAbsent(biomeName, n -> - Objects.requireNonNullElse(MinecraftServer.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); + Objects.requireNonNullElse(serverProcess.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); chunk.setBiome(finalX, finalY, finalZ, biome); } } @@ -205,7 +210,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { int index = x / 4 + (z / 4) * 4 + (y / 4) * 16; String biomeName = sectionBiomeInformation.getBiomes()[index]; Biome biome = biomeCache.computeIfAbsent(biomeName, n -> - Objects.requireNonNullElse(MinecraftServer.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); + Objects.requireNonNullElse(serverProcess.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); chunk.setBiome(finalX, finalY, finalZ, biome); } } @@ -247,7 +252,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { if (!properties.isEmpty()) block = block.withProperties(properties); // Handler - final BlockHandler handler = MinecraftServer.getBlockManager().getHandler(block.name()); + final BlockHandler handler = serverProcess.getBlockManager().getHandler(block.name()); if (handler != null) block = block.withHandler(handler); convertedPalette[i] = block; @@ -264,7 +269,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { chunk.setBlock(x, y + yOffset, z, block); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } } @@ -286,7 +291,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { final String tileEntityID = te.getString("id"); if (tileEntityID != null) { - final BlockHandler handler = MinecraftServer.getBlockManager().getHandlerOrDummy(tileEntityID); + final BlockHandler handler = serverProcess.getBlockManager().getHandlerOrDummy(tileEntityID); block = block.withHandler(handler); } // Remove anvil tags @@ -341,7 +346,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { alreadyLoaded.put(n, mcaFile); } catch (AnvilException | IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); return AsyncUtils.VOID_FUTURE; } } @@ -353,7 +358,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { mcaFile.writeColumnData(writer.toNBT(), chunk.getChunkX(), chunk.getChunkZ()); } catch (IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); return AsyncUtils.VOID_FUTURE; } return AsyncUtils.VOID_FUTURE; @@ -460,7 +465,7 @@ public void unloadChunk(Chunk chunk) { try { regionFile.close(); } catch (IOException e) { - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } } diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index ec148cc302a..10a249adf92 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -137,7 +137,7 @@ public Instance(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @N final ServerProcess process = MinecraftServer.process(); if (process != null) { - this.eventNode = process.eventHandler().map(this, EventFilter.INSTANCE); + this.eventNode = process.getGlobalEventHandler().map(this, EventFilter.INSTANCE); } else { // Local nodes require a server process this.eventNode = null; diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index 4caf952ea57..01187711cdf 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -3,6 +3,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.entity.damage.DamageType; import net.minestom.server.event.EventDispatcher; @@ -45,6 +46,9 @@ public final class ConnectionManager { private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class); + private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; + private static final long KEEP_ALIVE_DELAY = 10_000; private static final long KEEP_ALIVE_KICK = 30_000; private static final Component TIMEOUT_TEXT = Component.text("Timeout", NamedTextColor.RED); @@ -72,7 +76,15 @@ public final class ConnectionManager { // The uuid provider once a player login private volatile UuidProvider uuidProvider = (playerConnection, username) -> UUID.randomUUID(); // The player provider to have your own Player implementation - private volatile PlayerProvider playerProvider = Player::new; + private final PlayerProvider defaultPlayerProvider; + private volatile PlayerProvider playerProvider; + + public ConnectionManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); + defaultPlayerProvider = (uuid, username, connection) -> new Player(minecraftServer, uuid, username, connection); + playerProvider = defaultPlayerProvider; + } /** * Gets the number of "online" players, eg for the query response. @@ -198,7 +210,7 @@ public void setUuidProvider(@Nullable UuidProvider uuidProvider) { * @param playerProvider the new {@link PlayerProvider}, can be set to null to apply the default provider */ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { - this.playerProvider = playerProvider != null ? playerProvider : Player::new; + this.playerProvider = playerProvider != null ? playerProvider : defaultPlayerProvider; } /** @@ -220,7 +232,7 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { // Compression if (playerConnection instanceof PlayerSocketConnection socketConnection) { - final int threshold = MinecraftServer.getCompressionThreshold(); + final int threshold = minecraftServer.getCompressionThreshold(); if (threshold > 0) socketConnection.startCompression(); } @@ -263,7 +275,7 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); CompletableFuture configFuture = AsyncUtils.runAsync(() -> { - player.sendPacket(PluginMessagePacket.getBrandPacket()); + player.sendPacket(PluginMessagePacket.getBrandPacket(minecraftServer)); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); EventDispatcher.call(event); @@ -275,8 +287,8 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { if (event.willSendRegistryData()) { var registry = new HashMap(); registry.put("minecraft:chat_type", Messenger.chatRegistry()); - registry.put("minecraft:dimension_type", MinecraftServer.getDimensionTypeManager().toNBT()); - registry.put("minecraft:worldgen/biome", MinecraftServer.getBiomeManager().toNBT()); + registry.put("minecraft:dimension_type", serverProcess.getDimensionTypeManager().toNBT()); + registry.put("minecraft:worldgen/biome", serverProcess.getBiomeManager().toNBT()); registry.put("minecraft:damage_type", DamageType.getNBT()); player.sendPacket(new RegistryDataPacket(NBT.Compound(registry))); diff --git a/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java b/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java index 3edcda88b10..2b830804af7 100644 --- a/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java @@ -38,8 +38,8 @@ public int getId(@NotNull ConnectionState state) { * * @return the current brand name packet */ - public static @NotNull PluginMessagePacket getBrandPacket() { - final String brandName = MinecraftServer.getBrandName(); + public static @NotNull PluginMessagePacket getBrandPacket(MinecraftServer minecraftServer) { + final String brandName = minecraftServer.getBrandName(); final byte[] data = NetworkBuffer.makeArray(networkBuffer -> networkBuffer.write(STRING, brandName)); return new PluginMessagePacket("minecraft:brand", data); } diff --git a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java index 2319605aa00..a1f0378de5b 100644 --- a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java +++ b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java @@ -26,7 +26,7 @@ public void run() { try { serverProcess.ticker().tick(tickStart); } catch (Exception e) { - serverProcess.exception().handleException(e); + serverProcess.getExceptionManager().handleException(e); } fixTickRate(tickNs); } diff --git a/src/test/java/net/minestom/server/ServerProcessTest.java b/src/test/java/net/minestom/server/ServerProcessTest.java index 23fc5c7f2ec..b5ab64efce0 100644 --- a/src/test/java/net/minestom/server/ServerProcessTest.java +++ b/src/test/java/net/minestom/server/ServerProcessTest.java @@ -17,7 +17,7 @@ public void init() { assumeTrue(System.getenv("GITHUB_ACTIONS") == null); AtomicReference process = new AtomicReference<>(); - assertDoesNotThrow(() -> process.set(MinecraftServer.updateProcess())); + assertDoesNotThrow(() -> process.set(new MinecraftServer().updateProcess())); assertDoesNotThrow(() -> process.get().start(new InetSocketAddress("localhost", 25565))); assertThrows(Exception.class, () -> process.get().start(new InetSocketAddress("localhost", 25566))); assertDoesNotThrow(() -> process.get().stop()); @@ -28,7 +28,8 @@ public void tick() { // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); - var process = MinecraftServer.updateProcess(); + + var process = new MinecraftServer().updateProcess(); process.start(new InetSocketAddress("localhost", 25565)); var ticker = process.ticker(); assertDoesNotThrow(() -> ticker.tick(System.currentTimeMillis())); diff --git a/src/test/java/net/minestom/server/advancements/AdvancementIntegrationTest.java b/src/test/java/net/minestom/server/advancements/AdvancementIntegrationTest.java index d74d97e8b82..bcdd8789951 100644 --- a/src/test/java/net/minestom/server/advancements/AdvancementIntegrationTest.java +++ b/src/test/java/net/minestom/server/advancements/AdvancementIntegrationTest.java @@ -27,7 +27,7 @@ public void addAndRemoveViewer(Env env) { "minecraft:textures/block/stone.png" ); - AdvancementTab tab = env.process().advancement().createTab("minestom:minestom_tab", root); + AdvancementTab tab = env.process().getAdvancementManager().createTab("minestom:minestom_tab", root); // Add viewer tab.addViewer(player); @@ -70,8 +70,8 @@ public void removeViewerOnDisconnect(Env env) { "minecraft:textures/block/stone.png" ); - AdvancementTab tab1 = env.process().advancement().createTab("minestom:minestom_tab1", root1); - AdvancementTab tab2 = env.process().advancement().createTab("minestom:minestom_tab2", root2); + AdvancementTab tab1 = env.process().getAdvancementManager().createTab("minestom:minestom_tab1", root1); + AdvancementTab tab2 = env.process().getAdvancementManager().createTab("minestom:minestom_tab2", root2); tab1.addViewer(player); tab2.addViewer(player); diff --git a/src/test/java/net/minestom/server/command/CommandSuggestionIntegrationTest.java b/src/test/java/net/minestom/server/command/CommandSuggestionIntegrationTest.java index 638842a379e..c390878a4bf 100644 --- a/src/test/java/net/minestom/server/command/CommandSuggestionIntegrationTest.java +++ b/src/test/java/net/minestom/server/command/CommandSuggestionIntegrationTest.java @@ -35,7 +35,7 @@ public void suggestion(Env env) { suggestion.addEntry(new SuggestionEntry("test1")); })); - env.process().command().register(command); + env.process().getCommandManager().register(command); var listener = connection.trackIncoming(TabCompletePacket.class); player.addPacketToQueue(new ClientTabCompletePacket(3, "test te")); @@ -63,7 +63,7 @@ public void suggestionWithDefaults(Env env) { var command = new Command("foo"); command.addSyntax((sender,context)->{}, suggestArg, defaultArg); - env.process().command().register(command); + env.process().getCommandManager().register(command); var listener = connection.trackIncoming(TabCompletePacket.class); player.addPacketToQueue(new ClientTabCompletePacket(1, "foo 1")); diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index 42d6e2f2377..cfbc193142e 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -82,7 +82,7 @@ public void entityGC(Env env) { @Test public void entityNodeGC(Env env) { // Ensure that the entities GCed when a local listener is present - var node = env.process().eventHandler(); + var node = env.process().getGlobalEventHandler(); var entity = new Entity(EntityType.ZOMBIE); entity.eventNode().addListener(EntityTickEvent.class, event -> { }); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java index 833dc5bb973..a22e64b390f 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java @@ -145,10 +145,10 @@ public void playerJoinPackets(Env env) { public void refreshPlayerTest(Env env) { final int TEST_PERMISSION_LEVEL = 2; final var testDimension = DimensionType.builder(NamespaceID.from("minestom:test_dimension")).build(); - env.process().dimension().addDimension(testDimension); + env.process().getDimensionTypeManager().addDimension(testDimension); var instance = env.createFlatInstance(); - var instance2 = env.process().instance().createInstanceContainer(testDimension); + var instance2 = env.process().getInstanceManager().createInstanceContainer(testDimension); var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 42, 0)).join(); @@ -181,9 +181,9 @@ public void refreshPlayerTest(Env env) { public void deathLocationTest(Env env) { String dimensionNamespace = "minestom:test_dimension"; final var testDimension = DimensionType.builder(NamespaceID.from(dimensionNamespace)).build(); - env.process().dimension().addDimension(testDimension); + env.process().getDimensionTypeManager().addDimension(testDimension); - var instance = env.process().instance().createInstanceContainer(testDimension); + var instance = env.process().getInstanceManager().createInstanceContainer(testDimension); var connection = env.createConnection(); var player = connection.connect(instance, new Pos(5, 42, 2)).join(); diff --git a/src/test/java/net/minestom/server/event/EventNodeMapTest.java b/src/test/java/net/minestom/server/event/EventNodeMapTest.java index e803aa3e531..dc7a95e500d 100644 --- a/src/test/java/net/minestom/server/event/EventNodeMapTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeMapTest.java @@ -77,8 +77,8 @@ public void map() { @Test public void entityLocal() { - var process = MinecraftServer.updateProcess(); - var node = process.eventHandler(); + var process = new MinecraftServer().updateProcess(); + var node = process.getGlobalEventHandler(); var entity = new Entity(EntityType.ZOMBIE); AtomicBoolean result = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java index 429a26a0a49..fc6bf8278c2 100644 --- a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java @@ -22,7 +22,7 @@ public void basicJoin(boolean sharedInstance, Env env) { if (sharedInstance) { // Chunks get their viewers from the instance // Ensuring that the system works with shared instances is therefore important - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); instance = manager.createSharedInstance((InstanceContainer) instance); } diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java index 23c78ab95cf..05c66136165 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java @@ -107,7 +107,7 @@ public void viewable(Env env) { @Test public void viewableShared(Env env) { final InstanceContainer instance = (InstanceContainer) env.createFlatInstance(); - var shared = env.process().instance().createSharedInstance(instance); + var shared = env.process().getInstanceManager().createSharedInstance(instance); var sharedList = instance.getSharedInstances(); final Pos spawnPos = new Pos(0, 41, 0); @@ -124,7 +124,7 @@ public void viewableShared(Env env) { player.teleport(new Pos(10_000, 41, 0)).join(); assertEquals(0, viewable.getViewers().size()); - var shared2 = env.process().instance().createSharedInstance(instance); + var shared2 = env.process().getInstanceManager().createSharedInstance(instance); player.setInstance(shared2, spawnPos).join(); assertEquals(1, viewable.getViewers().size()); } diff --git a/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java b/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java index 5df0c70b1c6..2e121424067 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java @@ -18,7 +18,7 @@ public class GeneratorForkConsumerIntegrationTest { @Test public void empty(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); AtomicReference failed = new AtomicReference<>(); instance.setGenerator(unit -> { @@ -35,7 +35,7 @@ public void empty(Env env) { @Test public void local(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { unit.fork(setter -> { @@ -57,7 +57,7 @@ public void local(Env env) { @Test public void doubleLocal(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { unit.fork(setter -> { @@ -72,7 +72,7 @@ public void doubleLocal(Env env) { @Test public void neighborZ(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { unit.fork(setter -> { @@ -98,7 +98,7 @@ public void neighborZ(Env env) { @Test public void neighborX(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { unit.fork(setter -> { @@ -124,7 +124,7 @@ public void neighborX(Env env) { @Test public void neighborY(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { unit.fork(setter -> { @@ -148,7 +148,7 @@ public void neighborY(Env env) { @Test public void verticalAndHorizontalSectionBorders(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); Set points = ConcurrentHashMap.newKeySet(); instance.setGenerator(unit -> { diff --git a/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java b/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java index ec9b91cebac..9b946f7cc49 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java @@ -15,7 +15,7 @@ public class GeneratorForkIntegrationTest { @Test public void local(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); var block = Block.STONE; instance.setGenerator(unit -> { @@ -30,7 +30,7 @@ public void local(Env env) { @Test public void size(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); // Set the Generator instance.setGenerator(unit -> { @@ -47,7 +47,7 @@ public void size(Env env) { @Test public void signal(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); var block = Block.STONE; instance.setGenerator(unit -> { @@ -66,7 +66,7 @@ public void signal(Env env) { @Test public void air(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); @@ -80,7 +80,7 @@ public void air(Env env) { @Test public void fillHeight(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); @@ -96,7 +96,7 @@ public void fillHeight(Env env) { @Test public void biome(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); diff --git a/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java b/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java index e2ddf7d46b5..e5a7bdc383d 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java @@ -20,7 +20,7 @@ public class GeneratorIntegrationTest { @ParameterizedTest @ValueSource(booleans = {false, true}) public void loader(boolean data, Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var block = data ? Block.STONE.withNbt(NBT.Compound(Map.of("key", NBT.String("value")))) : Block.STONE; var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> unit.modifier().fill(block)); @@ -33,11 +33,11 @@ public void loader(boolean data, Env env) { @Test public void exceptionCatch(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); var ref = new AtomicReference(); - env.process().exception().setExceptionHandler(ref::set); + env.process().getExceptionManager().setExceptionHandler(ref::set); var exception = new RuntimeException(); instance.setGenerator(unit -> { @@ -51,7 +51,7 @@ public void exceptionCatch(Env env) { @Test public void fillHeightNegative(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> unit.modifier().fillHeight(-64, -60, Block.STONE)); instance.loadChunk(0, 0).join(); @@ -65,7 +65,7 @@ public void fillHeightNegative(Env env) { @Test public void fillHeightSingleSectionFull(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> unit.modifier().fillHeight(0, 16, Block.GRASS_BLOCK)); instance.loadChunk(0, 0).join(); @@ -76,7 +76,7 @@ public void fillHeightSingleSectionFull(Env env) { @Test public void fillHeightSingleSection(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> unit.modifier().fillHeight(4, 5, Block.GRASS_BLOCK)); instance.loadChunk(0, 0).join(); @@ -87,7 +87,7 @@ public void fillHeightSingleSection(Env env) { @Test public void fillHeightOverride(Env env) { - var manager = env.process().instance(); + var manager = env.process().getInstanceManager(); var instance = manager.createInstanceContainer(); instance.setGenerator(unit -> { unit.modifier().fillHeight(0, 39, Block.GRASS_BLOCK); diff --git a/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java index 8f2404e5a4c..b876ec9d65e 100644 --- a/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java @@ -14,7 +14,7 @@ public void registerAndUnregisterInstance(Env env) { var unregisterListener = env.listen(InstanceUnregisterEvent.class); registerListener.followup(); - Instance instance = env.process().instance().createInstanceContainer(); + Instance instance = env.process().getInstanceManager().createInstanceContainer(); unregisterListener.followup(); env.destroyInstance(instance); diff --git a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java index ed7173f89fe..728614c48b6 100644 --- a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java @@ -20,7 +20,7 @@ public class InstanceUnregisterIntegrationTest { @Test public void sharedInstance(Env env) { // Ensure that unregistering a shared instance does not unload the container chunks - var instanceManager = env.process().instance(); + var instanceManager = env.process().getInstanceManager(); var instance = instanceManager.createInstanceContainer(); var shared1 = instanceManager.createSharedInstance(instance); var connection = env.createConnection(); @@ -43,7 +43,7 @@ public void sharedInstance(Env env) { public void instanceGC(Env env) { var instance = env.createFlatInstance(); var ref = new WeakReference<>(instance); - env.process().instance().unregisterInstance(instance); + env.process().getInstanceManager().unregisterInstance(instance); //noinspection UnusedAssignment instance = null; @@ -56,13 +56,13 @@ final class Game { final Instance instance; Game(Env env) { - instance = env.process().instance().createInstanceContainer(); + instance = env.process().getInstanceManager().createInstanceContainer(); instance.eventNode().addListener(PlayerMoveEvent.class, e -> System.out.println(instance)); } } var game = new Game(env); var ref = new WeakReference<>(game); - env.process().instance().unregisterInstance(game.instance); + env.process().getInstanceManager().unregisterInstance(game.instance); //noinspection UnusedAssignment game = null; @@ -76,7 +76,7 @@ public void chunkGC(Env env) { var chunk = instance.loadChunk(0, 0).join(); var ref = new WeakReference<>(chunk); instance.unloadChunk(chunk); - env.process().instance().unregisterInstance(instance); + env.process().getInstanceManager().unregisterInstance(instance); env.tick(); // Required to remove the chunk from the thread dispatcher //noinspection UnusedAssignment @@ -87,12 +87,12 @@ public void chunkGC(Env env) { @Test public void testGCWithEventsLambda(Env env) { var ref = new WeakReference<>(new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD)); - env.process().instance().registerInstance(ref.get()); + env.process().getInstanceManager().registerInstance(ref.get()); tmp(ref.get()); ref.get().tick(0); - env.process().instance().unregisterInstance(ref.get()); + env.process().getInstanceManager().unregisterInstance(ref.get()); waitUntilCleared(ref); } diff --git a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java index a5ad6666bbf..3eac4fd2505 100644 --- a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java @@ -18,7 +18,7 @@ @EnvTest public class WorldRelightIntegrationTest { private @NotNull Instance createLightingInstance(@NotNull ServerProcess process) { - var instance = process.instance().createInstanceContainer(); + var instance = process.getInstanceManager().createInstanceContainer(); instance.setGenerator(unit -> { unit.modifier().fillHeight(39, 40, Block.STONE); unit.subdivide().forEach(u -> u.modifier().setBlock(0, 10, 0, Block.GLOWSTONE)); diff --git a/testing/src/main/java/net/minestom/testing/Env.java b/testing/src/main/java/net/minestom/testing/Env.java index 23f26476783..6961f0c1436 100644 --- a/testing/src/main/java/net/minestom/testing/Env.java +++ b/testing/src/main/java/net/minestom/testing/Env.java @@ -48,12 +48,12 @@ default boolean tickWhile(BooleanSupplier condition, Duration timeout) { } default @NotNull Instance createFlatInstance(IChunkLoader chunkLoader) { - var instance = process().instance().createInstanceContainer(chunkLoader); + var instance = process().getInstanceManager().createInstanceContainer(chunkLoader); instance.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); return instance; } default void destroyInstance(Instance instance) { - process().instance().unregisterInstance(instance); + process().getInstanceManager().unregisterInstance(instance); } } diff --git a/testing/src/main/java/net/minestom/testing/EnvImpl.java b/testing/src/main/java/net/minestom/testing/EnvImpl.java index 50c993f8f22..851743fe9ce 100644 --- a/testing/src/main/java/net/minestom/testing/EnvImpl.java +++ b/testing/src/main/java/net/minestom/testing/EnvImpl.java @@ -34,13 +34,13 @@ public EnvImpl(ServerProcess process) { @Override public @NotNull Collector trackEvent(@NotNull Class eventType, @NotNull EventFilter filter, @NotNull H actor) { var tracker = new EventCollector(actor); - this.process.eventHandler().map(actor, filter).addListener(eventType, tracker.events::add); + this.process.getGlobalEventHandler().map(actor, filter).addListener(eventType, tracker.events::add); return tracker; } @Override public @NotNull FlexibleListener listen(@NotNull Class eventType) { - var handler = process.eventHandler(); + var handler = process.getGlobalEventHandler(); var flexible = new FlexibleListenerImpl<>(eventType); var listener = EventListener.of(eventType, e -> flexible.handler.accept(e)); handler.addListener(listener); @@ -62,7 +62,7 @@ public EventCollector(Object handler) { @Override public @NotNull List collect() { - process.eventHandler().unmap(handler); + process.getGlobalEventHandler().unmap(handler); return List.copyOf(events); } } diff --git a/testing/src/main/java/net/minestom/testing/EnvTest.java b/testing/src/main/java/net/minestom/testing/EnvTest.java index cff8f74cfe1..310e88da11e 100644 --- a/testing/src/main/java/net/minestom/testing/EnvTest.java +++ b/testing/src/main/java/net/minestom/testing/EnvTest.java @@ -37,7 +37,7 @@ final class EnvParameterResolver extends TypeBasedParameterResolver { @Override public Env resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { - return new EnvImpl(MinecraftServer.updateProcess()); + return new EnvImpl(new MinecraftServer().updateProcess()); } } } diff --git a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java index f6c27013e89..5746e04d73e 100644 --- a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java @@ -37,19 +37,19 @@ final class TestConnectionImpl implements TestConnection { @Override public @NotNull CompletableFuture connect(@NotNull Instance instance, @NotNull Pos pos) { // Use player provider to disable queued chunk sending - process.connection().setPlayerProvider(TestPlayerImpl::new); + process.getConnectionManager().setPlayerProvider(TestPlayerImpl::new); playerConnection.setConnectionState(ConnectionState.LOGIN); - var player = process.connection().createPlayer(playerConnection, UUID.randomUUID(), "RandName"); + var player = process.getConnectionManager().createPlayer(playerConnection, UUID.randomUUID(), "RandName"); player.eventNode().addListener(AsyncPlayerConfigurationEvent.class, event -> { event.setSpawningInstance(instance); event.getPlayer().setRespawnPoint(pos); }); // Force the player through the entirety of the login process manually - process.connection().doConfiguration(player, true); - process.connection().transitionConfigToPlay(player); - process.connection().updateWaitingPlayers(); + process.getConnectionManager().doConfiguration(player, true); + process.getConnectionManager().transitionConfigToPlay(player); + process.getConnectionManager().updateWaitingPlayers(); return CompletableFuture.completedFuture(player); } From 1c2b172875ccc07f61b6cfba59dc779badb9ec6e Mon Sep 17 00:00:00 2001 From: MelonHell Date: Mon, 29 Jan 2024 02:11:24 +0300 Subject: [PATCH 02/16] more --- .../server/instance/EntityTracker.java | 5 +- .../server/instance/EntityTrackerImpl.java | 15 ++++-- .../minestom/server/instance/Instance.java | 20 +++++--- .../server/instance/InstanceContainer.java | 49 ++++++++++--------- .../server/instance/InstanceManager.java | 11 +++-- 5 files changed, 61 insertions(+), 39 deletions(-) diff --git a/src/main/java/net/minestom/server/instance/EntityTracker.java b/src/main/java/net/minestom/server/instance/EntityTracker.java index 0ca789ebd77..445b8e8724f 100644 --- a/src/main/java/net/minestom/server/instance/EntityTracker.java +++ b/src/main/java/net/minestom/server/instance/EntityTracker.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.MinecraftServer; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Entity; @@ -23,8 +24,8 @@ */ @ApiStatus.Experimental public sealed interface EntityTracker permits EntityTrackerImpl { - static @NotNull EntityTracker newTracker() { - return new EntityTrackerImpl(); + static @NotNull EntityTracker newTracker(MinecraftServer minecraftServer) { + return new EntityTrackerImpl(minecraftServer); } /** diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index bf61bf1a272..d2b5df819e7 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -27,6 +28,8 @@ import static net.minestom.server.utils.chunk.ChunkUtils.*; final class EntityTrackerImpl implements EntityTracker { + + private final MinecraftServer minecraftServer; static final AtomicInteger TARGET_COUNTER = new AtomicInteger(); // Store all data associated to a Target @@ -34,6 +37,10 @@ final class EntityTrackerImpl implements EntityTracker { final TargetEntry[] entries = EntityTracker.Target.TARGETS.stream().map((Function, TargetEntry>) TargetEntry::new).toArray(TargetEntry[]::new); private final Int2ObjectSyncMap entityPositions = Int2ObjectSyncMap.hashmap(); + EntityTrackerImpl(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + @Override public void register(@NotNull Entity entity, @NotNull Point point, @NotNull Target target, @Nullable Update update) { @@ -48,7 +55,7 @@ public void register(@NotNull Entity entity, @NotNull Point p } if (update != null) { update.referenceUpdate(point, this); - nearbyEntitiesByChunkRange(point, MinecraftServer.getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, minecraftServer.getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.add(newEntity); }); @@ -69,7 +76,7 @@ public void unregister(@NotNull Entity entity, } if (update != null) { update.referenceUpdate(point, null); - nearbyEntitiesByChunkRange(point, MinecraftServer.getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, minecraftServer.getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.remove(newEntity); }); @@ -181,7 +188,7 @@ private void difference(Point oldPoint, Point newPoint, @NotNull Target target, @NotNull Update update) { final TargetEntry entry = entries[target.ordinal()]; forDifferingChunksInRange(newPoint.chunkX(), newPoint.chunkZ(), oldPoint.chunkX(), oldPoint.chunkZ(), - MinecraftServer.getEntityViewDistance(), (chunkX, chunkZ) -> { + minecraftServer.getEntityViewDistance(), (chunkX, chunkZ) -> { // Add final List entities = entry.chunkEntities.get(getChunkIndex(chunkX, chunkZ)); if (entities == null || entities.isEmpty()) return; @@ -275,7 +282,7 @@ private Collection references() { } private void collectPlayers(EntityTracker tracker, Int2ObjectOpenHashMap map) { - tracker.nearbyEntitiesByChunkRange(point, MinecraftServer.getChunkViewDistance(), + tracker.nearbyEntitiesByChunkRange(point, minecraftServer.getChunkViewDistance(), EntityTracker.Target.PLAYERS, (player) -> map.putIfAbsent(player.getEntityId(), player)); } diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index 10a249adf92..d497c2ba021 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -18,6 +18,7 @@ import net.minestom.server.event.EventHandler; import net.minestom.server.event.EventNode; import net.minestom.server.event.instance.InstanceTickEvent; +import net.minestom.server.event.player.PlayerBlockBreakEvent; import net.minestom.server.event.trait.InstanceEvent; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; @@ -66,6 +67,7 @@ public abstract class Instance implements Block.Getter, Block.Setter, Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { + private final MinecraftServer minecraftServer; private boolean registered; private final DimensionType dimensionType; @@ -85,7 +87,7 @@ public abstract class Instance implements Block.Getter, Block.Setter, // Field for tick events private long lastTickAge = System.currentTimeMillis(); - private final EntityTracker entityTracker = new EntityTrackerImpl(); + private final EntityTracker entityTracker; private final ChunkCache blockRetriever = new ChunkCache(this, null, null); @@ -112,8 +114,8 @@ public abstract class Instance implements Block.Getter, Block.Setter, * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(uniqueId, dimensionType, dimensionType.getName()); + public Instance(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(minecraftServer, uniqueId, dimensionType, dimensionType.getName()); } /** @@ -122,9 +124,10 @@ public Instance(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + public Instance(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { Check.argCondition(!dimensionType.isRegistered(), "The dimension " + dimensionType.getName() + " is not registered! Please use DimensionTypeManager#addDimension"); + this.minecraftServer = minecraftServer; this.uniqueId = uniqueId; this.dimensionType = dimensionType; this.dimensionName = dimensionName.asString(); @@ -135,13 +138,14 @@ public Instance(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @N .withDynamic(Identity.UUID, this::getUniqueId) .build(); - final ServerProcess process = MinecraftServer.process(); + final ServerProcess process = minecraftServer.process(); if (process != null) { this.eventNode = process.getGlobalEventHandler().map(this, EventFilter.INSTANCE); } else { // Local nodes require a server process this.eventNode = null; } + entityTracker = new EntityTrackerImpl(minecraftServer); } /** @@ -173,7 +177,7 @@ public boolean placeBlock(@NotNull BlockHandler.Placement placement) { public abstract boolean placeBlock(@NotNull BlockHandler.Placement placement, boolean doBlockUpdates); /** - * Does call {@link net.minestom.server.event.player.PlayerBlockBreakEvent} + * Does call {@link PlayerBlockBreakEvent} * and send particle packets * * @param player the {@link Player} who break the block @@ -186,7 +190,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, } /** - * Does call {@link net.minestom.server.event.player.PlayerBlockBreakEvent} + * Does call {@link PlayerBlockBreakEvent} * and send particle packets * * @param player the {@link Player} who break the block @@ -697,7 +701,7 @@ public void tick(long time) { public @NotNull InstanceSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) { final Map> chunksMap = updater.referencesMapLong(getChunks(), ChunkUtils::getChunkIndex); final int[] entities = ArrayUtils.mapToIntArray(entityTracker.entities(), Entity::getEntityId); - return new SnapshotImpl.Instance(updater.reference(MinecraftServer.process()), + return new SnapshotImpl.Instance(updater.reference(minecraftServer.process()), getDimensionType(), getWorldAge(), getTime(), chunksMap, entities, tagHandler.readableCopy()); } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index 2bd1f2f8457..2742ac4f32e 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; @@ -32,6 +33,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.UnknownNullability; import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,7 +56,8 @@ public class InstanceContainer extends Instance { private static final Logger LOGGER = LoggerFactory.getLogger(InstanceContainer.class); - private static final AnvilLoader DEFAULT_LOADER = new AnvilLoader("world"); + private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private static final BlockFace[] BLOCK_UPDATE_FACES = new BlockFace[]{ BlockFace.WEST, BlockFace.EAST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.BOTTOM, BlockFace.TOP @@ -86,25 +89,27 @@ public class InstanceContainer extends Instance { protected InstanceContainer srcInstance; // only present if this instance has been created using a copy private long lastBlockChangeTime; // Time at which the last block change happened (#setBlock) - public InstanceContainer(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(uniqueId, dimensionType, null, dimensionType.getName()); + public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(minecraftServer, uniqueId, dimensionType, null, dimensionType.getName()); } - public InstanceContainer(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { - this(uniqueId, dimensionType, null, dimensionName); + public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + this(minecraftServer, uniqueId, dimensionType, null, dimensionName); } @ApiStatus.Experimental - public InstanceContainer(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - this(uniqueId, dimensionType, loader, dimensionType.getName()); + public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + this(minecraftServer, uniqueId, dimensionType, loader, dimensionType.getName()); } @ApiStatus.Experimental - public InstanceContainer(@NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { - super(uniqueId, dimensionType, dimensionName); + public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { + super(minecraftServer, uniqueId, dimensionType, dimensionName); setChunkSupplier(DynamicChunk::new); - setChunkLoader(Objects.requireNonNullElse(loader, DEFAULT_LOADER)); + setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(minecraftServer, "world"))); this.chunkLoader.loadInstance(this); + this.minecraftServer = minecraftServer; + this.serverProcess = minecraftServer.process(); } @Override @@ -150,7 +155,7 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in this.currentlyChangingBlocks.put(blockPosition, block); // Change id based on neighbors - final BlockPlacementRule blockPlacementRule = MinecraftServer.getBlockManager().getBlockPlacementRule(block); + final BlockPlacementRule blockPlacementRule = serverProcess.getBlockManager().getBlockPlacementRule(block); if (placement != null && blockPlacementRule != null && doBlockUpdates) { BlockPlacementRule.PlacementState rulePlacement; if (placement instanceof BlockHandler.PlayerPlacement pp) { @@ -261,7 +266,7 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { if (chunkLoader != null) { chunkLoader.unloadChunk(chunk); } - var dispatcher = MinecraftServer.process().dispatcher(); + var dispatcher = serverProcess.dispatcher(); dispatcher.deletePartition(chunk); } @@ -313,7 +318,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { completableFuture.complete(chunk); }) .exceptionally(throwable -> { - MinecraftServer.getExceptionManager().handleException(throwable); + serverProcess.getExceptionManager().handleException(throwable); return null; }); if (loader.supportsParallelLoading()) { @@ -366,7 +371,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { } forkChunk.sendChunk(); } else { - final long index = ChunkUtils.getChunkIndex(start); + final long index = getChunkIndex(start); this.generationForks.compute(index, (i, sectionModifiers) -> { if (sectionModifiers == null) sectionModifiers = new ArrayList<>(); sectionModifiers.add(sectionModifier); @@ -379,7 +384,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { // Apply awaiting forks processFork(chunk); } catch (Throwable e) { - MinecraftServer.getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } finally { // End generation refreshLastBlockChangeTime(); @@ -395,7 +400,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { } private void processFork(Chunk chunk) { - this.generationForks.compute(ChunkUtils.getChunkIndex(chunk), (aLong, sectionModifiers) -> { + this.generationForks.compute(getChunkIndex(chunk), (aLong, sectionModifiers) -> { if (sectionModifiers != null) { for (var sectionModifier : sectionModifiers) { applyFork(chunk, sectionModifier); @@ -423,9 +428,9 @@ private void applyGenerationData(Chunk chunk, GeneratorImpl.SectionModifierImpl Int2ObjectMaps.fastForEach(cache, blockEntry -> { final int index = blockEntry.getIntKey(); final Block block = blockEntry.getValue(); - final int x = ChunkUtils.blockIndexToChunkPositionX(index); - final int y = ChunkUtils.blockIndexToChunkPositionY(index) + height; - final int z = ChunkUtils.blockIndexToChunkPositionZ(index); + final int x = blockIndexToChunkPositionX(index); + final int y = blockIndexToChunkPositionY(index) + height; + final int z = blockIndexToChunkPositionZ(index); chunk.setBlock(x, y, z, block); }); } @@ -514,7 +519,7 @@ protected void addSharedInstance(SharedInstance sharedInstance) { * @see #getSrcInstance() to retrieve the "creation source" of the copied instance */ public synchronized InstanceContainer copy() { - InstanceContainer copiedInstance = new InstanceContainer(UUID.randomUUID(), getDimensionType()); + InstanceContainer copiedInstance = new InstanceContainer(minecraftServer, UUID.randomUUID(), getDimensionType()); copiedInstance.srcInstance = this; copiedInstance.tagHandler = this.tagHandler.copy(); copiedInstance.lastBlockChangeTime = this.lastBlockChangeTime; @@ -638,7 +643,7 @@ private void executeNeighboursBlockPlacementRule(@NotNull Point blockPosition, i final Block neighborBlock = cache.getBlock(neighborX, neighborY, neighborZ, Condition.TYPE); if (neighborBlock == null) continue; - final BlockPlacementRule neighborBlockPlacementRule = MinecraftServer.getBlockManager().getBlockPlacementRule(neighborBlock); + final BlockPlacementRule neighborBlockPlacementRule = serverProcess.getBlockManager().getBlockPlacementRule(neighborBlock); if (neighborBlockPlacementRule == null || updateDistance >= neighborBlockPlacementRule.maxUpdateDistance()) continue; final Vec neighborPosition = new Vec(neighborX, neighborY, neighborZ); @@ -668,7 +673,7 @@ private CompletableFuture loadOrRetrieve(int chunkX, int chunkZ, Supplier private void cacheChunk(@NotNull Chunk chunk) { this.chunks.put(getChunkIndex(chunk), chunk); - var dispatcher = MinecraftServer.process().dispatcher(); + var dispatcher = serverProcess.dispatcher(); dispatcher.createPartition(chunk); } } diff --git a/src/main/java/net/minestom/server/instance/InstanceManager.java b/src/main/java/net/minestom/server/instance/InstanceManager.java index 2a0bc676993..1fa9b36fba0 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManager.java +++ b/src/main/java/net/minestom/server/instance/InstanceManager.java @@ -20,9 +20,14 @@ * Used to register {@link Instance}. */ public final class InstanceManager { + private final MinecraftServer minecraftServer; private final Set instances = new CopyOnWriteArraySet<>(); + public InstanceManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + /** * Registers an {@link Instance} internally. *

@@ -46,7 +51,7 @@ public void registerInstance(@NotNull Instance instance) { */ @ApiStatus.Experimental public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - final InstanceContainer instanceContainer = new InstanceContainer(UUID.randomUUID(), dimensionType, loader); + final InstanceContainer instanceContainer = new InstanceContainer(minecraftServer, UUID.randomUUID(), dimensionType, loader); registerInstance(instanceContainer); return instanceContainer; } @@ -118,7 +123,7 @@ public void unregisterInstance(@NotNull Instance instance) { // Unload all chunks if (instance instanceof InstanceContainer) { instance.getChunks().forEach(instance::unloadChunk); - var dispatcher = MinecraftServer.process().dispatcher(); + var dispatcher = minecraftServer.process().dispatcher(); instance.getChunks().forEach(dispatcher::deletePartition); } // Unregister @@ -160,7 +165,7 @@ public void unregisterInstance(@NotNull Instance instance) { private void UNSAFE_registerInstance(@NotNull Instance instance) { instance.setRegistered(true); this.instances.add(instance); - var dispatcher = MinecraftServer.process().dispatcher(); + var dispatcher = minecraftServer.process().dispatcher(); instance.getChunks().forEach(dispatcher::createPartition); InstanceRegisterEvent event = new InstanceRegisterEvent(instance); EventDispatcher.call(event); From 43a2f6a88fff4e2cc0b28da18e390c2d7868d173 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Mon, 29 Jan 2024 11:32:56 +0300 Subject: [PATCH 03/16] and more --- .../src/main/java/net/minestom/demo/Main.java | 12 +-- .../minestom/server/ServerProcessImpl.java | 11 ++- .../server/command/CommandManager.java | 11 +-- .../net/minestom/server/entity/Entity.java | 39 +++++----- .../server/entity/EntityCreature.java | 12 +-- .../server/entity/EntityProjectile.java | 14 ++-- .../minestom/server/entity/ItemEntity.java | 8 +- .../minestom/server/entity/LivingEntity.java | 20 ++--- .../net/minestom/server/entity/Player.java | 78 +++++++++---------- .../server/entity/PlayerProjectile.java | 3 +- .../server/event/EventDispatcher.java | 20 ----- .../minestom/server/extras/lan/OpenToLAN.java | 34 ++++---- .../minestom/server/extras/query/Query.java | 5 +- .../minestom/server/instance/Instance.java | 3 +- .../server/instance/InstanceContainer.java | 9 +-- .../server/instance/InstanceManager.java | 5 +- .../server/inventory/AbstractInventory.java | 13 ++-- .../minestom/server/inventory/Inventory.java | 15 ++-- .../inventory/InventoryClickHandler.java | 6 +- .../server/inventory/PlayerInventory.java | 14 ++-- .../click/InventoryClickProcessor.java | 12 ++- .../server/listener/AbilitiesListener.java | 5 +- .../listener/AdvancementTabListener.java | 3 +- .../server/listener/AnimationListener.java | 3 +- .../listener/BlockPlacementListener.java | 16 ++-- .../server/listener/BookListener.java | 3 +- .../server/listener/ChatMessageListener.java | 14 +--- .../server/listener/EntityActionListener.java | 11 ++- .../listener/PlayerDiggingListener.java | 9 +-- .../server/listener/PlayerHeldListener.java | 3 +- .../listener/PlayerPositionListener.java | 3 +- .../server/listener/SpectateListener.java | 3 +- .../server/listener/UseEntityListener.java | 5 +- .../server/listener/UseItemListener.java | 7 +- .../server/listener/WindowListener.java | 3 +- .../common/PluginMessageListener.java | 3 +- .../listener/common/ResourcePackListener.java | 3 +- .../listener/common/SettingsListener.java | 3 +- .../manager/PacketListenerManager.java | 11 +-- .../listener/preplay/StatusListener.java | 8 +- .../server/network/ConnectionManager.java | 5 +- .../network/player/FakePlayerConnection.java | 4 + .../network/player/PlayerConnection.java | 10 ++- .../player/PlayerSocketConnection.java | 18 ++--- .../server/network/socket/Server.java | 10 ++- .../server/network/socket/Worker.java | 12 +-- .../minestom/testing/TestConnectionImpl.java | 5 ++ 47 files changed, 244 insertions(+), 280 deletions(-) delete mode 100644 src/main/java/net/minestom/server/event/EventDispatcher.java diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index 27424dbc15e..6756b31932c 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -31,11 +31,11 @@ public static void main(String[] args) { minecraftServer.init(); - BlockManager blockManager = minecraftServer.getBlockManager(); + BlockManager blockManager = minecraftServer.process().getBlockManager(); blockManager.registerBlockPlacementRule(new DripstonePlacementRule()); blockManager.registerHandler(TestBlockHandler.INSTANCE.getNamespaceId(), () -> TestBlockHandler.INSTANCE); - CommandManager commandManager = minecraftServer.getCommandManager(); + CommandManager commandManager = minecraftServer.process().getCommandManager(); commandManager.register(new TestCommand()); commandManager.register(new EntitySelectorCommand()); commandManager.register(new HealthCommand()); @@ -67,11 +67,11 @@ public static void main(String[] args) { commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED))); - minecraftServer.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); + minecraftServer.process().getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); - minecraftServer.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); + minecraftServer.process().getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); - minecraftServer.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { + minecraftServer.process().getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { ResponseData responseData = event.getResponseData(); responseData.addEntry(NamedAndIdentified.named("The first line is separated from the others")); responseData.addEntry(NamedAndIdentified.named("Could be a name, or a message")); @@ -113,7 +113,7 @@ public static void main(String[] args) { //MojangAuth.init(); // useful for testing - we don't need to worry about event calls so just set this to a long time - OpenToLAN.open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); + new OpenToLAN(minecraftServer).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); minecraftServer.start("0.0.0.0", 25565); // minecraftServer.start(java.net.UnixDomainSocketAddress.of("minestom-demo.sock")); diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java index c66bc546771..f0610b3efdb 100644 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -5,7 +5,6 @@ import net.minestom.server.adventure.bossbar.BossBarManager; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Entity; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ServerTickMonitorEvent; import net.minestom.server.exception.ExceptionManager; @@ -76,11 +75,11 @@ public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { this.minecraftServer = minecraftServer; this.exception = new ExceptionManager(); this.connection = new ConnectionManager(minecraftServer); - this.packetListener = new PacketListenerManager(); + this.packetListener = new PacketListenerManager(minecraftServer); this.packetProcessor = new PacketProcessor(packetListener); - this.instance = new InstanceManager(); + this.instance = new InstanceManager(minecraftServer); this.block = new BlockManager(); - this.command = new CommandManager(); + this.command = new CommandManager(minecraftServer); this.recipe = new RecipeManager(); this.team = new TeamManager(); this.eventHandler = new GlobalEventHandler(); @@ -91,7 +90,7 @@ public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { this.advancement = new AdvancementManager(); this.bossBar = new BossBarManager(); this.tag = new TagManager(); - this.server = new Server(packetProcessor); + this.server = new Server(minecraftServer, packetProcessor); this.dispatcher = ThreadDispatcher.singleThread(); this.ticker = new TickerImpl(); @@ -278,7 +277,7 @@ public void tick(long nanoTime) { final double acquisitionTimeMs = Acquirable.resetAcquiringTime() / 1e6D; final double tickTimeMs = (System.nanoTime() - nanoTime) / 1e6D; final TickMonitor tickMonitor = new TickMonitor(tickTimeMs, acquisitionTimeMs); - EventDispatcher.call(new ServerTickMonitorEvent(tickMonitor)); + getGlobalEventHandler().call(new ServerTickMonitorEvent(tickMonitor)); } } diff --git a/src/main/java/net/minestom/server/command/CommandManager.java b/src/main/java/net/minestom/server/command/CommandManager.java index 08486941e89..0dc45c724a6 100644 --- a/src/main/java/net/minestom/server/command/CommandManager.java +++ b/src/main/java/net/minestom/server/command/CommandManager.java @@ -6,7 +6,6 @@ import net.minestom.server.command.builder.CommandResult; import net.minestom.server.command.builder.ParsedCommand; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerCommandEvent; import net.minestom.server.network.packet.server.play.DeclareCommandsPacket; import net.minestom.server.utils.callback.CommandCallback; @@ -36,8 +35,10 @@ public final class CommandManager { private final Set commands = new HashSet<>(); private CommandCallback unknownCommandCallback; + private final MinecraftServer minecraftServer; - public CommandManager() { + public CommandManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; } /** @@ -107,7 +108,7 @@ public boolean commandExists(@NotNull String commandName) { // Command event if (sender instanceof Player player) { PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, command); - EventDispatcher.call(playerCommandEvent); + minecraftServer.process().getGlobalEventHandler().call(playerCommandEvent); if (playerCommandEvent.isCancelled()) return CommandResult.of(CommandResult.Type.CANCELLED, command); command = playerCommandEvent.getCommand(); @@ -140,7 +141,7 @@ class Reflection { try { callable.call(); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } }); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); @@ -148,7 +149,7 @@ class Reflection { return callable.call(); } } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); } } diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index e35d65462bb..c92cc9e6ba5 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -15,7 +15,6 @@ import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.EntityMeta; import net.minestom.server.entity.metadata.LivingEntityMeta; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.EventFilter; import net.minestom.server.event.EventHandler; import net.minestom.server.event.EventNode; @@ -93,6 +92,7 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev private static final AtomicInteger LAST_ENTITY_ID = new AtomicInteger(); private final CachedPacket destroyPacketCache = new CachedPacket(() -> new DestroyEntitiesPacket(getEntityId())); + public final MinecraftServer minecraftServer; protected Instance instance; protected Chunk currentChunk; @@ -180,7 +180,8 @@ public void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracke private final Acquirable acquirable = Acquirable.of(this); - public Entity(@NotNull EntityType entityType, @NotNull UUID uuid) { + public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { + this.minecraftServer = minecraftServer; this.id = generateId(); this.entityType = entityType; this.uuid = uuid; @@ -198,7 +199,7 @@ public Entity(@NotNull EntityType entityType, @NotNull UUID uuid) { this.gravityAcceleration = entityType.registry().acceleration(); this.gravityDragPerTick = entityType.registry().drag(); - final ServerProcess process = MinecraftServer.process(); + final ServerProcess process = minecraftServer.process(); if (process != null) { this.eventNode = process.getGlobalEventHandler().map(this, EventFilter.ENTITY); } else { @@ -207,8 +208,8 @@ public Entity(@NotNull EntityType entityType, @NotNull UUID uuid) { } } - public Entity(@NotNull EntityType entityType) { - this(entityType, UUID.randomUUID()); + public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { + this(minecraftServer, entityType, UUID.randomUUID()); } /** @@ -562,7 +563,7 @@ public void tick(long time) { update(time); ticks++; - EventDispatcher.call(new EntityTickEvent(this)); + minecraftServer.process().getGlobalEventHandler().call(new EntityTickEvent(this)); // remove expired effects effectTick(time); @@ -731,7 +732,7 @@ private void effectTick(long time) { if (time >= timedPotion.getStartingTime() + potionTime) { // Send the packet that the potion should no longer be applied timedPotion.getPotion().sendRemovePacket(this); - EventDispatcher.call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + minecraftServer.process().getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); return true; } return false; @@ -846,7 +847,7 @@ public void setBoundingBox(BoundingBox boundingBox) { @ApiStatus.Internal protected void refreshCurrentChunk(Chunk currentChunk) { this.currentChunk = currentChunk; - MinecraftServer.process().dispatcher().updateElement(this, currentChunk); + minecraftServer.process().dispatcher().updateElement(this, currentChunk); } /** @@ -875,7 +876,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull return teleport(spawnPosition); // Already in the instance, teleport to spawn point } AddEntityToInstanceEvent event = new AddEntityToInstanceEvent(instance, this); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); if (event.isCancelled()) return null; // TODO what to return? if (previousInstance != null) removeFromInstance(previousInstance); @@ -894,9 +895,9 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull } instance.getEntityTracker().register(this, spawnPosition, trackingTarget, trackingUpdate); spawn(); - EventDispatcher.call(new EntitySpawnEvent(this, instance)); + minecraftServer.process().getGlobalEventHandler().call(new EntitySpawnEvent(this, instance)); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } }); } @@ -919,7 +920,7 @@ public CompletableFuture setInstance(@NotNull Instance instance) { } private void removeFromInstance(Instance instance) { - EventDispatcher.call(new RemoveEntityFromInstanceEvent(instance, this)); + minecraftServer.process().getGlobalEventHandler().call(new RemoveEntityFromInstanceEvent(instance, this)); instance.getEntityTracker().unregister(this, trackingTarget, trackingUpdate); this.viewEngine.forManuals(this::removeViewer); } @@ -942,7 +943,7 @@ private void removeFromInstance(Instance instance) { */ public void setVelocity(@NotNull Vec velocity) { EntityVelocityEvent entityVelocityEvent = new EntityVelocityEvent(this, velocity); - EventDispatcher.callCancellable(entityVelocityEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(entityVelocityEvent, () -> { this.velocity = entityVelocityEvent.getVelocity(); sendPacketToViewersAndSelf(getVelocityPacket()); }); @@ -1460,7 +1461,7 @@ public void addEffect(@NotNull Potion potion) { removeEffect(potion.effect()); this.effects.add(new TimedPotion(potion, System.currentTimeMillis())); potion.sendAddPacket(this); - EventDispatcher.call(new EntityPotionAddEvent(this, potion)); + minecraftServer.process().getGlobalEventHandler().call(new EntityPotionAddEvent(this, potion)); } /** @@ -1472,7 +1473,7 @@ public void removeEffect(@NotNull PotionEffect effect) { this.effects.removeIf(timedPotion -> { if (timedPotion.getPotion().effect() == effect) { timedPotion.getPotion().sendRemovePacket(this); - EventDispatcher.call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + minecraftServer.process().getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); return true; } return false; @@ -1515,7 +1516,7 @@ public int getEffectLevel(@NotNull PotionEffect effect) { public void clearEffects() { for (TimedPotion timedPotion : effects) { timedPotion.getPotion().sendRemovePacket(this); - EventDispatcher.call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + minecraftServer.process().getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); } this.effects.clear(); } @@ -1531,11 +1532,11 @@ public void remove() { protected void remove(boolean permanent) { if (isRemoved()) return; - EventDispatcher.call(new EntityDespawnEvent(this)); + minecraftServer.process().getGlobalEventHandler().call(new EntityDespawnEvent(this)); try { despawn(); } catch (Throwable t) { - MinecraftServer.getExceptionManager().handleException(t); + minecraftServer.process().getExceptionManager().handleException(t); } // Remove passengers if any (also done with LivingEntity#kill) @@ -1544,7 +1545,7 @@ protected void remove(boolean permanent) { final Entity vehicle = this.vehicle; if (vehicle != null) vehicle.removePassenger(this); - MinecraftServer.process().dispatcher().removeElement(this); + minecraftServer.process().dispatcher().removeElement(this); this.removed = true; if (permanent) { Entity.ENTITY_BY_ID.remove(id); diff --git a/src/main/java/net/minestom/server/entity/EntityCreature.java b/src/main/java/net/minestom/server/entity/EntityCreature.java index fdbf64d3d27..24c995c845f 100644 --- a/src/main/java/net/minestom/server/entity/EntityCreature.java +++ b/src/main/java/net/minestom/server/entity/EntityCreature.java @@ -1,12 +1,12 @@ package net.minestom.server.entity; import com.extollit.gaming.ai.path.HydrazinePathFinder; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.ai.EntityAI; import net.minestom.server.entity.ai.EntityAIGroup; import net.minestom.server.entity.pathfinding.NavigableEntity; import net.minestom.server.entity.pathfinding.Navigator; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.entity.EntityAttackEvent; import net.minestom.server.instance.Instance; import net.minestom.server.utils.time.TimeUnit; @@ -33,13 +33,13 @@ public class EntityCreature extends LivingEntity implements NavigableEntity, Ent /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public EntityCreature(@NotNull EntityType entityType, @NotNull UUID uuid) { - super(entityType, uuid); + public EntityCreature(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(minecraftServer, entityType, uuid); heal(); } - public EntityCreature(@NotNull EntityType entityType) { - this(entityType, UUID.randomUUID()); + public EntityCreature(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { + this(minecraftServer, entityType, UUID.randomUUID()); } @Override @@ -134,7 +134,7 @@ public void attack(@NotNull Entity target, boolean swingHand) { if (swingHand) swingMainHand(); EntityAttackEvent attackEvent = new EntityAttackEvent(this, target); - EventDispatcher.call(attackEvent); + minecraftServer.process().getGlobalEventHandler().call(attackEvent); } /** diff --git a/src/main/java/net/minestom/server/entity/EntityProjectile.java b/src/main/java/net/minestom/server/entity/EntityProjectile.java index eda26624a04..676af1f2f0b 100644 --- a/src/main/java/net/minestom/server/entity/EntityProjectile.java +++ b/src/main/java/net/minestom/server/entity/EntityProjectile.java @@ -1,11 +1,11 @@ package net.minestom.server.entity; +import net.minestom.server.MinecraftServer; import net.minestom.server.collision.BoundingBox; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.projectile.ProjectileMeta; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.entity.EntityShootEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithEntityEvent; @@ -30,8 +30,8 @@ public class EntityProjectile extends Entity { private final Entity shooter; - public EntityProjectile(@Nullable Entity shooter, @NotNull EntityType entityType) { - super(entityType); + public EntityProjectile(@NotNull MinecraftServer minecraftServer, @Nullable Entity shooter, @NotNull EntityType entityType) { + super(minecraftServer, entityType); this.shooter = shooter; setup(); } @@ -50,7 +50,7 @@ public Entity getShooter() { public void shoot(Point to, double power, double spread) { final EntityShootEvent shootEvent = new EntityShootEvent(this.shooter, this, to, power, spread); - EventDispatcher.call(shootEvent); + minecraftServer.process().getGlobalEventHandler().call(shootEvent); if (shootEvent.isCancelled()) { remove(); return; @@ -105,7 +105,7 @@ public void tick(long time) { } super.onGround = false; setNoGravity(false); - EventDispatcher.call(new ProjectileUncollideEvent(this)); + minecraftServer.process().getGlobalEventHandler().call(new ProjectileUncollideEvent(this)); } } @@ -147,7 +147,7 @@ private boolean isStuck(Pos pos, Pos posNow) { } if (block.isSolid()) { final ProjectileCollideWithBlockEvent event = new ProjectileCollideWithBlockEvent(this, pos, block); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); if (!event.isCancelled()) { teleport(pos); return true; @@ -175,7 +175,7 @@ private boolean isStuck(Pos pos, Pos posNow) { if (victimOptional.isPresent()) { final LivingEntity target = victimOptional.get(); final ProjectileCollideWithEntityEvent event = new ProjectileCollideWithEntityEvent(this, pos, target); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); if (!event.isCancelled()) { return super.onGround; } diff --git a/src/main/java/net/minestom/server/entity/ItemEntity.java b/src/main/java/net/minestom/server/entity/ItemEntity.java index f0ff33d7bde..cbfc139060a 100644 --- a/src/main/java/net/minestom/server/entity/ItemEntity.java +++ b/src/main/java/net/minestom/server/entity/ItemEntity.java @@ -1,7 +1,7 @@ package net.minestom.server.entity; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.metadata.item.ItemEntityMeta; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.entity.EntityItemMergeEvent; import net.minestom.server.instance.EntityTracker; import net.minestom.server.item.ItemStack; @@ -38,8 +38,8 @@ public class ItemEntity extends Entity { private long spawnTime; private long pickupDelay; - public ItemEntity(@NotNull ItemStack itemStack) { - super(EntityType.ITEM); + public ItemEntity(@NotNull MinecraftServer minecraftServer, @NotNull ItemStack itemStack) { + super(minecraftServer, EntityType.ITEM); setItemStack(itemStack); setBoundingBox(0.25f, 0.25f, 0.25f); } @@ -85,7 +85,7 @@ public void update(long time) { if (!stackingRule.canApply(itemStack, totalAmount)) return; final ItemStack result = stackingRule.apply(itemStack, totalAmount); EntityItemMergeEvent entityItemMergeEvent = new EntityItemMergeEvent(this, itemEntity, result); - EventDispatcher.callCancellable(entityItemMergeEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(entityItemMergeEvent, () -> { setItemStack(entityItemMergeEvent.getResult()); itemEntity.remove(); }); diff --git a/src/main/java/net/minestom/server/entity/LivingEntity.java b/src/main/java/net/minestom/server/entity/LivingEntity.java index 368f9188233..f0f64346b7f 100644 --- a/src/main/java/net/minestom/server/entity/LivingEntity.java +++ b/src/main/java/net/minestom/server/entity/LivingEntity.java @@ -1,6 +1,7 @@ package net.minestom.server.entity; import net.kyori.adventure.sound.Sound.Source; +import net.minestom.server.MinecraftServer; import net.minestom.server.attribute.Attribute; import net.minestom.server.attribute.AttributeInstance; import net.minestom.server.collision.BoundingBox; @@ -9,7 +10,6 @@ import net.minestom.server.entity.damage.Damage; import net.minestom.server.entity.damage.DamageType; import net.minestom.server.entity.metadata.LivingEntityMeta; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.entity.EntityDamageEvent; import net.minestom.server.event.entity.EntityDeathEvent; import net.minestom.server.event.entity.EntityFireEvent; @@ -86,13 +86,13 @@ public class LivingEntity extends Entity implements EquipmentHandler { /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public LivingEntity(@NotNull EntityType entityType, @NotNull UUID uuid) { - super(entityType, uuid); + public LivingEntity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(minecraftServer, entityType, uuid); initEquipments(); } - public LivingEntity(@NotNull EntityType entityType) { - this(entityType, UUID.randomUUID()); + public LivingEntity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { + this(minecraftServer, entityType, UUID.randomUUID()); } private void initEquipments() { @@ -179,7 +179,7 @@ public void setBoots(@NotNull ItemStack itemStack) { private ItemStack getEquipmentItem(@NotNull ItemStack itemStack, @NotNull EquipmentSlot slot) { EntityEquipEvent entityEquipEvent = new EntityEquipEvent(this, itemStack, slot); - EventDispatcher.call(entityEquipEvent); + minecraftServer.process().getGlobalEventHandler().call(entityEquipEvent); return entityEquipEvent.getEquippedItem(); } @@ -199,7 +199,7 @@ public void update(long time) { if (!itemEntity.isPickable()) return; if (expandedBoundingBox.intersectEntity(loweredPosition, itemEntity)) { PickupItemEvent pickupItemEvent = new PickupItemEvent(this, itemEntity); - EventDispatcher.callCancellable(pickupItemEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(pickupItemEvent, () -> { final ItemStack item = itemEntity.getItemStack(); sendPacketToViewersAndSelf(new CollectItemPacket(itemEntity.getEntityId(), getEntityId(), item.amount())); itemEntity.remove(); @@ -267,7 +267,7 @@ public void kill() { } EntityDeathEvent entityDeathEvent = new EntityDeathEvent(this); - EventDispatcher.call(entityDeathEvent); + minecraftServer.process().getGlobalEventHandler().call(entityDeathEvent); } /** @@ -301,7 +301,7 @@ public void setFireForDuration(Duration duration) { // Do not start fire event if the fire needs to be removed (< 0 duration) if (duration.toMillis() > 0) { - EventDispatcher.callCancellable(entityFireEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(entityFireEvent, () -> { final long fireTime = entityFireEvent.getFireTime(TimeUnit.MILLISECOND); setOnFire(true); fireExtinguishTime = System.currentTimeMillis() + fireTime; @@ -329,7 +329,7 @@ public boolean damage(@NotNull Damage damage) { } EntityDamageEvent entityDamageEvent = new EntityDamageEvent(this, damage, damage.getSound(this)); - EventDispatcher.callCancellable(entityDamageEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(entityDamageEvent, () -> { // Set the last damage type since the event is not cancelled this.lastDamage = entityDamageEvent.getDamage(); diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 11c554d3c53..19add4d2648 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -20,7 +20,6 @@ import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.title.TitlePart; import net.minestom.server.MinecraftServer; -import net.minestom.server.ServerProcess; import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; @@ -28,6 +27,7 @@ import net.minestom.server.attribute.Attribute; import net.minestom.server.collision.BoundingBox; import net.minestom.server.command.CommandSender; +import net.minestom.server.command.builder.condition.CommandCondition; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; @@ -36,7 +36,6 @@ import net.minestom.server.entity.fakeplayer.FakePlayer; import net.minestom.server.entity.metadata.PlayerMeta; import net.minestom.server.entity.vehicle.PlayerVehicleInformation; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.inventory.InventoryOpenEvent; import net.minestom.server.event.item.ItemDropEvent; import net.minestom.server.event.item.ItemUpdateStateEvent; @@ -72,7 +71,6 @@ import net.minestom.server.recipe.RecipeManager; import net.minestom.server.scoreboard.BelowNameTag; import net.minestom.server.scoreboard.Team; -import net.minestom.server.scoreboard.TeamManager; import net.minestom.server.snapshot.EntitySnapshot; import net.minestom.server.snapshot.PlayerSnapshot; import net.minestom.server.snapshot.SnapshotImpl; @@ -162,11 +160,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // Load new chunks this.instance.loadOptionalChunk(chunkX, chunkZ).thenAccept(this::sendChunk); }; - final IntegerBiConsumer chunkRemover = (chunkX, chunkZ) -> { - // Unload old chunks - sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); - EventDispatcher.call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); - }; + final IntegerBiConsumer chunkRemover; private final AtomicInteger teleportId = new AtomicInteger(); private int receivedTeleportId; @@ -230,13 +224,8 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // The future is non-null when a resource pack is in-flight, and completed when all statuses have been received. private CompletableFuture resourcePackFuture = null; - public final MinecraftServer minecraftServer; - protected final ServerProcess serverProcess; - public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - super(EntityType.PLAYER, uuid); - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); + super(minecraftServer, EntityType.PLAYER, uuid); this.username = username; this.usernameComponent = Component.text(username); this.playerConnection = playerConnection; @@ -244,7 +233,7 @@ public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @Not setRespawnPoint(Pos.ZERO); this.settings = new PlayerSettings(); - this.inventory = new PlayerInventory(this); + this.inventory = new PlayerInventory(minecraftServer, this); setCanPickupItem(true); // By default @@ -268,6 +257,11 @@ public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @Not // When in configuration state no metadata updates can be sent. metadata.setNotifyAboutChanges(false); + chunkRemover = (chunkX, chunkZ) -> { + // Unload old chunks + sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); + }; } @ApiStatus.Internal @@ -323,12 +317,12 @@ public CompletableFuture UNSAFE_init() { } } PlayerSkinInitEvent skinInitEvent = new PlayerSkinInitEvent(this, profileSkin); - EventDispatcher.call(skinInitEvent); + minecraftServer.process().getGlobalEventHandler().call(skinInitEvent); this.skin = skinInitEvent.getSkin(); // FIXME: when using Geyser, this line remove the skin of the client PacketUtils.broadcastPlayPacket(getAddPlayerToList()); - var connectionManager = serverProcess.getConnectionManager(); + var connectionManager = minecraftServer.process().getConnectionManager(); for (var player : connectionManager.getOnlinePlayers()) { if (player != this) { sendPacket(player.getAddPlayerToList()); @@ -339,7 +333,7 @@ public CompletableFuture UNSAFE_init() { } //Teams - for (Team team : serverProcess.getTeamManager().getTeams()) { + for (Team team : minecraftServer.process().getTeamManager().getTeams()) { sendPacket(team.createTeamsCreationPacket()); } @@ -348,7 +342,7 @@ public CompletableFuture UNSAFE_init() { // Recipes start { - RecipeManager recipeManager = serverProcess.getRecipeManager(); + RecipeManager recipeManager = minecraftServer.process().getRecipeManager(); sendPacket(recipeManager.getDeclareRecipesPacket()); List recipesIdentifier = new ArrayList<>(); @@ -392,7 +386,7 @@ public void startConfigurationPhase() { // Remove the player, then send them back to configuration remove(false); - var connectionManager = serverProcess.getConnectionManager(); + var connectionManager = minecraftServer.process().getConnectionManager(); connectionManager.transitionPlayToConfig(this); } @@ -425,7 +419,7 @@ public void update(long time) { EntityTracker.Target.EXPERIENCE_ORBS, experienceOrb -> { if (expandedBoundingBox.intersectEntity(loweredPosition, experienceOrb)) { PickupExperienceEvent pickupExperienceEvent = new PickupExperienceEvent(this, experienceOrb); - EventDispatcher.callCancellable(pickupExperienceEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(pickupExperienceEvent, () -> { short experienceCount = pickupExperienceEvent.getExperienceCount(); // TODO give to player experienceOrb.remove(); }); @@ -442,7 +436,7 @@ public void update(long time) { Check.notNull(itemUpdateStateEvent, "#callItemUpdateStateEvent returned null."); // Refresh hand - final boolean isOffHand = itemUpdateStateEvent.getHand() == Player.Hand.OFF; + final boolean isOffHand = itemUpdateStateEvent.getHand() == Hand.OFF; refreshActiveHand(false, isOffHand, false); final ItemStack foodItem = itemUpdateStateEvent.getItemStack(); @@ -450,7 +444,7 @@ public void update(long time) { if (isFood) { PlayerEatEvent playerEatEvent = new PlayerEatEvent(this, foodItem, eatingHand); - EventDispatcher.call(playerEatEvent); + minecraftServer.process().getGlobalEventHandler().call(playerEatEvent); } refreshEating(null); @@ -460,7 +454,7 @@ public void update(long time) { if (EXPERIMENT_PERFORM_POSE_UPDATES) updatePose(); // Tick event - EventDispatcher.call(new PlayerTickEvent(this)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerTickEvent(this)); } @Override @@ -490,7 +484,7 @@ public void kill() { // Call player death event PlayerDeathEvent playerDeathEvent = new PlayerDeathEvent(this, deathText, chatMessage); - EventDispatcher.call(playerDeathEvent); + minecraftServer.process().getGlobalEventHandler().call(playerDeathEvent); deathText = playerDeathEvent.getDeathText(); chatMessage = playerDeathEvent.getChatMessage(); @@ -528,7 +522,7 @@ public void respawn() { 0, gameMode, gameMode, false, levelFlat, deathLocation, portalCooldown, RespawnPacket.COPY_ALL)); PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this); - EventDispatcher.call(respawnEvent); + minecraftServer.process().getGlobalEventHandler().call(respawnEvent); triggerStatus((byte) (24 + permissionLevel)); // Set permission level refreshIsDead(false); updatePose(); @@ -563,11 +557,11 @@ private void refreshClientStateAfterRespawn() { /** * Refreshes the command list for this player. This checks the - * {@link net.minestom.server.command.builder.condition.CommandCondition}s + * {@link CommandCondition}s * again, and any changes will be visible to the player. */ public void refreshCommands() { - sendPacket(serverProcess.getCommandManager().createDeclareCommandsPacket(this)); + sendPacket(minecraftServer.process().getCommandManager().createDeclareCommandsPacket(this)); } @Override @@ -581,14 +575,14 @@ public void remove(boolean permanent) { if (permanent) { this.packets.clear(); - EventDispatcher.call(new PlayerDisconnectEvent(this)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerDisconnectEvent(this)); } super.remove(permanent); final Inventory currentInventory = getOpenInventory(); if (currentInventory != null) currentInventory.removeViewer(this); - serverProcess.getBossBarManager().removeAllBossBars(this); + minecraftServer.process().getBossBarManager().removeAllBossBars(this); // Advancement tabs cache { Set advancementTabs = AdvancementTab.getTabs(this); @@ -667,7 +661,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // One or more chunks need to be loaded final Thread runThread = Thread.currentThread(); CountDownLatch latch = new CountDownLatch(1); - Scheduler scheduler = serverProcess.getSchedulerManager(); + Scheduler scheduler = minecraftServer.process().getSchedulerManager(); CompletableFuture future = new CompletableFuture<>() { @Override public Void join() { @@ -761,7 +755,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); } - EventDispatcher.call(new PlayerSpawnEvent(this, instance, firstSpawn)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerSpawnEvent(this, instance, firstSpawn)); } @ApiStatus.Internal @@ -809,7 +803,7 @@ private void sendPendingChunks() { if (chunk == null || !chunk.isLoaded()) continue; sendPacket(chunk.getFullDataPacket()); - EventDispatcher.call(new PlayerChunkLoadEvent(this, chunkX, chunkZ)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerChunkLoadEvent(this, chunkX, chunkZ)); pendingChunkCount -= 1f; batchSize += 1; @@ -859,7 +853,7 @@ protected void updatePose() { } /** - * Returns true if the player can fit at the current position with the given {@link net.minestom.server.entity.Entity.Pose}, false otherwise. + * Returns true if the player can fit at the current position with the given {@link Pose}, false otherwise. * * @param pose The pose to check */ @@ -983,12 +977,12 @@ public void clearTitle() { @Override public void showBossBar(@NotNull BossBar bar) { - serverProcess.getBossBarManager().addBossBar(this, bar); + minecraftServer.process().getBossBarManager().addBossBar(this, bar); } @Override public void hideBossBar(@NotNull BossBar bar) { - serverProcess.getBossBarManager().removeBossBar(this, bar); + minecraftServer.process().getBossBarManager().removeBossBar(this, bar); } @Override @@ -1271,7 +1265,7 @@ public void setUsernameField(@NotNull String username) { public boolean dropItem(@NotNull ItemStack item) { if (item.isAir()) return false; ItemDropEvent itemDropEvent = new ItemDropEvent(this, item); - EventDispatcher.call(itemDropEvent); + minecraftServer.process().getGlobalEventHandler().call(itemDropEvent); return !itemDropEvent.isCancelled(); } @@ -1560,7 +1554,7 @@ public GameMode getGameMode() { */ public boolean setGameMode(@NotNull GameMode gameMode) { PlayerGameModeChangeEvent playerGameModeChangeEvent = new PlayerGameModeChangeEvent(this, gameMode); - EventDispatcher.call(playerGameModeChangeEvent); + minecraftServer.process().getGlobalEventHandler().call(playerGameModeChangeEvent); if (playerGameModeChangeEvent.isCancelled()) { // Abort return false; @@ -1708,7 +1702,7 @@ public void setBelowNameTag(BelowNameTag belowNameTag) { public boolean openInventory(@NotNull Inventory inventory) { InventoryOpenEvent inventoryOpenEvent = new InventoryOpenEvent(inventory, this); - EventDispatcher.callCancellable(inventoryOpenEvent, () -> { + minecraftServer.process().getGlobalEventHandler().callCancellable(inventoryOpenEvent, () -> { Inventory openInventory = getOpenInventory(); if (openInventory != null) { openInventory.removeViewer(this); @@ -2060,7 +2054,7 @@ public void interpretPacketQueue() { kick(Component.text("Too Many Packets", NamedTextColor.RED)); return; } - final PacketListenerManager manager = serverProcess.getPacketListenerManager(); + final PacketListenerManager manager = minecraftServer.process().getPacketListenerManager(); // This method is NOT thread-safe this.packets.drain(packet -> manager.processClientPacket(packet, playerConnection), PACKET_PER_TICK); } @@ -2081,7 +2075,7 @@ public void refreshOnGround(boolean onGround) { this.onGround = onGround; if (this.onGround && this.isFlyingWithElytra()) { this.setFlyingWithElytra(false); - EventDispatcher.call(new PlayerStopFlyingWithElytraEvent(this)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerStopFlyingWithElytraEvent(this)); } } @@ -2155,7 +2149,7 @@ public void refreshEating(@Nullable Hand eatingHand) { return null; ItemUpdateStateEvent itemUpdateStateEvent = new ItemUpdateStateEvent(this, hand, updatedItem); - EventDispatcher.call(itemUpdateStateEvent); + minecraftServer.process().getGlobalEventHandler().call(itemUpdateStateEvent); return itemUpdateStateEvent; } diff --git a/src/main/java/net/minestom/server/entity/PlayerProjectile.java b/src/main/java/net/minestom/server/entity/PlayerProjectile.java index d62c6e75fa5..303f9247056 100644 --- a/src/main/java/net/minestom/server/entity/PlayerProjectile.java +++ b/src/main/java/net/minestom/server/entity/PlayerProjectile.java @@ -8,7 +8,6 @@ import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.projectile.ProjectileMeta; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.entity.EntityShootEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithEntityEvent; @@ -87,7 +86,7 @@ public void shoot(@NotNull Point from, @NotNull Point to, double power, double s dz += random.nextGaussian() * spread; final EntityShootEvent shootEvent = new EntityShootEvent(this.shooter, this, from, power, spread); - EventDispatcher.call(shootEvent); + minecraftServer.process().getGlobalEventHandler().call(shootEvent); if (shootEvent.isCancelled()) { remove(); return; diff --git a/src/main/java/net/minestom/server/event/EventDispatcher.java b/src/main/java/net/minestom/server/event/EventDispatcher.java deleted file mode 100644 index 6d0738ef6e8..00000000000 --- a/src/main/java/net/minestom/server/event/EventDispatcher.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.minestom.server.event; - -import net.minestom.server.MinecraftServer; -import net.minestom.server.event.trait.CancellableEvent; -import org.jetbrains.annotations.NotNull; - -public final class EventDispatcher { - - public static void call(@NotNull Event event) { - MinecraftServer.getGlobalEventHandler().call(event); - } - - public static ListenerHandle getHandle(@NotNull Class handleType) { - return MinecraftServer.getGlobalEventHandler().getHandle(handleType); - } - - public static void callCancellable(@NotNull CancellableEvent event, @NotNull Runnable successCallback) { - MinecraftServer.getGlobalEventHandler().callCancellable(event, successCallback); - } -} diff --git a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java index e9b5b6e0d99..b2d42c557b5 100644 --- a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java +++ b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java @@ -1,7 +1,6 @@ package net.minestom.server.extras.lan; import net.minestom.server.MinecraftServer; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.timer.Task; import net.minestom.server.utils.time.Cooldown; @@ -29,16 +28,19 @@ * @see wiki.vg */ public class OpenToLAN { - private static final InetSocketAddress PING_ADDRESS = new InetSocketAddress("224.0.2.60", 4445); + private final InetSocketAddress PING_ADDRESS = new InetSocketAddress("224.0.2.60", 4445); - private static final Logger LOGGER = LoggerFactory.getLogger(OpenToLAN.class); + private final Logger LOGGER = LoggerFactory.getLogger(OpenToLAN.class); - private static volatile Cooldown eventCooldown; - private static volatile DatagramSocket socket = null; - private static volatile DatagramPacket packet = null; - private static volatile Task task = null; + private volatile Cooldown eventCooldown; + private volatile DatagramSocket socket = null; + private volatile DatagramPacket packet = null; + private volatile Task task = null; - private OpenToLAN() { + private final MinecraftServer minecraftServer; + + public OpenToLAN(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; } /** @@ -46,7 +48,7 @@ private OpenToLAN() { * * @return {@code true} if it was opened successfully, {@code false} otherwise */ - public static boolean open() { + public boolean open() { return open(new OpenToLANConfig()); } @@ -56,7 +58,7 @@ public static boolean open() { * @param config the configuration * @return {@code true} if it was opened successfully, {@code false} otherwise */ - public static boolean open(@NotNull OpenToLANConfig config) { + public boolean open(@NotNull OpenToLANConfig config) { Objects.requireNonNull(config, "config"); if (socket != null) return false; @@ -68,7 +70,7 @@ public static boolean open(@NotNull OpenToLANConfig config) { } eventCooldown = new Cooldown(config.delayBetweenEvent); - task = MinecraftServer.getSchedulerManager().buildTask(OpenToLAN::ping) + task = minecraftServer.process().getSchedulerManager().buildTask(this::ping) .repeat(config.delayBetweenPings) .schedule(); return true; @@ -79,7 +81,7 @@ public static boolean open(@NotNull OpenToLANConfig config) { * * @return {@code true} if it was closed, {@code false} if it was already closed */ - public static boolean close() { + public boolean close() { if (socket == null) return false; task.cancel(); socket.close(); @@ -94,18 +96,18 @@ public static boolean close() { * * @return {@code true} if it is, {@code false} otherwise */ - public static boolean isOpen() { + public boolean isOpen() { return socket != null; } /** * Performs the ping. */ - private static void ping() { - if (!MinecraftServer.getServer().isOpen()) return; + private void ping() { + if (!minecraftServer.process().getServer().isOpen()) return; if (packet == null || eventCooldown.isReady(System.currentTimeMillis())) { final ServerListPingEvent event = new ServerListPingEvent(OPEN_TO_LAN); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); final byte[] data = OPEN_TO_LAN.getPingResponse(event.getResponseData()).getBytes(StandardCharsets.UTF_8); packet = new DatagramPacket(data, data.length, PING_ADDRESS); diff --git a/src/main/java/net/minestom/server/extras/query/Query.java b/src/main/java/net/minestom/server/extras/query/Query.java index 964b7ccbb3e..ab562e9f15a 100644 --- a/src/main/java/net/minestom/server/extras/query/Query.java +++ b/src/main/java/net/minestom/server/extras/query/Query.java @@ -5,7 +5,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.extras.query.event.BasicQueryEvent; import net.minestom.server.extras.query.event.FullQueryEvent; import net.minestom.server.timer.Task; @@ -188,11 +187,11 @@ private void run() { if (remaining == 0) { // basic BasicQueryEvent event = new BasicQueryEvent(sender, sessionID); - EventDispatcher.callCancellable(event, () -> + minecraftServer.process().getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } else if (remaining == 5) { // full FullQueryEvent event = new FullQueryEvent(minecraftServer, sender, sessionID); - EventDispatcher.callCancellable(event, () -> + minecraftServer.process().getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } } diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index d497c2ba021..55324b7aded 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -13,7 +13,6 @@ import net.minestom.server.entity.ExperienceOrb; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.PFInstanceSpace; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.EventFilter; import net.minestom.server.event.EventHandler; import net.minestom.server.event.EventNode; @@ -674,7 +673,7 @@ public void tick(long time) { // Tick event { // Process tick events - EventDispatcher.call(new InstanceTickEvent(this, time, lastTickAge)); + minecraftServer.process().getGlobalEventHandler().call(new InstanceTickEvent(this, time, lastTickAge)); // Set last tick age this.lastTickAge = time; } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index 2742ac4f32e..a026565af9a 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -7,7 +7,6 @@ import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.instance.InstanceChunkLoadEvent; import net.minestom.server.event.instance.InstanceChunkUnloadEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; @@ -27,13 +26,11 @@ import net.minestom.server.utils.block.BlockUtils; import net.minestom.server.utils.chunk.ChunkCache; import net.minestom.server.utils.chunk.ChunkSupplier; -import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.UnknownNullability; import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -225,7 +222,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, return false; } PlayerBlockBreakEvent blockBreakEvent = new PlayerBlockBreakEvent(player, block, Block.AIR, blockPosition, blockFace); - EventDispatcher.call(blockBreakEvent); + minecraftServer.process().getGlobalEventHandler().call(blockBreakEvent); final boolean allowed = !blockBreakEvent.isCancelled(); if (allowed) { // Break or change the broken block based on event result @@ -257,7 +254,7 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { final int chunkX = chunk.getChunkX(); final int chunkZ = chunk.getChunkZ(); chunk.sendPacketToViewers(new UnloadChunkPacket(chunkX, chunkZ)); - EventDispatcher.call(new InstanceChunkUnloadEvent(this, chunk)); + minecraftServer.process().getGlobalEventHandler().call(new InstanceChunkUnloadEvent(this, chunk)); // Remove all entities in chunk getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES).forEach(Entity::remove); // Clear cache @@ -312,7 +309,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { cacheChunk(chunk); chunk.onLoad(); - EventDispatcher.call(new InstanceChunkLoadEvent(this, chunk)); + minecraftServer.process().getGlobalEventHandler().call(new InstanceChunkLoadEvent(this, chunk)); final CompletableFuture future = this.loadingChunks.remove(index); assert future == completableFuture : "Invalid future: " + future; completableFuture.complete(chunk); diff --git a/src/main/java/net/minestom/server/instance/InstanceManager.java b/src/main/java/net/minestom/server/instance/InstanceManager.java index 1fa9b36fba0..5212b24b5c0 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManager.java +++ b/src/main/java/net/minestom/server/instance/InstanceManager.java @@ -1,7 +1,6 @@ package net.minestom.server.instance; import net.minestom.server.MinecraftServer; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.instance.InstanceRegisterEvent; import net.minestom.server.event.instance.InstanceUnregisterEvent; import net.minestom.server.utils.validate.Check; @@ -118,7 +117,7 @@ public void unregisterInstance(@NotNull Instance instance) { Check.stateCondition(!instance.getPlayers().isEmpty(), "You cannot unregister an instance with players inside."); synchronized (instance) { InstanceUnregisterEvent event = new InstanceUnregisterEvent(instance); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); // Unload all chunks if (instance instanceof InstanceContainer) { @@ -168,6 +167,6 @@ private void UNSAFE_registerInstance(@NotNull Instance instance) { var dispatcher = minecraftServer.process().dispatcher(); instance.getChunks().forEach(dispatcher::createPartition); InstanceRegisterEvent event = new InstanceRegisterEvent(instance); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); } } diff --git a/src/main/java/net/minestom/server/inventory/AbstractInventory.java b/src/main/java/net/minestom/server/inventory/AbstractInventory.java index 99cfc2fb0d8..4957d2953a1 100644 --- a/src/main/java/net/minestom/server/inventory/AbstractInventory.java +++ b/src/main/java/net/minestom/server/inventory/AbstractInventory.java @@ -1,6 +1,6 @@ package net.minestom.server.inventory; -import net.minestom.server.event.EventDispatcher; +import net.minestom.server.MinecraftServer; import net.minestom.server.event.inventory.InventoryItemChangeEvent; import net.minestom.server.event.inventory.PlayerInventoryItemChangeEvent; import net.minestom.server.inventory.click.InventoryClickProcessor; @@ -28,20 +28,23 @@ public sealed abstract class AbstractInventory implements InventoryClickHandler, private static final VarHandle ITEM_UPDATER = MethodHandles.arrayElementVarHandle(ItemStack[].class); + public final MinecraftServer minecraftServer; private final int size; protected final ItemStack[] itemStacks; // list of conditions/callbacks assigned to this inventory protected final List inventoryConditions = new CopyOnWriteArrayList<>(); // the click processor which process all the clicks in the inventory - protected final InventoryClickProcessor clickProcessor = new InventoryClickProcessor(); + protected final InventoryClickProcessor clickProcessor; private final TagHandler tagHandler = TagHandler.newHandler(); - protected AbstractInventory(int size) { + protected AbstractInventory(@NotNull MinecraftServer minecraftServer, int size) { + this.minecraftServer = minecraftServer; this.size = size; this.itemStacks = new ItemStack[getSize()]; Arrays.fill(itemStacks, ItemStack.AIR); + clickProcessor = new InventoryClickProcessor(minecraftServer); } /** @@ -79,9 +82,9 @@ protected final void safeItemInsert(int slot, @NotNull ItemStack itemStack, bool UNSAFE_itemInsert(slot, itemStack, sendPacket); } if (this instanceof PlayerInventory inv) { - EventDispatcher.call(new PlayerInventoryItemChangeEvent(inv.player, slot, previous, itemStack)); + minecraftServer.process().getGlobalEventHandler().call(new PlayerInventoryItemChangeEvent(inv.player, slot, previous, itemStack)); } else if (this instanceof Inventory inv) { - EventDispatcher.call(new InventoryItemChangeEvent(inv, slot, previous, itemStack)); + minecraftServer.process().getGlobalEventHandler().call(new InventoryItemChangeEvent(inv, slot, previous, itemStack)); } } diff --git a/src/main/java/net/minestom/server/inventory/Inventory.java b/src/main/java/net/minestom/server/inventory/Inventory.java index be9c688fa61..e79c04fa1ac 100644 --- a/src/main/java/net/minestom/server/inventory/Inventory.java +++ b/src/main/java/net/minestom/server/inventory/Inventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.Viewable; import net.minestom.server.entity.Player; import net.minestom.server.inventory.click.ClickType; @@ -44,8 +45,8 @@ public non-sealed class Inventory extends AbstractInventory implements Viewable // (player -> cursor item) map, used by the click listeners private final ConcurrentHashMap cursorPlayersItem = new ConcurrentHashMap<>(); - public Inventory(@NotNull InventoryType inventoryType, @NotNull Component title) { - super(inventoryType.getSize()); + public Inventory(@NotNull MinecraftServer minecraftServer, @NotNull InventoryType inventoryType, @NotNull Component title) { + super(minecraftServer, inventoryType.getSize()); this.id = generateId(); this.inventoryType = inventoryType; this.title = title; @@ -53,8 +54,8 @@ public Inventory(@NotNull InventoryType inventoryType, @NotNull Component title) this.offset = getSize(); } - public Inventory(@NotNull InventoryType inventoryType, @NotNull String title) { - this(inventoryType, Component.text(title)); + public Inventory(@NotNull MinecraftServer minecraftServer, @NotNull InventoryType inventoryType, @NotNull String title) { + this(minecraftServer, inventoryType, Component.text(title)); } private static byte generateId() { @@ -230,7 +231,7 @@ public boolean leftClick(@NotNull Player player, int slot) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } this.cursorPlayersItem.put(player, clickResult.getCursor()); - callClickEvent(player, isInWindow ? this : null, slot, ClickType.LEFT_CLICK, clicked, cursor); + callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.LEFT_CLICK, clicked, cursor); return true; } @@ -253,7 +254,7 @@ public boolean rightClick(@NotNull Player player, int slot) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } this.cursorPlayersItem.put(player, clickResult.getCursor()); - callClickEvent(player, isInWindow ? this : null, slot, ClickType.RIGHT_CLICK, clicked, cursor); + callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.RIGHT_CLICK, clicked, cursor); return true; } @@ -303,7 +304,7 @@ public boolean changeHeld(@NotNull Player player, int slot, int key) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } playerInventory.setItemStack(convertedKey, clickResult.getCursor()); - callClickEvent(player, isInWindow ? this : null, slot, ClickType.CHANGE_HELD, clicked, getCursorItem(player)); + callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.CHANGE_HELD, clicked, getCursorItem(player)); return true; } diff --git a/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java b/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java index 5fa175416eb..77ee58f48a5 100644 --- a/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java +++ b/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.inventory.InventoryClickEvent; import net.minestom.server.inventory.click.ClickType; import net.minestom.server.item.ItemStack; @@ -76,8 +76,8 @@ public sealed interface InventoryClickHandler permits AbstractInventory { */ boolean doubleClick(@NotNull Player player, int slot); - default void callClickEvent(@NotNull Player player, Inventory inventory, int slot, + default void callClickEvent(@NotNull GlobalEventHandler globalEventHandler, @NotNull Player player, Inventory inventory, int slot, @NotNull ClickType clickType, @NotNull ItemStack clicked, @NotNull ItemStack cursor) { - EventDispatcher.call(new InventoryClickEvent(inventory, player, slot, clickType, clicked, cursor)); + globalEventHandler.call(new InventoryClickEvent(inventory, player, slot, clickType, clicked, cursor)); } } diff --git a/src/main/java/net/minestom/server/inventory/PlayerInventory.java b/src/main/java/net/minestom/server/inventory/PlayerInventory.java index bb2158419cc..a2aa46ab75e 100644 --- a/src/main/java/net/minestom/server/inventory/PlayerInventory.java +++ b/src/main/java/net/minestom/server/inventory/PlayerInventory.java @@ -1,8 +1,8 @@ package net.minestom.server.inventory; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.item.EntityEquipEvent; import net.minestom.server.inventory.click.ClickType; import net.minestom.server.inventory.click.InventoryClickResult; @@ -25,8 +25,8 @@ public non-sealed class PlayerInventory extends AbstractInventory implements Equ protected final Player player; private ItemStack cursorItem = ItemStack.AIR; - public PlayerInventory(@NotNull Player player) { - super(INVENTORY_SIZE); + public PlayerInventory(@NotNull MinecraftServer minecraftServer, @NotNull Player player) { + super(minecraftServer, INVENTORY_SIZE); this.player = player; } @@ -145,7 +145,7 @@ protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean }; if (equipmentSlot != null) { EntityEquipEvent entityEquipEvent = new EntityEquipEvent(player, itemStack, equipmentSlot); - EventDispatcher.call(entityEquipEvent); + minecraftServer.process().getGlobalEventHandler().call(entityEquipEvent); itemStack = entityEquipEvent.getEquippedItem(); } this.itemStacks[slot] = itemStack; @@ -195,7 +195,7 @@ public boolean leftClick(@NotNull Player player, int slot) { } setItemStack(convertedSlot, clickResult.getClicked()); setCursorItem(clickResult.getCursor()); - callClickEvent(player, null, convertedSlot, ClickType.LEFT_CLICK, clicked, cursor); + callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, null, convertedSlot, ClickType.LEFT_CLICK, clicked, cursor); return true; } @@ -211,7 +211,7 @@ public boolean rightClick(@NotNull Player player, int slot) { } setItemStack(convertedSlot, clickResult.getClicked()); setCursorItem(clickResult.getCursor()); - callClickEvent(player, null, convertedSlot, ClickType.RIGHT_CLICK, clicked, cursor); + callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, null, convertedSlot, ClickType.RIGHT_CLICK, clicked, cursor); return true; } @@ -279,7 +279,7 @@ public boolean changeHeld(@NotNull Player player, int slot, int key) { } setItemStack(convertedSlot, clickResult.getClicked()); setItemStack(convertedKey, clickResult.getCursor()); - callClickEvent(player, null, convertedSlot, ClickType.CHANGE_HELD, clicked, cursorItem); + callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, null, convertedSlot, ClickType.CHANGE_HELD, clicked, cursorItem); return true; } diff --git a/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java b/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java index 634a9ef2aa4..70c392885d9 100644 --- a/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java +++ b/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java @@ -1,8 +1,8 @@ package net.minestom.server.inventory.click; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.inventory.InventoryClickEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.AbstractInventory; @@ -31,6 +31,12 @@ public final class InventoryClickProcessor { private final Map> leftDraggingMap = new ConcurrentHashMap<>(); private final Map> rightDraggingMap = new ConcurrentHashMap<>(); + private final MinecraftServer minecraftServer; + + public InventoryClickProcessor(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + public @NotNull InventoryClickResult leftClick(@NotNull Player player, @NotNull AbstractInventory inventory, int slot, @NotNull ItemStack clicked, @NotNull ItemStack cursor) { @@ -427,7 +433,7 @@ public final class InventoryClickProcessor { { InventoryPreClickEvent inventoryPreClickEvent = new InventoryPreClickEvent(eventInventory, player, slot, clickType, clickResult.getClicked(), clickResult.getCursor()); - EventDispatcher.call(inventoryPreClickEvent); + minecraftServer.process().getGlobalEventHandler().call(inventoryPreClickEvent); clickResult.setCursor(inventoryPreClickEvent.getCursorItem()); clickResult.setClicked(inventoryPreClickEvent.getClickedItem()); if (inventoryPreClickEvent.isCancelled()) { @@ -463,7 +469,7 @@ public final class InventoryClickProcessor { private void callClickEvent(@NotNull Player player, @Nullable AbstractInventory inventory, int slot, @NotNull ClickType clickType, @NotNull ItemStack clicked, @NotNull ItemStack cursor) { final Inventory eventInventory = inventory instanceof Inventory ? (Inventory) inventory : null; - EventDispatcher.call(new InventoryClickEvent(eventInventory, player, slot, clickType, clicked, cursor)); + minecraftServer.process().getGlobalEventHandler().call(new InventoryClickEvent(eventInventory, player, slot, clickType, clicked, cursor)); } public void clearCache(@NotNull Player player) { diff --git a/src/main/java/net/minestom/server/listener/AbilitiesListener.java b/src/main/java/net/minestom/server/listener/AbilitiesListener.java index 69eddadfbfc..78ade72af04 100644 --- a/src/main/java/net/minestom/server/listener/AbilitiesListener.java +++ b/src/main/java/net/minestom/server/listener/AbilitiesListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerStartFlyingEvent; import net.minestom.server.event.player.PlayerStopFlyingEvent; import net.minestom.server.network.packet.client.play.ClientPlayerAbilitiesPacket; @@ -18,10 +17,10 @@ public static void listener(ClientPlayerAbilitiesPacket packet, Player player) { if (isFlying) { PlayerStartFlyingEvent startFlyingEvent = new PlayerStartFlyingEvent(player); - EventDispatcher.call(startFlyingEvent); + player.minecraftServer.process().getGlobalEventHandler().call(startFlyingEvent); } else { PlayerStopFlyingEvent stopFlyingEvent = new PlayerStopFlyingEvent(player); - EventDispatcher.call(stopFlyingEvent); + player.minecraftServer.process().getGlobalEventHandler().call(stopFlyingEvent); } } } diff --git a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java index 3a8edbd121b..912714fb572 100644 --- a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java +++ b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.AdvancementTabEvent; import net.minestom.server.network.packet.client.play.ClientAdvancementTabPacket; @@ -10,7 +9,7 @@ public class AdvancementTabListener { public static void listener(ClientAdvancementTabPacket packet, Player player) { final String tabIdentifier = packet.tabIdentifier(); if (tabIdentifier != null) { - EventDispatcher.call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); + player.minecraftServer.process().getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); } } } diff --git a/src/main/java/net/minestom/server/listener/AnimationListener.java b/src/main/java/net/minestom/server/listener/AnimationListener.java index 42e249c7386..6028ea6c20c 100644 --- a/src/main/java/net/minestom/server/listener/AnimationListener.java +++ b/src/main/java/net/minestom/server/listener/AnimationListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerHandAnimationEvent; import net.minestom.server.item.ItemStack; import net.minestom.server.network.packet.client.play.ClientAnimationPacket; @@ -13,7 +12,7 @@ public static void animationListener(ClientAnimationPacket packet, Player player final ItemStack itemStack = player.getItemInHand(hand); //itemStack.onLeftClick(player, hand); PlayerHandAnimationEvent handAnimationEvent = new PlayerHandAnimationEvent(player, hand); - EventDispatcher.callCancellable(handAnimationEvent, () -> { + player.minecraftServer.process().getGlobalEventHandler().callCancellable(handAnimationEvent, () -> { switch (hand) { case MAIN -> player.swingMainHand(); case OFF -> player.swingOffHand(); diff --git a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java index 46980b6ac46..e8fa0d15aeb 100644 --- a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java +++ b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java @@ -1,13 +1,11 @@ package net.minestom.server.listener; -import net.minestom.server.MinecraftServer; import net.minestom.server.collision.CollisionUtils; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerBlockInteractEvent; import net.minestom.server.event.player.PlayerBlockPlaceEvent; import net.minestom.server.event.player.PlayerUseItemOnBlockEvent; @@ -16,7 +14,6 @@ import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; -import net.minestom.server.instance.block.BlockManager; import net.minestom.server.instance.block.rule.BlockPlacementRule; import net.minestom.server.inventory.PlayerInventory; import net.minestom.server.item.ItemStack; @@ -27,10 +24,7 @@ import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.utils.validate.Check; -import java.util.concurrent.atomic.AtomicBoolean; - public class BlockPlacementListener { - private static final BlockManager BLOCK_MANAGER = MinecraftServer.getBlockManager(); public static void listener(ClientPlayerBlockPlacementPacket packet, Player player) { final PlayerInventory playerInventory = player.getInventory(); @@ -57,7 +51,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Interact at block // FIXME: onUseOnBlock PlayerBlockInteractEvent playerBlockInteractEvent = new PlayerBlockInteractEvent(player, hand, interactedBlock, blockPosition, cursorPosition, blockFace); - EventDispatcher.call(playerBlockInteractEvent); + player.minecraftServer.process().getGlobalEventHandler().call(playerBlockInteractEvent); boolean blockUse = playerBlockInteractEvent.isBlockingItemUse(); if (!playerBlockInteractEvent.isCancelled()) { final var handler = interactedBlock.handler(); @@ -76,7 +70,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play if (!useMaterial.isBlock()) { // Player didn't try to place a block but interacted with one PlayerUseItemOnBlockEvent event = new PlayerUseItemOnBlockEvent(player, hand, usedItem, blockPosition, cursorPosition, blockFace); - EventDispatcher.call(event); + player.minecraftServer.process().getGlobalEventHandler().call(event); // Ack the block change. This is required to reset the client prediction to the server state. player.sendPacket(new AcknowledgeBlockChangePacket(packet.sequence())); return; @@ -96,7 +90,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Get the newly placed block position //todo it feels like it should be possible to have better replacement rules than this, feels pretty scuffed. Point placementPosition = blockPosition; - var interactedPlacementRule = BLOCK_MANAGER.getBlockPlacementRule(interactedBlock); + var interactedPlacementRule = player.minecraftServer.process().getBlockManager().getBlockPlacementRule(interactedBlock); if (!interactedBlock.isAir() && (interactedPlacementRule == null || !interactedPlacementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(interactedBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is not replaceable, try to place next to it. @@ -106,7 +100,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play placementPosition = blockPosition.add(offsetX, offsetY, offsetZ); var placementBlock = instance.getBlock(placementPosition); - var placementRule = BLOCK_MANAGER.getBlockPlacementRule(placementBlock); + var placementRule = player.minecraftServer.process().getBlockManager().getBlockPlacementRule(placementBlock); if (!placementBlock.registry().isReplaceable() && !(placementRule != null && placementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(placementBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is still not replaceable, cancel the placement @@ -155,7 +149,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // BlockPlaceEvent check PlayerBlockPlaceEvent playerBlockPlaceEvent = new PlayerBlockPlaceEvent(player, placedBlock, blockFace, placementPosition, packet.hand()); playerBlockPlaceEvent.consumeBlock(player.getGameMode() != GameMode.CREATIVE); - EventDispatcher.call(playerBlockPlaceEvent); + player.minecraftServer.process().getGlobalEventHandler().call(playerBlockPlaceEvent); if (playerBlockPlaceEvent.isCancelled()) { refresh(player, chunk); return; diff --git a/src/main/java/net/minestom/server/listener/BookListener.java b/src/main/java/net/minestom/server/listener/BookListener.java index 936a3944807..297f774a476 100644 --- a/src/main/java/net/minestom/server/listener/BookListener.java +++ b/src/main/java/net/minestom/server/listener/BookListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.book.EditBookEvent; import net.minestom.server.item.ItemStack; import net.minestom.server.network.packet.client.play.ClientEditBookPacket; @@ -12,7 +11,7 @@ public class BookListener { public static void listener(ClientEditBookPacket packet, Player player) { int slot = PlayerInventoryUtils.convertClientInventorySlot(packet.slot()); ItemStack itemStack = player.getInventory().getItemStack(slot); - EventDispatcher.call(new EditBookEvent(player, itemStack, packet.pages(), packet.title())); + player.minecraftServer.process().getGlobalEventHandler().call(new EditBookEvent(player, itemStack, packet.pages(), packet.title())); } } diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index f9b127c938d..b11a56f068d 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -2,15 +2,10 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; -import net.minestom.server.MinecraftServer; -import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerChatEvent; import net.minestom.server.message.ChatPosition; import net.minestom.server.message.Messenger; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.play.ClientChatMessagePacket; import net.minestom.server.network.packet.client.play.ClientCommandChatPacket; import org.jetbrains.annotations.NotNull; @@ -20,13 +15,10 @@ public class ChatMessageListener { - private static final CommandManager COMMAND_MANAGER = MinecraftServer.getCommandManager(); - private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); - public static void commandChatListener(ClientCommandChatPacket packet, Player player) { final String command = packet.message(); if (Messenger.canReceiveCommand(player)) { - COMMAND_MANAGER.execute(player, command); + player.minecraftServer.process().getCommandManager().execute(player, command); } else { Messenger.sendRejectionMessage(player); } @@ -39,11 +31,11 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl return; } - final Collection players = CONNECTION_MANAGER.getOnlinePlayers(); + final Collection players = player.minecraftServer.process().getConnectionManager().getOnlinePlayers(); PlayerChatEvent playerChatEvent = new PlayerChatEvent(player, players, () -> buildDefaultChatMessage(player, message), message); // Call the event - EventDispatcher.callCancellable(playerChatEvent, () -> { + player.minecraftServer.process().getGlobalEventHandler().callCancellable(playerChatEvent, () -> { final Function formatFunction = playerChatEvent.getChatFormatFunction(); Component textObject; diff --git a/src/main/java/net/minestom/server/listener/EntityActionListener.java b/src/main/java/net/minestom/server/listener/EntityActionListener.java index 680d87e3295..45a43262c69 100644 --- a/src/main/java/net/minestom/server/listener/EntityActionListener.java +++ b/src/main/java/net/minestom/server/listener/EntityActionListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.*; import net.minestom.server.network.packet.client.play.ClientEntityActionPacket; @@ -25,9 +24,9 @@ private static void setSneaking(Player player, boolean sneaking) { if (oldState != sneaking) { if (sneaking) { - EventDispatcher.call(new PlayerStartSneakingEvent(player)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStartSneakingEvent(player)); } else { - EventDispatcher.call(new PlayerStopSneakingEvent(player)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStopSneakingEvent(player)); } } } @@ -39,15 +38,15 @@ private static void setSprinting(Player player, boolean sprinting) { if (oldState != sprinting) { if (sprinting) { - EventDispatcher.call(new PlayerStartSprintingEvent(player)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStartSprintingEvent(player)); } else { - EventDispatcher.call(new PlayerStopSprintingEvent(player)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStopSprintingEvent(player)); } } } private static void startFlyingElytra(Player player) { player.setFlyingWithElytra(true); - EventDispatcher.call(new PlayerStartFlyingWithElytraEvent(player)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStartFlyingWithElytraEvent(player)); } } diff --git a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java index 47414120ff3..4e6f692e84e 100644 --- a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java @@ -5,7 +5,6 @@ import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; import net.minestom.server.entity.metadata.PlayerMeta; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.item.ItemUpdateStateEvent; import net.minestom.server.event.player.PlayerCancelDiggingEvent; import net.minestom.server.event.player.PlayerFinishDiggingEvent; @@ -83,7 +82,7 @@ private static DiggingResult startDigging(Player player, Instance instance, Poin final boolean instantBreak = player.isInstantBreak() || block.registry().hardness() == 0; if (!instantBreak) { PlayerStartDiggingEvent playerStartDiggingEvent = new PlayerStartDiggingEvent(player, block, blockPosition, blockFace); - EventDispatcher.call(playerStartDiggingEvent); + player.minecraftServer.process().getGlobalEventHandler().call(playerStartDiggingEvent); return new DiggingResult(block, !playerStartDiggingEvent.isCancelled()); } // Client only send a single STARTED_DIGGING when insta-break is enabled @@ -93,7 +92,7 @@ private static DiggingResult startDigging(Player player, Instance instance, Poin private static DiggingResult cancelDigging(Player player, Instance instance, Point blockPosition) { final Block block = instance.getBlock(blockPosition); PlayerCancelDiggingEvent playerCancelDiggingEvent = new PlayerCancelDiggingEvent(player, block, blockPosition); - EventDispatcher.call(playerCancelDiggingEvent); + player.minecraftServer.process().getGlobalEventHandler().call(playerCancelDiggingEvent); return new DiggingResult(block, true); } @@ -105,7 +104,7 @@ private static DiggingResult finishDigging(Player player, Instance instance, Poi } PlayerFinishDiggingEvent playerFinishDiggingEvent = new PlayerFinishDiggingEvent(player, block, blockPosition); - EventDispatcher.call(playerFinishDiggingEvent); + player.minecraftServer.process().getGlobalEventHandler().call(playerFinishDiggingEvent); return breakBlock(instance, player, blockPosition, playerFinishDiggingEvent.getBlock(), blockFace); } @@ -167,7 +166,7 @@ private static void swapItemHand(Player player) { final ItemStack mainHand = inventory.getItemInMainHand(); final ItemStack offHand = inventory.getItemInOffHand(); PlayerSwapItemEvent swapItemEvent = new PlayerSwapItemEvent(player, offHand, mainHand); - EventDispatcher.callCancellable(swapItemEvent, () -> { + player.minecraftServer.process().getGlobalEventHandler().callCancellable(swapItemEvent, () -> { inventory.setItemInMainHand(swapItemEvent.getMainHandItem()); inventory.setItemInOffHand(swapItemEvent.getOffHandItem()); }); diff --git a/src/main/java/net/minestom/server/listener/PlayerHeldListener.java b/src/main/java/net/minestom/server/listener/PlayerHeldListener.java index b4d14fa816a..292011281fe 100644 --- a/src/main/java/net/minestom/server/listener/PlayerHeldListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerHeldListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerChangeHeldSlotEvent; import net.minestom.server.network.packet.client.play.ClientHeldItemChangePacket; import net.minestom.server.utils.MathUtils; @@ -17,7 +16,7 @@ public static void heldListener(ClientHeldItemChangePacket packet, Player player final byte slot = (byte) packet.slot(); PlayerChangeHeldSlotEvent changeHeldSlotEvent = new PlayerChangeHeldSlotEvent(player, slot); - EventDispatcher.call(changeHeldSlotEvent); + player.minecraftServer.process().getGlobalEventHandler().call(changeHeldSlotEvent); if (!changeHeldSlotEvent.isCancelled()) { // Event hasn't been canceled, process it diff --git a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java index 3b7d3cdad2b..bcb91ac5fab 100644 --- a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java @@ -2,7 +2,6 @@ import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerMoveEvent; import net.minestom.server.instance.Instance; import net.minestom.server.network.packet.client.play.*; @@ -54,7 +53,7 @@ private static void processMovement(@NotNull Player player, @NotNull Pos packetP } PlayerMoveEvent playerMoveEvent = new PlayerMoveEvent(player, packetPosition, onGround); - EventDispatcher.call(playerMoveEvent); + player.minecraftServer.process().getGlobalEventHandler().call(playerMoveEvent); if (!currentPosition.equals(player.getPosition())) { // Player has been teleported in the event return; diff --git a/src/main/java/net/minestom/server/listener/SpectateListener.java b/src/main/java/net/minestom/server/listener/SpectateListener.java index cab7033f35c..593ac059fca 100644 --- a/src/main/java/net/minestom/server/listener/SpectateListener.java +++ b/src/main/java/net/minestom/server/listener/SpectateListener.java @@ -3,7 +3,6 @@ import net.minestom.server.entity.Entity; import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerSpectateEvent; import net.minestom.server.instance.Instance; import net.minestom.server.network.packet.client.play.ClientSpectatePacket; @@ -42,7 +41,7 @@ public static void listener(ClientSpectatePacket packet, Player player) { // Despite the name of this packet being spectate, it is sent when the player // uses their hotbar to switch between entities, which actually performs a teleport // instead of a spectate. - EventDispatcher.call(new PlayerSpectateEvent(player, target)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerSpectateEvent(player, target)); } } diff --git a/src/main/java/net/minestom/server/listener/UseEntityListener.java b/src/main/java/net/minestom/server/listener/UseEntityListener.java index 8040d759182..18602993b2f 100644 --- a/src/main/java/net/minestom/server/listener/UseEntityListener.java +++ b/src/main/java/net/minestom/server/listener/UseEntityListener.java @@ -5,7 +5,6 @@ import net.minestom.server.entity.Entity; import net.minestom.server.entity.LivingEntity; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.entity.EntityAttackEvent; import net.minestom.server.event.player.PlayerEntityInteractEvent; import net.minestom.server.network.packet.client.play.ClientInteractEntityPacket; @@ -21,10 +20,10 @@ public static void useEntityListener(ClientInteractEntityPacket packet, Player p if (type instanceof ClientInteractEntityPacket.Attack) { if (entity instanceof LivingEntity && ((LivingEntity) entity).isDead()) // Can't attack dead entities return; - EventDispatcher.call(new EntityAttackEvent(player, entity)); + player.minecraftServer.process().getGlobalEventHandler().call(new EntityAttackEvent(player, entity)); } else if (type instanceof ClientInteractEntityPacket.InteractAt interactAt) { Point interactPosition = new Vec(interactAt.targetX(), interactAt.targetY(), interactAt.targetZ()); - EventDispatcher.call(new PlayerEntityInteractEvent(player, entity, interactAt.hand(), interactPosition)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerEntityInteractEvent(player, entity, interactAt.hand(), interactPosition)); } } } diff --git a/src/main/java/net/minestom/server/listener/UseItemListener.java b/src/main/java/net/minestom/server/listener/UseItemListener.java index 4ffb8dd4565..5b5a522dd34 100644 --- a/src/main/java/net/minestom/server/listener/UseItemListener.java +++ b/src/main/java/net/minestom/server/listener/UseItemListener.java @@ -2,7 +2,6 @@ import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerItemAnimationEvent; import net.minestom.server.event.player.PlayerPreEatEvent; import net.minestom.server.event.player.PlayerUseItemEvent; @@ -19,7 +18,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { ItemStack itemStack = hand == Player.Hand.MAIN ? inventory.getItemInMainHand() : inventory.getItemInOffHand(); //itemStack.onRightClick(player, hand); PlayerUseItemEvent useItemEvent = new PlayerUseItemEvent(player, hand, itemStack); - EventDispatcher.call(useItemEvent); + player.minecraftServer.process().getGlobalEventHandler().call(useItemEvent); final PlayerInventory playerInventory = player.getInventory(); if (useItemEvent.isCancelled()) { @@ -57,7 +56,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { // Eating code, contains the eating time customisation PlayerPreEatEvent playerPreEatEvent = new PlayerPreEatEvent(player, itemStack, hand, player.getDefaultEatingTime()); - EventDispatcher.callCancellable(playerPreEatEvent, () -> player.refreshEating(hand, playerPreEatEvent.getEatingTime())); + player.minecraftServer.process().getGlobalEventHandler().callCancellable(playerPreEatEvent, () -> player.refreshEating(hand, playerPreEatEvent.getEatingTime())); if (playerPreEatEvent.isCancelled()) { cancelAnimation = true; @@ -66,7 +65,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { if (!cancelAnimation && itemAnimationType != null) { PlayerItemAnimationEvent playerItemAnimationEvent = new PlayerItemAnimationEvent(player, itemAnimationType, hand); - EventDispatcher.callCancellable(playerItemAnimationEvent, () -> { + player.minecraftServer.process().getGlobalEventHandler().callCancellable(playerItemAnimationEvent, () -> { player.refreshActiveHand(true, hand == Player.Hand.OFF, false); player.sendPacketToViewers(player.getMetadataPacket()); }); diff --git a/src/main/java/net/minestom/server/listener/WindowListener.java b/src/main/java/net/minestom/server/listener/WindowListener.java index dfdf2e6751f..29065b1e4b1 100644 --- a/src/main/java/net/minestom/server/listener/WindowListener.java +++ b/src/main/java/net/minestom/server/listener/WindowListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.inventory.AbstractInventory; import net.minestom.server.inventory.Inventory; @@ -86,7 +85,7 @@ public static void pong(ClientPongPacket packet, Player player) { public static void closeWindowListener(ClientCloseWindowPacket packet, Player player) { // if windowId == 0 then it is player's inventory, meaning that they hadn't been any open inventory packet InventoryCloseEvent inventoryCloseEvent = new InventoryCloseEvent(player.getOpenInventory(), player); - EventDispatcher.call(inventoryCloseEvent); + player.minecraftServer.process().getGlobalEventHandler().call(inventoryCloseEvent); player.closeInventory(true); diff --git a/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java b/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java index 68004eca189..d3ef8582dc6 100644 --- a/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java +++ b/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener.common; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerPluginMessageEvent; import net.minestom.server.network.packet.client.common.ClientPluginMessagePacket; @@ -9,7 +8,7 @@ public class PluginMessageListener { public static void listener(ClientPluginMessagePacket packet, Player player) { PlayerPluginMessageEvent pluginMessageEvent = new PlayerPluginMessageEvent(player, packet.channel(), packet.data()); - EventDispatcher.call(pluginMessageEvent); + player.minecraftServer.process().getGlobalEventHandler().call(pluginMessageEvent); } } diff --git a/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java b/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java index 5cf0c328d58..fae47153dcb 100644 --- a/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java +++ b/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java @@ -1,14 +1,13 @@ package net.minestom.server.listener.common; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerResourcePackStatusEvent; import net.minestom.server.network.packet.client.common.ClientResourcePackStatusPacket; public class ResourcePackListener { public static void listener(ClientResourcePackStatusPacket packet, Player player) { - EventDispatcher.call(new PlayerResourcePackStatusEvent(player, packet.status())); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerResourcePackStatusEvent(player, packet.status())); // Run adventure callbacks for the resource pack player.onResourcePackStatus(packet.id(), packet.status()); diff --git a/src/main/java/net/minestom/server/listener/common/SettingsListener.java b/src/main/java/net/minestom/server/listener/common/SettingsListener.java index 8d25bfe1d10..db3c23ff013 100644 --- a/src/main/java/net/minestom/server/listener/common/SettingsListener.java +++ b/src/main/java/net/minestom/server/listener/common/SettingsListener.java @@ -1,7 +1,6 @@ package net.minestom.server.listener.common; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerSettingsChangeEvent; import net.minestom.server.network.packet.client.common.ClientSettingsPacket; @@ -10,6 +9,6 @@ public static void listener(ClientSettingsPacket packet, Player player) { Player.PlayerSettings settings = player.getSettings(); // Since viewDistance bounds checking is performed in the refresh function, it is not necessary to check it here settings.refresh(packet.locale(), packet.viewDistance(), packet.chatMessageType(), packet.chatColors(), packet.displayedSkinParts(), packet.mainHand(), packet.enableTextFiltering(), packet.allowsListing()); - EventDispatcher.call(new PlayerSettingsChangeEvent(player)); + player.minecraftServer.process().getGlobalEventHandler().call(new PlayerSettingsChangeEvent(player)); } } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java index b9f764813f9..8b67de2913a 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java @@ -1,7 +1,6 @@ package net.minestom.server.listener.manager; import net.minestom.server.MinecraftServer; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.PlayerPacketEvent; import net.minestom.server.listener.*; import net.minestom.server.listener.common.KeepAliveListener; @@ -37,8 +36,10 @@ public final class PacketListenerManager { private final static Logger LOGGER = LoggerFactory.getLogger(PacketListenerManager.class); private final Map, PacketPrePlayListenerConsumer>[] listeners = new Map[ConnectionState.values().length]; + private final MinecraftServer minecraftServer; - public PacketListenerManager() { + public PacketListenerManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; for (int i = 0; i < listeners.length; i++) { listeners[i] = new ConcurrentHashMap<>(); } @@ -69,7 +70,7 @@ public PacketListenerManager() { setPlayListener(ClientPongPacket.class, WindowListener::pong); setPlayListener(ClientEntityActionPacket.class, EntityActionListener::listener); setPlayListener(ClientHeldItemChangePacket.class, PlayerHeldListener::heldListener); - setPlayListener(ClientPlayerBlockPlacementPacket.class, BlockPlacementListener::listener); + setPlayListener(ClientPlayerBlockPlacementPacket.class, (packet1, player1) -> new BlockPlacementListener(minecraftServer).listener(packet1, player1)); setPlayListener(ClientSteerVehiclePacket.class, PlayerVehicleListener::steerVehicleListener); setPlayListener(ClientVehicleMovePacket.class, PlayerVehicleListener::vehicleMoveListener); setPlayListener(ClientSteerBoatPacket.class, PlayerVehicleListener::boatSteerListener); @@ -118,7 +119,7 @@ public void processClientPacket(@NotNull T packet, @Not // Event if (state == ConnectionState.PLAY) { PlayerPacketEvent playerPacketEvent = new PlayerPacketEvent(connection.getPlayer(), packet); - EventDispatcher.call(playerPacketEvent); + minecraftServer.process().getGlobalEventHandler().call(playerPacketEvent); if (playerPacketEvent.isCancelled()) { return; } @@ -129,7 +130,7 @@ public void processClientPacket(@NotNull T packet, @Not packetListenerConsumer.accept(packet, connection); } catch (Exception e) { // Packet is likely invalid - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java index 7c07de39db6..31f6706702e 100644 --- a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java @@ -1,7 +1,5 @@ package net.minestom.server.listener.preplay; -import net.minestom.server.MinecraftServer; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.server.ClientPingServerEvent; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.network.packet.client.status.PingPacket; @@ -17,13 +15,13 @@ public final class StatusListener { public static void requestListener(@NotNull StatusRequestPacket packet, @NotNull PlayerConnection connection) { final ServerListPingType pingVersion = ServerListPingType.fromModernProtocolVersion(connection.getProtocolVersion()); final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connection, pingVersion); - EventDispatcher.callCancellable(statusRequestEvent, () -> + connection.minecraftServer.process().getGlobalEventHandler().callCancellable(statusRequestEvent, () -> connection.sendPacket(new ResponsePacket(pingVersion.getPingResponse(statusRequestEvent.getResponseData())))); } public static void pingListener(@NotNull PingPacket packet, @NotNull PlayerConnection connection) { final ClientPingServerEvent clientPingEvent = new ClientPingServerEvent(connection, packet.number()); - EventDispatcher.call(clientPingEvent); + connection.minecraftServer.process().getGlobalEventHandler().call(clientPingEvent); if (clientPingEvent.isCancelled()) { connection.disconnect(); @@ -32,7 +30,7 @@ public static void pingListener(@NotNull PingPacket packet, @NotNull PlayerConne connection.sendPacket(new PongPacket(clientPingEvent.getPayload())); connection.disconnect(); } else { - MinecraftServer.getSchedulerManager().buildTask(() -> { + connection.minecraftServer.process().getSchedulerManager().buildTask(() -> { connection.sendPacket(new PongPacket(clientPingEvent.getPayload())); connection.disconnect(); }).delay(clientPingEvent.getDelay()).schedule(); diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index 01187711cdf..5a8a6be582c 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -6,7 +6,6 @@ import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.entity.damage.DamageType; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; import net.minestom.server.event.player.AsyncPlayerPreLoginEvent; import net.minestom.server.instance.Instance; @@ -238,7 +237,7 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { // Call pre login event AsyncPlayerPreLoginEvent asyncPlayerPreLoginEvent = new AsyncPlayerPreLoginEvent(player); - EventDispatcher.call(asyncPlayerPreLoginEvent); + minecraftServer.process().getGlobalEventHandler().call(asyncPlayerPreLoginEvent); if (!player.isOnline()) return; // Player has been kicked @@ -278,7 +277,7 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { player.sendPacket(PluginMessagePacket.getBrandPacket(minecraftServer)); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); - EventDispatcher.call(event); + minecraftServer.process().getGlobalEventHandler().call(event); final Instance spawningInstance = event.getSpawningInstance(); Check.notNull(spawningInstance, "You need to specify a spawning instance in the AsyncPlayerConfigurationEvent"); diff --git a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java index e498109f407..98b3fafa87e 100644 --- a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java @@ -13,6 +13,10 @@ public class FakePlayerConnection extends PlayerConnection { + public FakePlayerConnection() { + super(); + } + @Override public void sendPacket(@NotNull SendablePacket packet) { FakePlayerController controller = getFakePlayer().getController(); diff --git a/src/main/java/net/minestom/server/network/player/PlayerConnection.java b/src/main/java/net/minestom/server/network/player/PlayerConnection.java index 5bd15373633..f44bfd6402e 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerConnection.java @@ -19,12 +19,14 @@ * It can be extended to create a new kind of player (NPC for instance). */ public abstract class PlayerConnection { + public final MinecraftServer minecraftServer; private Player player; private volatile ConnectionState connectionState; private PlayerPublicKey playerPublicKey; volatile boolean online; - public PlayerConnection() { + public PlayerConnection(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; this.online = true; this.connectionState = ConnectionState.HANDSHAKE; } @@ -83,7 +85,7 @@ public int getProtocolVersion() { * @return the server address used */ public @Nullable String getServerAddress() { - return MinecraftServer.getServer().getAddress(); + return minecraftServer.process().getServer().getAddress(); } @@ -95,7 +97,7 @@ public int getProtocolVersion() { * @return the server port used */ public int getServerPort() { - return MinecraftServer.getServer().getPort(); + return minecraftServer.process().getServer().getPort(); } /** @@ -103,7 +105,7 @@ public int getServerPort() { */ public void disconnect() { this.online = false; - MinecraftServer.getConnectionManager().removePlayer(this); + minecraftServer.process().getConnectionManager().removePlayer(this); final Player player = getPlayer(); if (player != null && !player.isRemoved()) { player.scheduleNextTick(Entity::remove); diff --git a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java index 1ff4ee9b420..3d420d940df 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java @@ -3,7 +3,6 @@ import net.minestom.server.MinecraftServer; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.entity.Player; -import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.ListenerHandle; import net.minestom.server.event.player.PlayerPacketOutEvent; import net.minestom.server.extras.mojangAuth.MojangCrypt; @@ -74,14 +73,15 @@ public class PlayerSocketConnection extends PlayerConnection { private final AtomicReference tickBuffer = new AtomicReference<>(POOL.get()); private BinaryBuffer cacheBuffer; - private final ListenerHandle outgoing = EventDispatcher.getHandle(PlayerPacketOutEvent.class); + private final ListenerHandle outgoing; - public PlayerSocketConnection(@NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { - super(); + public PlayerSocketConnection(@NotNull MinecraftServer minecraftServer, @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { + super(minecraftServer); this.worker = worker; this.workerQueue = worker.queue(); this.channel = channel; this.remoteAddress = remoteAddress; + this.outgoing = minecraftServer.process().getGlobalEventHandler().getHandle(PlayerPacketOutEvent.class); } public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProcessor) { @@ -93,7 +93,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces try { encryptionContext.decrypt().update(input, input.duplicate()); } catch (ShortBufferException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); return; } } @@ -109,7 +109,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces packet = packetProcessor.process(this, id, payload); } catch (Exception e) { // Error while reading the packet - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } finally { if (payload.position() != payload.limit()) { LOGGER.warn("WARNING: Packet ({}) 0x{} not fully read ({}) {}", getConnectionState(), Integer.toHexString(id), payload, packet); @@ -117,7 +117,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces } }); } catch (DataFormatException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); disconnect(); } } @@ -148,7 +148,7 @@ public void setEncryptionKey(@NotNull SecretKey secretKey) { */ public void startCompression() { Check.stateCondition(compressed, "Compression is already enabled!"); - final int threshold = MinecraftServer.getCompressionThreshold(); + final int threshold = minecraftServer.getCompressionThreshold(); Check.stateCondition(threshold == 0, "Compression cannot be enabled because the threshold is equal to 0"); sendPacket(new SetCompressionPacket(threshold)); this.compressed = true; @@ -384,7 +384,7 @@ private void writeBufferSync(@NotNull ByteBuffer buffer, int index, int length) length = encryptionContext.encrypt().update(buffer.slice(index, length), output); writeBufferSync0(output, 0, length); } catch (ShortBufferException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } return; } diff --git a/src/main/java/net/minestom/server/network/socket/Server.java b/src/main/java/net/minestom/server/network/socket/Server.java index 7becae6e14a..5f6eb95d55d 100644 --- a/src/main/java/net/minestom/server/network/socket/Server.java +++ b/src/main/java/net/minestom/server/network/socket/Server.java @@ -26,6 +26,7 @@ public final class Server { private volatile boolean stop; private final Selector selector = Selector.open(); + private final MinecraftServer minecraftServer; private final PacketProcessor packetProcessor; private final List workers; private int index; @@ -35,10 +36,11 @@ public final class Server { private String address; private int port; - public Server(PacketProcessor packetProcessor) throws IOException { + public Server(MinecraftServer minecraftServer, PacketProcessor packetProcessor) throws IOException { + this.minecraftServer = minecraftServer; this.packetProcessor = packetProcessor; Worker[] workers = new Worker[WORKER_COUNT]; - Arrays.setAll(workers, value -> new Worker(this)); + Arrays.setAll(workers, value -> new Worker(minecraftServer,this)); this.workers = List.of(workers); } @@ -88,7 +90,7 @@ public void start() { } }); } catch (IOException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } } }, "Ms-entrypoint").start(); @@ -113,7 +115,7 @@ public void stop() { Files.deleteIfExists(unixDomainSocketAddress.getPath()); } } catch (IOException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } this.selector.wakeup(); this.workers.forEach(worker -> worker.selector.wakeup()); diff --git a/src/main/java/net/minestom/server/network/socket/Worker.java b/src/main/java/net/minestom/server/network/socket/Worker.java index bc30cf88f21..7123ebd7c77 100644 --- a/src/main/java/net/minestom/server/network/socket/Worker.java +++ b/src/main/java/net/minestom/server/network/socket/Worker.java @@ -25,11 +25,13 @@ public final class Worker extends MinestomThread { final Selector selector; private final Map connectionMap = new ConcurrentHashMap<>(); + private final MinecraftServer minecraftServer; private final Server server; private final MpscUnboundedXaddArrayQueue queue = new MpscUnboundedXaddArrayQueue<>(1024); - Worker(Server server) { + Worker(MinecraftServer minecraftServer, Server server) { super("Ms-worker-" + COUNTER.getAndIncrement()); + this.minecraftServer = minecraftServer; this.server = server; try { this.selector = Selector.open(); @@ -49,7 +51,7 @@ public void run() { try { this.queue.drain(Runnable::run); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } // Flush all connections if needed for (PlayerSocketConnection connection : connectionMap.values()) { @@ -86,12 +88,12 @@ public void run() { // TODO print exception? (should ignore disconnection) connection.disconnect(); } catch (Throwable t) { - MinecraftServer.getExceptionManager().handleException(t); + minecraftServer.process().getExceptionManager().handleException(t); connection.disconnect(); } }); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } } } @@ -111,7 +113,7 @@ public void disconnect(PlayerSocketConnection connection, SocketChannel channel) } void receiveConnection(SocketChannel channel) throws IOException { - this.connectionMap.put(channel, new PlayerSocketConnection(this, channel, channel.getRemoteAddress())); + this.connectionMap.put(channel, new PlayerSocketConnection(minecraftServer, this, channel, channel.getRemoteAddress())); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); if (channel.getLocalAddress() instanceof InetSocketAddress) { diff --git a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java index 5746e04d73e..4a41ec57f18 100644 --- a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java @@ -61,6 +61,11 @@ final class TestConnectionImpl implements TestConnection { } final class PlayerConnectionImpl extends PlayerConnection { + + PlayerConnectionImpl() { + super(); + } + @Override public void sendPacket(@NotNull SendablePacket packet) { final var serverPacket = this.extractPacket(packet); From 8e17990819efe3afb69ae6525fb38dd82256aaf1 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Mon, 29 Jan 2024 17:14:52 +0300 Subject: [PATCH 04/16] Moooooore --- .../src/main/java/net/minestom/demo/Main.java | 2 +- .../java/net/minestom/demo/PlayerInit.java | 6 +- .../demo/commands/SidebarCommand.java | 7 +- .../net/minestom/server/MinecraftServer.java | 22 +-- .../server/MinecraftServerObject.java | 5 + .../net/minestom/server/ServerProcess.java | 6 + .../minestom/server/ServerProcessImpl.java | 126 ++++++++++-------- .../java/net/minestom/server/Viewable.java | 6 +- .../advancements/AdvancementManager.java | 8 +- .../server/advancements/AdvancementTab.java | 9 +- .../server/adventure/audience/Audiences.java | 44 +++--- .../audience/IterableAudienceProvider.java | 11 +- .../audience/PacketGroupingAudience.java | 25 +++- .../audience/SingleAudienceProvider.java | 20 ++- .../adventure/bossbar/BossBarHolder.java | 10 +- .../adventure/bossbar/BossBarListener.java | 15 ++- .../adventure/bossbar/BossBarManager.java | 17 +-- .../server/command/CommandManager.java | 6 +- .../server/command/CommandSender.java | 3 + .../server/command/ConsoleSender.java | 15 ++- .../server/command/GraphConverter.java | 22 +-- .../minestom/server/command/ServerSender.java | 12 ++ .../command/builder/CommandDispatcher.java | 5 +- .../builder/arguments/ArgumentCommand.java | 3 +- .../net/minestom/server/entity/Entity.java | 22 +-- .../minestom/server/entity/EntityView.java | 4 +- .../minestom/server/entity/ExperienceOrb.java | 5 +- .../net/minestom/server/entity/Player.java | 22 +-- .../server/entity/PlayerProjectile.java | 10 +- .../entity/ai/goal/CombinedAttackGoal.java | 2 +- .../entity/ai/goal/RangedAttackGoal.java | 2 +- .../server/entity/fakeplayer/FakePlayer.java | 12 +- .../server/entity/hologram/Hologram.java | 8 +- .../net/minestom/server/event/EventNode.java | 55 ++++---- .../minestom/server/event/EventNodeImpl.java | 9 +- .../server/event/EventNodeLazyImpl.java | 5 +- .../server/event/GlobalEventHandler.java | 6 +- .../event/server/ServerListPingEvent.java | 9 +- .../server/exception/ExceptionManager.java | 7 +- .../minestom/server/extras/MojangAuth.java | 29 ++-- .../minestom/server/extras/lan/OpenToLAN.java | 2 +- .../server/extras/mojangAuth/MojangCrypt.java | 33 +++-- .../minestom/server/extras/query/Query.java | 2 +- .../extras/query/event/BasicQueryEvent.java | 5 +- .../query/response/BasicQueryResponse.java | 11 +- .../server/instance/DynamicChunk.java | 18 ++- .../server/instance/EntityTrackerImpl.java | 6 +- .../minestom/server/instance/Explosion.java | 2 +- .../server/instance/GeneratorImpl.java | 35 +++-- .../server/instance/IChunkLoader.java | 4 +- .../minestom/server/instance/Instance.java | 14 +- .../server/instance/InstanceContainer.java | 8 +- .../server/instance/InstanceManager.java | 2 +- .../server/instance/LightingChunk.java | 5 +- .../net/minestom/server/instance/Section.java | 5 +- .../server/instance/SharedInstance.java | 5 +- .../minestom/server/instance/WorldBorder.java | 2 +- .../instance/palette/AdaptivePalette.java | 9 +- .../instance/palette/FlexiblePalette.java | 12 +- .../server/instance/palette/Palette.java | 13 +- .../minestom/server/inventory/Inventory.java | 5 + .../server/inventory/type/AnvilInventory.java | 9 +- .../inventory/type/BeaconInventory.java | 9 +- .../inventory/type/BrewingStandInventory.java | 9 +- .../type/EnchantmentTableInventory.java | 9 +- .../inventory/type/FurnaceInventory.java | 9 +- .../inventory/type/VillagerInventory.java | 13 +- .../listener/AdvancementTabListener.java | 2 +- .../server/listener/ChatMessageListener.java | 2 +- .../server/listener/PlayConfigListener.java | 6 +- .../server/listener/TabCompleteListener.java | 8 +- .../manager/PacketListenerManager.java | 2 +- .../listener/preplay/ConfigListener.java | 5 +- .../listener/preplay/LoginListener.java | 41 +++--- .../listener/preplay/StatusListener.java | 2 +- .../net/minestom/server/map/MapColors.java | 4 +- .../minestom/server/message/Messenger.java | 5 +- .../server/monitoring/BenchmarkManager.java | 7 +- .../server/network/ConnectionManager.java | 10 +- .../network/packet/server/CachedPacket.java | 11 +- .../packet/server/common/TagsPacket.java | 8 +- .../network/player/FakePlayerConnection.java | 5 +- .../player/PlayerSocketConnection.java | 5 +- .../minestom/server/ping/ResponseData.java | 13 +- .../server/ping/ServerListPingType.java | 5 +- .../minestom/server/registry/Registry.java | 3 +- .../server/scoreboard/BelowNameTag.java | 16 ++- .../minestom/server/scoreboard/Sidebar.java | 16 ++- .../minestom/server/scoreboard/TabList.java | 10 +- .../net/minestom/server/scoreboard/Team.java | 18 ++- .../server/scoreboard/TeamBuilder.java | 5 +- .../server/scoreboard/TeamManager.java | 11 +- .../server/snapshot/ServerSnapshot.java | 4 +- .../server/snapshot/SnapshotImpl.java | 5 +- .../minestom/server/thread/Acquirable.java | 5 +- .../server/thread/AcquirableCollection.java | 5 +- .../server/thread/ThreadDispatcher.java | 13 +- .../minestom/server/thread/TickThread.java | 8 +- .../minestom/server/utils/PacketUtils.java | 51 +++---- .../server/utils/async/AsyncUtils.java | 4 +- .../server/utils/entity/EntityFinder.java | 10 +- .../server/utils/mojang/MojangUtils.java | 2 - 102 files changed, 713 insertions(+), 482 deletions(-) create mode 100644 src/main/java/net/minestom/server/MinecraftServerObject.java diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index 6756b31932c..2d496200d94 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -63,7 +63,7 @@ public static void main(String[] args) { commandManager.register(new NotificationCommand()); commandManager.register(new TestCommand2()); commandManager.register(new ConfigCommand()); - commandManager.register(new SidebarCommand()); + commandManager.register(new SidebarCommand(minecraftServer)); commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED))); diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index ef55dc59753..6680f10b3be 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -74,10 +74,10 @@ public PlayerInit(MinecraftServer minecraftServer) { // System.out.println("load end"); // }); - inventory = new Inventory(InventoryType.CHEST_1_ROW, Component.text("Test inventory")); + inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, Component.text("Test inventory")); inventory.setItemStack(3, ItemStack.of(Material.DIAMOND, 34)); - DEMO_NODE = EventNode.all("demo") + DEMO_NODE = EventNode.all(minecraftServer, "demo") .addListener(EntityAttackEvent.class, event -> { final Entity source = event.getEntity(); final Entity entity = event.getTarget(); @@ -107,7 +107,7 @@ public PlayerInit(MinecraftServer minecraftServer) { ItemStack droppedItem = event.getItemStack(); Pos playerPos = player.getPosition(); - ItemEntity itemEntity = new ItemEntity(droppedItem); + ItemEntity itemEntity = new ItemEntity(minecraftServer, droppedItem); itemEntity.setPickupDelay(Duration.of(500, TimeUnit.MILLISECOND)); itemEntity.setInstance(player.getInstance(), playerPos.withY(y -> y + 1.5)); Vec velocity = playerPos.direction().mul(6); diff --git a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java index 139a4ff4e5b..45afe2dd201 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java @@ -3,6 +3,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -14,12 +15,14 @@ import org.jetbrains.annotations.Nullable; public class SidebarCommand extends Command { - private final Sidebar sidebar = new Sidebar(Component.text("DEMO").decorate(TextDecoration.BOLD)); + private final Sidebar sidebar; private int currentLine = 0; - public SidebarCommand() { + public SidebarCommand(MinecraftServer minecraftServer) { super("sidebar"); + sidebar = new Sidebar(minecraftServer, Component.text("DEMO").decorate(TextDecoration.BOLD)); + addLine("BLANK ", Sidebar.NumberFormat.blank()); addLine("STYLE ", Sidebar.NumberFormat.styled(Component.empty().decorate(TextDecoration.STRIKETHROUGH).color(NamedTextColor.GRAY))); addLine("FIXED ", Sidebar.NumberFormat.fixed(Component.text("FIXED").color(NamedTextColor.GRAY))); diff --git a/src/main/java/net/minestom/server/MinecraftServer.java b/src/main/java/net/minestom/server/MinecraftServer.java index 7edeba96096..5f574954a25 100644 --- a/src/main/java/net/minestom/server/MinecraftServer.java +++ b/src/main/java/net/minestom/server/MinecraftServer.java @@ -1,31 +1,13 @@ package net.minestom.server; import net.kyori.adventure.text.logger.slf4j.ComponentLogger; -import net.minestom.server.advancements.AdvancementManager; -import net.minestom.server.adventure.bossbar.BossBarManager; -import net.minestom.server.command.CommandManager; -import net.minestom.server.event.GlobalEventHandler; -import net.minestom.server.exception.ExceptionManager; -import net.minestom.server.gamedata.tags.TagManager; -import net.minestom.server.instance.InstanceManager; -import net.minestom.server.instance.block.BlockManager; -import net.minestom.server.listener.manager.PacketListenerManager; -import net.minestom.server.monitoring.BenchmarkManager; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.PacketProcessor; import net.minestom.server.network.packet.server.common.PluginMessagePacket; import net.minestom.server.network.packet.server.play.ServerDifficultyPacket; -import net.minestom.server.network.socket.Server; -import net.minestom.server.recipe.RecipeManager; -import net.minestom.server.scoreboard.TeamManager; import net.minestom.server.thread.TickSchedulerThread; -import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.Difficulty; -import net.minestom.server.world.DimensionTypeManager; -import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.UnknownNullability; @@ -102,7 +84,7 @@ public String getBrandName() { */ public void setBrandName(@NotNull String brandName) { this.brandName = brandName; - PacketUtils.broadcastPlayPacket(PluginMessagePacket.getBrandPacket(this)); + PacketUtils.broadcastPlayPacket(this, PluginMessagePacket.getBrandPacket(this)); } /** @@ -122,7 +104,7 @@ public Difficulty getDifficulty() { */ public void setDifficulty(@NotNull Difficulty difficulty) { this.difficulty = difficulty; - PacketUtils.broadcastPlayPacket(new ServerDifficultyPacket(difficulty, true)); + PacketUtils.broadcastPlayPacket(this, new ServerDifficultyPacket(difficulty, true)); } @ApiStatus.Experimental diff --git a/src/main/java/net/minestom/server/MinecraftServerObject.java b/src/main/java/net/minestom/server/MinecraftServerObject.java new file mode 100644 index 00000000000..c1e795323bc --- /dev/null +++ b/src/main/java/net/minestom/server/MinecraftServerObject.java @@ -0,0 +1,5 @@ +package net.minestom.server; + +public interface MinecraftServerObject { + MinecraftServer getMinecraftServer(); +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/ServerProcess.java b/src/main/java/net/minestom/server/ServerProcess.java index edebd3341d1..5b589115d2a 100644 --- a/src/main/java/net/minestom/server/ServerProcess.java +++ b/src/main/java/net/minestom/server/ServerProcess.java @@ -1,10 +1,12 @@ package net.minestom.server; import net.minestom.server.advancements.AdvancementManager; +import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.adventure.bossbar.BossBarManager; import net.minestom.server.command.CommandManager; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.exception.ExceptionManager; +import net.minestom.server.extras.MojangAuth; import net.minestom.server.gamedata.tags.TagManager; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.InstanceManager; @@ -138,6 +140,10 @@ public interface ServerProcess extends Snapshotable { boolean isAlive(); + Audiences getAudiences(); + + MojangAuth getMojangAuth(); + @ApiStatus.NonExtendable interface Ticker { void tick(long nanoTime); diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java index f0610b3efdb..35170997b3a 100644 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -2,12 +2,14 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.advancements.AdvancementManager; +import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.adventure.bossbar.BossBarManager; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Entity; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ServerTickMonitorEvent; import net.minestom.server.exception.ExceptionManager; +import net.minestom.server.extras.MojangAuth; import net.minestom.server.gamedata.tags.TagManager; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; @@ -45,23 +47,23 @@ final class ServerProcessImpl implements ServerProcess { private static final Logger LOGGER = LoggerFactory.getLogger(ServerProcessImpl.class); private static final Boolean SHUTDOWN_ON_SIGNAL = PropertyUtils.getBoolean("minestom.shutdown-on-signal", true); - private final ExceptionManager exception; - private final ConnectionManager connection; - private final PacketListenerManager packetListener; + private final ExceptionManager exceptionManager; + private final ConnectionManager connectionManager; + private final PacketListenerManager packetListenerManager; private final PacketProcessor packetProcessor; - private final InstanceManager instance; - private final BlockManager block; - private final CommandManager command; - private final RecipeManager recipe; - private final TeamManager team; - private final GlobalEventHandler eventHandler; - private final SchedulerManager scheduler; - private final BenchmarkManager benchmark; - private final DimensionTypeManager dimension; - private final BiomeManager biome; - private final AdvancementManager advancement; - private final BossBarManager bossBar; - private final TagManager tag; + private final InstanceManager instanceManager; + private final BlockManager blockManager; + private final CommandManager commandManager; + private final RecipeManager recipeManager; + private final TeamManager teamManager; + private final GlobalEventHandler globalEventHandler; + private final SchedulerManager schedulerManager; + private final BenchmarkManager benchmarkManager; + private final DimensionTypeManager dimensionTypeManager; + private final BiomeManager biomeManager; + private final AdvancementManager advancementManager; + private final BossBarManager bossBarManager; + private final TagManager tagManager; private final Server server; private final ThreadDispatcher dispatcher; @@ -70,110 +72,114 @@ final class ServerProcessImpl implements ServerProcess { private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); private final MinecraftServer minecraftServer; + private final Audiences audiences; + private final MojangAuth mojangAuth; public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { this.minecraftServer = minecraftServer; - this.exception = new ExceptionManager(); - this.connection = new ConnectionManager(minecraftServer); - this.packetListener = new PacketListenerManager(minecraftServer); - this.packetProcessor = new PacketProcessor(packetListener); - this.instance = new InstanceManager(minecraftServer); - this.block = new BlockManager(); - this.command = new CommandManager(minecraftServer); - this.recipe = new RecipeManager(); - this.team = new TeamManager(); - this.eventHandler = new GlobalEventHandler(); - this.scheduler = new SchedulerManager(); - this.benchmark = new BenchmarkManager(); - this.dimension = new DimensionTypeManager(); - this.biome = new BiomeManager(); - this.advancement = new AdvancementManager(); - this.bossBar = new BossBarManager(); - this.tag = new TagManager(); + this.exceptionManager = new ExceptionManager(minecraftServer); + this.connectionManager = new ConnectionManager(minecraftServer); + this.packetListenerManager = new PacketListenerManager(minecraftServer); + this.packetProcessor = new PacketProcessor(packetListenerManager); + this.instanceManager = new InstanceManager(minecraftServer); + this.blockManager = new BlockManager(); + this.commandManager = new CommandManager(minecraftServer); + this.recipeManager = new RecipeManager(); + this.teamManager = new TeamManager(minecraftServer); + this.globalEventHandler = new GlobalEventHandler(minecraftServer); + this.schedulerManager = new SchedulerManager(); + this.benchmarkManager = new BenchmarkManager(minecraftServer); + this.dimensionTypeManager = new DimensionTypeManager(); + this.biomeManager = new BiomeManager(); + this.advancementManager = new AdvancementManager(minecraftServer); + this.bossBarManager = new BossBarManager(minecraftServer); + this.tagManager = new TagManager(); this.server = new Server(minecraftServer, packetProcessor); + this.audiences = new Audiences(minecraftServer); + this.mojangAuth = new MojangAuth(minecraftServer); - this.dispatcher = ThreadDispatcher.singleThread(); + this.dispatcher = ThreadDispatcher.singleThread(minecraftServer); this.ticker = new TickerImpl(); } @Override public @NotNull ConnectionManager getConnectionManager() { - return connection; + return connectionManager; } @Override public @NotNull InstanceManager getInstanceManager() { - return instance; + return instanceManager; } @Override public @NotNull BlockManager getBlockManager() { - return block; + return blockManager; } @Override public @NotNull CommandManager getCommandManager() { - return command; + return commandManager; } @Override public @NotNull RecipeManager getRecipeManager() { - return recipe; + return recipeManager; } @Override public @NotNull TeamManager getTeamManager() { - return team; + return teamManager; } @Override public @NotNull GlobalEventHandler getGlobalEventHandler() { - return eventHandler; + return globalEventHandler; } @Override public @NotNull SchedulerManager getSchedulerManager() { - return scheduler; + return schedulerManager; } @Override public @NotNull BenchmarkManager getBenchmarkManager() { - return benchmark; + return benchmarkManager; } @Override public @NotNull DimensionTypeManager getDimensionTypeManager() { - return dimension; + return dimensionTypeManager; } @Override public @NotNull BiomeManager getBiomeManager() { - return biome; + return biomeManager; } @Override public @NotNull AdvancementManager getAdvancementManager() { - return advancement; + return advancementManager; } @Override public @NotNull BossBarManager getBossBarManager() { - return bossBar; + return bossBarManager; } @Override public @NotNull TagManager getTagManager() { - return tag; + return tagManager; } @Override public @NotNull ExceptionManager getExceptionManager() { - return exception; + return exceptionManager; } @Override public @NotNull PacketListenerManager getPacketListenerManager() { - return packetListener; + return packetListenerManager; } @Override @@ -208,7 +214,7 @@ public void start(@NotNull SocketAddress socketAddress) { try { server.init(socketAddress); } catch (IOException e) { - exception.handleException(e); + exceptionManager.handleException(e); throw new RuntimeException(e); } @@ -226,11 +232,11 @@ public void stop() { if (!stopped.compareAndSet(false, true)) return; LOGGER.info("Stopping " + minecraftServer.getBrandName() + " server."); - scheduler.shutdown(); - connection.shutdown(); + schedulerManager.shutdown(); + connectionManager.shutdown(); server.stop(); LOGGER.info("Shutting down all thread pools."); - benchmark.disable(); + benchmarkManager.disable(); dispatcher.shutdown(); LOGGER.info(minecraftServer.getBrandName() + " server stopped successfully."); } @@ -240,11 +246,16 @@ public boolean isAlive() { return started.get() && !stopped.get(); } + @Override + public Audiences getAudiences() { + return audiences; + } + @Override public @NotNull ServerSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) { List> instanceRefs = new ArrayList<>(); Int2ObjectOpenHashMap> entityRefs = new Int2ObjectOpenHashMap<>(); - for (Instance instance : instance.getInstances()) { + for (Instance instance : instanceManager.getInstances()) { instanceRefs.add(updater.reference(instance)); for (Entity entity : instance.getEntities()) { entityRefs.put(entity.getEntityId(), updater.reference(entity)); @@ -253,6 +264,11 @@ public boolean isAlive() { return new SnapshotImpl.Server(MappedCollection.plainReferences(instanceRefs), entityRefs); } + @Override + public MojangAuth getMojangAuth() { + return mojangAuth; + } + private final class TickerImpl implements Ticker { @Override public void tick(long nanoTime) { diff --git a/src/main/java/net/minestom/server/Viewable.java b/src/main/java/net/minestom/server/Viewable.java index 6cf1c0b5936..5632e211153 100644 --- a/src/main/java/net/minestom/server/Viewable.java +++ b/src/main/java/net/minestom/server/Viewable.java @@ -15,7 +15,7 @@ /** * Represents something which can be displayed or hidden to players. */ -public interface Viewable { +public interface Viewable extends MinecraftServerObject { /** * Adds a viewer. @@ -60,7 +60,7 @@ default boolean isViewer(@NotNull Player player) { */ default void sendPacketToViewers(@NotNull SendablePacket packet) { if (packet instanceof ServerPacket serverPacket) { - PacketUtils.sendGroupedPacket(getViewers(), serverPacket); + PacketUtils.sendGroupedPacket(getMinecraftServer(), getViewers(), serverPacket); } else { getViewers().forEach(player -> player.sendPacket(packet)); } @@ -91,7 +91,7 @@ default void sendPacketToViewersAndSelf(@NotNull SendablePacket packet) { * @return the audience */ default @NotNull Audience getViewersAsAudience() { - return PacketGroupingAudience.of(this.getViewers()); + return PacketGroupingAudience.of(getMinecraftServer(), this.getViewers()); } /** diff --git a/src/main/java/net/minestom/server/advancements/AdvancementManager.java b/src/main/java/net/minestom/server/advancements/AdvancementManager.java index 2ce596795c8..c6fd29520f0 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementManager.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementManager.java @@ -1,5 +1,6 @@ package net.minestom.server.advancements; +import net.minestom.server.MinecraftServer; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -17,6 +18,11 @@ public class AdvancementManager { // root identifier = its advancement tab private final Map advancementTabMap = new ConcurrentHashMap<>(); + private final MinecraftServer minecraftServer; + + public AdvancementManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } /** * Creates a new {@link AdvancementTab} with a single {@link AdvancementRoot}. @@ -30,7 +36,7 @@ public class AdvancementManager { public AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root) { Check.stateCondition(advancementTabMap.containsKey(rootIdentifier), "A tab with the identifier '" + rootIdentifier + "' already exists"); - final AdvancementTab advancementTab = new AdvancementTab(rootIdentifier, root); + final AdvancementTab advancementTab = new AdvancementTab(minecraftServer, rootIdentifier, root); this.advancementTabMap.put(rootIdentifier, advancementTab); return advancementTab; } diff --git a/src/main/java/net/minestom/server/advancements/AdvancementTab.java b/src/main/java/net/minestom/server/advancements/AdvancementTab.java index 8228a5ddd1e..a58b1f88643 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementTab.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementTab.java @@ -1,5 +1,6 @@ package net.minestom.server.advancements; +import net.minestom.server.MinecraftServer; import net.minestom.server.Viewable; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.AdvancementsPacket; @@ -25,6 +26,7 @@ public class AdvancementTab implements Viewable { private final Set viewers = new HashSet<>(); + private final MinecraftServer minecraftServer; private final AdvancementRoot root; // Advancement -> its parent @@ -34,7 +36,8 @@ public class AdvancementTab implements Viewable { // will never change (since the root identifier is always the same) protected final AdvancementsPacket removePacket; - protected AdvancementTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root) { + protected AdvancementTab(MinecraftServer minecraftServer, @NotNull String rootIdentifier, @NotNull AdvancementRoot root) { + this.minecraftServer = minecraftServer; this.root = root; cacheAdvancement(rootIdentifier, root, null); this.removePacket = new AdvancementsPacket(false, List.of(), List.of(rootIdentifier), List.of()); @@ -165,4 +168,8 @@ private void removePlayer(@NotNull Player player) { } } + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/adventure/audience/Audiences.java b/src/main/java/net/minestom/server/adventure/audience/Audiences.java index 764b3864555..2eae867359c 100644 --- a/src/main/java/net/minestom/server/adventure/audience/Audiences.java +++ b/src/main/java/net/minestom/server/adventure/audience/Audiences.java @@ -5,6 +5,7 @@ import net.kyori.adventure.key.Keyed; import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; +import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.NotNull; import java.util.function.Predicate; @@ -13,14 +14,21 @@ * Utility class to access Adventure audiences. */ public class Audiences { - private static final SingleAudienceProvider audience = new SingleAudienceProvider(); + + private final MinecraftServer minecraftServer; + private final SingleAudienceProvider audience; + + public Audiences(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + audience = new SingleAudienceProvider(minecraftServer); + } /** * Gets the {@link AudienceProvider} that provides forwarding audiences. * * @return the instance */ - public static @NotNull AudienceProvider single() { + public @NotNull AudienceProvider single() { return audience; } @@ -29,7 +37,7 @@ public class Audiences { * * @return the instance */ - public static @NotNull AudienceProvider> iterable() { + public @NotNull AudienceProvider> iterable() { return audience.collection; } @@ -40,7 +48,7 @@ public class Audiences { * * @return all audience members */ - public static @NotNull Audience all() { + public @NotNull Audience all() { return Audience.audience(audience.server, audience.customs()); } @@ -49,7 +57,7 @@ public class Audiences { * * @return all players */ - public static @NotNull Audience players() { + public @NotNull Audience players() { return audience.players; } @@ -59,8 +67,8 @@ public class Audiences { * @param filter the predicate * @return all players matching the predicate */ - public static @NotNull Audience players(@NotNull Predicate filter) { - return PacketGroupingAudience.of(MinecraftServer.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); + public @NotNull Audience players(ConnectionManager connectionManager, @NotNull Predicate filter) { + return PacketGroupingAudience.of(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); } /** @@ -68,8 +76,8 @@ public class Audiences { * * @return the console */ - public static @NotNull Audience console() { - return MinecraftServer.getCommandManager().getConsoleSender(); + public @NotNull Audience console() { + return minecraftServer.process().getCommandManager().getConsoleSender(); } /** @@ -77,7 +85,7 @@ public class Audiences { * * @return the audience of all players and the console */ - public static @NotNull Audience server() { + public @NotNull Audience server() { return audience.server; } @@ -86,7 +94,7 @@ public class Audiences { * * @return all custom audience members */ - public static @NotNull Audience customs() { + public @NotNull Audience customs() { return Audience.audience(audience.iterable().customs()); } @@ -96,7 +104,7 @@ public class Audiences { * @param keyed the keyed object * @return all custom audience members stored using the key of the object */ - public static @NotNull Audience custom(@NotNull Keyed keyed) { + public @NotNull Audience custom(@NotNull Keyed keyed) { return custom(keyed.key()); } @@ -106,7 +114,7 @@ public class Audiences { * @param key the key * @return all custom audience members stored using the key */ - public static @NotNull Audience custom(@NotNull Key key) { + public @NotNull Audience custom(@NotNull Key key) { return Audience.audience(audience.iterable().custom(key)); } @@ -118,7 +126,7 @@ public class Audiences { * @param filter the predicate * @return all custom audience members stored using the key */ - public static @NotNull Audience custom(@NotNull Keyed keyed, Predicate filter) { + public @NotNull Audience custom(@NotNull Keyed keyed, Predicate filter) { return custom(keyed.key(), filter); } @@ -130,7 +138,7 @@ public class Audiences { * @param filter the predicate * @return all custom audience members stored using the key */ - public static @NotNull Audience custom(@NotNull Key key, Predicate filter) { + public @NotNull Audience custom(@NotNull Key key, Predicate filter) { return Audience.audience(audience.iterable().custom(key, filter)); } @@ -140,7 +148,7 @@ public class Audiences { * @param filter the predicate * @return all matching custom audience members */ - public static @NotNull Audience customs(@NotNull Predicate filter) { + public @NotNull Audience customs(@NotNull Predicate filter) { return Audience.audience(audience.iterable().customs(filter)); } @@ -150,7 +158,7 @@ public class Audiences { * @param filter the predicate * @return all matching audience members */ - public static @NotNull Audience all(@NotNull Predicate filter) { + public @NotNull Audience all(@NotNull Predicate filter) { return Audience.audience(audience.iterable().all(filter)); } @@ -159,7 +167,7 @@ public class Audiences { * * @return the registry */ - public static @NotNull AudienceRegistry registry() { + public @NotNull AudienceRegistry registry() { return audience.iterable().registry(); } } diff --git a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java index f2f3ff0ffb0..df9590db409 100644 --- a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java @@ -18,10 +18,13 @@ * A provider of iterable audiences. */ class IterableAudienceProvider implements AudienceProvider> { - private final List console = List.of(MinecraftServer.getCommandManager().getConsoleSender()); + private final List console; private final AudienceRegistry registry = new AudienceRegistry(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new); + private final MinecraftServer minecraftServer; - protected IterableAudienceProvider() { + protected IterableAudienceProvider(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.console = List.of(minecraftServer.process().getCommandManager().getConsoleSender()); } @Override @@ -35,12 +38,12 @@ protected IterableAudienceProvider() { @Override public @NotNull Iterable players() { - return MinecraftServer.getConnectionManager().getOnlinePlayers(); + return minecraftServer.process().getConnectionManager().getOnlinePlayers(); } @Override public @NotNull Iterable players(@NotNull Predicate filter) { - return MinecraftServer.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList(); + return minecraftServer.process().getConnectionManager().getOnlinePlayers().stream().filter(filter).toList(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index 70a99c3d51e..9314650e5ec 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -10,6 +10,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.title.TitlePart; import net.minestom.server.MinecraftServer; +import net.minestom.server.MinecraftServerObject; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; @@ -27,7 +28,7 @@ /** * An audience implementation that sends grouped packets if possible. */ -public interface PacketGroupingAudience extends ForwardingAudience { +public interface PacketGroupingAudience extends ForwardingAudience, MinecraftServerObject { /** * Creates a packet grouping audience that copies an iterable of players. The @@ -37,8 +38,18 @@ public interface PacketGroupingAudience extends ForwardingAudience { * @param players the players * @return the audience */ - static @NotNull PacketGroupingAudience of(@NotNull Collection players) { - return () -> players; + static @NotNull PacketGroupingAudience of(MinecraftServer minecraftServer, @NotNull Collection players) { + return new PacketGroupingAudience() { + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + + @Override + public @NotNull Collection<@NotNull Player> getPlayers() { + return players; + } + }; } /** @@ -54,12 +65,12 @@ public interface PacketGroupingAudience extends ForwardingAudience { * @param packet the packet to broadcast */ default void sendGroupedPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(getPlayers(), packet); + PacketUtils.sendGroupedPacket(getMinecraftServer(), getPlayers(), packet); } @Override default void sendMessage(@NotNull Identity source, @NotNull Component message, @NotNull MessageType type) { - Messenger.sendMessage(this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); + Messenger.sendMessage(getMinecraftServer(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); } @Override @@ -89,12 +100,12 @@ default void resetTitle() { @Override default void showBossBar(@NotNull BossBar bar) { - this.getPlayers().stream().findAny().ifPresent((p) -> p.minecraftServer.process().getBossBarManager().addBossBar(this.getPlayers(), bar)); + getMinecraftServer().process().getBossBarManager().addBossBar(this.getPlayers(), bar); } @Override default void hideBossBar(@NotNull BossBar bar) { - this.getPlayers().stream().findAny().ifPresent((p) -> p.minecraftServer.process().getBossBarManager().removeBossBar(this.getPlayers(), bar)); + getMinecraftServer().process().getBossBarManager().removeBossBar(this.getPlayers(), bar); } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java index 262dfb9a150..526e164d1ef 100644 --- a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java @@ -14,11 +14,17 @@ */ class SingleAudienceProvider implements AudienceProvider { - protected final IterableAudienceProvider collection = new IterableAudienceProvider(); - protected final Audience players = PacketGroupingAudience.of(MinecraftServer.getConnectionManager().getOnlinePlayers()); - protected final Audience server = Audience.audience(this.players, MinecraftServer.getCommandManager().getConsoleSender()); - - protected SingleAudienceProvider() { + protected final IterableAudienceProvider collection; + protected final Audience players; + protected final Audience server; + @NotNull + private final MinecraftServer minecraftServer; + + protected SingleAudienceProvider(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.collection = new IterableAudienceProvider(minecraftServer); + this.players = PacketGroupingAudience.of(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers()); + this.server = Audience.audience(this.players, minecraftServer.process().getCommandManager().getConsoleSender()); } /** @@ -42,12 +48,12 @@ protected SingleAudienceProvider() { @Override public @NotNull Audience players(@NotNull Predicate filter) { - return PacketGroupingAudience.of(MinecraftServer.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); + return PacketGroupingAudience.of(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); } @Override public @NotNull Audience console() { - return MinecraftServer.getCommandManager().getConsoleSender(); + return minecraftServer.process().getCommandManager().getConsoleSender(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java index 4607ab23cc2..fd18c6afb7b 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java @@ -2,6 +2,7 @@ import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.Viewable; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.entity.Player; @@ -20,9 +21,11 @@ final class BossBarHolder implements Viewable { final UUID uuid = UUID.randomUUID(); final Set players = new CopyOnWriteArraySet<>(); + private final MinecraftServer minecraftServer; final BossBar bar; - BossBarHolder(@NotNull BossBar bar) { + BossBarHolder(MinecraftServer minecraftServer, @NotNull BossBar bar) { + this.minecraftServer = minecraftServer; this.bar = bar; } @@ -72,4 +75,9 @@ public boolean removeViewer(@NotNull Player player) { public @NotNull Set getViewers() { return Collections.unmodifiableSet(this.players); } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java index 8d36ec6fdb9..8583f75bf3c 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java @@ -3,6 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; @@ -16,6 +17,7 @@ * for players. */ class BossBarListener implements BossBar.Listener { + private final MinecraftServer minecraftServer; private final BossBarManager manager; /** @@ -23,34 +25,35 @@ class BossBarListener implements BossBar.Listener { * * @param manager the manager instance */ - BossBarListener(BossBarManager manager) { + BossBarListener(MinecraftServer minecraftServer, BossBarManager manager) { + this.minecraftServer = minecraftServer; this.manager = manager; } @Override public void bossBarNameChanged(@NotNull BossBar bar, @NotNull Component oldName, @NotNull Component newName) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(holder.players, holder.createTitleUpdate(newName))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createTitleUpdate(newName))); } @Override public void bossBarProgressChanged(@NotNull BossBar bar, float oldProgress, float newProgress) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(holder.players, holder.createPercentUpdate(newProgress))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createPercentUpdate(newProgress))); } @Override public void bossBarColorChanged(@NotNull BossBar bar, @NotNull BossBar.Color oldColor, @NotNull BossBar.Color newColor) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(holder.players, holder.createColorUpdate(newColor))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createColorUpdate(newColor))); } @Override public void bossBarOverlayChanged(@NotNull BossBar bar, BossBar.@NotNull Overlay oldOverlay, BossBar.@NotNull Overlay newOverlay) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(holder.players, holder.createOverlayUpdate(newOverlay))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createOverlayUpdate(newOverlay))); } @Override public void bossBarFlagsChanged(@NotNull BossBar bar, @NotNull Set flagsAdded, @NotNull Set flagsRemoved) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(holder.players, holder.createFlagsUpdate())); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createFlagsUpdate())); } private void doIfRegistered(@NotNull BossBar bar, @NotNull Consumer consumer) { diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java index b1a9fc4b7ce..7c0d82da52d 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java @@ -23,16 +23,17 @@ * @see Audience#hideBossBar(BossBar) */ public class BossBarManager { - private final BossBarListener listener = new BossBarListener(this); + private final BossBarListener listener; private final Map> playerBars = new ConcurrentHashMap<>(); final Map bars = new ConcurrentHashMap<>(); + private final MinecraftServer minecraftServer; /** * Creates a new boss bar manager. - * - * @see MinecraftServer#getBossBarManager() */ - public BossBarManager() { + public BossBarManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.listener = new BossBarListener(minecraftServer,this); } /** @@ -75,7 +76,7 @@ public void addBossBar(@NotNull Collection players, @NotNull BossBar bar BossBarHolder holder = this.getOrCreateHandler(bar); Collection addedPlayers = players.stream().filter(holder::addViewer).toList(); if (!addedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(addedPlayers, holder.createAddPacket()); + PacketUtils.sendGroupedPacket(minecraftServer, addedPlayers, holder.createAddPacket()); } } @@ -90,7 +91,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar if (holder != null) { Collection removedPlayers = players.stream().filter(holder::removeViewer).toList(); if (!removedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(removedPlayers, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(minecraftServer, removedPlayers, holder.createRemovePacket()); } } } @@ -103,7 +104,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar public void destroyBossBar(@NotNull BossBar bossBar) { BossBarHolder holder = this.bars.remove(bossBar); if (holder != null) { - PacketUtils.sendGroupedPacket(holder.players, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createRemovePacket()); for (Player player : holder.players) { this.removePlayer(player, holder); } @@ -158,7 +159,7 @@ public void removeAllBossBars(@NotNull Player player) { */ private @NotNull BossBarHolder getOrCreateHandler(@NotNull BossBar bar) { return this.bars.computeIfAbsent(bar, bossBar -> { - BossBarHolder holder = new BossBarHolder(bossBar); + BossBarHolder holder = new BossBarHolder(minecraftServer, bossBar); bossBar.addListener(this.listener); return holder; }); diff --git a/src/main/java/net/minestom/server/command/CommandManager.java b/src/main/java/net/minestom/server/command/CommandManager.java index 0dc45c724a6..42e0a94f4aa 100644 --- a/src/main/java/net/minestom/server/command/CommandManager.java +++ b/src/main/java/net/minestom/server/command/CommandManager.java @@ -27,8 +27,8 @@ public final class CommandManager { public static final String COMMAND_PREFIX = "/"; - private final ServerSender serverSender = new ServerSender(); - private final ConsoleSender consoleSender = new ConsoleSender(); + private final ServerSender serverSender; + private final ConsoleSender consoleSender; private final CommandParser parser = CommandParser.parser(); private final CommandDispatcher dispatcher = new CommandDispatcher(this); private final Map commandMap = new HashMap<>(); @@ -39,6 +39,8 @@ public final class CommandManager { public CommandManager(MinecraftServer minecraftServer) { this.minecraftServer = minecraftServer; + this.serverSender = new ServerSender(minecraftServer); + this.consoleSender = new ConsoleSender(minecraftServer); } /** diff --git a/src/main/java/net/minestom/server/command/CommandSender.java b/src/main/java/net/minestom/server/command/CommandSender.java index 20a22bac01f..bcb5595af5e 100644 --- a/src/main/java/net/minestom/server/command/CommandSender.java +++ b/src/main/java/net/minestom/server/command/CommandSender.java @@ -3,6 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identified; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.permission.PermissionHandler; import net.minestom.server.tag.Taggable; @@ -82,4 +83,6 @@ default Player asPlayer() { default ConsoleSender asConsole() { throw new ClassCastException("CommandSender is not the ConsoleSender"); } + + MinecraftServer getMinecraftServer(); } diff --git a/src/main/java/net/minestom/server/command/ConsoleSender.java b/src/main/java/net/minestom/server/command/ConsoleSender.java index d97bc82ae1c..59d5b5145ed 100644 --- a/src/main/java/net/minestom/server/command/ConsoleSender.java +++ b/src/main/java/net/minestom/server/command/ConsoleSender.java @@ -1,13 +1,11 @@ package net.minestom.server.command; -import java.util.UUID; - import net.kyori.adventure.audience.MessageType; -import net.kyori.adventure.identity.Identified; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointers; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.logger.slf4j.ComponentLogger; +import net.minestom.server.MinecraftServer; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -29,6 +27,12 @@ public class ConsoleSender implements CommandSender { .withStatic(Identity.UUID, this.identity.uuid()) .build(); + private final MinecraftServer minecraftServer; + + public ConsoleSender(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + @Override public void sendMessage(@NotNull String message) { LOGGER.info(message); @@ -55,6 +59,11 @@ public ConsoleSender asConsole() { return this; } + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + @Override public @NotNull TagHandler tagHandler() { return tagHandler; diff --git a/src/main/java/net/minestom/server/command/GraphConverter.java b/src/main/java/net/minestom/server/command/GraphConverter.java index 46d75c402fd..7338ba2f8fd 100644 --- a/src/main/java/net/minestom/server/command/GraphConverter.java +++ b/src/main/java/net/minestom/server/command/GraphConverter.java @@ -1,10 +1,10 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.arguments.*; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.DeclareCommandsPacket; import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; @@ -17,12 +17,12 @@ private GraphConverter() { } @Contract("_, _ -> new") - public static DeclareCommandsPacket createPacket(Graph graph, @Nullable Player player) { + public static DeclareCommandsPacket createPacket(Graph graph, @NotNull CommandSender sender) { List nodes = new ArrayList<>(); List> redirects = new ArrayList<>(); Map, Integer> argToPacketId = new HashMap<>(); final AtomicInteger idSource = new AtomicInteger(0); - final int rootId = append(graph.root(), nodes, redirects, idSource, null, player, argToPacketId)[0]; + final int rootId = append(graph.root(), nodes, redirects, idSource, null, sender, argToPacketId)[0]; for (var r : redirects) { r.accept(graph, rootId); } @@ -31,9 +31,10 @@ public static DeclareCommandsPacket createPacket(Graph graph, @Nullable Player p private static int[] append(Graph.Node graphNode, List to, List> redirects, AtomicInteger id, @Nullable AtomicInteger redirect, - @Nullable Player player, Map, Integer> argToPacketId) { + @NotNull CommandSender sender, Map, Integer> argToPacketId) { final Graph.Execution execution = graphNode.execution(); - if (player != null && execution != null) { + + if (sender instanceof Player player && execution != null) { if (!execution.test(player)) return new int[0]; } @@ -43,7 +44,7 @@ private static int[] append(Graph.Node graphNode, List 0) { argToPacketId.put(children.get(i).argument(), append[0]); } @@ -78,7 +79,6 @@ private static int[] append(Graph.Node graphNode, List node.redirectedNode = root); } else { redirects.add((graph, root) -> { - var sender = player == null ? MinecraftServer.getCommandManager().getConsoleSender() : player; final List> args = CommandParser.parser().parse(sender, graph, shortcut).args(); final Argument last = args.get(args.size() - 1); if (last.allowSpace()) { @@ -119,7 +119,7 @@ private static int[] append(Graph.Node graphNode, List) arg, null, List.of()), to, - redirects, id, r, player, argToPacketId); + redirects, id, r, sender, argToPacketId); if (append.length == 1) { res[appendIndex++] = append[0]; } else { diff --git a/src/main/java/net/minestom/server/command/ServerSender.java b/src/main/java/net/minestom/server/command/ServerSender.java index ee0496e01a0..5fd671abf72 100644 --- a/src/main/java/net/minestom/server/command/ServerSender.java +++ b/src/main/java/net/minestom/server/command/ServerSender.java @@ -2,6 +2,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; @@ -23,6 +24,12 @@ public class ServerSender implements CommandSender { private final Set permissions = Collections.unmodifiableSet(new HashSet<>()); private final TagHandler tagHandler = TagHandler.newHandler(); + private final MinecraftServer minecraftServer; + + public ServerSender(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + @NotNull @Override public Set getAllPermissions() { @@ -38,4 +45,9 @@ public Set getAllPermissions() { public @NotNull Identity identity() { return Identity.nil(); } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java index 637dca8ad32..b6460a4eade 100644 --- a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java +++ b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java @@ -2,6 +2,7 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandParser; import net.minestom.server.command.CommandSender; @@ -25,8 +26,8 @@ public CommandDispatcher(CommandManager manager) { this.manager = manager; } - public CommandDispatcher() { - this(new CommandManager()); + public CommandDispatcher(MinecraftServer minecraftServer) { + this(new CommandManager(minecraftServer)); } /** diff --git a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java index 5ffe90d3573..49ab401e56d 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java @@ -1,6 +1,5 @@ package net.minestom.server.command.builder.arguments; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.command.builder.CommandResult; @@ -26,7 +25,7 @@ public CommandResult parse(@NotNull CommandSender sender, @NotNull String input) final String commandString = !shortcut.isEmpty() ? shortcut + StringUtils.SPACE + input : input; - CommandDispatcher dispatcher = MinecraftServer.getCommandManager().getDispatcher(); + CommandDispatcher dispatcher = sender.getMinecraftServer().process().getCommandManager().getDispatcher(); CommandResult result = dispatcher.parse(sender, commandString); if (onlyCorrect && result.getType() != CommandResult.Type.SUCCESS) diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index c92cc9e6ba5..8d8a91a47c2 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -91,7 +91,7 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev private static final Map ENTITY_BY_UUID = new ConcurrentHashMap<>(); private static final AtomicInteger LAST_ENTITY_ID = new AtomicInteger(); - private final CachedPacket destroyPacketCache = new CachedPacket(() -> new DestroyEntitiesPacket(getEntityId())); + private final CachedPacket destroyPacketCache; public final MinecraftServer minecraftServer; protected Instance instance; @@ -206,6 +206,7 @@ public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType enti // Local nodes require a server process this.eventNode = null; } + destroyPacketCache = new CachedPacket(minecraftServer, () -> new DestroyEntitiesPacket(getEntityId())); } public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { @@ -1332,21 +1333,21 @@ public void refreshPosition(@NotNull final Pos newPosition, boolean ignoreView) final Chunk chunk = getChunk(); if (distanceX > 8 || distanceY > 8 || distanceZ > 8) { - PacketUtils.prepareViewablePacket(chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); + PacketUtils.prepareViewablePacket(minecraftServer, chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); } else if (positionChange && viewChange) { - PacketUtils.prepareViewablePacket(chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(minecraftServer, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); // Fix head rotation - PacketUtils.prepareViewablePacket(chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(minecraftServer, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); } else if (positionChange) { // This is a confusing fix for a confusing issue. If rotation is only sent when the entity actually changes, then spawning an entity // on the ground causes the entity not to update its rotation correctly. It works fine if the entity is spawned in the air. Very weird. - PacketUtils.prepareViewablePacket(chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(minecraftServer, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, onGround), this); } else if (viewChange) { - PacketUtils.prepareViewablePacket(chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); - PacketUtils.prepareViewablePacket(chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(minecraftServer, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(minecraftServer,chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); } this.lastSyncedPosition = position; @@ -1631,7 +1632,7 @@ private void scheduleRemove(TaskSchedule schedule) { protected void synchronizePosition(boolean includeSelf) { final Pos posCache = this.position; final ServerPacket packet = new EntityTeleportPacket(getEntityId(), posCache, isOnGround()); - PacketUtils.prepareViewablePacket(currentChunk, packet, this); + PacketUtils.prepareViewablePacket(minecraftServer, currentChunk, packet, this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); this.lastSyncedPosition = posCache; } @@ -1830,6 +1831,11 @@ public boolean hasCollision() { return hasCollision; } + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + public enum Pose { STANDING, FALL_FLYING, diff --git a/src/main/java/net/minestom/server/entity/EntityView.java b/src/main/java/net/minestom/server/entity/EntityView.java index f9cc581d494..79b1afc0d14 100644 --- a/src/main/java/net/minestom/server/entity/EntityView.java +++ b/src/main/java/net/minestom/server/entity/EntityView.java @@ -4,7 +4,6 @@ import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; -import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.instance.EntityTracker; import net.minestom.server.instance.Instance; @@ -17,7 +16,6 @@ import java.util.function.Predicate; final class EntityView { - private static final int RANGE = MinecraftServer.getEntityViewDistance(); private final Entity entity; private final Set manualViewers = new HashSet<>(); @@ -230,7 +228,7 @@ private Collection references() { final Point point = trackedLocation.point(); Int2ObjectOpenHashMap entityMap = new Int2ObjectOpenHashMap<>(lastSize); - instance.getEntityTracker().nearbyEntitiesByChunkRange(point, RANGE, target, + instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.minecraftServer.getEntityViewDistance(), target, (entity) -> entityMap.putIfAbsent(entity.getEntityId(), entity)); this.lastSize = entityMap.size(); return entityMap.values(); diff --git a/src/main/java/net/minestom/server/entity/ExperienceOrb.java b/src/main/java/net/minestom/server/entity/ExperienceOrb.java index 87dec2a436a..5c663e665cb 100644 --- a/src/main/java/net/minestom/server/entity/ExperienceOrb.java +++ b/src/main/java/net/minestom/server/entity/ExperienceOrb.java @@ -1,5 +1,6 @@ package net.minestom.server.entity; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import java.util.Comparator; @@ -10,8 +11,8 @@ public class ExperienceOrb extends Entity { private Player target; private long lastTargetUpdateTick; - public ExperienceOrb(short experienceCount) { - super(EntityType.EXPERIENCE_ORB); + public ExperienceOrb(MinecraftServer minecraftServer, short experienceCount) { + super(minecraftServer, EntityType.EXPERIENCE_ORB); setBoundingBox(0.5f, 0.5f, 0.5f); //todo vanilla sets random velocity here? this.experienceCount = experienceCount; diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 19add4d2648..f67dba316d1 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -23,7 +23,6 @@ import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; -import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.attribute.Attribute; import net.minestom.server.collision.BoundingBox; import net.minestom.server.command.CommandSender; @@ -320,7 +319,7 @@ public CompletableFuture UNSAFE_init() { minecraftServer.process().getGlobalEventHandler().call(skinInitEvent); this.skin = skinInitEvent.getSkin(); // FIXME: when using Geyser, this line remove the skin of the client - PacketUtils.broadcastPlayPacket(getAddPlayerToList()); + PacketUtils.broadcastPlayPacket(minecraftServer, getAddPlayerToList()); var connectionManager = minecraftServer.process().getConnectionManager(); for (var player : connectionManager.getOnlinePlayers()) { @@ -496,7 +495,7 @@ public void kill() { // #buildDeathMessage can return null, check here if (chatMessage != null) { - Audiences.players().sendMessage(chatMessage); + minecraftServer.process().getAudiences().players().sendMessage(chatMessage); } // Set death location @@ -598,7 +597,7 @@ public void remove(boolean permanent) { // Clear all viewable chunks ChunkUtils.forChunksInRange(chunkX, chunkZ, minecraftServer.getChunkViewDistance(), chunkRemover); // Remove from the tab-list - PacketUtils.broadcastPlayPacket(getRemovePlayerToList()); + PacketUtils.broadcastPlayPacket(minecraftServer, getRemovePlayerToList()); // Prevent the player from being stuck in loading screen, or just unable to interact with the server // This should be considered as a bug, since the player will ultimately time out anyway. @@ -1142,7 +1141,7 @@ public double getEyeHeight() { */ public void setDisplayName(@Nullable Component displayName) { this.displayName = displayName; - PacketUtils.broadcastPlayPacket(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); + PacketUtils.broadcastPlayPacket(minecraftServer, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); } /** @@ -1184,11 +1183,11 @@ public synchronized void setSkin(@Nullable PlayerSkin skin) { { // Remove player - PacketUtils.broadcastPlayPacket(removePlayerPacket); + PacketUtils.broadcastPlayPacket(minecraftServer, removePlayerPacket); sendPacketToViewers(destroyEntitiesPacket); // Show player again - PacketUtils.broadcastPlayPacket(addPlayerPacket); + PacketUtils.broadcastPlayPacket(minecraftServer, addPlayerPacket); getViewers().forEach(player -> showPlayer(player.getPlayerConnection())); } @@ -1566,7 +1565,7 @@ public boolean setGameMode(@NotNull GameMode gameMode) { // Condition to prevent sending the packets before spawning the player if (isActive()) { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.CHANGE_GAMEMODE, gameMode.id())); - PacketUtils.broadcastPlayPacket(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); + PacketUtils.broadcastPlayPacket(minecraftServer, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); } // The client updates their abilities based on the GameMode as follows @@ -2067,7 +2066,7 @@ public void interpretPacketQueue() { public void refreshLatency(int latency) { this.latency = latency; if (getPlayerConnection().getConnectionState() == ConnectionState.PLAY) { - PacketUtils.broadcastPlayPacket(new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); + PacketUtils.broadcastPlayPacket(minecraftServer, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); } } @@ -2341,6 +2340,11 @@ public Player asPlayer() { return this; } + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + protected void sendChunkUpdates(Chunk newChunk) { if (chunkUpdateLimitChecker.addToHistory(newChunk)) { final int newX = newChunk.getChunkX(); diff --git a/src/main/java/net/minestom/server/entity/PlayerProjectile.java b/src/main/java/net/minestom/server/entity/PlayerProjectile.java index 303f9247056..85568a872b7 100644 --- a/src/main/java/net/minestom/server/entity/PlayerProjectile.java +++ b/src/main/java/net/minestom/server/entity/PlayerProjectile.java @@ -23,8 +23,8 @@ public class PlayerProjectile extends LivingEntity { private final Entity shooter; private long cooldown = 0; - public PlayerProjectile(Entity shooter, EntityType type) { - super(type); + public PlayerProjectile(MinecraftServer minecraftServer, Entity shooter, EntityType type) { + super(minecraftServer, type); this.shooter = shooter; this.hasCollision = false; setup(); @@ -50,7 +50,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Check if we're inside of a block if (insideBlock != null) { var e = new ProjectileCollideWithBlockEvent(this, Pos.fromPoint(spawnPosition), instance.getBlock(spawnPosition)); - MinecraftServer.getGlobalEventHandler().call(e); + minecraftServer.process().getGlobalEventHandler().call(e); } return res; @@ -148,7 +148,7 @@ public void tick(long time) { if (collided != null && collided.collisionShapes()[0] != shooter) { if (collided.collisionShapes()[0] instanceof Entity entity) { var e = new ProjectileCollideWithEntityEvent(this, collided.newPosition(), entity); - MinecraftServer.getGlobalEventHandler().call(e); + minecraftServer.process().getGlobalEventHandler().call(e); return; } } @@ -172,7 +172,7 @@ public void tick(long time) { if (hitBlock == null) return; var e = new ProjectileCollideWithBlockEvent(this, Pos.fromPoint(hitPoint), hitBlock); - MinecraftServer.getGlobalEventHandler().call(e); + minecraftServer.process().getGlobalEventHandler().call(e); } } } diff --git a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java index 5dff8b4efe8..8247dab8684 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java @@ -178,7 +178,7 @@ public void tick(long time) { Function projectileGenerator = this.projectileGenerator; if (projectileGenerator == null) { - projectileGenerator = shooter -> new EntityProjectile(shooter, EntityType.ARROW); + projectileGenerator = shooter -> new EntityProjectile(shooter.minecraftServer, shooter, EntityType.ARROW); } EntityProjectile projectile = projectileGenerator.apply(this.entityCreature); projectile.setInstance(this.entityCreature.getInstance(), this.entityCreature.getPosition()); diff --git a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java index 07187d26f4b..7aeefeb1d0e 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java @@ -84,7 +84,7 @@ public void setProjectileGenerator(Function projectile private ProjectileGenerator getProjectileGeneratorOrDefault() { if (projectileGenerator == null) { - setProjectileGenerator(shooter -> new EntityProjectile(shooter, EntityType.ARROW)); + setProjectileGenerator(shooter -> new EntityProjectile(shooter.minecraftServer, shooter, EntityType.ARROW)); } return projectileGenerator; } diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index 9ce34f07583..2298eb6c643 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -53,9 +53,9 @@ public class FakePlayer extends Player implements NavigableEntity { protected FakePlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - super(minecraftServer, uuid, username, new FakePlayerConnection()); - this.connectionManager = serverProcess.getConnectionManager(); - this.packetListenerManager = serverProcess.getPacketListenerManager(); + super(minecraftServer, uuid, username, new FakePlayerConnection(minecraftServer)); + this.connectionManager = minecraftServer.process().getConnectionManager(); + this.packetListenerManager = minecraftServer.process().getPacketListenerManager(); this.option = option; @@ -68,10 +68,10 @@ protected FakePlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uui if (event.getPlayer().equals(this)) if (event.isFirstSpawn()) { spawnCallback.accept(this); - serverProcess.getGlobalEventHandler().removeListener(spawnListener); + minecraftServer.process().getGlobalEventHandler().removeListener(spawnListener); } }).build(); - serverProcess.getGlobalEventHandler().addListener(spawnListener); + minecraftServer.process().getGlobalEventHandler().addListener(spawnListener); } playerConnection.setConnectionState(ConnectionState.LOGIN); @@ -166,7 +166,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - serverProcess.getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.SERVER_TICK).schedule(); + minecraftServer.process().getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.SERVER_TICK).schedule(); } } } diff --git a/src/main/java/net/minestom/server/entity/hologram/Hologram.java b/src/main/java/net/minestom/server/entity/hologram/Hologram.java index c0467499b9f..3d0bf168457 100644 --- a/src/main/java/net/minestom/server/entity/hologram/Hologram.java +++ b/src/main/java/net/minestom/server/entity/hologram/Hologram.java @@ -1,6 +1,7 @@ package net.minestom.server.entity.hologram; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; @@ -61,7 +62,7 @@ public Hologram(Instance instance, Pos spawnPosition, Component text, boolean au * @param autoViewable {@code true}if the hologram should be visible automatically, otherwise {@code false}. */ public Hologram(Instance instance, Pos spawnPosition, Component text, boolean autoViewable, boolean marker) { - this.entity = new Entity(EntityType.ARMOR_STAND); + this.entity = new Entity(instance.minecraftServer, EntityType.ARMOR_STAND); ArmorStandMeta armorStandMeta = (ArmorStandMeta) entity.getEntityMeta(); @@ -185,4 +186,9 @@ public Set getViewers() { private void checkRemoved() { Check.stateCondition(isRemoved(), "You cannot interact with a removed Hologram"); } + + @Override + public MinecraftServer getMinecraftServer() { + return entity.getMinecraftServer(); + } } diff --git a/src/main/java/net/minestom/server/event/EventNode.java b/src/main/java/net/minestom/server/event/EventNode.java index c3a0d5e0728..feffd05be0d 100644 --- a/src/main/java/net/minestom/server/event/EventNode.java +++ b/src/main/java/net/minestom/server/event/EventNode.java @@ -1,5 +1,6 @@ package net.minestom.server.event; +import net.minestom.server.MinecraftServer; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.tag.Tag; import net.minestom.server.tag.TagReadable; @@ -31,9 +32,10 @@ public sealed interface EventNode permits EventNodeImpl { * @param name The name of the node * @return An event node with no filtering */ - @Contract(value = "_ -> new", pure = true) - static @NotNull EventNode all(@NotNull String name) { - return type(name, EventFilter.ALL); + @Contract(value = "_, _ -> new", pure = true) + static @NotNull EventNode all(@NotNull MinecraftServer minecraftServer, + @NotNull String name) { + return type(minecraftServer, name, EventFilter.ALL); } /** @@ -50,10 +52,11 @@ public sealed interface EventNode permits EventNodeImpl { * @param The resulting event type of the node * @return A node with just an event type filter */ - @Contract(value = "_, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull String name, + @Contract(value = "_, _, _ -> new", pure = true) + static @NotNull EventNode type(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter) { - return create(name, filter, null); + return create(minecraftServer, name, filter, null); } /** @@ -75,11 +78,12 @@ public sealed interface EventNode permits EventNodeImpl { * @param The resulting event type of the node * @return A node with an event type filter as well as a condition on the event. */ - @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode event(@NotNull String name, + @Contract(value = "_, _, _, _ -> new", pure = true) + static @NotNull EventNode event(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(name, filter, (e, h) -> predicate.test(e)); + return create(minecraftServer, name, filter, (e, h) -> predicate.test(e)); } /** @@ -103,11 +107,12 @@ public sealed interface EventNode permits EventNodeImpl { * @param The handler type of the event filter * @return A node with an event type filter as well as a condition on the event. */ - @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull String name, + @Contract(value = "_, _, _, _ -> new", pure = true) + static @NotNull EventNode type(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @NotNull BiPredicate predicate) { - return create(name, filter, predicate); + return create(minecraftServer, name, filter, predicate); } /** @@ -128,11 +133,12 @@ public sealed interface EventNode permits EventNodeImpl { * @param The handler type of the event filter * @return A node with an event type filter as well as a condition on the event. */ - @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode value(@NotNull String name, + @Contract(value = "_, _, _, _ -> new", pure = true) + static @NotNull EventNode value(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(name, filter, (e, h) -> predicate.test(h)); + return create(minecraftServer, name, filter, (e, h) -> predicate.test(h)); } /** @@ -147,11 +153,12 @@ public sealed interface EventNode permits EventNodeImpl { * @param The resulting event type of the node * @return A node with an event type filter as well as a handler with the provided tag */ - @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull String name, + @Contract(value = "_, _, _, _ -> new", pure = true) + static @NotNull EventNode tag(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag) { - return create(name, filter, (e, h) -> h.hasTag(tag)); + return create(minecraftServer, name, filter, (e, h) -> h.hasTag(tag)); } /** @@ -165,19 +172,21 @@ public sealed interface EventNode permits EventNodeImpl { * @param The resulting event type of the node * @return A node with an event type filter as well as a handler with the provided tag */ - @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull String name, + @Contract(value = "_, _, _, _, _ -> new", pure = true) + static @NotNull EventNode tag(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag, @NotNull Predicate<@Nullable V> consumer) { - return create(name, filter, (e, h) -> consumer.test(h.getTag(tag))); + return create(minecraftServer, name, filter, (e, h) -> consumer.test(h.getTag(tag))); } - private static EventNode create(@NotNull String name, + private static EventNode create(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { //noinspection unchecked - return new EventNodeImpl<>(name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); + return new EventNodeImpl<>(minecraftServer, name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); } /** diff --git a/src/main/java/net/minestom/server/event/EventNodeImpl.java b/src/main/java/net/minestom/server/event/EventNodeImpl.java index c535c452c92..2a07e96cbb7 100644 --- a/src/main/java/net/minestom/server/event/EventNodeImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeImpl.java @@ -30,6 +30,7 @@ non-sealed class EventNodeImpl implements EventNode { final Map> registeredMappedNode = Caffeine.newBuilder() .weakKeys().weakValues().>build().asMap(); + private final MinecraftServer minecraftServer; final String name; final EventFilter filter; final BiPredicate predicate; @@ -37,9 +38,11 @@ non-sealed class EventNodeImpl implements EventNode { volatile int priority; volatile EventNodeImpl parent; - EventNodeImpl(@NotNull String name, + EventNodeImpl(@NotNull MinecraftServer minecraftServer, + @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { + this.minecraftServer = minecraftServer; this.name = name; this.filter = filter; this.predicate = predicate; @@ -156,7 +159,7 @@ public void removeChildren(@NotNull String name, @NotNull Class eve public @NotNull EventNode map(@NotNull H value, @NotNull EventFilter filter) { EventNodeImpl node; synchronized (GLOBAL_CHILD_LOCK) { - node = new EventNodeLazyImpl<>(this, value, filter); + node = new EventNodeLazyImpl<>(minecraftServer,this, value, filter); Check.stateCondition(node.parent != null, "Node already has a parent"); Check.stateCondition(Objects.equals(parent, node), "Cannot map to self"); EventNodeImpl previous = this.mappedNodeCache.putIfAbsent(value, (EventNodeImpl) node); @@ -326,7 +329,7 @@ public void call(@NotNull E event) { try { listener.accept(event); } catch (Throwable e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } } diff --git a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java index 6e0c613a711..b47d812c2b1 100644 --- a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java @@ -1,5 +1,6 @@ package net.minestom.server.event; +import net.minestom.server.MinecraftServer; import org.jetbrains.annotations.NotNull; import java.lang.invoke.MethodHandles; @@ -23,9 +24,9 @@ final class EventNodeLazyImpl extends EventNodeImpl { @SuppressWarnings("unused") private boolean mapped; - EventNodeLazyImpl(@NotNull EventNodeImpl holder, + EventNodeLazyImpl(@NotNull MinecraftServer minecraftServer, @NotNull EventNodeImpl holder, @NotNull Object owner, @NotNull EventFilter filter) { - super(owner.toString(), filter, null); + super(minecraftServer, owner.toString(), filter, null); this.holder = holder; this.owner = new WeakReference<>(owner); } diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandler.java b/src/main/java/net/minestom/server/event/GlobalEventHandler.java index 1cc2df9a99d..db85dd75247 100644 --- a/src/main/java/net/minestom/server/event/GlobalEventHandler.java +++ b/src/main/java/net/minestom/server/event/GlobalEventHandler.java @@ -1,10 +1,12 @@ package net.minestom.server.event; +import net.minestom.server.MinecraftServer; + /** * Object containing all the global event listeners. */ public final class GlobalEventHandler extends EventNodeImpl { - public GlobalEventHandler() { - super("global", EventFilter.ALL, null); + public GlobalEventHandler(MinecraftServer minecraftServer) { + super(minecraftServer,"global", EventFilter.ALL, null); } } diff --git a/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java b/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java index be299151fcd..09425ea1943 100644 --- a/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java +++ b/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java @@ -1,5 +1,6 @@ package net.minestom.server.event.server; +import net.minestom.server.MinecraftServer; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.ping.ResponseData; @@ -25,8 +26,8 @@ public class ServerListPingEvent implements CancellableEvent { * * @param type the ping type to respond with */ - public ServerListPingEvent(@NotNull ServerListPingType type) { - this(null, type); + public ServerListPingEvent(@NotNull MinecraftServer minecraftServer, @NotNull ServerListPingType type) { + this(minecraftServer, null, type); } /** @@ -35,8 +36,8 @@ public ServerListPingEvent(@NotNull ServerListPingType type) { * @param connection the player connection, if the ping type is modern * @param type the ping type to respond with */ - public ServerListPingEvent(@Nullable PlayerConnection connection, @NotNull ServerListPingType type) { - this.responseData = new ResponseData(); + public ServerListPingEvent(@NotNull MinecraftServer minecraftServer, @Nullable PlayerConnection connection, @NotNull ServerListPingType type) { + this.responseData = new ResponseData(minecraftServer); this.connection = connection; this.type = type; } diff --git a/src/main/java/net/minestom/server/exception/ExceptionManager.java b/src/main/java/net/minestom/server/exception/ExceptionManager.java index 1ee7870e905..338f0dfb847 100644 --- a/src/main/java/net/minestom/server/exception/ExceptionManager.java +++ b/src/main/java/net/minestom/server/exception/ExceptionManager.java @@ -9,6 +9,11 @@ public final class ExceptionManager { private ExceptionHandler exceptionHandler; + private final MinecraftServer minecraftServer; + + public ExceptionManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } /** * Handles an exception, if no {@link ExceptionHandler} is set, it just prints the stack trace. @@ -19,7 +24,7 @@ public void handleException(Throwable e) { if (e instanceof OutOfMemoryError) { // OOM should be handled manually e.printStackTrace(); - MinecraftServer.stopCleanly(); + minecraftServer.stopCleanly(); return; } this.getExceptionHandler().handleException(e); diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index 6ace166c9f1..6990fc3a4a0 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -8,28 +8,39 @@ import java.security.KeyPair; public final class MojangAuth { - public static final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); - private static volatile boolean enabled = false; - private static volatile KeyPair keyPair; + public final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); + private volatile boolean enabled = false; + private volatile KeyPair keyPair; + private final MinecraftServer minecraftServer; + private final MojangCrypt mojangCrypt; + + public MojangAuth(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + this.mojangCrypt = new MojangCrypt(minecraftServer); + } /** * Enables mojang authentication on the server. *

* Be aware that enabling a proxy will make Mojang authentication ignored. */ - public static void init() { + public void init() { Check.stateCondition(enabled, "Mojang auth is already enabled!"); - Check.stateCondition(MinecraftServer.process().isAlive(), "The server has already been started!"); - MojangAuth.enabled = true; + Check.stateCondition(minecraftServer.process().isAlive(), "The server has already been started!"); + enabled = true; // Generate necessary fields... - MojangAuth.keyPair = MojangCrypt.generateKeyPair(); + keyPair = mojangCrypt.generateKeyPair(); } - public static boolean isEnabled() { + public boolean isEnabled() { return enabled; } - public static @Nullable KeyPair getKeyPair() { + public @Nullable KeyPair getKeyPair() { return keyPair; } + + public MojangCrypt getMojangCrypt() { + return mojangCrypt; + } } diff --git a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java index b2d42c557b5..c9902562a0b 100644 --- a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java +++ b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java @@ -106,7 +106,7 @@ public boolean isOpen() { private void ping() { if (!minecraftServer.process().getServer().isOpen()) return; if (packet == null || eventCooldown.isReady(System.currentTimeMillis())) { - final ServerListPingEvent event = new ServerListPingEvent(OPEN_TO_LAN); + final ServerListPingEvent event = new ServerListPingEvent(minecraftServer, OPEN_TO_LAN); minecraftServer.process().getGlobalEventHandler().call(event); final byte[] data = OPEN_TO_LAN.getPingResponse(event.getResponseData()).getBytes(StandardCharsets.UTF_8); diff --git a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java index 995524f4eeb..e9252ba2c0b 100644 --- a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java +++ b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java @@ -12,30 +12,35 @@ import java.security.*; public final class MojangCrypt { - private static final Logger LOGGER = LoggerFactory.getLogger(MojangCrypt.class); + private final Logger LOGGER = LoggerFactory.getLogger(MojangCrypt.class); + private final MinecraftServer minecraftServer; - public static @Nullable KeyPair generateKeyPair() { + public MojangCrypt(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + + public @Nullable KeyPair generateKeyPair() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); return keyGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); LOGGER.error("Key pair generation failed!"); return null; } } - public static byte @Nullable [] digestData(String data, PublicKey publicKey, SecretKey secretKey) { + public byte @Nullable [] digestData(String data, PublicKey publicKey, SecretKey secretKey) { try { return digestData("SHA-1", data.getBytes("ISO_8859_1"), secretKey.getEncoded(), publicKey.getEncoded()); } catch (UnsupportedEncodingException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); return null; } } - private static byte @Nullable [] digestData(String algorithm, byte[]... data) { + private byte @Nullable [] digestData(String algorithm, byte[]... data) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); for (byte[] bytes : data) { @@ -43,42 +48,42 @@ public final class MojangCrypt { } return digest.digest(); } catch (NoSuchAlgorithmException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); return null; } } - public static SecretKey decryptByteToSecretKey(PrivateKey privateKey, byte[] bytes) { + public SecretKey decryptByteToSecretKey(PrivateKey privateKey, byte[] bytes) { return new SecretKeySpec(decryptUsingKey(privateKey, bytes), "AES"); } - public static byte[] decryptUsingKey(Key key, byte[] bytes) { + public byte[] decryptUsingKey(Key key, byte[] bytes) { return cipherData(2, key, bytes); } - private static byte[] cipherData(int mode, Key key, byte[] data) { + private byte[] cipherData(int mode, Key key, byte[] data) { try { return setupCipher(mode, key.getAlgorithm(), key).doFinal(data); } catch (IllegalBlockSizeException | BadPaddingException var4) { - MinecraftServer.getExceptionManager().handleException(var4); + minecraftServer.process().getExceptionManager().handleException(var4); } LOGGER.error("Cipher data failed!"); return null; } - private static Cipher setupCipher(int mode, String transformation, Key key) { + private Cipher setupCipher(int mode, String transformation, Key key) { try { Cipher cipher4 = Cipher.getInstance(transformation); cipher4.init(mode, key); return cipher4; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException var4) { - MinecraftServer.getExceptionManager().handleException(var4); + minecraftServer.process().getExceptionManager().handleException(var4); } LOGGER.error("Cipher creation failed!"); return null; } - public static Cipher getCipher(int mode, Key key) { + public Cipher getCipher(int mode, Key key) { try { Cipher cipher3 = Cipher.getInstance("AES/CFB8/NoPadding"); cipher3.init(mode, key, new IvParameterSpec(key.getEncoded())); diff --git a/src/main/java/net/minestom/server/extras/query/Query.java b/src/main/java/net/minestom/server/extras/query/Query.java index ab562e9f15a..cd4d421463d 100644 --- a/src/main/java/net/minestom/server/extras/query/Query.java +++ b/src/main/java/net/minestom/server/extras/query/Query.java @@ -186,7 +186,7 @@ private void run() { int remaining = data.remaining(); if (remaining == 0) { // basic - BasicQueryEvent event = new BasicQueryEvent(sender, sessionID); + BasicQueryEvent event = new BasicQueryEvent(minecraftServer, sender, sessionID); minecraftServer.process().getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } else if (remaining == 5) { // full diff --git a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java index b3f4ba09d41..c0fd8cb172d 100644 --- a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java @@ -1,5 +1,6 @@ package net.minestom.server.extras.query.event; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.response.BasicQueryResponse; import org.jetbrains.annotations.NotNull; @@ -16,7 +17,7 @@ public class BasicQueryEvent extends QueryEvent { * @param sessionID the session ID * @param sender the sender */ - public BasicQueryEvent(@NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new BasicQueryResponse()); + public BasicQueryEvent(MinecraftServer minecraftServer, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new BasicQueryResponse(minecraftServer)); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java index f18780397d7..1046da512f8 100644 --- a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java @@ -12,16 +12,19 @@ * A basic query response containing a fixed set of responses. */ public class BasicQueryResponse implements Writeable { + @NotNull + private final MinecraftServer minecraftServer; private String motd, gametype, map, numPlayers, maxPlayers; /** * Creates a new basic query response with pre-filled default values. */ - public BasicQueryResponse() { + public BasicQueryResponse(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; this.motd = "A Minestom Server"; this.gametype = "SMP"; this.map = "world"; - this.numPlayers = String.valueOf(MinecraftServer.getConnectionManager().getOnlinePlayerCount()); + this.numPlayers = String.valueOf(minecraftServer.process().getConnectionManager().getOnlinePlayerCount()); this.maxPlayers = String.valueOf(Integer.parseInt(this.numPlayers) + 1); } @@ -142,7 +145,7 @@ public void write(@NotNull BinaryWriter writer) { writer.writeNullTerminatedString(this.map, Query.CHARSET); writer.writeNullTerminatedString(this.numPlayers, Query.CHARSET); writer.writeNullTerminatedString(this.maxPlayers, Query.CHARSET); - writer.writeShort((short) MinecraftServer.getServer().getPort()); // TODO little endian? - writer.writeNullTerminatedString(Objects.requireNonNullElse(MinecraftServer.getServer().getAddress(), ""), Query.CHARSET); + writer.writeShort((short) minecraftServer.process().getServer().getPort()); // TODO little endian? + writer.writeNullTerminatedString(Objects.requireNonNullElse(minecraftServer.process().getServer().getAddress(), ""), Query.CHARSET); } } diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java index 41cf928dc0d..a718691b16c 100644 --- a/src/main/java/net/minestom/server/instance/DynamicChunk.java +++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java @@ -6,7 +6,6 @@ import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; -import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.PFBlock; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockHandler; @@ -24,7 +23,6 @@ import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.chunk.ChunkUtils; -import net.minestom.server.utils.validate.Check; import net.minestom.server.world.biomes.Biome; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -52,13 +50,16 @@ public class DynamicChunk extends Chunk { protected final Int2ObjectOpenHashMap tickableMap = new Int2ObjectOpenHashMap<>(0); private long lastChange; - final CachedPacket chunkCache = new CachedPacket(this::createChunkPacket); + final CachedPacket chunkCache; + public final MinecraftServer minecraftServer; public DynamicChunk(@NotNull Instance instance, int chunkX, int chunkZ) { super(instance, chunkX, chunkZ, true); + this.minecraftServer = instance.minecraftServer; var sectionsTemp = new Section[maxSection - minSection]; - Arrays.setAll(sectionsTemp, value -> new Section()); + Arrays.setAll(sectionsTemp, value -> new Section(minecraftServer)); this.sections = List.of(sectionsTemp); + chunkCache = new CachedPacket(minecraftServer, this::createChunkPacket); } @Override @@ -182,7 +183,7 @@ public void tick(long time) { final Section section = getSectionAt(y); final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return MinecraftServer.getBiomeManager().getById(id); + return minecraftServer.process().getBiomeManager().getById(id); } @Override @@ -315,7 +316,7 @@ protected LightData createLightData(boolean sendLater) { clonedSections[i] = sections.get(i).clone(); var entities = instance.getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES); final int[] entityIds = ArrayUtils.mapToIntArray(entities, Entity::getEntityId); - return new SnapshotImpl.Chunk(minSection, chunkX, chunkZ, + return new SnapshotImpl.Chunk(minecraftServer, minSection, chunkX, chunkZ, clonedSections, entries.clone(), entityIds, updater.reference(instance), tagHandler().readableCopy()); } @@ -366,4 +367,9 @@ private static long[] encodeBlocks(int[] blocks, int bitsPerEntry) { return data; } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index d2b5df819e7..98492b80b1c 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.MinecraftServer; -import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -286,6 +285,11 @@ private void collectPlayers(EntityTracker tracker, Int2ObjectOpenHashMap EntityTracker.Target.PLAYERS, (player) -> map.putIfAbsent(player.getEntityId(), player)); } + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + final class SetImpl extends AbstractSet { @Override public @NotNull Iterator iterator() { diff --git a/src/main/java/net/minestom/server/instance/Explosion.java b/src/main/java/net/minestom/server/instance/Explosion.java index 186be7a1da3..4c179791c19 100644 --- a/src/main/java/net/minestom/server/instance/Explosion.java +++ b/src/main/java/net/minestom/server/instance/Explosion.java @@ -73,7 +73,7 @@ public void apply(@NotNull Instance instance) { ExplosionPacket packet = new ExplosionPacket(centerX, centerY, centerZ, strength, records, 0, 0, 0); postExplosion(instance, blocks, packet); - PacketUtils.sendGroupedPacket(instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getMinecraftServer(), instance.getPlayers(), packet); postSend(instance, blocks); } diff --git a/src/main/java/net/minestom/server/instance/GeneratorImpl.java b/src/main/java/net/minestom/server/instance/GeneratorImpl.java index e4169b8d990..7a6b495a74d 100644 --- a/src/main/java/net/minestom/server/instance/GeneratorImpl.java +++ b/src/main/java/net/minestom/server/instance/GeneratorImpl.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -22,17 +23,17 @@ final class GeneratorImpl { private static final Vec SECTION_SIZE = new Vec(16); - static GenerationUnit section(Section section, int sectionX, int sectionY, int sectionZ, + static GenerationUnit section(MinecraftServer minecraftServer, Section section, int sectionX, int sectionY, int sectionZ, boolean fork) { final Vec start = SECTION_SIZE.mul(sectionX, sectionY, sectionZ); final Vec end = start.add(SECTION_SIZE); final UnitModifier modifier = new SectionModifierImpl(SECTION_SIZE, start, end, section.blockPalette(), section.biomePalette(), new Int2ObjectOpenHashMap<>(0), fork); - return unit(modifier, start, end, null); + return unit(minecraftServer, modifier, start, end, null); } - static GenerationUnit section(Section section, int sectionX, int sectionY, int sectionZ) { - return section(section, sectionX, sectionY, sectionZ, false); + static GenerationUnit section(MinecraftServer minecraftServer, Section section, int sectionX, int sectionY, int sectionZ) { + return section(minecraftServer, section, sectionX, sectionY, sectionZ, false); } static UnitImpl chunk(Chunk chunk, int minSection, int maxSection, @@ -40,7 +41,7 @@ static UnitImpl chunk(Chunk chunk, int minSection, int maxSection, final int minY = minSection * 16; AtomicInteger sectionCounterY = new AtomicInteger(minSection); List sections = chunkSections.stream() - .map(section -> section(section, chunkX, sectionCounterY.getAndIncrement(), chunkZ)) + .map(section -> section(chunk.instance.minecraftServer, section, chunkX, sectionCounterY.getAndIncrement(), chunkZ)) .toList(); final Vec size = new Vec(16, (maxSection - minSection) * 16, 16); @@ -48,7 +49,7 @@ static UnitImpl chunk(Chunk chunk, int minSection, int maxSection, final Vec end = new Vec(chunkX * 16 + 16, size.y() + minY, chunkZ * 16 + 16); final UnitModifier modifier = new AreaModifierImpl(chunk, size, start, end, 1, sections.size(), 1, sections); - return unit(modifier, start, end, sections); + return unit(chunk.instance.minecraftServer, modifier, start, end, sections); } static UnitImpl chunk(int minSection, int maxSection, @@ -60,7 +61,7 @@ static UnitImpl chunk(Chunk chunk) { return chunk(chunk, chunk.minSection, chunk.maxSection, chunk.getSections(), chunk.getChunkX(), chunk.getChunkZ()); } - static UnitImpl unit(UnitModifier modifier, Point start, Point end, + static UnitImpl unit(MinecraftServer minecraftServer, UnitModifier modifier, Point start, Point end, List divided) { if (start.x() > end.x() || start.y() > end.y() || start.z() > end.z()) { throw new IllegalArgumentException("absoluteStart must be before absoluteEnd"); @@ -72,7 +73,7 @@ static UnitImpl unit(UnitModifier modifier, Point start, Point end, throw new IllegalArgumentException("absoluteEnd must be a multiple of 16"); } final Point size = end.sub(start); - return new UnitImpl(modifier, size, start, end, divided, new CopyOnWriteArrayList<>()); + return new UnitImpl(minecraftServer, modifier, size, start, end, divided, new CopyOnWriteArrayList<>()); } static final class DynamicFork implements Block.Setter { @@ -80,6 +81,12 @@ static final class DynamicFork implements Block.Setter { int width, height, depth; List sections; + private final MinecraftServer minecraftServer; + + DynamicFork(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } + @Override public void setBlock(int x, int y, int z, @NotNull Block block) { resize(x, y, z); @@ -100,7 +107,7 @@ private void resize(int x, int y, int z) { this.width = 1; this.height = 1; this.depth = 1; - this.sections = List.of(section(new Section(), sectionX, sectionY, sectionZ, true)); + this.sections = List.of(section(minecraftServer, new Section(minecraftServer), sectionX, sectionY, sectionZ, true)); } else if (x < minSection.x() || y < minSection.y() || z < minSection.z() || x >= minSection.x() + width * 16 || y >= minSection.y() + height * 16 || z >= minSection.z() + depth * 16) { // Resize necessary @@ -134,7 +141,7 @@ private void resize(int x, int y, int z) { final int newX = coordinates.blockX() + startX; final int newY = coordinates.blockY() + startY; final int newZ = coordinates.blockZ() + startZ; - final GenerationUnit unit = section(new Section(), newX, newY, newZ, true); + final GenerationUnit unit = section(minecraftServer, new Section(minecraftServer), newX, newY, newZ, true); newSections[i] = unit; } } @@ -147,7 +154,7 @@ private void resize(int x, int y, int z) { } } - record UnitImpl(UnitModifier modifier, Point size, + record UnitImpl(MinecraftServer minecraftServer, UnitModifier modifier, Point size, Point absoluteStart, Point absoluteEnd, List divided, List forks) implements GenerationUnit { @@ -170,7 +177,7 @@ record UnitImpl(UnitModifier modifier, Point size, for (int sectionX = minSectionX; sectionX < maxSectionX; sectionX++) { for (int sectionY = minSectionY; sectionY < maxSectionY; sectionY++) { for (int sectionZ = minSectionZ; sectionZ < maxSectionZ; sectionZ++) { - final GenerationUnit unit = section(new Section(), sectionX, sectionY, sectionZ, true); + final GenerationUnit unit = section(minecraftServer, new Section(minecraftServer), sectionX, sectionY, sectionZ, true); units[index++] = unit; } } @@ -182,7 +189,7 @@ record UnitImpl(UnitModifier modifier, Point size, @Override public void fork(@NotNull Consumer consumer) { - DynamicFork dynamicFork = new DynamicFork(); + DynamicFork dynamicFork = new DynamicFork(minecraftServer); consumer.accept(dynamicFork); final Point startSection = dynamicFork.minSection; if (startSection == null) @@ -205,7 +212,7 @@ private GenerationUnit registerFork(Point start, List sections, final Point size = end.sub(start); final AreaModifierImpl modifier = new AreaModifierImpl(null, size, start, end, width, height, depth, sections); - final UnitImpl fork = new UnitImpl(modifier, size, start, end, sections, forks); + final UnitImpl fork = new UnitImpl(minecraftServer, modifier, size, start, end, sections, forks); forks.add(fork); return fork; } diff --git a/src/main/java/net/minestom/server/instance/IChunkLoader.java b/src/main/java/net/minestom/server/instance/IChunkLoader.java index 549f32e0099..4fa5e3d17f9 100644 --- a/src/main/java/net/minestom/server/instance/IChunkLoader.java +++ b/src/main/java/net/minestom/server/instance/IChunkLoader.java @@ -58,7 +58,7 @@ default void loadInstance(@NotNull Instance instance) { * @return a {@link CompletableFuture} executed when the {@link Chunk} is done saving, * should be called even if the saving failed (you can throw an exception). */ - default @NotNull CompletableFuture saveChunks(@NotNull Collection chunks) { + default @NotNull CompletableFuture saveChunks(MinecraftServer minecraftServer, @NotNull Collection chunks) { if (supportsParallelSaving()) { ExecutorService parallelSavingThreadPool = ForkJoinPool.commonPool(); chunks.forEach(c -> parallelSavingThreadPool.execute(() -> saveChunk(c))); @@ -66,7 +66,7 @@ default void loadInstance(@NotNull Instance instance) { parallelSavingThreadPool.shutdown(); parallelSavingThreadPool.awaitTermination(1L, java.util.concurrent.TimeUnit.DAYS); } catch (InterruptedException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } return AsyncUtils.VOID_FUTURE; } else { diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index 55324b7aded..e8464845b1c 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -4,6 +4,7 @@ import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointers; import net.minestom.server.MinecraftServer; +import net.minestom.server.MinecraftServerObject; import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.adventure.audience.PacketGroupingAudience; @@ -64,9 +65,9 @@ * you need to be sure to signal the {@link ThreadDispatcher} of every partition/element changes. */ public abstract class Instance implements Block.Getter, Block.Setter, - Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { + Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience, MinecraftServerObject { - private final MinecraftServer minecraftServer; + public final MinecraftServer minecraftServer; private boolean registered; private final DimensionType dimensionType; @@ -450,7 +451,7 @@ public long getTime() { */ public void setTime(long time) { this.time = time; - PacketUtils.sendGroupedPacket(getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(minecraftServer, getPlayers(), createTimePacket()); } /** @@ -665,7 +666,7 @@ public void tick(long time) { this.time += timeRate; // time needs to be sent to players if (timeUpdate != null && !Cooldown.hasCooldown(time, lastTimeUpdate, timeUpdate)) { - PacketUtils.sendGroupedPacket(getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(minecraftServer, getPlayers(), createTimePacket()); this.lastTimeUpdate = time; } @@ -771,4 +772,9 @@ public void setExplosionSupplier(@Nullable ExplosionSupplier supplier) { public @NotNull Pointers pointers() { return this.pointers; } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index a026565af9a..50352a96e4e 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -53,7 +53,7 @@ public class InstanceContainer extends Instance { private static final Logger LOGGER = LoggerFactory.getLogger(InstanceContainer.class); - private final MinecraftServer minecraftServer; + public final MinecraftServer minecraftServer; private final ServerProcess serverProcess; private static final BlockFace[] BLOCK_UPDATE_FACES = new BlockFace[]{ @@ -102,7 +102,7 @@ public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID @ApiStatus.Experimental public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { super(minecraftServer, uniqueId, dimensionType, dimensionName); - setChunkSupplier(DynamicChunk::new); + setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(instance, chunkX, chunkZ)); setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(minecraftServer, "world"))); this.chunkLoader.loadInstance(this); this.minecraftServer = minecraftServer; @@ -230,7 +230,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, UNSAFE_setBlock(chunk, x, y, z, resultBlock, null, new BlockHandler.PlayerDestroy(block, this, blockPosition, player), doBlockUpdates, 0); // Send the block break effect packet - PacketUtils.sendGroupedPacket(chunk.getViewers(), + PacketUtils.sendGroupedPacket(minecraftServer, chunk.getViewers(), new EffectPacket(2001 /*Block break + block break sound*/, blockPosition, block.stateId(), false), // Prevent the block breaker to play the particles and sound two times (viewer) -> !viewer.equals(player)); @@ -284,7 +284,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { @Override public @NotNull CompletableFuture saveChunksToStorage() { - return chunkLoader.saveChunks(getChunks()); + return chunkLoader.saveChunks(minecraftServer, getChunks()); } protected @NotNull CompletableFuture<@NotNull Chunk> retrieveChunk(int chunkX, int chunkZ) { diff --git a/src/main/java/net/minestom/server/instance/InstanceManager.java b/src/main/java/net/minestom/server/instance/InstanceManager.java index 5212b24b5c0..beed2d7b751 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManager.java +++ b/src/main/java/net/minestom/server/instance/InstanceManager.java @@ -102,7 +102,7 @@ public void registerInstance(@NotNull Instance instance) { Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); - final SharedInstance sharedInstance = new SharedInstance(UUID.randomUUID(), instanceContainer); + final SharedInstance sharedInstance = new SharedInstance(instanceContainer.minecraftServer, UUID.randomUUID(), instanceContainer); return registerSharedInstance(sharedInstance); } diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index c1bf4f16bee..b1242d6b7bb 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minestom.server.MinecraftServer; import net.minestom.server.collision.Shape; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -38,7 +37,7 @@ public class LightingChunk extends DynamicChunk { private static final ExecutorService pool = Executors.newWorkStealingPool(); private int[] heightmap; - final CachedPacket lightCache = new CachedPacket(this::createLightPacket); + final CachedPacket lightCache = new CachedPacket(minecraftServer, this::createLightPacket); boolean sendNeighbours = true; boolean chunkLoaded = false; @@ -257,7 +256,7 @@ static void updateAfterGeneration(LightingChunk chunk) { return; } - sendingTask = MinecraftServer.getSchedulerManager().scheduleTask(() -> { + sendingTask = chunk.minecraftServer.process().getSchedulerManager().scheduleTask(() -> { queueLock.lock(); var copy = new ArrayList<>(sendQueue); sendQueue.clear(); diff --git a/src/main/java/net/minestom/server/instance/Section.java b/src/main/java/net/minestom/server/instance/Section.java index 1222856a78a..4789cb07224 100644 --- a/src/main/java/net/minestom/server/instance/Section.java +++ b/src/main/java/net/minestom/server/instance/Section.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.MinecraftServer; import net.minestom.server.instance.light.Light; import net.minestom.server.instance.palette.Palette; import net.minestom.server.network.NetworkBuffer; @@ -27,8 +28,8 @@ private Section(Palette blockPalette, Palette biomePalette, Light skyLight, Ligh this.blockLight = blockLight; } - public Section() { - this(Palette.blocks(), Palette.biomes()); + public Section(MinecraftServer minecraftServer) { + this(Palette.blocks(minecraftServer), Palette.biomes(minecraftServer)); } public Palette blockPalette() { diff --git a/src/main/java/net/minestom/server/instance/SharedInstance.java b/src/main/java/net/minestom/server/instance/SharedInstance.java index 925252634cb..6f02c94f7d0 100644 --- a/src/main/java/net/minestom/server/instance/SharedInstance.java +++ b/src/main/java/net/minestom/server/instance/SharedInstance.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; import net.minestom.server.instance.block.Block; @@ -21,8 +22,8 @@ public class SharedInstance extends Instance { private final InstanceContainer instanceContainer; - public SharedInstance(@NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { - super(uniqueId, instanceContainer.getDimensionType()); + public SharedInstance(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { + super(minecraftServer, uniqueId, instanceContainer.getDimensionType()); this.instanceContainer = instanceContainer; } diff --git a/src/main/java/net/minestom/server/instance/WorldBorder.java b/src/main/java/net/minestom/server/instance/WorldBorder.java index 6243b54122b..595adb4dac4 100644 --- a/src/main/java/net/minestom/server/instance/WorldBorder.java +++ b/src/main/java/net/minestom/server/instance/WorldBorder.java @@ -254,7 +254,7 @@ private void refreshCenter() { } private void sendPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getMinecraftServer(), instance.getPlayers(), packet); } public enum CollisionAxis { diff --git a/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java b/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java index d64930f9a95..e34dda78703 100644 --- a/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.MathUtils; import org.jetbrains.annotations.NotNull; @@ -13,9 +14,11 @@ */ final class AdaptivePalette implements Palette, Cloneable { final byte dimension, defaultBitsPerEntry, maxBitsPerEntry; + private final MinecraftServer minecraftServer; SpecializedPalette palette; - AdaptivePalette(byte dimension, byte maxBitsPerEntry, byte bitsPerEntry) { + AdaptivePalette(MinecraftServer minecraftServer, byte dimension, byte maxBitsPerEntry, byte bitsPerEntry) { + this.minecraftServer = minecraftServer; validateDimension(dimension); this.dimension = dimension; this.maxBitsPerEntry = maxBitsPerEntry; @@ -56,7 +59,7 @@ public void fill(int value) { @Override public void setAll(@NotNull EntrySupplier supplier) { - SpecializedPalette newPalette = new FlexiblePalette(this); + SpecializedPalette newPalette = new FlexiblePalette(minecraftServer, this); newPalette.setAll(supplier); this.palette = newPalette; } @@ -139,7 +142,7 @@ SpecializedPalette optimizedPalette() { Palette flexiblePalette() { SpecializedPalette currentPalette = this.palette; if (currentPalette instanceof FilledPalette filledPalette) { - currentPalette = new FlexiblePalette(this); + currentPalette = new FlexiblePalette(minecraftServer, this); currentPalette.fill(filledPalette.value()); this.palette = currentPalette; } diff --git a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java index 89e07e9f0c7..c9fa96849af 100644 --- a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java @@ -19,6 +19,7 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { private static final ThreadLocal WRITE_CACHE = ThreadLocal.withInitial(() -> new int[4096]); + private final MinecraftServer minecraftServer; // Specific to this palette type private final AdaptivePalette adaptivePalette; private byte bitsPerEntry; @@ -30,7 +31,8 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { // value = palette index private Int2IntOpenHashMap valueToPaletteMap; - FlexiblePalette(AdaptivePalette adaptivePalette, byte bitsPerEntry) { + FlexiblePalette(MinecraftServer minecraftServer, AdaptivePalette adaptivePalette, byte bitsPerEntry) { + this.minecraftServer = minecraftServer; this.adaptivePalette = adaptivePalette; this.bitsPerEntry = bitsPerEntry; @@ -45,8 +47,8 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { this.values = new long[(maxSize() + valuesPerLong - 1) / valuesPerLong]; } - FlexiblePalette(AdaptivePalette adaptivePalette) { - this(adaptivePalette, adaptivePalette.defaultBitsPerEntry); + FlexiblePalette(MinecraftServer minecraftServer, AdaptivePalette adaptivePalette) { + this(minecraftServer, adaptivePalette, adaptivePalette.defaultBitsPerEntry); } @Override @@ -203,7 +205,7 @@ public int dimension() { palette.count = count; return palette; } catch (CloneNotSupportedException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); throw new IllegalStateException("Weird thing happened"); } } @@ -268,7 +270,7 @@ private void updateAll(int[] paletteValues) { void resize(byte newBitsPerEntry) { newBitsPerEntry = newBitsPerEntry > maxBitsPerEntry() ? 15 : newBitsPerEntry; - FlexiblePalette palette = new FlexiblePalette(adaptivePalette, newBitsPerEntry); + FlexiblePalette palette = new FlexiblePalette(minecraftServer, adaptivePalette, newBitsPerEntry); palette.paletteToValueList = paletteToValueList; palette.valueToPaletteMap = valueToPaletteMap; getAll(palette::set); diff --git a/src/main/java/net/minestom/server/instance/palette/Palette.java b/src/main/java/net/minestom/server/instance/palette/Palette.java index 93a14b9b3cb..359a570b418 100644 --- a/src/main/java/net/minestom/server/instance/palette/Palette.java +++ b/src/main/java/net/minestom/server/instance/palette/Palette.java @@ -1,5 +1,6 @@ package net.minestom.server.instance.palette; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.NetworkBuffer; import org.jetbrains.annotations.NotNull; @@ -11,16 +12,16 @@ * 0 is the default value. */ public interface Palette extends NetworkBuffer.Writer { - static Palette blocks() { - return newPalette(16, 8, 4); + static Palette blocks(MinecraftServer minecraftServer) { + return newPalette(minecraftServer, 16, 8, 4); } - static Palette biomes() { - return newPalette(4, 3, 1); + static Palette biomes(MinecraftServer minecraftServer) { + return newPalette(minecraftServer, 4, 3, 1); } - static Palette newPalette(int dimension, int maxBitsPerEntry, int bitsPerEntry) { - return new AdaptivePalette((byte) dimension, (byte) maxBitsPerEntry, (byte) bitsPerEntry); + static Palette newPalette(MinecraftServer minecraftServer, int dimension, int maxBitsPerEntry, int bitsPerEntry) { + return new AdaptivePalette(minecraftServer, (byte) dimension, (byte) maxBitsPerEntry, (byte) bitsPerEntry); } int get(int x, int y, int z); diff --git a/src/main/java/net/minestom/server/inventory/Inventory.java b/src/main/java/net/minestom/server/inventory/Inventory.java index e79c04fa1ac..c3c902b1c89 100644 --- a/src/main/java/net/minestom/server/inventory/Inventory.java +++ b/src/main/java/net/minestom/server/inventory/Inventory.java @@ -392,4 +392,9 @@ private void updateAll(Player player) { player.getInventory().update(); update(player); } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java b/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java index 8a7c9f2c154..d826bedf32f 100644 --- a/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -10,12 +11,12 @@ public class AnvilInventory extends Inventory { private short repairCost; - public AnvilInventory(@NotNull Component title) { - super(InventoryType.ANVIL, title); + public AnvilInventory(MinecraftServer minecraftServer, @NotNull Component title) { + super(minecraftServer, InventoryType.ANVIL, title); } - public AnvilInventory(@NotNull String title) { - super(InventoryType.ANVIL, title); + public AnvilInventory(MinecraftServer minecraftServer, @NotNull String title) { + super(minecraftServer, InventoryType.ANVIL, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java b/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java index 30551dae67c..47be3963e3b 100644 --- a/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -13,12 +14,12 @@ public class BeaconInventory extends Inventory { private PotionEffect firstPotionEffect; private PotionEffect secondPotionEffect; - public BeaconInventory(@NotNull Component title) { - super(InventoryType.BEACON, title); + public BeaconInventory(MinecraftServer minecraftServer, @NotNull Component title) { + super(minecraftServer, InventoryType.BEACON, title); } - public BeaconInventory(@NotNull String title) { - super(InventoryType.BEACON, title); + public BeaconInventory(MinecraftServer minecraftServer, @NotNull String title) { + super(minecraftServer, InventoryType.BEACON, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java b/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java index ed0bc7d783d..6fa8f2ee3a8 100644 --- a/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -11,12 +12,12 @@ public class BrewingStandInventory extends Inventory { private short brewTime; private short fuelTime; - public BrewingStandInventory(@NotNull Component title) { - super(InventoryType.BREWING_STAND, title); + public BrewingStandInventory(MinecraftServer minecraftServer, @NotNull Component title) { + super(minecraftServer, InventoryType.BREWING_STAND, title); } - public BrewingStandInventory(@NotNull String title) { - super(InventoryType.BREWING_STAND, title); + public BrewingStandInventory(MinecraftServer minecraftServer, @NotNull String title) { + super(minecraftServer, InventoryType.BREWING_STAND, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java b/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java index bd855c32a51..03944333418 100644 --- a/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -14,12 +15,12 @@ public class EnchantmentTableInventory extends Inventory { private final short[] enchantmentShown = new short[EnchantmentSlot.values().length]; private final short[] enchantmentLevel = new short[EnchantmentSlot.values().length]; - public EnchantmentTableInventory(@NotNull Component title) { - super(InventoryType.ENCHANTMENT, title); + public EnchantmentTableInventory(MinecraftServer minecraftServer, @NotNull Component title) { + super(minecraftServer, InventoryType.ENCHANTMENT, title); } - public EnchantmentTableInventory(@NotNull String title) { - super(InventoryType.ENCHANTMENT, title); + public EnchantmentTableInventory(MinecraftServer minecraftServer, @NotNull String title) { + super(minecraftServer, InventoryType.ENCHANTMENT, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java b/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java index 9e357da9936..47a236ddc6b 100644 --- a/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -13,12 +14,12 @@ public class FurnaceInventory extends Inventory { private short progressArrow; private short maximumProgress; - public FurnaceInventory(@NotNull Component title) { - super(InventoryType.FURNACE, title); + public FurnaceInventory(MinecraftServer minecraftServer, @NotNull Component title) { + super(minecraftServer, InventoryType.FURNACE, title); } - public FurnaceInventory(@NotNull String title) { - super(InventoryType.FURNACE, title); + public FurnaceInventory(MinecraftServer minecraftServer, @NotNull String title) { + super(minecraftServer, InventoryType.FURNACE, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java index 048fa581393..5b8e27481c0 100644 --- a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; @@ -13,19 +14,21 @@ import java.util.List; public class VillagerInventory extends Inventory { - private final CachedPacket tradeCache = new CachedPacket(this::createTradePacket); + private final CachedPacket tradeCache; private final List trades = new ArrayList<>(); private int villagerLevel; private int experience; private boolean regularVillager; private boolean canRestock; - public VillagerInventory(@NotNull Component title) { - super(InventoryType.MERCHANT, title); + public VillagerInventory(MinecraftServer minecraftServer, @NotNull Component title) { + super(minecraftServer, InventoryType.MERCHANT, title); + tradeCache = new CachedPacket(minecraftServer, this::createTradePacket); } - public VillagerInventory(@NotNull String title) { - super(InventoryType.MERCHANT, title); + public VillagerInventory(MinecraftServer minecraftServer, @NotNull String title) { + super(minecraftServer, InventoryType.MERCHANT, title); + tradeCache = new CachedPacket(minecraftServer, this::createTradePacket); } public List getTrades() { diff --git a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java index 912714fb572..7dc78705c2c 100644 --- a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java +++ b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java @@ -9,7 +9,7 @@ public class AdvancementTabListener { public static void listener(ClientAdvancementTabPacket packet, Player player) { final String tabIdentifier = packet.tabIdentifier(); if (tabIdentifier != null) { - player.minecraftServer.process().getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); + player.getMinecraftServer().process().getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); } } } diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index b11a56f068d..1ddf2f33edc 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -51,7 +51,7 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl final Collection recipients = playerChatEvent.getRecipients(); if (!recipients.isEmpty()) { // delegate to the messenger to avoid sending messages we shouldn't be - Messenger.sendMessage(recipients, textObject, ChatPosition.CHAT, player.getUuid()); + Messenger.sendMessage(player.getMinecraftServer(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); } }); } diff --git a/src/main/java/net/minestom/server/listener/PlayConfigListener.java b/src/main/java/net/minestom/server/listener/PlayConfigListener.java index d486125beab..dde21f91ca9 100644 --- a/src/main/java/net/minestom/server/listener/PlayConfigListener.java +++ b/src/main/java/net/minestom/server/listener/PlayConfigListener.java @@ -1,15 +1,11 @@ package net.minestom.server.listener; -import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.client.play.ClientConfigurationAckPacket; import org.jetbrains.annotations.NotNull; public class PlayConfigListener { - private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); - public static void configAckListener(@NotNull ClientConfigurationAckPacket packet, @NotNull Player player) { - CONNECTION_MANAGER.doConfiguration(player, false); + player.minecraftServer.process().getConnectionManager().doConfiguration(player, false); } } diff --git a/src/main/java/net/minestom/server/listener/TabCompleteListener.java b/src/main/java/net/minestom/server/listener/TabCompleteListener.java index c86ab4055b0..0d0f973d77d 100644 --- a/src/main/java/net/minestom/server/listener/TabCompleteListener.java +++ b/src/main/java/net/minestom/server/listener/TabCompleteListener.java @@ -1,6 +1,6 @@ package net.minestom.server.listener; -import net.minestom.server.MinecraftServer; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.suggestion.Suggestion; import net.minestom.server.entity.Player; @@ -12,7 +12,7 @@ public class TabCompleteListener { public static void listener(ClientTabCompletePacket packet, Player player) { final String text = packet.text(); - final Suggestion suggestion = getSuggestion(player, text); + final Suggestion suggestion = getSuggestion(player.minecraftServer.process().getCommandManager(), player, text); if (suggestion != null) { player.sendPacket(new TabCompletePacket( packet.transactionId(), @@ -25,7 +25,7 @@ public static void listener(ClientTabCompletePacket packet, Player player) { } } - public static @Nullable Suggestion getSuggestion(CommandSender commandSender, String text) { + public static @Nullable Suggestion getSuggestion(CommandManager commandManager, CommandSender commandSender, String text) { if (text.startsWith("/")) { text = text.substring(1); } @@ -35,6 +35,6 @@ public static void listener(ClientTabCompletePacket packet, Player player) { // it works as intended :) text = text + '\00'; } - return MinecraftServer.getCommandManager().parseCommand(commandSender, text).suggestion(commandSender); + return commandManager.parseCommand(commandSender, text).suggestion(commandSender); } } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java index 8b67de2913a..d60958aa1db 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java @@ -70,7 +70,7 @@ public PacketListenerManager(MinecraftServer minecraftServer) { setPlayListener(ClientPongPacket.class, WindowListener::pong); setPlayListener(ClientEntityActionPacket.class, EntityActionListener::listener); setPlayListener(ClientHeldItemChangePacket.class, PlayerHeldListener::heldListener); - setPlayListener(ClientPlayerBlockPlacementPacket.class, (packet1, player1) -> new BlockPlacementListener(minecraftServer).listener(packet1, player1)); + setPlayListener(ClientPlayerBlockPlacementPacket.class, BlockPlacementListener::listener); setPlayListener(ClientSteerVehiclePacket.class, PlayerVehicleListener::steerVehicleListener); setPlayListener(ClientVehicleMovePacket.class, PlayerVehicleListener::vehicleMoveListener); setPlayListener(ClientSteerBoatPacket.class, PlayerVehicleListener::boatSteerListener); diff --git a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java index 054ccaf7c2b..983391bb82e 100644 --- a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java @@ -1,15 +1,12 @@ package net.minestom.server.listener.preplay; -import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.client.configuration.ClientFinishConfigurationPacket; import org.jetbrains.annotations.NotNull; public final class ConfigListener { - private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); public static void finishConfigListener(@NotNull ClientFinishConfigurationPacket packet, @NotNull Player player) { - CONNECTION_MANAGER.transitionConfigToPlay(player); + player.minecraftServer.process().getConnectionManager().transitionConfigToPlay(player); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java index c14c02beb3e..9ce4b035138 100644 --- a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java @@ -9,9 +9,7 @@ import net.minestom.server.entity.Player; import net.minestom.server.extras.MojangAuth; import net.minestom.server.extras.bungee.BungeeCordProxy; -import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.extras.velocity.VelocityProxy; -import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.client.login.ClientEncryptionResponsePacket; import net.minestom.server.network.packet.client.login.ClientLoginAcknowledgedPacket; @@ -40,13 +38,13 @@ import static net.minestom.server.network.NetworkBuffer.STRING; public final class LoginListener { - private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); private static final Gson GSON = new Gson(); private static final Component ALREADY_CONNECTED = Component.text("You are already on this server", NamedTextColor.RED); public static final Component INVALID_PROXY_RESPONSE = Component.text("Invalid proxy response!", NamedTextColor.RED); public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @NotNull PlayerConnection connection) { + MojangAuth mojangAuth = connection.minecraftServer.process().getMojangAuth(); final boolean isSocketConnection = connection instanceof PlayerSocketConnection; // Proxy support (only for socket clients) and cache the login username if (isSocketConnection) { @@ -63,16 +61,16 @@ public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @N } } - if (MojangAuth.isEnabled() && isSocketConnection) { + if (mojangAuth.isEnabled() && isSocketConnection) { // Mojang auth - if (CONNECTION_MANAGER.getOnlinePlayerByUsername(packet.username()) != null) { + if (connection.minecraftServer.process().getConnectionManager().getOnlinePlayerByUsername(packet.username()) != null) { connection.sendPacket(new LoginDisconnectPacket(ALREADY_CONNECTED)); connection.disconnect(); return; } final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection; - final byte[] publicKey = MojangAuth.getKeyPair().getPublic().getEncoded(); + final byte[] publicKey = mojangAuth.getKeyPair().getPublic().getEncoded(); byte[] nonce = new byte[4]; ThreadLocalRandom.current().nextBytes(nonce); socketConnection.setNonce(nonce); @@ -82,15 +80,16 @@ public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @N // Offline final UUID playerUuid = bungee && isSocketConnection ? ((PlayerSocketConnection) connection).gameProfile().uuid() : - CONNECTION_MANAGER.getPlayerConnectionUuid(connection, packet.username()); - CONNECTION_MANAGER.createPlayer(connection, playerUuid, packet.username()); + connection.minecraftServer.process().getConnectionManager().getPlayerConnectionUuid(connection, packet.username()); + connection.minecraftServer.process().getConnectionManager().createPlayer(connection, playerUuid, packet.username()); } } public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResponsePacket packet, @NotNull PlayerConnection connection) { // Encryption is only support for socket connection + MojangAuth mojangAuth = connection.minecraftServer.process().getMojangAuth(); if (!(connection instanceof PlayerSocketConnection socketConnection)) return; - AsyncUtils.runAsync(() -> { + AsyncUtils.runAsync(connection.minecraftServer, () -> { final String loginUsername = socketConnection.getLoginUsername(); if (loginUsername == null || loginUsername.isEmpty()) { // Shouldn't happen @@ -99,14 +98,14 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp final boolean hasPublicKey = connection.playerPublicKey() != null; final boolean verificationFailed = hasPublicKey || !Arrays.equals(socketConnection.getNonce(), - MojangCrypt.decryptUsingKey(MojangAuth.getKeyPair().getPrivate(), packet.encryptedVerifyToken())); + mojangAuth.getMojangCrypt().decryptUsingKey(mojangAuth.getKeyPair().getPrivate(), packet.encryptedVerifyToken())); if (verificationFailed) { MinecraftServer.LOGGER.error("Encryption failed for {}", loginUsername); return; } - final byte[] digestedData = MojangCrypt.digestData("", MojangAuth.getKeyPair().getPublic(), getSecretKey(packet.sharedSecret())); + final byte[] digestedData = mojangAuth.getMojangCrypt().digestData("", mojangAuth.getKeyPair().getPublic(), getSecretKey(mojangAuth, packet.sharedSecret())); if (digestedData == null) { // Incorrect key, probably because of the client MinecraftServer.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); @@ -117,14 +116,14 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp final String serverId = new BigInteger(digestedData).toString(16); final String username = URLEncoder.encode(loginUsername, StandardCharsets.UTF_8); - final String url = String.format(MojangAuth.AUTH_URL, username, serverId); + final String url = String.format(mojangAuth.AUTH_URL, username, serverId); // TODO: Add ability to add ip query tag. See: https://wiki.vg/Protocol_Encryption#Authentication final HttpClient client = HttpClient.newHttpClient(); final HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).whenComplete((response, throwable) -> { if (throwable != null) { - MinecraftServer.getExceptionManager().handleException(throwable); + connection.minecraftServer.process().getExceptionManager().handleException(throwable); if (socketConnection.getPlayer() != null) { socketConnection.getPlayer().kick(Component.text("Failed to contact Mojang's Session Servers (Are they down?)")); } else { @@ -143,13 +142,13 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp } return; } - socketConnection.setEncryptionKey(getSecretKey(packet.sharedSecret())); + socketConnection.setEncryptionKey(getSecretKey(mojangAuth, packet.sharedSecret())); UUID profileUUID = java.util.UUID.fromString(gameProfile.get("id").getAsString() .replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); final String profileName = gameProfile.get("name").getAsString(); MinecraftServer.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); - CONNECTION_MANAGER.createPlayer(connection, profileUUID, profileName); + connection.minecraftServer.process().getConnectionManager().createPlayer(connection, profileUUID, profileName); List propertyList = new ArrayList<>(); for (JsonElement element : gameProfile.get("properties").getAsJsonArray()) { JsonObject object = element.getAsJsonObject(); @@ -157,14 +156,14 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp } socketConnection.UNSAFE_setProfile(new GameProfile(profileUUID, profileName, propertyList)); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + connection.minecraftServer.process().getExceptionManager().handleException(e); } }); }); } - private static SecretKey getSecretKey(byte[] sharedSecret) { - return MojangCrypt.decryptByteToSecretKey(MojangAuth.getKeyPair().getPrivate(), sharedSecret); + private static SecretKey getSecretKey(MojangAuth mojangAuth, byte[] sharedSecret) { + return mojangAuth.getMojangCrypt().decryptByteToSecretKey(mojangAuth.getKeyPair().getPrivate(), sharedSecret); } public static void loginPluginResponseListener(@NotNull ClientLoginPluginResponsePacket packet, @NotNull PlayerConnection connection) { @@ -189,7 +188,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons try { address = InetAddress.getByName(buffer.read(STRING)); } catch (UnknownHostException e) { - MinecraftServer.getExceptionManager().handleException(e); + connection.minecraftServer.process().getExceptionManager().handleException(e); return; } final int port = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort(); @@ -202,7 +201,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons if (success) { socketConnection.setRemoteAddress(socketAddress); socketConnection.UNSAFE_setProfile(gameProfile); - CONNECTION_MANAGER.createPlayer(connection, gameProfile.uuid(), gameProfile.name()); + connection.minecraftServer.process().getConnectionManager().createPlayer(connection, gameProfile.uuid(), gameProfile.name()); } else { LoginDisconnectPacket disconnectPacket = new LoginDisconnectPacket(INVALID_PROXY_RESPONSE); socketConnection.sendPacket(disconnectPacket); @@ -213,7 +212,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons public static void loginAckListener(@NotNull ClientLoginAcknowledgedPacket ignored, @NotNull PlayerConnection connection) { final Player player = Objects.requireNonNull(connection.getPlayer()); - CONNECTION_MANAGER.doConfiguration(player, true); + connection.minecraftServer.process().getConnectionManager().doConfiguration(player, true); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java index 31f6706702e..96d6bc3cbc4 100644 --- a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java @@ -14,7 +14,7 @@ public final class StatusListener { public static void requestListener(@NotNull StatusRequestPacket packet, @NotNull PlayerConnection connection) { final ServerListPingType pingVersion = ServerListPingType.fromModernProtocolVersion(connection.getProtocolVersion()); - final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connection, pingVersion); + final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connection.minecraftServer, connection, pingVersion); connection.minecraftServer.process().getGlobalEventHandler().callCancellable(statusRequestEvent, () -> connection.sendPacket(new ResponsePacket(pingVersion.getPingResponse(statusRequestEvent.getResponseData())))); } diff --git a/src/main/java/net/minestom/server/map/MapColors.java b/src/main/java/net/minestom/server/map/MapColors.java index 342b360efe6..8fcb7556981 100644 --- a/src/main/java/net/minestom/server/map/MapColors.java +++ b/src/main/java/net/minestom/server/map/MapColors.java @@ -1,7 +1,5 @@ package net.minestom.server.map; -import net.minestom.server.MinecraftServer; - import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; @@ -103,7 +101,7 @@ public enum MapColors { reduction = Integer.parseInt(reductionStr); } catch (NumberFormatException e) { System.err.println("Invalid integer in reduction argument: " + reductionStr); - MinecraftServer.getExceptionManager().handleException(e); + throw new RuntimeException(e); } if (reduction < 0 || reduction >= 255) { diff --git a/src/main/java/net/minestom/server/message/Messenger.java b/src/main/java/net/minestom/server/message/Messenger.java index 16af3663e65..42636438e60 100644 --- a/src/main/java/net/minestom/server/message/Messenger.java +++ b/src/main/java/net/minestom/server/message/Messenger.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.SystemChatPacket; import net.minestom.server.utils.PacketUtils; @@ -92,9 +93,9 @@ public static boolean sendMessage(@NotNull Player player, @NotNull Component mes * @param position the position * @param uuid the UUID of the sender, if any */ - public static void sendMessage(@NotNull Collection players, @NotNull Component message, + public static void sendMessage(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull Component message, @NotNull ChatPosition position, @Nullable UUID uuid) { - PacketUtils.sendGroupedPacket(players, new SystemChatPacket(message, false), + PacketUtils.sendGroupedPacket(minecraftServer, players, new SystemChatPacket(message, false), player -> getChatMessageType(player).accepts(position)); } diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java index 84c502629a3..ab669fefc1e 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java @@ -52,6 +52,11 @@ public final class BenchmarkManager { private boolean enabled = false; private volatile boolean stop = false; private long time; + private final MinecraftServer minecraftServer; + + public BenchmarkManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + } public void enable(@NotNull Duration duration) { Check.stateCondition(enabled, "A benchmark is already running, please disable it first."); @@ -72,7 +77,7 @@ public void enable(@NotNull Duration duration) { try { Thread.sleep(time); } catch (InterruptedException e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } } stop = false; diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index 5a8a6be582c..dba52286a19 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -11,6 +11,7 @@ import net.minestom.server.instance.Instance; import net.minestom.server.message.Messenger; import net.minestom.server.network.packet.client.login.ClientLoginStartPacket; +import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.common.KeepAlivePacket; import net.minestom.server.network.packet.server.common.PluginMessagePacket; import net.minestom.server.network.packet.server.common.TagsPacket; @@ -45,6 +46,8 @@ public final class ConnectionManager { private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class); + public final CachedPacket defaultTags; + private final MinecraftServer minecraftServer; private final ServerProcess serverProcess; @@ -81,6 +84,7 @@ public final class ConnectionManager { public ConnectionManager(MinecraftServer minecraftServer) { this.minecraftServer = minecraftServer; this.serverProcess = minecraftServer.process(); + this.defaultTags = new CachedPacket(minecraftServer, new TagsPacket(serverProcess.getTagManager().getTagMap())); defaultPlayerProvider = (uuid, username, connection) -> new Player(minecraftServer, uuid, username, connection); playerProvider = defaultPlayerProvider; } @@ -226,7 +230,7 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { @ApiStatus.Internal public @NotNull CompletableFuture transitionLoginToConfig(@NotNull Player player) { - return AsyncUtils.runAsync(() -> { + return AsyncUtils.runAsync(minecraftServer, () -> { final PlayerConnection playerConnection = player.getPlayerConnection(); // Compression @@ -273,7 +277,7 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { } player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); - CompletableFuture configFuture = AsyncUtils.runAsync(() -> { + CompletableFuture configFuture = AsyncUtils.runAsync(minecraftServer, () -> { player.sendPacket(PluginMessagePacket.getBrandPacket(minecraftServer)); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); @@ -291,7 +295,7 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { registry.put("minecraft:damage_type", DamageType.getNBT()); player.sendPacket(new RegistryDataPacket(NBT.Compound(registry))); - player.sendPacket(TagsPacket.DEFAULT_TAGS); + player.sendPacket(defaultTags); } // Wait for pending resource packs if any diff --git a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java index 9138e16844a..fe39482bdec 100644 --- a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java @@ -1,5 +1,6 @@ package net.minestom.server.network.packet.server; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.ApiStatus; @@ -21,13 +22,15 @@ public final class CachedPacket implements SendablePacket { private final Supplier packetSupplier; private volatile SoftReference packet; + private final MinecraftServer minecraftServer; - public CachedPacket(@NotNull Supplier<@NotNull ServerPacket> packetSupplier) { + public CachedPacket(MinecraftServer minecraftServer, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { this.packetSupplier = packetSupplier; + this.minecraftServer = minecraftServer; } - public CachedPacket(@NotNull ServerPacket packet) { - this(() -> packet); + public CachedPacket(MinecraftServer minecraftServer, @NotNull ServerPacket packet) { + this(minecraftServer, () -> packet); } public void invalidate() { @@ -50,7 +53,7 @@ public void invalidate() { SoftReference ref = packet; FramedPacket cache; if (ref == null || (cache = ref.get()) == null) { - cache = PacketUtils.allocateTrimmedPacket(state, packetSupplier.get()); + cache = PacketUtils.allocateTrimmedPacket(minecraftServer, state, packetSupplier.get()); this.packet = new SoftReference<>(cache); } return cache; diff --git a/src/main/java/net/minestom/server/network/packet/server/common/TagsPacket.java b/src/main/java/net/minestom/server/network/packet/server/common/TagsPacket.java index 5906ad48a29..febcaaae2a8 100644 --- a/src/main/java/net/minestom/server/network/packet/server/common/TagsPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/common/TagsPacket.java @@ -1,14 +1,11 @@ package net.minestom.server.network.packet.server.common; -import net.minestom.server.MinecraftServer; import net.minestom.server.gamedata.tags.Tag; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.NetworkBuffer; -import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.ServerPacketIdentifier; import net.minestom.server.utils.PacketUtils; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.EnumMap; @@ -18,8 +15,6 @@ import static net.minestom.server.network.NetworkBuffer.*; public record TagsPacket(@NotNull Map> tagsMap) implements ServerPacket { - @ApiStatus.Internal - public static final CachedPacket DEFAULT_TAGS = new CachedPacket(new TagsPacket(MinecraftServer.getTagManager().getTagMap())); public TagsPacket { tagsMap = Map.copyOf(tagsMap); @@ -53,7 +48,8 @@ public int getId(@NotNull ConnectionState state) { return switch (state) { case CONFIGURATION -> ServerPacketIdentifier.CONFIGURATION_TAGS; case PLAY -> ServerPacketIdentifier.TAGS; - default -> PacketUtils.invalidPacketState(getClass(), state, ConnectionState.CONFIGURATION, ConnectionState.PLAY); + default -> + PacketUtils.invalidPacketState(getClass(), state, ConnectionState.CONFIGURATION, ConnectionState.PLAY); }; } diff --git a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java index 98b3fafa87e..e1d6387cd42 100644 --- a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java @@ -1,5 +1,6 @@ package net.minestom.server.network.player; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.entity.fakeplayer.FakePlayer; import net.minestom.server.entity.fakeplayer.FakePlayerController; @@ -13,8 +14,8 @@ public class FakePlayerConnection extends PlayerConnection { - public FakePlayerConnection() { - super(); + public FakePlayerConnection(MinecraftServer minecraftServer) { + super(minecraftServer); } @Override diff --git a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java index 3d420d940df..e23d4d16a3e 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java @@ -138,7 +138,8 @@ public void consumeCache(BinaryBuffer buffer) { */ public void setEncryptionKey(@NotNull SecretKey secretKey) { Check.stateCondition(encryptionContext != null, "Encryption is already enabled!"); - this.encryptionContext = new EncryptionContext(MojangCrypt.getCipher(1, secretKey), MojangCrypt.getCipher(2, secretKey)); + MojangCrypt mojangCrypt = minecraftServer.process().getMojangAuth().getMojangCrypt(); + this.encryptionContext = new EncryptionContext(mojangCrypt.getCipher(1, secretKey), mojangCrypt.getCipher(2, secretKey)); } /** @@ -369,7 +370,7 @@ private void writeServerPacketSync(ServerPacket serverPacket, boolean compressed } } try (var hold = ObjectPool.PACKET_POOL.hold()) { - var buffer = PacketUtils.createFramedPacket(getConnectionState(), hold.get(), serverPacket, compressed); + var buffer = PacketUtils.createFramedPacket(minecraftServer, getConnectionState(), hold.get(), serverPacket, compressed); writeBufferSync(buffer, 0, buffer.limit()); } } diff --git a/src/main/java/net/minestom/server/ping/ResponseData.java b/src/main/java/net/minestom/server/ping/ResponseData.java index 885d850b020..85fb2b3d789 100644 --- a/src/main/java/net/minestom/server/ping/ResponseData.java +++ b/src/main/java/net/minestom/server/ping/ResponseData.java @@ -7,8 +7,6 @@ import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.event.server.ServerListPingEvent; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.identity.NamedAndIdentified; import org.jetbrains.annotations.NotNull; @@ -23,6 +21,8 @@ public class ResponseData { private static final Component DEFAULT_DESCRIPTION = Component.text("Minestom Server"); private final List entries; + @NotNull + private final MinecraftServer minecraftServer; private String version; private int protocol; @@ -35,11 +35,12 @@ public class ResponseData { /** * Constructs a new {@link ResponseData}. */ - public ResponseData() { + public ResponseData(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; this.entries = new ArrayList<>(); this.version = MinecraftServer.VERSION_NAME; this.protocol = MinecraftServer.PROTOCOL_VERSION; - this.online = MinecraftServer.getConnectionManager().getOnlinePlayerCount(); + this.online = minecraftServer.process().getConnectionManager().getOnlinePlayerCount(); this.maxPlayer = this.online + 1; this.description = DEFAULT_DESCRIPTION; this.favicon = ""; @@ -326,6 +327,10 @@ public boolean arePlayersHidden() { return ServerListPingType.getModernPingResponse(this, true); } + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + /** * Represents a player line in the server list hover. * diff --git a/src/main/java/net/minestom/server/ping/ServerListPingType.java b/src/main/java/net/minestom/server/ping/ServerListPingType.java index e30a3bc9296..91cfbb1ca09 100644 --- a/src/main/java/net/minestom/server/ping/ServerListPingType.java +++ b/src/main/java/net/minestom/server/ping/ServerListPingType.java @@ -4,7 +4,6 @@ import com.google.gson.JsonObject; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.minestom.server.MinecraftServer; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.extras.lan.OpenToLAN; import net.minestom.server.utils.identity.NamedAndIdentified; @@ -44,7 +43,7 @@ public enum ServerListPingType { * Only the description formatted as a legacy string is sent. * Ping events with this ping version are not cancellable. */ - OPEN_TO_LAN(ServerListPingType::getOpenToLANPing); + OPEN_TO_LAN(data -> getOpenToLANPing(data)); private final Function pingResponseCreator; @@ -75,7 +74,7 @@ public enum ServerListPingType { * @see OpenToLAN */ public static @NotNull String getOpenToLANPing(@NotNull ResponseData data) { - return String.format(LAN_PING_FORMAT, SECTION.serialize(data.getDescription()), MinecraftServer.getServer().getPort()); + return String.format(LAN_PING_FORMAT, SECTION.serialize(data.getDescription()), data.getMinecraftServer().process().getServer().getPort()); } /** diff --git a/src/main/java/net/minestom/server/registry/Registry.java b/src/main/java/net/minestom/server/registry/Registry.java index e343c512a3f..f048dac6578 100644 --- a/src/main/java/net/minestom/server/registry/Registry.java +++ b/src/main/java/net/minestom/server/registry/Registry.java @@ -2,7 +2,6 @@ import com.google.gson.ToNumberPolicy; import com.google.gson.stream.JsonReader; -import net.minestom.server.MinecraftServer; import net.minestom.server.collision.BoundingBox; import net.minestom.server.collision.CollisionUtils; import net.minestom.server.collision.Shape; @@ -69,7 +68,7 @@ public static Map> load(Resource resource) { reader.endObject(); } } catch (IOException e) { - MinecraftServer.getExceptionManager().handleException(e); + throw new RuntimeException(e); } return map; } diff --git a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java index b5817c96772..682807f224d 100644 --- a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java +++ b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java @@ -1,6 +1,7 @@ package net.minestom.server.scoreboard; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket; import org.jetbrains.annotations.NotNull; @@ -21,6 +22,7 @@ public class BelowNameTag implements Scoreboard { private final Set viewers = new CopyOnWriteArraySet<>(); private final Set unmodifiableViewers = Collections.unmodifiableSet(viewers); + private final MinecraftServer minecraftServer; private final String objectiveName; private final ScoreboardObjectivePacket scoreboardObjectivePacket; @@ -30,11 +32,11 @@ public class BelowNameTag implements Scoreboard { * * @param name The objective name of the scoreboard * @param value The value of the scoreboard - * @deprecated Use {@link #BelowNameTag(String, Component)} + * @deprecated Use {@link #BelowNameTag(MinecraftServer, String, Component)} */ @Deprecated - public BelowNameTag(String name, String value) { - this(name, Component.text(value)); + public BelowNameTag(MinecraftServer minecraftServer, String name, String value) { + this(minecraftServer, name, Component.text(value)); } /** @@ -43,7 +45,8 @@ public BelowNameTag(String name, String value) { * @param name The objective name of the scoreboard * @param value The value of the scoreboard */ - public BelowNameTag(String name, Component value) { + public BelowNameTag(MinecraftServer minecraftServer, String name, Component value) { + this.minecraftServer = minecraftServer; this.objectiveName = BELOW_NAME_TAG_PREFIX + name; this.scoreboardObjectivePacket = this.getCreationObjectivePacket(value, ScoreboardObjectivePacket.Type.INTEGER); } @@ -79,4 +82,9 @@ public boolean removeViewer(@NotNull Player player) { public Set getViewers() { return unmodifiableViewers; } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/scoreboard/Sidebar.java b/src/main/java/net/minestom/server/scoreboard/Sidebar.java index 73adccbd40f..c4eaaa250c4 100644 --- a/src/main/java/net/minestom/server/scoreboard/Sidebar.java +++ b/src/main/java/net/minestom/server/scoreboard/Sidebar.java @@ -3,6 +3,7 @@ import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.server.play.*; @@ -48,17 +49,18 @@ public class Sidebar implements Scoreboard { private final String objectiveName; + private final MinecraftServer minecraftServer; private Component title; /** * Creates a new sidebar * * @param title The title of the sidebar - * @deprecated Use {@link #Sidebar(Component)} + * @deprecated Use {@link #Sidebar(MinecraftServer, Component)} */ @Deprecated - public Sidebar(@NotNull String title) { - this(Component.text(title)); + public Sidebar(MinecraftServer minecraftServer, @NotNull String title) { + this(minecraftServer, Component.text(title)); } /** @@ -66,7 +68,8 @@ public Sidebar(@NotNull String title) { * * @param title The title of the sidebar */ - public Sidebar(@NotNull Component title) { + public Sidebar(MinecraftServer minecraftServer, @NotNull Component title) { + this.minecraftServer = minecraftServer; this.title = title; this.objectiveName = SCOREBOARD_PREFIX + COUNTER.incrementAndGet(); @@ -241,6 +244,11 @@ public Set getViewers() { return this.objectiveName; } + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } + /** * This class is used to create a line for the sidebar. */ diff --git a/src/main/java/net/minestom/server/scoreboard/TabList.java b/src/main/java/net/minestom/server/scoreboard/TabList.java index e2f8dfbd8fa..9c1246082dd 100644 --- a/src/main/java/net/minestom/server/scoreboard/TabList.java +++ b/src/main/java/net/minestom/server/scoreboard/TabList.java @@ -1,6 +1,7 @@ package net.minestom.server.scoreboard; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.PlayerListHeaderAndFooterPacket; import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket; @@ -26,6 +27,7 @@ public class TabList implements Scoreboard { private final Set viewers = new CopyOnWriteArraySet<>(); private final Set unmodifiableViewers = Collections.unmodifiableSet(viewers); + private final MinecraftServer minecraftServer; private final String objectiveName; private Component header = Component.empty(); @@ -33,7 +35,8 @@ public class TabList implements Scoreboard { private ScoreboardObjectivePacket.Type type; - public TabList(String name, ScoreboardObjectivePacket.Type type) { + public TabList(MinecraftServer minecraftServer, String name, ScoreboardObjectivePacket.Type type) { + this.minecraftServer = minecraftServer; this.objectiveName = TAB_LIST_PREFIX + name; this.type = type; @@ -97,4 +100,9 @@ public Set getViewers() { public String getObjectiveName() { return this.objectiveName; } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/scoreboard/Team.java b/src/main/java/net/minestom/server/scoreboard/Team.java index 3084820c091..a20d48eada4 100644 --- a/src/main/java/net/minestom/server/scoreboard/Team.java +++ b/src/main/java/net/minestom/server/scoreboard/Team.java @@ -75,12 +75,15 @@ public class Team implements PacketGroupingAudience { // Adventure private final Pointers pointers; + private final MinecraftServer minecraftServer; + /** * Default constructor to creates a team. * * @param teamName The registry name for the team */ - protected Team(@NotNull String teamName) { + protected Team(MinecraftServer minecraftServer, @NotNull String teamName) { + this.minecraftServer = minecraftServer; this.teamName = teamName; this.teamDisplayName = Component.empty(); @@ -128,7 +131,7 @@ public void addMembers(@NotNull Collection<@NotNull String> toAdd) { final TeamsPacket addPlayerPacket = new TeamsPacket(teamName, new TeamsPacket.AddEntitiesToTeamAction(toAdd)); // Sends to all online players the add player packet - PacketUtils.broadcastPlayPacket(addPlayerPacket); + PacketUtils.broadcastPlayPacket(minecraftServer, addPlayerPacket); // invalidate player members this.isPlayerMembersUpToDate = false; @@ -159,7 +162,7 @@ public void removeMembers(@NotNull Collection<@NotNull String> toRemove) { final TeamsPacket removePlayerPacket = new TeamsPacket(teamName, new TeamsPacket.RemoveEntitiesToTeamAction(toRemove)); // Sends to all online player the remove player packet - PacketUtils.broadcastPlayPacket(removePlayerPacket); + PacketUtils.broadcastPlayPacket(minecraftServer, removePlayerPacket); // Removes the member from the team this.members.removeAll(toRemove); @@ -463,7 +466,7 @@ public Component getSuffix() { public void sendUpdatePacket() { final var info = new TeamsPacket.UpdateTeamAction(teamDisplayName, friendlyFlags, nameTagVisibility, collisionRule, teamColor, prefix, suffix); - PacketUtils.broadcastPlayPacket(new TeamsPacket(teamName, info)); + PacketUtils.broadcastPlayPacket(minecraftServer, new TeamsPacket(teamName, info)); } @Override @@ -472,7 +475,7 @@ public void sendUpdatePacket() { this.playerMembers.clear(); for (String member : this.members) { - Player player = MinecraftServer.getConnectionManager().getOnlinePlayerByUsername(member); + Player player = minecraftServer.process().getConnectionManager().getOnlinePlayerByUsername(member); if (player != null) { this.playerMembers.add(player); @@ -489,4 +492,9 @@ public void sendUpdatePacket() { public @NotNull Pointers pointers() { return this.pointers; } + + @Override + public MinecraftServer getMinecraftServer() { + return minecraftServer; + } } diff --git a/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java b/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java index c82edba2df0..ab9ed47ddb0 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.packet.server.play.TeamsPacket.CollisionRule; import net.minestom.server.network.packet.server.play.TeamsPacket.NameTagVisibility; @@ -29,8 +30,8 @@ public class TeamBuilder { * @param name The name of the new team * @param teamManager The manager for the team */ - public TeamBuilder(String name, TeamManager teamManager) { - this(teamManager.exists(name) ? teamManager.getTeam(name) : new Team(name), teamManager); + public TeamBuilder(MinecraftServer minecraftServer, String name, TeamManager teamManager) { + this(teamManager.exists(name) ? teamManager.getTeam(name) : new Team(minecraftServer, name), teamManager); } /** diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManager.java b/src/main/java/net/minestom/server/scoreboard/TeamManager.java index 8eb2a2399b7..7db8303f397 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamManager.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamManager.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.LivingEntity; import net.minestom.server.entity.Player; import net.minestom.server.utils.PacketUtils; @@ -22,11 +23,13 @@ public final class TeamManager { * Represents all registered teams */ private final Set teams; + private final MinecraftServer minecraftServer; /** * Default constructor */ - public TeamManager() { + public TeamManager(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; this.teams = new CopyOnWriteArraySet<>(); } @@ -37,7 +40,7 @@ public TeamManager() { */ protected void registerNewTeam(@NotNull Team team) { this.teams.add(team); - PacketUtils.broadcastPlayPacket(team.createTeamsCreationPacket()); + PacketUtils.broadcastPlayPacket(minecraftServer, team.createTeamsCreationPacket()); } /** @@ -60,7 +63,7 @@ public boolean deleteTeam(@NotNull String registryName) { */ public boolean deleteTeam(@NotNull Team team) { // Sends to all online players a team destroy packet - PacketUtils.broadcastPlayPacket(team.createTeamDestructionPacket()); + PacketUtils.broadcastPlayPacket(minecraftServer, team.createTeamDestructionPacket()); return this.teams.remove(team); } @@ -71,7 +74,7 @@ public boolean deleteTeam(@NotNull Team team) { * @return the team builder */ public TeamBuilder createBuilder(@NotNull String name) { - return new TeamBuilder(name, this); + return new TeamBuilder(minecraftServer, name, this); } /** diff --git a/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java b/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java index 3c1dac2ce86..49bd20f4794 100644 --- a/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java +++ b/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java @@ -21,7 +21,7 @@ public sealed interface ServerSnapshot extends Snapshot @UnknownNullability EntitySnapshot entity(int id); @ApiStatus.Experimental - static ServerSnapshot update() { - return SnapshotUpdater.update(MinecraftServer.process()); + static ServerSnapshot update(MinecraftServer minecraftServer) { + return SnapshotUpdater.update(minecraftServer.process()); } } diff --git a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java index 9d1e01ea833..3592e350d36 100644 --- a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java +++ b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java @@ -75,7 +75,8 @@ public record Instance(AtomicReference serverRef, } } - public record Chunk(int minSection, int chunkX, int chunkZ, + public record Chunk(MinecraftServer minecraftServer, + int minSection, int chunkX, int chunkZ, Section[] sections, Int2ObjectOpenHashMap blockEntries, int[] entitiesIds, @@ -103,7 +104,7 @@ public record Chunk(int minSection, int chunkX, int chunkZ, final Section section = sections[getChunkCoordinate(y) - minSection]; final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return MinecraftServer.getBiomeManager().getById(id); + return minecraftServer.process().getBiomeManager().getById(id); } @Override diff --git a/src/main/java/net/minestom/server/thread/Acquirable.java b/src/main/java/net/minestom/server/thread/Acquirable.java index 4730006416b..2cd0a077b7f 100644 --- a/src/main/java/net/minestom/server/thread/Acquirable.java +++ b/src/main/java/net/minestom/server/thread/Acquirable.java @@ -1,5 +1,6 @@ package net.minestom.server.thread; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Entity; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.ApiStatus; @@ -112,9 +113,9 @@ default void sync(@NotNull Consumer consumer) { * @param consumer the callback to execute once the element has been safely acquired * @see #sync(Consumer) */ - default void async(@NotNull Consumer consumer) { + default void async(MinecraftServer minecraftServer, @NotNull Consumer consumer) { // TODO per-thread list - AsyncUtils.runAsync(() -> sync(consumer)); + AsyncUtils.runAsync(minecraftServer, () -> sync(consumer)); } /** diff --git a/src/main/java/net/minestom/server/thread/AcquirableCollection.java b/src/main/java/net/minestom/server/thread/AcquirableCollection.java index cf8541b28bf..db1946d2dc1 100644 --- a/src/main/java/net/minestom/server/thread/AcquirableCollection.java +++ b/src/main/java/net/minestom/server/thread/AcquirableCollection.java @@ -1,5 +1,6 @@ package net.minestom.server.thread; +import net.minestom.server.MinecraftServer; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -35,8 +36,8 @@ public void acquireSync(@NotNull Consumer consumer) { } } - public void acquireAsync(@NotNull Consumer consumer) { - AsyncUtils.runAsync(() -> acquireSync(consumer)); + public void acquireAsync(MinecraftServer minecraftServer, @NotNull Consumer consumer) { + AsyncUtils.runAsync(minecraftServer, () -> acquireSync(consumer)); } public @NotNull Stream unwrap() { diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java index 6c073eca691..fb35ea87c6c 100644 --- a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java @@ -1,5 +1,6 @@ package net.minestom.server.thread; +import net.minestom.server.MinecraftServer; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; import org.jctools.queues.MessagePassingQueue; @@ -30,20 +31,20 @@ public final class ThreadDispatcher

{ // Requests consumed at the end of each tick private final MessagePassingQueue> updates = new MpscUnboundedArrayQueue<>(1024); - private ThreadDispatcher(ThreadProvider

provider, int threadCount) { + private ThreadDispatcher(MinecraftServer minecraftServer, ThreadProvider

provider, int threadCount) { this.provider = provider; TickThread[] threads = new TickThread[threadCount]; - Arrays.setAll(threads, TickThread::new); + Arrays.setAll(threads, (i) -> new TickThread(minecraftServer, i)); this.threads = List.of(threads); this.threads.forEach(Thread::start); } - public static

@NotNull ThreadDispatcher

of(@NotNull ThreadProvider

provider, int threadCount) { - return new ThreadDispatcher<>(provider, threadCount); + public static

@NotNull ThreadDispatcher

of(MinecraftServer minecraftServer,@NotNull ThreadProvider

provider, int threadCount) { + return new ThreadDispatcher<>(minecraftServer, provider, threadCount); } - public static

@NotNull ThreadDispatcher

singleThread() { - return of(ThreadProvider.counter(), 1); + public static

@NotNull ThreadDispatcher

singleThread(MinecraftServer minecraftServer) { + return of(minecraftServer, ThreadProvider.counter(), 1); } @Unmodifiable diff --git a/src/main/java/net/minestom/server/thread/TickThread.java b/src/main/java/net/minestom/server/thread/TickThread.java index 27d6db51d86..1316d8a9b87 100644 --- a/src/main/java/net/minestom/server/thread/TickThread.java +++ b/src/main/java/net/minestom/server/thread/TickThread.java @@ -23,6 +23,7 @@ @ApiStatus.Internal public final class TickThread extends MinestomThread { private final ReentrantLock lock = new ReentrantLock(); + private final MinecraftServer minecraftServer; private volatile boolean stop; private CountDownLatch latch; @@ -30,8 +31,9 @@ public final class TickThread extends MinestomThread { private long tickNum = 0; private final List entries = new ArrayList<>(); - public TickThread(int number) { + public TickThread(MinecraftServer minecraftServer, int number) { super(MinecraftServer.THREAD_NAME_TICK + "-" + number); + this.minecraftServer = minecraftServer; } public static @Nullable TickThread current() { @@ -48,7 +50,7 @@ public void run() { try { tick(); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } this.lock.unlock(); // #acquire() callbacks @@ -73,7 +75,7 @@ private void tick() { try { element.tick(tickTime); } catch (Throwable e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } } } diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index f5e8c256fb7..46c6adcca21 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -77,16 +77,16 @@ private PacketUtils() { * @param packet the packet */ @SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience - public static void sendPacket(@NotNull Audience audience, @NotNull ServerPacket packet) { + public static void sendPacket(MinecraftServer minecraftServer, @NotNull Audience audience, @NotNull ServerPacket packet) { if (audience instanceof Player player) { player.sendPacket(packet); } else if (audience instanceof PacketGroupingAudience groupingAudience) { - PacketUtils.sendGroupedPacket(groupingAudience.getPlayers(), packet); + PacketUtils.sendGroupedPacket(minecraftServer, groupingAudience.getPlayers(), packet); } else if (audience instanceof ForwardingAudience.Single singleAudience) { - PacketUtils.sendPacket(singleAudience.audience(), packet); + PacketUtils.sendPacket(minecraftServer, singleAudience.audience(), packet); } else if (audience instanceof ForwardingAudience forwardingAudience) { for (Audience member : forwardingAudience.audiences()) { - PacketUtils.sendPacket(member, packet); + PacketUtils.sendPacket(minecraftServer, member, packet); } } } @@ -100,9 +100,9 @@ public static void sendPacket(@NotNull Audience audience, @NotNull ServerPacket * @param packet the packet to send to the players * @param predicate predicate to ignore specific players */ - public static void sendGroupedPacket(@NotNull Collection players, @NotNull ServerPacket packet, + public static void sendGroupedPacket(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull ServerPacket packet, @NotNull Predicate predicate) { - final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(packet) : packet; + final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(minecraftServer, packet) : packet; players.forEach(player -> { if (predicate.test(player)) player.sendPacket(sendablePacket); @@ -149,16 +149,16 @@ private static boolean isTranslatable(final @NotNull Component component) { * * @see #sendGroupedPacket(Collection, ServerPacket, Predicate) */ - public static void sendGroupedPacket(@NotNull Collection players, @NotNull ServerPacket packet) { - sendGroupedPacket(players, packet, player -> true); + public static void sendGroupedPacket(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull ServerPacket packet) { + sendGroupedPacket(minecraftServer, players, packet, player -> true); } - public static void broadcastPlayPacket(@NotNull ServerPacket packet) { - sendGroupedPacket(MinecraftServer.getConnectionManager().getOnlinePlayers(), packet); + public static void broadcastPlayPacket(MinecraftServer minecraftServer, @NotNull ServerPacket packet) { + sendGroupedPacket(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers(), packet); } @ApiStatus.Experimental - public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull ServerPacket serverPacket, + public static void prepareViewablePacket(MinecraftServer minecraftServer, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket, @Nullable Entity entity) { if (entity != null && !entity.hasPredictableViewers()) { // Operation cannot be optimized @@ -166,17 +166,17 @@ public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull Se return; } if (!VIEWABLE_PACKET) { - sendGroupedPacket(viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); + sendGroupedPacket(minecraftServer, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); return; } final Player exception = entity instanceof Player ? (Player) entity : null; ViewableStorage storage = VIEWABLE_STORAGE_MAP.get(viewable, (unused) -> new ViewableStorage()); - storage.append(viewable, serverPacket, exception); + storage.append(minecraftServer, viewable, serverPacket, exception); } @ApiStatus.Experimental - public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { - prepareViewablePacket(viewable, serverPacket, null); + public static void prepareViewablePacket(MinecraftServer minecraftServer, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { + prepareViewablePacket(minecraftServer, viewable, serverPacket, null); } @ApiStatus.Internal @@ -244,12 +244,13 @@ public static void flush() { return remaining; } - public static void writeFramedPacket(@NotNull ConnectionState state, + public static void writeFramedPacket(MinecraftServer minecraftServer, + @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { writeFramedPacket(buffer, packet.getId(state), packet, - compression ? MinecraftServer.getCompressionThreshold() : 0); + compression ? minecraftServer.getCompressionThreshold() : 0); } public static void writeFramedPacket(@NotNull ByteBuffer buffer, @@ -297,20 +298,20 @@ public static void writeFramedPacket(@NotNull ByteBuffer buffer, } @ApiStatus.Internal - public static ByteBuffer createFramedPacket(@NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { - writeFramedPacket(state, buffer, packet, compression); + public static ByteBuffer createFramedPacket(MinecraftServer minecraftServer, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { + writeFramedPacket(minecraftServer, state, buffer, packet, compression); return buffer.flip(); } @ApiStatus.Internal - public static ByteBuffer createFramedPacket(@NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet) { - return createFramedPacket(state, buffer, packet, MinecraftServer.getCompressionThreshold() > 0); + public static ByteBuffer createFramedPacket(MinecraftServer minecraftServer, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet) { + return createFramedPacket(minecraftServer, state, buffer, packet, minecraftServer.getCompressionThreshold() > 0); } @ApiStatus.Internal - public static FramedPacket allocateTrimmedPacket(@NotNull ConnectionState state, @NotNull ServerPacket packet) { + public static FramedPacket allocateTrimmedPacket(MinecraftServer minecraftServer, @NotNull ConnectionState state, @NotNull ServerPacket packet) { try (var hold = ObjectPool.PACKET_POOL.hold()) { - final ByteBuffer temp = PacketUtils.createFramedPacket(state, hold.get(), packet); + final ByteBuffer temp = PacketUtils.createFramedPacket(minecraftServer, state, hold.get(), packet); final int size = temp.remaining(); final ByteBuffer buffer = ByteBuffer.allocateDirect(size).put(0, temp, 0, size); return new FramedPacket(packet, buffer); @@ -322,10 +323,10 @@ private static final class ViewableStorage { private final Int2ObjectMap entityIdMap = new Int2ObjectOpenHashMap<>(); private final BinaryBuffer buffer = ObjectPool.BUFFER_POOL.getAndRegister(this); - private synchronized void append(Viewable viewable, ServerPacket serverPacket, @Nullable Player exception) { + private synchronized void append(MinecraftServer minecraftServer, Viewable viewable, ServerPacket serverPacket, @Nullable Player exception) { try (var hold = ObjectPool.PACKET_POOL.hold()) { // Viewable storage is only used for play packets, so fine to assume this. - final ByteBuffer framedPacket = createFramedPacket(ConnectionState.PLAY, hold.get(), serverPacket); + final ByteBuffer framedPacket = createFramedPacket(minecraftServer, ConnectionState.PLAY, hold.get(), serverPacket); final int packetSize = framedPacket.limit(); if (packetSize >= buffer.capacity()) { process(viewable); diff --git a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java index b3619b1ccc7..2d7e5933627 100644 --- a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java +++ b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java @@ -15,12 +15,12 @@ public static CompletableFuture empty() { return (CompletableFuture) VOID_FUTURE; } - public static @NotNull CompletableFuture runAsync(@NotNull Runnable runnable) { + public static @NotNull CompletableFuture runAsync(MinecraftServer minecraftServer, @NotNull Runnable runnable) { return CompletableFuture.runAsync(() -> { try { runnable.run(); } catch (Exception e) { - MinecraftServer.getExceptionManager().handleException(e); + minecraftServer.process().getExceptionManager().handleException(e); } }); } diff --git a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java index 6df9b4fc0de..cf9fec518c4 100644 --- a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java +++ b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.objects.Object2BooleanMaps; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -11,8 +10,6 @@ import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; import net.minestom.server.instance.Instance; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.math.IntRange; import net.minestom.server.utils.validate.Check; @@ -29,7 +26,6 @@ * It is based on the target selectors used in commands. */ public class EntityFinder { - private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); private TargetSelector targetSelector; @@ -131,7 +127,7 @@ public EntityFinder setDifference(float dx, float dy, float dz) { public @NotNull List<@NotNull Entity> find(@Nullable Instance instance, @Nullable Entity self) { if (targetSelector == TargetSelector.MINESTOM_USERNAME) { Check.notNull(constantName, "The player name should not be null when searching for it"); - final Player player = MinecraftServer.getConnectionManager().getOnlinePlayerByUsername(constantName); + final Player player = instance.minecraftServer.process().getConnectionManager().getOnlinePlayerByUsername(constantName); return player != null ? List.of(player) : List.of(); } else if (targetSelector == TargetSelector.MINESTOM_UUID) { Check.notNull(constantUuid, "The UUID should not be null when searching for it"); @@ -310,7 +306,7 @@ private static class ToggleableMap extends Object2BooleanOpenHashMap { private static @NotNull List<@NotNull Entity> findTarget(@Nullable Instance instance, @NotNull TargetSelector targetSelector, @NotNull Point startPosition, @Nullable Entity self) { - final var players = instance != null ? instance.getPlayers() : CONNECTION_MANAGER.getOnlinePlayers(); + final var players = instance != null ? instance.getPlayers() : instance.minecraftServer.process().getConnectionManager().getOnlinePlayers(); if (targetSelector == TargetSelector.NEAREST_PLAYER) { return players.stream() .min(Comparator.comparingDouble(p -> p.getPosition().distanceSquared(startPosition))) @@ -326,7 +322,7 @@ private static class ToggleableMap extends Object2BooleanOpenHashMap { return List.copyOf(instance.getEntities()); } // Get entities from every instance - var instances = MinecraftServer.getInstanceManager().getInstances(); + var instances = instance.minecraftServer.process().getInstanceManager().getInstances(); List entities = new ArrayList<>(); for (Instance inst : instances) { entities.addAll(inst.getEntities()); diff --git a/src/main/java/net/minestom/server/utils/mojang/MojangUtils.java b/src/main/java/net/minestom/server/utils/mojang/MojangUtils.java index f99a65f2ca2..3249c558ce8 100644 --- a/src/main/java/net/minestom/server/utils/mojang/MojangUtils.java +++ b/src/main/java/net/minestom/server/utils/mojang/MojangUtils.java @@ -4,7 +4,6 @@ import com.github.benmanes.caffeine.cache.Caffeine; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import net.minestom.server.MinecraftServer; import net.minestom.server.utils.url.URLUtils; import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; @@ -51,7 +50,6 @@ public final class MojangUtils { } return jsonObject; } catch (IOException e) { - MinecraftServer.getExceptionManager().handleException(e); throw new RuntimeException(e); } }); From c6e3815b9abe649027a1e813447bf1ec4b8b8b68 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Mon, 29 Jan 2024 18:29:51 +0300 Subject: [PATCH 05/16] and more... --- .../java/net/minestom/server/event/Event.java | 2 - .../server/event/trait/CancellableEvent.java | 2 - .../minestom/server/inventory/Inventory.java | 2 +- .../minestom/server/scoreboard/Sidebar.java | 2 +- .../minestom/server/thread/Acquirable.java | 2 +- .../minestom/server/utils/PacketUtils.java | 12 +- .../EntityBlockPhysicsIntegrationTest.java | 130 +++++++++--------- .../EntityBlockTouchTickIntegrationTest.java | 12 +- ...ityProjectileCollisionIntegrationTest.java | 30 ++-- .../PlacementCollisionIntegrationTest.java | 11 +- .../minestom/server/command/ArgumentTest.java | 12 +- .../server/command/ArgumentTypeTest.java | 22 +-- .../server/command/CommandConditionTest.java | 15 +- .../server/command/CommandManagerTest.java | 14 +- .../command/CommandPacketFilteringTest.java | 4 +- .../server/command/CommandParseTest.java | 4 +- .../server/command/CommandSenderTest.java | 9 +- .../command/CommandSyntaxMultiTest.java | 8 +- .../command/CommandSyntaxSingleTest.java | 7 +- .../minestom/server/command/CommandTest.java | 4 +- .../server/command/SubcommandTest.java | 7 +- .../EntityBoundingBoxIntegrationTest.java | 8 +- .../entity/EntityInstanceIntegrationTest.java | 4 +- .../EntityLineOfSightIntegrationTest.java | 34 ++--- .../entity/EntityMetaIntegrationTest.java | 6 +- .../EntityProjectileIntegrationTest.java | 10 +- .../entity/EntityRemovalIntegrationTest.java | 19 +-- .../entity/EntityTeleportIntegrationTest.java | 8 +- .../entity/EntityVelocityIntegrationTest.java | 14 +- .../EntityViewDirectionIntegrationTest.java | 14 +- .../entity/EntityViewIntegrationTest.java | 14 +- .../entity/PassengerIntegrationTest.java | 10 +- .../entity/ai/ClosestEntityTargetTest.java | 14 +- .../player/PlayerMovementIntegrationTest.java | 3 +- .../PlayerRespawnChunkIntegrationTest.java | 5 +- .../server/event/EventNodeGraphTest.java | 22 +-- .../server/event/EventNodeMapTest.java | 20 ++- .../server/event/EventNodeQueryTest.java | 32 +++-- .../minestom/server/event/EventNodeTest.java | 37 +++-- .../instance/AnvilLoaderIntegrationTest.java | 4 +- .../instance/ChunkViewerIntegrationTest.java | 3 +- .../EntityTrackerIntegrationTest.java | 16 +-- .../server/instance/EntityTrackerTest.java | 45 +++--- .../server/instance/GeneratorTest.java | 59 +++++--- .../instance/InstanceContainerTest.java | 4 +- .../InstanceUnregisterIntegrationTest.java | 2 +- .../server/instance/light/BlockLightTest.java | 31 +++-- .../light/LightParityIntegrationTest.java | 13 +- .../palette/PaletteOptimizationTest.java | 17 ++- .../server/instance/palette/PaletteTest.java | 70 ++++++---- .../inventory/InventoryCloseStateTest.java | 2 +- .../inventory/InventoryIntegrationTest.java | 16 +-- .../server/inventory/InventoryTest.java | 14 +- .../integration/HeldClickIntegrationTest.java | 2 +- .../integration/LeftClickIntegrationTest.java | 2 +- .../RightClickIntegrationTest.java | 2 +- .../server/network/SendablePacketTest.java | 6 +- .../server/network/SocketWriteTest.java | 20 ++- .../network/socket/ServerAddressTest.java | 13 +- .../server/permission/TestPermissions.java | 6 +- .../ChunkSnapshotIntegrationTest.java | 4 +- .../EntitySnapshotIntegrationTest.java | 8 +- .../InstanceSnapshotIntegrationTest.java | 2 +- .../server/thread/AcquirableTest.java | 6 +- .../server/thread/ThreadDispatcherTest.java | 15 +- .../utils/TranslationIntegrationTest.java | 8 +- .../main/java/net/minestom/testing/Env.java | 2 + .../java/net/minestom/testing/EnvImpl.java | 12 +- .../java/net/minestom/testing/EnvTest.java | 3 +- .../minestom/testing/TestConnectionImpl.java | 8 +- .../net/minestom/testing/TestPlayerImpl.java | 2 +- 71 files changed, 576 insertions(+), 426 deletions(-) diff --git a/src/main/java/net/minestom/server/event/Event.java b/src/main/java/net/minestom/server/event/Event.java index a41a182868a..34b257f71b6 100644 --- a/src/main/java/net/minestom/server/event/Event.java +++ b/src/main/java/net/minestom/server/event/Event.java @@ -2,8 +2,6 @@ /** * Event which can be listened to by an {@link EventNode} using {@link EventNode#addListener(EventListener)}. - *

- * Called using {@link EventDispatcher#call(Event)}. */ public interface Event { } diff --git a/src/main/java/net/minestom/server/event/trait/CancellableEvent.java b/src/main/java/net/minestom/server/event/trait/CancellableEvent.java index e75efce9c81..56eeb0148d8 100644 --- a/src/main/java/net/minestom/server/event/trait/CancellableEvent.java +++ b/src/main/java/net/minestom/server/event/trait/CancellableEvent.java @@ -1,11 +1,9 @@ package net.minestom.server.event.trait; import net.minestom.server.event.Event; -import net.minestom.server.event.EventDispatcher; /** * Represents an {@link Event} which can be cancelled. - * Called using {@link EventDispatcher#callCancellable(CancellableEvent, Runnable)}. */ public interface CancellableEvent extends Event { diff --git a/src/main/java/net/minestom/server/inventory/Inventory.java b/src/main/java/net/minestom/server/inventory/Inventory.java index c3c902b1c89..da0a8b373cf 100644 --- a/src/main/java/net/minestom/server/inventory/Inventory.java +++ b/src/main/java/net/minestom/server/inventory/Inventory.java @@ -24,7 +24,7 @@ /** * Represents an inventory which can be viewed by a collection of {@link Player}. *

- * You can create one with {@link Inventory#Inventory(InventoryType, String)} or by making your own subclass. + * You can create one with {@link Inventory#Inventory(MinecraftServer, InventoryType, String)} or by making your own subclass. * It can then be opened using {@link Player#openInventory(Inventory)}. */ public non-sealed class Inventory extends AbstractInventory implements Viewable { diff --git a/src/main/java/net/minestom/server/scoreboard/Sidebar.java b/src/main/java/net/minestom/server/scoreboard/Sidebar.java index c4eaaa250c4..8c2a7558e53 100644 --- a/src/main/java/net/minestom/server/scoreboard/Sidebar.java +++ b/src/main/java/net/minestom/server/scoreboard/Sidebar.java @@ -20,7 +20,7 @@ /** * Represents a sidebar which can contain up to 16 {@link ScoreboardLine}. *

- * In order to use it you need to create a new instance using the constructor {@link #Sidebar(String)} and create new lines + * In order to use it you need to create a new instance using the constructor {@link #Sidebar(MinecraftServer, String)} and create new lines * with {@link #createLine(ScoreboardLine)}. You can then add a {@link Player} to the viewing list using {@link #addViewer(Player)} * and remove him later with {@link #removeViewer(Player)}. *

diff --git a/src/main/java/net/minestom/server/thread/Acquirable.java b/src/main/java/net/minestom/server/thread/Acquirable.java index 2cd0a077b7f..b0b5ad6ca00 100644 --- a/src/main/java/net/minestom/server/thread/Acquirable.java +++ b/src/main/java/net/minestom/server/thread/Acquirable.java @@ -99,7 +99,7 @@ default boolean isLocal() { * Free if the element is already present in the current thread, blocking otherwise. * * @param consumer the callback to execute once the element has been safely acquired - * @see #async(Consumer) + * @see #async(MinecraftServer, Consumer) */ default void sync(@NotNull Consumer consumer) { Acquired acquired = lock(); diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index 46c6adcca21..58b8159eac6 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -19,7 +19,10 @@ import net.minestom.server.entity.Player; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.NetworkBuffer; -import net.minestom.server.network.packet.server.*; +import net.minestom.server.network.packet.server.CachedPacket; +import net.minestom.server.network.packet.server.ComponentHoldingServerPacket; +import net.minestom.server.network.packet.server.FramedPacket; +import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.utils.binary.BinaryBuffer; @@ -64,7 +67,7 @@ private PacketUtils() { *

    *
  1. If {@code audience} is a {@link Player}, send the packet to them.
  2. *
  3. Otherwise, if {@code audience} is a {@link PacketGroupingAudience}, call - * {@link #sendGroupedPacket(Collection, ServerPacket)} on the players that the + * {@link #sendGroupedPacket(MinecraftServer, Collection, ServerPacket)} on the players that the * grouping audience contains.
  4. *
  5. Otherwise, if {@code audience} is a {@link ForwardingAudience.Single}, * call this method on the single audience inside the forwarding audience.
  6. @@ -114,7 +117,6 @@ public static void sendGroupedPacket(MinecraftServer minecraftServer, @NotNull C * Note: {@link ComponentHoldingServerPacket}s are not translated inside a {@link CachedPacket}. * * @see CachedPacket#body(ConnectionState) - * @see PlayerSocketConnection#writePacketSync(SendablePacket, boolean) */ static boolean shouldUseCachePacket(final @NotNull ServerPacket packet) { if (!MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION) return GROUPED_PACKET; @@ -144,10 +146,10 @@ private static boolean isTranslatable(final @NotNull Component component) { } /** - * Same as {@link #sendGroupedPacket(Collection, ServerPacket, Predicate)} + * Same as {@link #sendGroupedPacket(MinecraftServer, Collection, ServerPacket, Predicate)} * but with the player validator sets to null. * - * @see #sendGroupedPacket(Collection, ServerPacket, Predicate) + * @see #sendGroupedPacket(MinecraftServer, Collection, ServerPacket, Predicate) */ public static void sendGroupedPacket(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull ServerPacket packet) { sendGroupedPacket(minecraftServer, players, packet, player -> true); diff --git a/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java index 55dc5ecb27e..eac29525498 100644 --- a/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java @@ -1,7 +1,5 @@ package net.minestom.server.collision; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; @@ -9,6 +7,8 @@ import net.minestom.server.entity.EntityType; import net.minestom.server.entity.metadata.other.SlimeMeta; import net.minestom.server.instance.block.Block; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import java.util.List; @@ -49,7 +49,7 @@ public void entityPhysicsCheckCollision(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 43, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -67,7 +67,7 @@ public void entityPhysicsCheckSlab(Env env) { instance.setBlock(0, 42, 0, Block.STONE_SLAB); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 44, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -80,7 +80,7 @@ public void entityPhysicsCheckShallowAngle(Env env) { var instance = env.createFlatInstance(); instance.setBlock(13, 99, 16, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(12.812, 100.0, 16.498)).join(); PhysicsResult res = CollisionUtils.handlePhysics(entity, new Vec(0.273, -0.0784, 0.0)); @@ -95,7 +95,7 @@ public void entityPhysicsCheckFallFence(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.OAK_FENCE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -114,7 +114,7 @@ public void entityPhysicsCheckFallHitCarpet(Env env) { instance.setBlock(0, 42, 0, Block.OAK_FENCE); instance.setBlock(0, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 54.0625, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -128,7 +128,7 @@ public void entityPhysicsCheckFallHitFence(Env env) { instance.setBlock(0, 42, 0, Block.OAK_FENCE); instance.setBlock(0, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 54.0625, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -141,7 +141,7 @@ public void entityPhysicsCheckHorizontalFence(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 0, Block.OAK_FENCE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.25, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -155,7 +155,7 @@ public void entityPhysicsCheckMultipleBlocksPassFirst(Env env) { instance.setBlock(4, 40, -1, Block.SANDSTONE_STAIRS); instance.setBlock(16, 40, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.0, 40.51, 0.0)).join(); assertEquals(instance, entity.getInstance()); @@ -171,7 +171,7 @@ public void entityPhysicsCheckMultipleBlocksHitFirst(Env env) { instance.loadChunk(0, -1).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.0, 40.51, 0.0)).join(); assertEquals(instance, entity.getInstance()); @@ -186,7 +186,7 @@ public void entityPhysicsCheckHorizontalCarpetedFence(Env env) { instance.setBlock(1, 42, 0, Block.OAK_FENCE); instance.setBlock(1, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.25, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -205,7 +205,7 @@ public void entityPhysicsCheckDiagonalCarpetedFenceX(Env env) { instance.setBlock(1, 42, 0, Block.OAK_FENCE); instance.setBlock(1, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.075, 44.0625, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -224,7 +224,7 @@ public void entityPhysicsCheckDiagonalCarpetedFenceZ(Env env) { instance.setBlock(0, 42, 1, Block.OAK_FENCE); instance.setBlock(0, 43, 1, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 44.0625, 0.075)).join(); assertEquals(instance, entity.getInstance()); @@ -248,7 +248,7 @@ public void entityPhysicsCheckDiagonalCarpetedFenceXZ(Env env) { instance.setBlock(0, 43, 0, Block.BROWN_CARPET); instance.setBlock(-1, 43, 1, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(-0.925, 44.0625, 0.075)).join(); assertEquals(instance, entity.getInstance()); @@ -269,7 +269,7 @@ public void entityPhysicsCheckFallHitFenceLongMove(Env env) { instance.setBlock(0, 42, 0, Block.OAK_FENCE); instance.setBlock(0, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 54.0625, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -283,7 +283,7 @@ public void entityPhysicsCheckFenceAboveHead(Env env) { instance.setBlock(0, 45, 0, Block.OAK_FENCE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.0, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -297,7 +297,7 @@ public void entityPhysicsCheckDiagonal(Env env) { instance.setBlock(1, 43, 1, Block.STONE); instance.setBlock(1, 43, 2, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -313,7 +313,7 @@ public void entityPhysicsCheckDirectSlide(Env env) { instance.setBlock(1, 43, 1, Block.STONE); instance.setBlock(1, 43, 2, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.69, 42, 0.69)).join(); assertEquals(instance, entity.getInstance()); @@ -328,7 +328,7 @@ public void entityPhysicsCheckCorner(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); instance.setBlock(5, 43, -5, Block.STONE); @@ -349,7 +349,7 @@ public void entityPhysicsCheckEnclosedHit(Env env) { instance.setBlock(8, 42, 8, Block.STONE); - var entity = new Entity(EntityType.SLIME); + var entity = new Entity(env.minecraftServer(), EntityType.SLIME); SlimeMeta meta = (SlimeMeta) entity.getEntityMeta(); meta.setSize(20); @@ -371,7 +371,7 @@ public void entityPhysicsCheckEnclosedHitSubBlock(Env env) { instance.setBlock(8, 42, 8, Block.LANTERN); - var entity = new Entity(EntityType.SLIME); + var entity = new Entity(env.minecraftServer(), EntityType.SLIME); SlimeMeta meta = (SlimeMeta) entity.getEntityMeta(); meta.setSize(20); @@ -389,7 +389,7 @@ public void entityPhysicsCheckEnclosedMiss(Env env) { var instance = env.createFlatInstance(); instance.setBlock(11, 43, 11, Block.STONE); - var entity = new Entity(EntityType.SLIME); + var entity = new Entity(env.minecraftServer(), EntityType.SLIME); SlimeMeta meta = (SlimeMeta) entity.getEntityMeta(); meta.setSize(5); @@ -408,7 +408,7 @@ public void entityPhysicsCheckEntityHit(Env env) { Point z3 = new Pos(11, 0, 0); Point movement = new Pos(20, 1, 0); - BoundingBox bb = new Entity(EntityType.ZOMBIE).getBoundingBox(); + BoundingBox bb = new Entity(env.minecraftServer(), EntityType.ZOMBIE).getBoundingBox(); SweepResult sweepResultFinal = new SweepResult(1, 0, 0, 0, null, null); @@ -424,7 +424,7 @@ public void entityPhysicsCheckEdgeClip(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0.7)).join(); assertEquals(instance, entity.getInstance()); @@ -437,7 +437,7 @@ public void entityPhysicsCheckEdgeClipSmall(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.6999, 42, 0.6999)).join(); PhysicsResult res = CollisionUtils.handlePhysics(entity, new Vec(0.702, 0, 0.702)); @@ -453,7 +453,7 @@ public void entityPhysicsCheckDoorSubBlockNorth(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -468,7 +468,7 @@ public void entityPhysicsCheckDoorSubBlockSouth(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -483,7 +483,7 @@ public void entityPhysicsCheckDoorSubBlockWest(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -498,7 +498,7 @@ public void entityPhysicsCheckDoorSubBlockEast(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -513,7 +513,7 @@ public void entityPhysicsCheckDoorSubBlockUp(Env env) { instance.setBlock(0, 44, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.7, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -528,7 +528,7 @@ public void entityPhysicsCheckDoorSubBlockDown(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.2, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -541,7 +541,7 @@ public void entityPhysicsCheckOnGround(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 40, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 50, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -554,7 +554,7 @@ public void entityPhysicsCheckStairTop(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.ACACIA_STAIRS); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.4, 42.5, 0.9)).join(); assertEquals(instance, entity.getInstance()); @@ -567,7 +567,7 @@ public void entityPhysicsCheckStairTopSmall(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.ACACIA_STAIRS); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.4, 42.5, 0.9)).join(); assertEquals(instance, entity.getInstance()); @@ -583,7 +583,7 @@ public void entityPhysicsCheckNotOnGround(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 50, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -596,7 +596,7 @@ public void entityPhysicsCheckNotOnGroundHitUp(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 60, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 50, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -611,7 +611,7 @@ public void entityPhysicsCheckSlide(Env env) { instance.setBlock(1, 43, 2, Block.STONE); instance.setBlock(1, 43, 3, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -624,7 +624,7 @@ public void entityPhysicsSmallMoveCollide(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.6, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -638,7 +638,7 @@ public void entityPhysicsSmallMoveC0(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.7, 42, 0.5)).join(); @@ -653,7 +653,7 @@ public void entityPhysicsSmallMoveC1(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.5, 42, 0.7)).join(); @@ -668,7 +668,7 @@ public void entityPhysicsSmallMoveC2(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.8, 42, 1.3)).join(); @@ -683,7 +683,7 @@ public void entityPhysicsSmallMoveC3(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.7, 42, 1.1)).join(); @@ -698,7 +698,7 @@ public void entityPhysicsSmallMoveC4(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.1, 42, 1.3)).join(); @@ -713,7 +713,7 @@ public void entityPhysicsSmallMoveC5(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.3, 42, 1.1)).join(); @@ -728,7 +728,7 @@ public void entityPhysicsSmallMoveC6(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.1, 42, 0.7)).join(); @@ -743,7 +743,7 @@ public void entityPhysicsSmallMoveC7(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.3, 42, 0.8)).join(); @@ -759,7 +759,7 @@ public void entityPhysicsSmallMoveC0E(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.51, 42.51, 0.5)).join(); @@ -774,7 +774,7 @@ public void entityPhysicsSmallMoveC1E(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 43, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.50, 42.51, 0.51)).join(); @@ -789,7 +789,7 @@ public void entityPhysicsSmallMoveC2E(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 1, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.51, 42.50, 0.51)).join(); @@ -808,7 +808,7 @@ public void entityPhysicsCheckNoCollision(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -822,7 +822,7 @@ public void entityPhysicsCheckBlockMiss(Env env) { instance.setBlock(0, 43, 2, Block.STONE); instance.setBlock(2, 43, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -843,7 +843,7 @@ public void entityPhysicsCheckBlockDirections(Env env) { instance.setBlock(0, 41, 0, Block.STONE); instance.setBlock(0, 44, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -867,7 +867,7 @@ public void entityPhysicsCheckBlockDirections(Env env) { @Test public void entityPhysicsCheckLargeVelocityMiss(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -882,7 +882,7 @@ public void entityPhysicsCheckLargeVelocityMiss(Env env) { @Test public void entityPhysicsCheckLargeVelocityHit(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -899,7 +899,7 @@ public void entityPhysicsCheckLargeVelocityHit(Env env) { @Test public void entityPhysicsCheckNoMove(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(5, 42, 5)).join(); assertEquals(instance, entity.getInstance()); @@ -925,7 +925,7 @@ public void entityPhysicsRepeatedCollision(Env env) { instance.setBlock(0, 43, -1, Block.STONE); instance.setBlock(-1, 43, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.1, 0.5)).join(); PhysicsResult res = CollisionUtils.handlePhysics(entity, new Vec(0, 0, 0)); @@ -943,7 +943,7 @@ public void entityPhysicsRepeatedCollision(Env env) { @Test public void entityPhysicsCheckNoMoveCache(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(5, 42, 5)).join(); assertEquals(instance, entity.getInstance()); @@ -957,7 +957,7 @@ public void entityPhysicsCheckNoMoveCache(Env env) { @Test public void entityPhysicsCheckNoMoveLargeVelocityHit(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -976,7 +976,7 @@ public void entityPhysicsCheckNoMoveLargeVelocityHit(Env env) { @Test public void entityPhysicsCheckLargeVelocityHitNoMove(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -999,7 +999,7 @@ public void entityPhysicsCheckDoorSubBlockSouthRepeat(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -1019,7 +1019,7 @@ public void entityPhysicsCheckCollisionDownCache(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -1039,7 +1039,7 @@ public void entityPhysicsCheckGravityCached(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -1066,7 +1066,7 @@ public void entityBlockPositionTestSlightlyAbove(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 43.00001, 0)); var deltaPos = new Vec(0.0, -10, 0.0); @@ -1081,7 +1081,7 @@ public void entityBlockPositionTestFarAbove(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 43.5, 0)); var deltaPos = new Vec(0.0, -10, 0.0); diff --git a/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java index f5fbb8a9b99..91c3917bfe4 100644 --- a/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java @@ -1,7 +1,5 @@ package net.minestom.server.collision; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; @@ -10,6 +8,8 @@ import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockHandler; import net.minestom.server.utils.NamespaceID; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(1, 42, 0, Block.STONE.withHandler(handler)); instance.setBlock(0, 42, 10, Block.STONE.withHandler(handler)); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0.7)).join(); entity.tick(0); @@ -85,7 +85,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(1001, 42, 1000, Block.STONE.withHandler(handler)); instance.setBlock(1000, 42, 1010, Block.STONE.withHandler(handler)); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(1000, 42, 1000.7)).join(); entity.tick(0); @@ -130,7 +130,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(1001, 42, 1000, Block.STONE.withHandler(handler)); instance.setBlock(1000, 42, 1010, Block.STONE.withHandler(handler)); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(1000.699, 42, 1000)).join(); entity.tick(0); @@ -178,7 +178,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(-1001, 42, -1000, Block.STONE.withHandler(handler)); instance.setBlock(-1000, 42, -1010, Block.STONE.withHandler(handler)); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(-1000.301, 42, -1000)).join(); entity.tick(0); diff --git a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java index ee893bba4cc..34ca2978433 100644 --- a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java @@ -1,8 +1,6 @@ package net.minestom.server.collision; import net.minestom.server.MinecraftServer; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; @@ -17,6 +15,8 @@ import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; import net.minestom.server.utils.time.TimeUnit; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicReference; @@ -31,10 +31,10 @@ public void blockShootAndBlockRemoval(Env env) { final Instance instance = env.createFlatInstance(); instance.getWorldBorder().setDiameter(1000.0); - final Entity shooter = new Entity(EntityType.SKELETON); + final Entity shooter = new Entity(env.minecraftServer(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 40, 0)).join(); - final EntityProjectile projectile = new EntityProjectile(shooter, EntityType.ARROW); + final EntityProjectile projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); projectile.setInstance(instance, shooter.getPosition().withY(y -> y + shooter.getEyeHeight())).join(); final Point blockPosition = new Vec(5, 40, 0); @@ -43,7 +43,7 @@ public void blockShootAndBlockRemoval(Env env) { projectile.shoot(blockPosition, 1, 0); final var eventRef = new AtomicReference(); - MinecraftServer.getGlobalEventHandler().addListener(ProjectileCollideWithBlockEvent.class, eventRef::set); + env.minecraftServer().process().getGlobalEventHandler().addListener(ProjectileCollideWithBlockEvent.class, eventRef::set); final long tick = TimeUnit.SERVER_TICK.getDuration().toMillis(); for (int i = 0; i < MinecraftServer.TICK_PER_SECOND; ++i) { @@ -56,7 +56,7 @@ public void blockShootAndBlockRemoval(Env env) { assertEquals(block, event.getBlock()); final var eventRef2 = new AtomicReference(); - MinecraftServer.getGlobalEventHandler().addListener(ProjectileUncollideEvent.class, eventRef2::set); + env.minecraftServer().process().getGlobalEventHandler().addListener(ProjectileUncollideEvent.class, eventRef2::set); eventRef.set(null); instance.setBlock(blockPosition, Block.AIR); @@ -75,7 +75,7 @@ public void entityShoot(Env env) { final Instance instance = env.createFlatInstance(); instance.getWorldBorder().setDiameter(1000.0); - final Entity shooter = new Entity(EntityType.SKELETON); + final Entity shooter = new Entity(env.minecraftServer(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 40, 0)).join(); for (double dx = 1; dx <= 3; dx += .2) { @@ -88,21 +88,21 @@ private void singleEntityShoot( Entity shooter, final Point targetPosition ) { - final EntityProjectile projectile = new EntityProjectile(shooter, EntityType.ARROW); + final EntityProjectile projectile = new EntityProjectile(shooter.getMinecraftServer(), shooter, EntityType.ARROW); projectile.setInstance(instance, shooter.getPosition().withY(y -> y + shooter.getEyeHeight())).join(); - final LivingEntity target = new LivingEntity(EntityType.RABBIT); + final LivingEntity target = new LivingEntity(shooter.getMinecraftServer(), EntityType.RABBIT); target.setInstance(instance, Pos.fromPoint(targetPosition)).join(); projectile.shoot(targetPosition, 1, 0); final var eventRef = new AtomicReference(); - final var eventNode = EventNode.all("projectile-test"); + final var eventNode = EventNode.all(shooter.getMinecraftServer(), "projectile-test"); eventNode.addListener(ProjectileCollideWithEntityEvent.class, event -> { event.getEntity().remove(); eventRef.set(event); - MinecraftServer.getGlobalEventHandler().removeChild(eventNode); + shooter.getMinecraftServer().process().getGlobalEventHandler().removeChild(eventNode); }); - MinecraftServer.getGlobalEventHandler().addChild(eventNode); + shooter.getMinecraftServer().process().getGlobalEventHandler().addChild(eventNode); final long tick = TimeUnit.SERVER_TICK.getDuration().toMillis(); for (int i = 0; i < MinecraftServer.TICK_PER_SECOND; ++i) { @@ -123,16 +123,16 @@ public void entitySelfShoot(Env env) { final Instance instance = env.createFlatInstance(); instance.getWorldBorder().setDiameter(1000.0); - final LivingEntity shooter = new LivingEntity(EntityType.SKELETON); + final LivingEntity shooter = new LivingEntity(env.minecraftServer(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 40, 0)).join(); - final EntityProjectile projectile = new EntityProjectile(shooter, EntityType.ARROW); + final EntityProjectile projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); projectile.setInstance(instance, shooter.getPosition().withY(y -> y + shooter.getEyeHeight())).join(); projectile.shoot(new Vec(0, 60, 0), 1, 0); final var eventRef = new AtomicReference(); - MinecraftServer.getGlobalEventHandler().addListener(ProjectileCollideWithEntityEvent.class, event -> { + env.minecraftServer().process().getGlobalEventHandler().addListener(ProjectileCollideWithEntityEvent.class, event -> { event.getEntity().remove(); eventRef.set(event); }); diff --git a/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java b/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java index 27a2f36c19f..089049a6f05 100644 --- a/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java @@ -1,15 +1,16 @@ package net.minestom.server.collision; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import net.minestom.server.instance.block.Block; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; @EnvTest public class PlacementCollisionIntegrationTest { @@ -23,14 +24,14 @@ public void empty(Env env) { @Test public void entityBlock(Env env) { var instance = env.createFlatInstance(); - new Entity(EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40, 0)).join(); + new Entity(env.minecraftServer(), EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40, 0)).join(); assertNotNull(BlockCollision.canPlaceBlockAt(instance, new Vec(0, 40, 0), Block.STONE)); } @Test public void slab(Env env) { var instance = env.createFlatInstance(); - new Entity(EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40.75, 0)).join(); + new Entity(env.minecraftServer(), EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40.75, 0)).join(); assertNull(BlockCollision.canPlaceBlockAt(instance, new Vec(0, 40, 0), Block.STONE_SLAB)); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTest.java b/src/test/java/net/minestom/server/command/ArgumentTest.java index f31ba6fb020..fe5fb17e8dd 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTest.java @@ -1,5 +1,6 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -15,8 +16,9 @@ public class ArgumentTest { @Test public void testParseSelf() { - assertEquals("example", Argument.parse(new ServerSender(), ArgumentType.String("example"))); - assertEquals(55, Argument.parse(new ServerSender(), ArgumentType.Integer("55"))); + MinecraftServer minecraftServer = new MinecraftServer(); + assertEquals("example", Argument.parse(new ServerSender(minecraftServer), ArgumentType.String("example"))); + assertEquals(55, Argument.parse(new ServerSender(minecraftServer), ArgumentType.Integer("55"))); } @Test @@ -31,16 +33,18 @@ public void testCallback() { @Test public void testDefaultValue() { + MinecraftServer minecraftServer = new MinecraftServer(); var arg = ArgumentType.String("id"); assertFalse(arg.isOptional()); arg.setDefaultValue("default value"); assertTrue(arg.isOptional()); - assertEquals("default value", arg.getDefaultValue().apply(new ServerSender())); + assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(minecraftServer))); } @Test public void testSuggestionCallback() { + MinecraftServer minecraftServer = new MinecraftServer(); var arg = ArgumentType.String("id"); assertFalse(arg.hasSuggestion()); @@ -49,7 +53,7 @@ public void testSuggestionCallback() { assertTrue(arg.hasSuggestion()); Suggestion suggestion = new Suggestion("input", 2, 4); - arg.getSuggestionCallback().apply(new ServerSender(), new CommandContext("input"), suggestion); + arg.getSuggestionCallback().apply(new ServerSender(minecraftServer), new CommandContext("input"), suggestion); assertEquals(suggestion.getEntries(), List.of(new SuggestionEntry("entry"))); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java index edc08e4f40d..5015cc3e2dd 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java @@ -5,6 +5,7 @@ import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentEnum; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -16,7 +17,6 @@ import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.minestom.server.particle.Particle; -import net.minestom.server.potion.PotionEffect; import net.minestom.server.tag.Tag; import net.minestom.server.utils.location.RelativeVec; import net.minestom.server.utils.math.FloatRange; @@ -376,16 +376,17 @@ enum ExampleEnum {FIRST, SECOND, Third, fourth} @Test public void testArgumentGroup() { + MinecraftServer minecraftServer = new MinecraftServer(); var arg = ArgumentType.Group("group", ArgumentType.Integer("integer"), ArgumentType.String("string"), ArgumentType.Double("double")); // Test normal input - var context1 = arg.parse(new ServerSender(), "1234 1234 1234"); + var context1 = arg.parse(new ServerSender(minecraftServer), "1234 1234 1234"); assertEquals(1234, context1.get("integer")); assertEquals("1234", context1.get("string")); assertEquals(1234.0, context1.get("double")); // Test different input + trailing spaces - var context2 = arg.parse(new ServerSender(), "1234 abcd 1234.5678 "); + var context2 = arg.parse(new ServerSender(minecraftServer), "1234 abcd 1234.5678 "); assertEquals(1234, context2.get("integer")); assertEquals("abcd", context2.get("string")); assertEquals(1234.5678, context2.get("double")); @@ -452,7 +453,8 @@ public void testArgumentWord() { @Test public void testArgumentMapWithSender() { - var serverSender = new ServerSender(); + MinecraftServer minecraftServer = new MinecraftServer(); + var serverSender = new ServerSender(minecraftServer); var arg = ArgumentType.Word("word").from("word1", "word2", "word3") .map((sender, s) -> { @@ -464,18 +466,22 @@ public void testArgumentMapWithSender() { } private static void assertArg(Argument arg, T expected, String input) { - assertEquals(expected, arg.parse(new ServerSender(), input)); + MinecraftServer minecraftServer = new MinecraftServer(); + assertEquals(expected, arg.parse(new ServerSender(minecraftServer), input)); } private static void assertArrayArg(Argument arg, T[] expected, String input) { - assertArrayEquals(expected, arg.parse(new ServerSender(), input)); + MinecraftServer minecraftServer = new MinecraftServer(); + assertArrayEquals(expected, arg.parse(new ServerSender(minecraftServer), input)); } private static void assertValidArg(Argument arg, String input) { - assertDoesNotThrow(() -> arg.parse(new ServerSender(), input)); + MinecraftServer minecraftServer = new MinecraftServer(); + assertDoesNotThrow(() -> arg.parse(new ServerSender(minecraftServer), input)); } private static void assertInvalidArg(Argument arg, String input) { - assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(), input)); + MinecraftServer minecraftServer = new MinecraftServer(); + assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(minecraftServer), input)); } } diff --git a/src/test/java/net/minestom/server/command/CommandConditionTest.java b/src/test/java/net/minestom/server/command/CommandConditionTest.java index f7450b020c9..36fbfb2d629 100644 --- a/src/test/java/net/minestom/server/command/CommandConditionTest.java +++ b/src/test/java/net/minestom/server/command/CommandConditionTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; import net.kyori.adventure.identity.Identity; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.permission.Permission; @@ -17,7 +18,8 @@ public class CommandConditionTest { @Test public void mainCondition() { - var dispatcher = new CommandDispatcher(); + MinecraftServer minecraftServer = new MinecraftServer(); + var dispatcher = new CommandDispatcher(minecraftServer); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -40,7 +42,8 @@ public void mainCondition() { @Test public void subCondition() { - var dispatcher = new CommandDispatcher(); + MinecraftServer minecraftServer = new MinecraftServer(); + var dispatcher = new CommandDispatcher(minecraftServer); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -84,7 +87,8 @@ public void subCondition() { @Test public void subConditionOverride() { - var dispatcher = new CommandDispatcher(); + MinecraftServer minecraftServer = new MinecraftServer(); + var dispatcher = new CommandDispatcher(minecraftServer); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -140,5 +144,10 @@ private static final class Sender implements CommandSender { public @NotNull Identity identity() { return Identity.nil(); } + + @Override + public MinecraftServer getMinecraftServer() { + return null; + } } } diff --git a/src/test/java/net/minestom/server/command/CommandManagerTest.java b/src/test/java/net/minestom/server/command/CommandManagerTest.java index 5d9b24d4afc..ad084bd8434 100644 --- a/src/test/java/net/minestom/server/command/CommandManagerTest.java +++ b/src/test/java/net/minestom/server/command/CommandManagerTest.java @@ -1,10 +1,10 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandResult; import net.minestom.server.command.builder.arguments.ArgumentType; import net.minestom.server.network.packet.server.play.DeclareCommandsPacket; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicBoolean; @@ -15,7 +15,8 @@ public class CommandManagerTest { @Test public void testCommandRegistration() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); var command = new Command("name1", "name2"); @@ -34,7 +35,8 @@ public void testCommandRegistration() { @Test public void testUnknownCommandCallback() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); AtomicBoolean check = new AtomicBoolean(false); manager.setUnknownCommandCallback((sender, command) -> check.set(true)); @@ -50,7 +52,8 @@ public void testUnknownCommandCallback() { @Test public void testSharedArgumentSyntaxABFirst() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); @@ -78,7 +81,8 @@ public void testSharedArgumentSyntaxABFirst() { @Test public void testSharedArgumentSyntaxAFirst() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java index 0ce8a207fba..04e1b8efad4 100644 --- a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java +++ b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java @@ -1,5 +1,6 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentType; import net.minestom.server.entity.Player; @@ -11,7 +12,8 @@ @SuppressWarnings("ConstantConditions") public class CommandPacketFilteringTest { - private static final Player PLAYER = new Player(UUID.randomUUID(), "", null); + private static final MinecraftServer minecraftServer = new MinecraftServer(); + private static final Player PLAYER = new Player(minecraftServer, UUID.randomUUID(), "", null); @Test public void singleCommandFilteredFalse() { diff --git a/src/test/java/net/minestom/server/command/CommandParseTest.java b/src/test/java/net/minestom/server/command/CommandParseTest.java index 5f2a03b5ee1..5bda34def5a 100644 --- a/src/test/java/net/minestom/server/command/CommandParseTest.java +++ b/src/test/java/net/minestom/server/command/CommandParseTest.java @@ -1,5 +1,6 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.arguments.ArgumentType; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -143,7 +144,8 @@ private static void assertValid(Graph graph, String input, AtomicBoolean executo } private static CommandParser.Result parseCommand(Graph graph, String input) { - return CommandParser.parser().parse(new ServerSender(), graph, input); + MinecraftServer minecraftServer = new MinecraftServer(); + return CommandParser.parser().parse(new ServerSender(minecraftServer), graph, input); } @NotNull diff --git a/src/test/java/net/minestom/server/command/CommandSenderTest.java b/src/test/java/net/minestom/server/command/CommandSenderTest.java index fe2b5186f3b..7f579a901b1 100644 --- a/src/test/java/net/minestom/server/command/CommandSenderTest.java +++ b/src/test/java/net/minestom/server/command/CommandSenderTest.java @@ -4,6 +4,7 @@ import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.MinecraftServer; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -14,7 +15,8 @@ import java.util.HashSet; import java.util.Set; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class CommandSenderTest { @@ -81,5 +83,10 @@ public void sendMessage(@NotNull Identity source, @NotNull Component message, @N public @NotNull Identity identity() { return Identity.nil(); } + + @Override + public MinecraftServer getMinecraftServer() { + return null; + } } } diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java index ca0fec6265f..b7ff0ae8d20 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java @@ -1,17 +1,14 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.Argument; import org.junit.jupiter.api.Test; -import java.lang.String; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import static net.minestom.server.command.builder.arguments.ArgumentType.Float; -import static net.minestom.server.command.builder.arguments.ArgumentType.Integer; import static net.minestom.server.command.builder.arguments.ArgumentType.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @@ -48,9 +45,10 @@ public void similarArgs() { } private static void assertSyntax(List>> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { + MinecraftServer minecraftServer = new MinecraftServer(); final String commandName = "name"; - var manager = new CommandManager(); + var manager = new CommandManager(minecraftServer); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java index 381eb2c0c3b..ed2550d23cd 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java @@ -1,5 +1,6 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.Argument; @@ -7,13 +8,10 @@ import net.minestom.server.item.Enchantment; import org.junit.jupiter.api.Test; -import java.lang.String; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import static net.minestom.server.command.builder.arguments.ArgumentType.Integer; -import static net.minestom.server.command.builder.arguments.ArgumentType.String; import static net.minestom.server.command.builder.arguments.ArgumentType.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @@ -149,9 +147,10 @@ public void singleLoopDoubleGroup() { } private static void assertSyntax(List> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { + MinecraftServer minecraftServer = new MinecraftServer(); final String commandName = "name"; - var manager = new CommandManager(); + var manager = new CommandManager(minecraftServer); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandTest.java b/src/test/java/net/minestom/server/command/CommandTest.java index 420530aa47c..d6f674a8d8d 100644 --- a/src/test/java/net/minestom/server/command/CommandTest.java +++ b/src/test/java/net/minestom/server/command/CommandTest.java @@ -1,5 +1,6 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; import org.jetbrains.annotations.NotNull; @@ -28,7 +29,8 @@ public void testNames() { @Test public void testGlobalListener() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); AtomicBoolean hasRun = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/SubcommandTest.java b/src/test/java/net/minestom/server/command/SubcommandTest.java index 6ed762fa232..2139add221b 100644 --- a/src/test/java/net/minestom/server/command/SubcommandTest.java +++ b/src/test/java/net/minestom/server/command/SubcommandTest.java @@ -1,5 +1,6 @@ package net.minestom.server.command; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import org.junit.jupiter.api.Test; @@ -12,7 +13,8 @@ public class SubcommandTest { @Test public void testSubCommands() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); var parent = new Command("parent"); var child = new Command("child"); @@ -34,7 +36,8 @@ public void testSubCommands() { @Test public void testSubCommandConditions() { - var manager = new CommandManager(); + MinecraftServer minecraftServer = new MinecraftServer(); + var manager = new CommandManager(minecraftServer); var parent = new Command("parent"); var child = new Command("child"); diff --git a/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java index dc20cd87d83..22d38f18524 100644 --- a/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java @@ -1,13 +1,13 @@ package net.minestom.server.entity; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.collision.BoundingBox; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.item.PickupItemEvent; import net.minestom.server.instance.Instance; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -58,7 +58,7 @@ public void pickupItem(Env env) { final var instance = env.createFlatInstance(); final var listener = env.listen(PickupItemEvent.class); final var spawnPos = new Pos(0, 42, 0); - final var entity = new LivingEntity(EntityType.ZOMBIE); + final var entity = new LivingEntity(env.minecraftServer(), EntityType.ZOMBIE); entity.setCanPickupItem(true); entity.setInstance(instance, spawnPos).join(); @@ -74,7 +74,7 @@ public void pickupItem(Env env) { } private void dropItem(final Instance instance, final Pos position) { - final var entity = new ItemEntity(ItemStack.of(Material.STONE)); + final var entity = new ItemEntity(instance.getMinecraftServer(), ItemStack.of(Material.STONE)); entity.hasPhysics = false; entity.setNoGravity(true); entity.setInstance(instance, position).join(); diff --git a/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java index 5a9d128ef0d..484bb2b3a47 100644 --- a/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java @@ -1,8 +1,8 @@ package net.minestom.server.entity; +import net.minestom.server.coordinate.Pos; import net.minestom.testing.Env; import net.minestom.testing.EnvTest; -import net.minestom.server.coordinate.Pos; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -16,7 +16,7 @@ public class EntityInstanceIntegrationTest { @Test public void entityJoin(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); assertEquals(new Pos(0, 42, 0), entity.getPosition()); diff --git a/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java index a6bb809294a..4e6c5bf5899 100644 --- a/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java @@ -1,9 +1,9 @@ package net.minestom.server.entity; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.instance.block.Block; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @@ -14,11 +14,11 @@ public class EntityLineOfSightIntegrationTest { public void entityPhysicsCheckLineOfSight(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0)).join(); assertEquals(entity2, entity.getLineOfSightEntity(20, (e) -> true)); @@ -38,11 +38,11 @@ public void entityPhysicsCheckLineOfSight(Env env) { public void entityPhysicsCheckLineOfSightBehind(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(-10, 42, 0)).join(); assertNull(entity.getLineOfSightEntity(20, (e) -> true)); @@ -62,11 +62,11 @@ public void entityPhysicsCheckLineOfSightBehind(Env env) { public void entityPhysicsCheckLineOfSightNearMiss(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0.31)).join(); assertNull(entity.getLineOfSightEntity(20, (e) -> true)); @@ -86,11 +86,11 @@ public void entityPhysicsCheckLineOfSightNearMiss(Env env) { public void entityPhysicsCheckLineOfSightNearHit(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0.3)).join(); assertEquals(entity2, entity.getLineOfSightEntity(20, (e) -> true)); @@ -112,14 +112,14 @@ public void entityPhysicsCheckLineOfSightNearHit(Env env) { public void entityPhysicsCheckLineOfSightCorrectOrder(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0)).join(); - var entity3 = new Entity(EntityTypes.ZOMBIE); + var entity3 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity3.setInstance(instance, new Pos(5, 42, 0)).join(); assertEquals(entity3, entity.getLineOfSightEntity(20, (e) -> true)); @@ -133,11 +133,11 @@ public void entityPhysicsCheckLineOfSightCorrectOrder(Env env) { public void entityPhysicsCheckLineOfSightBigMiss(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 10)).join(); assertNull(entity.getLineOfSightEntity(20, (e) -> true)); @@ -148,11 +148,11 @@ public void entityPhysicsCheckLineOfSightBigMiss(Env env) { public void entityPhysicsCheckLineOfSightLargeBoundingBox(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(EntityTypes.ZOMBIE); + var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(6, 42, 0)).join(); entity2.setBoundingBox(4.0, 2.0, 4.0); diff --git a/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java index d4bc0029ea9..6d61e5e274f 100644 --- a/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java @@ -1,10 +1,10 @@ package net.minestom.server.entity; import net.kyori.adventure.text.Component; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.network.packet.server.play.EntityMetaDataPacket; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -92,7 +92,7 @@ public void customName(Env env) { var incomingPackets = connection.trackIncoming(EntityMetaDataPacket.class); //Creates entity and name. - Entity entity = new Entity(EntityType.BEE); + Entity entity = new Entity(env.minecraftServer(), EntityType.BEE); entity.setAutoViewable(false); entity.getEntityMeta().setNotifyAboutChanges(false); entity.setCustomName(Component.text("Custom Name")); diff --git a/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java index 814257ce83d..74d32489015 100644 --- a/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java @@ -1,8 +1,8 @@ package net.minestom.server.entity; +import net.minestom.server.coordinate.Pos; import net.minestom.testing.Env; import net.minestom.testing.EnvTest; -import net.minestom.server.coordinate.Pos; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -12,9 +12,9 @@ public class EntityProjectileIntegrationTest { @Test public void gravityVelocity(Env env) { var instance = env.createFlatInstance(); - var shooter = new EntityCreature(EntityType.SKELETON); + var shooter = new EntityCreature(env.minecraftServer(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 42, 0)).join(); - var projectile = new EntityProjectile(shooter, EntityType.ARROW); + var projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); var from = new Pos(0, 42, 0).add(0, shooter.getEyeHeight(), shooter.getPosition().direction().z()); var target = from.add(0, 0, 10); @@ -44,9 +44,9 @@ public void gravityVelocity(Env env) { @Test public void noGravityVelocity(Env env) { var instance = env.createFlatInstance(); - var shooter = new EntityCreature(EntityType.SKELETON); + var shooter = new EntityCreature(env.minecraftServer(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 42, 0)).join(); - var projectile = new EntityProjectile(shooter, EntityType.ARROW); + var projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); var from = new Pos(0, 42, 0).add(0, shooter.getEyeHeight(), shooter.getPosition().direction().z()); var target = from.add(0, 0, 10); diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index cfbc193142e..c3db8a2a387 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -1,11 +1,12 @@ package net.minestom.server.entity; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.entity.EntityTickEvent; import net.minestom.server.network.packet.server.play.DestroyEntitiesPacket; import net.minestom.server.utils.time.TimeUnit; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import java.lang.ref.WeakReference; @@ -24,7 +25,7 @@ public void destructionPacket(Env env) { var connection = env.createConnection(); connection.connect(instance, new Pos(0, 40, 0)).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); var tracker = connection.trackIncoming(DestroyEntitiesPacket.class); @@ -35,7 +36,7 @@ public void destructionPacket(Env env) { @Test public void instanceRemoval(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); assertFalse(entity.isRemoved()); @@ -47,7 +48,7 @@ public void instanceRemoval(Env env) { @Test public void tickTimedRemoval(Env env) throws InterruptedException { var instance = env.createFlatInstance(); - var entity = new TestEntity(2, TimeUnit.SERVER_TICK); + var entity = new TestEntity(env.minecraftServer(), 2, TimeUnit.SERVER_TICK); entity.setInstance(instance, new Pos(0, 40, 0)).join(); assertFalse(entity.isRemoved()); @@ -68,7 +69,7 @@ public void tickTimedRemoval(Env env) throws InterruptedException { public void entityGC(Env env) { // Ensure that entities do not stay in memory after they are removed var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); entity.remove(); @@ -83,7 +84,7 @@ public void entityGC(Env env) { public void entityNodeGC(Env env) { // Ensure that the entities GCed when a local listener is present var node = env.process().getGlobalEventHandler(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.eventNode().addListener(EntityTickEvent.class, event -> { }); node.call(new EntityTickEvent(entity)); @@ -97,8 +98,8 @@ public void entityNodeGC(Env env) { } static final class TestEntity extends Entity { - public TestEntity(long delay, TemporalUnit unit) { - super(EntityType.ZOMBIE); + public TestEntity(MinecraftServer minecraftServer, long delay, TemporalUnit unit) { + super(minecraftServer, EntityType.ZOMBIE); scheduleRemove(delay, unit); } } diff --git a/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java index 22b32a5d527..9ea0035cf99 100644 --- a/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java @@ -1,11 +1,11 @@ package net.minestom.server.entity; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.network.packet.server.play.EntityTeleportPacket; import net.minestom.server.network.packet.server.play.PlayerPositionAndLookPacket; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -16,7 +16,7 @@ public class EntityTeleportIntegrationTest { @Test public void entityChunkTeleport(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); assertEquals(new Pos(0, 42, 0), entity.getPosition()); @@ -28,7 +28,7 @@ public void entityChunkTeleport(Env env) { @Test public void entityTeleport(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); assertEquals(new Pos(0, 42, 0), entity.getPosition()); diff --git a/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java index 2ee0bd4296c..1e9e80adebd 100644 --- a/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java @@ -1,12 +1,12 @@ package net.minestom.server.entity; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.Instance; import net.minestom.server.network.packet.server.play.EntityVelocityPacket; import net.minestom.server.utils.chunk.ChunkUtils; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; @@ -21,7 +21,7 @@ public void gravity(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); env.tick(); // Ensure velocity downwards is present @@ -40,7 +40,7 @@ public void singleKnockback(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); env.tick(); env.tick(); // Ensures the entity is onGround @@ -71,7 +71,7 @@ public void doubleKnockback(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(EntityTypes.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); env.tick(); env.tick(); // Ensures the entity is onGround @@ -145,7 +145,7 @@ public void testHasVelocity(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); // Should be false because the new entity should have no velocity assertFalse(entity.hasVelocity()); @@ -170,7 +170,7 @@ public void countVelocityPackets(Env env) { var instance = env.createFlatInstance(); var viewerConnection = env.createConnection(); viewerConnection.connect(instance, new Pos(1, 40, 1)).join(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0,40,0)).join(); AtomicInteger i = new AtomicInteger(); diff --git a/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java index 00d15fb47f6..4802b2c05a8 100644 --- a/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java @@ -1,8 +1,8 @@ package net.minestom.server.entity; +import net.minestom.server.coordinate.Pos; import net.minestom.testing.Env; import net.minestom.testing.EnvTest; -import net.minestom.server.coordinate.Pos; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,7 +15,7 @@ public class EntityViewDirectionIntegrationTest { @Test public void viewYawAndPitch(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); entity.setView(0, 0); assertEquals(0, entity.getPosition().yaw()); @@ -50,7 +50,7 @@ public void viewYawAndPitch(Env env) { @Test public void lookAtPos(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); double eyeHeight = entity.getEyeHeight(); // adding this to some position Y coordinates, to look horizontally entity.setInstance(instance, new Pos(0, 40, 0)).join(); @@ -90,8 +90,8 @@ public void lookAtPos(Env env) { public void lookAtEntitySameType(Env env) { var instance = env.createFlatInstance(); // same type, same eye height - var e1 = new Entity(EntityType.ZOMBIE); - var e2 = new Entity(EntityType.ZOMBIE); + var e1 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var e2 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); e1.setInstance(instance, new Pos(0, 40, 0)).join(); e2.setInstance(instance, new Pos(0, 40, 0)).join(); @@ -124,9 +124,9 @@ public void lookAtEntitySameType(Env env) { public void lookAtEntityDifferentType(Env env) { var instance = env.createFlatInstance(); // same type, same eye height - var e1 = new Entity(EntityType.ZOMBIE); + var e1 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); // a chicken has a lower eye height than a zombie - var e2 = new Entity(EntityType.CHICKEN); + var e2 = new Entity(env.minecraftServer(), EntityType.CHICKEN); e1.setInstance(instance, new Pos(0, 40, 0)).join(); e2.setInstance(instance, new Pos(0, 40, 0)).join(); diff --git a/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java index 181b303252a..8815a9b5cec 100644 --- a/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java @@ -1,9 +1,9 @@ package net.minestom.server.entity; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.network.packet.server.play.SpawnEntityPacket; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @@ -14,7 +14,7 @@ public class EntityViewIntegrationTest { @Test public void emptyEntity(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 42)).join(); assertEquals(0, entity.getViewers().size()); } @@ -128,8 +128,8 @@ public void livingVehicle(Env env) { var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 40, 0)).join(); - var vehicle = new Entity(EntityType.ZOMBIE); - var passenger = new Entity(EntityType.ZOMBIE); + var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var passenger = new Entity(env.minecraftServer(), EntityType.ZOMBIE); var tracker = connection.trackIncoming(SpawnEntityPacket.class); @@ -158,11 +158,11 @@ public void vehicleInheritance(Env env) { var p1 = env.createPlayer(instance, new Pos(0, 40, 0)); var p2 = env.createPlayer(instance, new Pos(0, 40, 0)); - var vehicle = new Entity(EntityType.ZOMBIE); + var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); vehicle.setInstance(instance, new Pos(0, 40, 0)).join(); vehicle.addPassenger(p1); - var vehicle2 = new Entity(EntityType.ZOMBIE); + var vehicle2 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); vehicle2.setInstance(instance, new Pos(0, 40, 0)).join(); vehicle2.addPassenger(p2); diff --git a/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java b/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java index 2b9402f1cbf..edb9b2b3588 100644 --- a/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java @@ -1,8 +1,8 @@ package net.minestom.server.entity; +import net.minestom.server.coordinate.Pos; import net.minestom.testing.Env; import net.minestom.testing.EnvTest; -import net.minestom.server.coordinate.Pos; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @@ -13,8 +13,8 @@ public class PassengerIntegrationTest { @Test public void passenger(Env env) { var instance = env.createFlatInstance(); - var vehicle = new Entity(EntityType.ZOMBIE); - var passenger = new Entity(EntityType.ZOMBIE); + var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var passenger = new Entity(env.minecraftServer(), EntityType.ZOMBIE); vehicle.setInstance(instance, new Pos(0, 40, 0)).join(); passenger.setInstance(instance, new Pos(0, 40, 0)).join(); @@ -30,8 +30,8 @@ public void passenger(Env env) { @Test public void passengerTeleport(Env env) { var instance = env.createFlatInstance(); - var vehicle = new Entity(EntityType.ZOMBIE); - var passenger = new Entity(EntityType.ZOMBIE); + var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var passenger = new Entity(env.minecraftServer(), EntityType.ZOMBIE); vehicle.setInstance(instance, new Pos(0, 40, 0)).join(); passenger.setInstance(instance, new Pos(0, 40, 5000)).join(); diff --git a/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java b/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java index 5c34c621e1b..5a6f7ee3267 100644 --- a/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java +++ b/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java @@ -1,11 +1,11 @@ package net.minestom.server.entity.ai; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.ai.target.ClosestEntityTarget; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -18,19 +18,19 @@ public class ClosestEntityTargetTest { public void validFindTarget(Env env) { var instance = env.createFlatInstance(); - var self = new EntityCreature(EntityType.ZOMBIE); + var self = new EntityCreature(env.minecraftServer(), EntityType.ZOMBIE); self.setInstance(instance, new Pos(0, 42, 0)).join(); - var spider = new EntityCreature(EntityType.SPIDER); + var spider = new EntityCreature(env.minecraftServer(), EntityType.SPIDER); spider.setInstance(instance, new Pos(-3, 42, -3)).join(); - var secondSpider = new EntityCreature(EntityType.SPIDER); + var secondSpider = new EntityCreature(env.minecraftServer(), EntityType.SPIDER); secondSpider.setInstance(instance, new Pos(-4, 42, -4)).join(); - var skeleton = new EntityCreature(EntityType.SKELETON); + var skeleton = new EntityCreature(env.minecraftServer(), EntityType.SKELETON); skeleton.setInstance(instance, new Pos(5, 42, 5)).join(); - var zombie = new EntityCreature(EntityType.ZOMBIE); + var zombie = new EntityCreature(env.minecraftServer(), EntityType.ZOMBIE); zombie.setInstance(instance, new Pos(10, 42, -10)).join(); assertEquals(5, instance.getEntities().size(), "Not all entities are in the instance"); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java index 6b4eac36b13..eec6054981f 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java @@ -1,6 +1,5 @@ package net.minestom.server.entity.player; -import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Player; @@ -64,7 +63,7 @@ public void singleTickMovementUpdate(Env env) { @Test public void chunkUpdateDebounceTest(Env env) { final Instance flatInstance = env.createFlatInstance(); - final int viewDiameter = MinecraftServer.getChunkViewDistance() * 2 + 1; + final int viewDiameter = env.minecraftServer().getChunkViewDistance() * 2 + 1; // Preload all possible chunks to avoid issues due to async loading Set> chunks = new HashSet<>(); ChunkUtils.forChunksInRange(0, 0, viewDiameter+2, (x, z) -> chunks.add(flatInstance.loadChunk(x, z))); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java index 9835a2f5d68..219866ebf74 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java @@ -1,6 +1,5 @@ package net.minestom.server.entity.player; -import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.client.play.ClientStatusPacket; @@ -46,7 +45,7 @@ public void testChunkReloadCount(Env env) { player.setHealth(0); player.respawn(); // Player should have all their chunks reloaded - int chunkLoads = ChunkUtils.getChunkCount(Math.min(MinecraftServer.getChunkViewDistance(), player.getSettings().getViewDistance())); + int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.minecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance())); loadChunkTracker.assertCount(chunkLoads); } @@ -62,7 +61,7 @@ public void testPlayerTryRespawn(Env env) { player.interpretPacketQueue(); List dataPacketList = loadChunkTracker.collect(); Set duplicateCheck = new HashSet<>(); - int actualViewDistance = Math.min(MinecraftServer.getChunkViewDistance(), player.getSettings().getViewDistance()); + int actualViewDistance = Math.min(env.minecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance()); int chunkLoads = ChunkUtils.getChunkCount(actualViewDistance); loadChunkTracker.assertCount(chunkLoads); for (ChunkDataPacket packet : dataPacketList) { diff --git a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java index c9f650b9eca..1f20afbfb29 100644 --- a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java @@ -1,5 +1,6 @@ package net.minestom.server.event; +import net.minestom.server.MinecraftServer; import org.junit.jupiter.api.Test; import java.util.List; @@ -10,14 +11,16 @@ public class EventNodeGraphTest { @Test public void single() { - EventNode node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + EventNode node = EventNode.all(minecraftServer,"main"); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of())); } @Test public void singleChild() { - EventNode node = EventNode.all("main"); - node.addChild(EventNode.all("child")); + MinecraftServer minecraftServer = new MinecraftServer(); + EventNode node = EventNode.all(minecraftServer,"main"); + node.addChild(EventNode.all(minecraftServer,"child")); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child", "Event", 0, List.of()) ))); @@ -25,19 +28,20 @@ public void singleChild() { @Test public void childrenPriority() { + MinecraftServer minecraftServer = new MinecraftServer(); { - EventNode node = EventNode.all("main"); - node.addChild(EventNode.all("child1").setPriority(5)); - node.addChild(EventNode.all("child2").setPriority(10)); + EventNode node = EventNode.all(minecraftServer,"main"); + node.addChild(EventNode.all(minecraftServer,"child1").setPriority(5)); + node.addChild(EventNode.all(minecraftServer,"child2").setPriority(10)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) ))); } { - EventNode node = EventNode.all("main"); - node.addChild(EventNode.all("child2").setPriority(10)); - node.addChild(EventNode.all("child1").setPriority(5)); + EventNode node = EventNode.all(minecraftServer, "main"); + node.addChild(EventNode.all(minecraftServer,"child2").setPriority(10)); + node.addChild(EventNode.all(minecraftServer,"child1").setPriority(5)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) diff --git a/src/test/java/net/minestom/server/event/EventNodeMapTest.java b/src/test/java/net/minestom/server/event/EventNodeMapTest.java index dc7a95e500d..5a8517d5831 100644 --- a/src/test/java/net/minestom/server/event/EventNodeMapTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeMapTest.java @@ -17,8 +17,9 @@ public class EventNodeMapTest { @Test public void uniqueMapping() { + MinecraftServer minecraftServer = new MinecraftServer(); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all("main"); + var node = EventNode.all(minecraftServer,"main"); var itemNode1 = node.map(item, EventFilter.ITEM); var itemNode2 = node.map(item, EventFilter.ITEM); assertNotNull(itemNode1); @@ -32,8 +33,9 @@ public void uniqueMapping() { @Test public void lazyRegistration() { + MinecraftServer minecraftServer = new MinecraftServer(); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all("main"); + var node = (EventNodeImpl) EventNode.all(minecraftServer,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertFalse(node.registeredMappedNode.containsKey(item)); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { @@ -43,8 +45,9 @@ public void lazyRegistration() { @Test public void secondMap() { + MinecraftServer minecraftServer = new MinecraftServer(); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all("main"); + var node = (EventNodeImpl) EventNode.all(minecraftServer,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertSame(itemNode, itemNode.map(item, EventFilter.ITEM)); assertThrows(Exception.class, () -> itemNode.map(ItemStack.AIR, EventFilter.ITEM)); @@ -52,8 +55,9 @@ public void secondMap() { @Test public void map() { + MinecraftServer minecraftServer = new MinecraftServer(); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all("main"); + var node = EventNode.all(minecraftServer, "main"); AtomicBoolean result = new AtomicBoolean(false); var itemNode = node.map(item, EventFilter.ITEM); @@ -77,9 +81,10 @@ public void map() { @Test public void entityLocal() { - var process = new MinecraftServer().updateProcess(); + MinecraftServer minecraftServer = new MinecraftServer(); + var process = minecraftServer.updateProcess(); var node = process.getGlobalEventHandler(); - var entity = new Entity(EntityType.ZOMBIE); + var entity = new Entity(minecraftServer, EntityType.ZOMBIE); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventNodeTest.EntityTestEvent.class, event -> result.set(true)); @@ -103,9 +108,10 @@ public void entityLocal() { @Test public void ownerGC() { + MinecraftServer minecraftServer = new MinecraftServer(); // Ensure that the mapped object gets GCed var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all("main"); + var node = EventNode.all(minecraftServer,"main"); var itemNode = node.map(item, EventFilter.ITEM); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { }); diff --git a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java index 9e035b0f764..052c2cd7922 100644 --- a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java @@ -1,5 +1,6 @@ package net.minestom.server.event; +import net.minestom.server.MinecraftServer; import net.minestom.server.event.trait.EntityEvent; import net.minestom.server.event.trait.PlayerEvent; import org.junit.jupiter.api.Test; @@ -13,12 +14,13 @@ public class EventNodeQueryTest { @Test public void find() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer, "main"); assertEquals(List.of(), node.findChildren("test")); - var child1 = EventNode.all("test"); - var child2 = EventNode.all("test"); - var child3 = EventNode.all("test3"); + var child1 = EventNode.all(minecraftServer,"test"); + var child2 = EventNode.all(minecraftServer,"test"); + var child3 = EventNode.all(minecraftServer,"test3"); node.addChild(child1); node.addChild(child2); @@ -34,12 +36,13 @@ public void find() { @Test public void findType() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); assertEquals(List.of(), node.findChildren("test", Event.class)); - var child1 = EventNode.type("test", EventFilter.PLAYER); - var child2 = EventNode.type("test", EventFilter.ENTITY); - var child3 = EventNode.type("test3", EventFilter.ENTITY); + var child1 = EventNode.type(minecraftServer, "test", EventFilter.PLAYER); + var child2 = EventNode.type(minecraftServer, "test", EventFilter.ENTITY); + var child3 = EventNode.type(minecraftServer, "test3", EventFilter.ENTITY); node.addChild(child1); node.addChild(child2); @@ -59,18 +62,19 @@ public void findType() { @Test public void replace() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); - var child1 = EventNode.all("test"); - var child2 = EventNode.all("test"); - var child3 = EventNode.all("test3"); + var child1 = EventNode.all(minecraftServer,"test"); + var child2 = EventNode.all(minecraftServer,"test"); + var child3 = EventNode.all(minecraftServer,"test3"); node.addChild(child1); node.addChild(child2); node.addChild(child3); - var tmp1 = EventNode.all("tmp1"); - var tmp2 = EventNode.all("tmp2"); + var tmp1 = EventNode.all(minecraftServer,"tmp1"); + var tmp2 = EventNode.all(minecraftServer,"tmp2"); node.replaceChildren("test", tmp1); assertEqualsIgnoreOrder(List.of(child2), node.findChildren("test")); diff --git a/src/test/java/net/minestom/server/event/EventNodeTest.java b/src/test/java/net/minestom/server/event/EventNodeTest.java index 114033a08a7..58dab585b74 100644 --- a/src/test/java/net/minestom/server/event/EventNodeTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeTest.java @@ -1,5 +1,6 @@ package net.minestom.server.event; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Entity; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.event.trait.EntityEvent; @@ -58,7 +59,8 @@ record EntityTestEvent(Entity entity) implements EntityEvent { @Test public void testCall() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventTest.class, eventTest -> result.set(true)); node.addListener(listener); @@ -75,7 +77,8 @@ public void testCall() { @Test public void testHandle() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); var handle = node.getHandle(EventTest.class); assertSame(handle, node.getHandle(EventTest.class)); @@ -85,7 +88,8 @@ public void testHandle() { @Test public void testCancellable() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.builder(CancellableTest.class) .handler(event -> { @@ -104,7 +108,8 @@ public void testCancellable() { @Test public void recursiveSub() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result1 = new AtomicBoolean(false); AtomicBoolean result2 = new AtomicBoolean(false); var listener1 = EventListener.of(Recursive1.class, event -> result1.set(true)); @@ -145,14 +150,15 @@ public void recursiveSub() { @Test public void testChildren() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); AtomicInteger result = new AtomicInteger(0); - var child1 = EventNode.all("child1").setPriority(1) + var child1 = EventNode.all(minecraftServer,"child1").setPriority(1) .addListener(EventTest.class, eventTest -> { assertEquals(0, result.get(), "child1 should be called before child2"); result.set(1); }); - var child2 = EventNode.all("child2").setPriority(2) + var child2 = EventNode.all(minecraftServer,"child2").setPriority(2) .addListener(EventTest.class, eventTest -> { assertEquals(1, result.get(), "child2 should be called after child1"); result.set(2); @@ -179,12 +185,13 @@ public void testChildren() { @Test public void testFiltering() { + MinecraftServer minecraftServer = new MinecraftServer(); AtomicBoolean result = new AtomicBoolean(false); AtomicBoolean childResult = new AtomicBoolean(false); - var node = EventNode.type("item_node", EventFilter.ITEM, + var node = EventNode.type(minecraftServer,"item_node", EventFilter.ITEM, (event, item) -> item.material() == Material.DIAMOND); - var child = EventNode.type("item_node2", EventFilter.ITEM) + var child = EventNode.type(minecraftServer,"item_node2", EventFilter.ITEM) .addListener(ItemTestEvent.class, event -> childResult.set(true)); node.addChild(child); @@ -203,7 +210,8 @@ public void testFiltering() { @Test public void testBinding() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result = new AtomicBoolean(false); var binding = EventBinding.filtered(EventFilter.ITEM, itemStack -> itemStack.material() == Material.DIAMOND) @@ -225,7 +233,8 @@ public void testBinding() { @Test public void nodeEmptyGC() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); var ref = new WeakReference<>(node); //noinspection UnusedAssignment @@ -235,7 +244,8 @@ public void nodeEmptyGC() { @Test public void nodeGC() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); var ref = new WeakReference<>(node); node.addListener(EventTest.class, event -> { }); @@ -262,7 +272,8 @@ public void nodeGC() { @Test public void nodeMapGC() { - var node = EventNode.all("main"); + MinecraftServer minecraftServer = new MinecraftServer(); + var node = EventNode.all(minecraftServer,"main"); var handler = ItemStack.AIR; var mapped = node.map(handler, EventFilter.ITEM); diff --git a/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java b/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java index 1e8f352c6de..395dd776f5e 100644 --- a/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java @@ -51,7 +51,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) public void loadHouse(Env env) { // load a world that contains only a basic house and make sure it is loaded properly - AnvilLoader chunkLoader = new AnvilLoader(worldFolder) { + AnvilLoader chunkLoader = new AnvilLoader(env.minecraftServer(), worldFolder) { // Force loads inside current thread @Override public boolean supportsParallelLoading() { @@ -146,7 +146,7 @@ public boolean supportsParallelSaving() { @Test public void loadAndSaveChunk(Env env) throws InterruptedException { - Instance instance = env.createFlatInstance(new AnvilLoader(worldFolder) { + Instance instance = env.createFlatInstance(new AnvilLoader(env.minecraftServer(), worldFolder) { // Force loads inside current thread @Override public boolean supportsParallelLoading() { diff --git a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java index fc6bf8278c2..468e7affe42 100644 --- a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java @@ -1,6 +1,5 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.network.packet.server.play.ChunkDataPacket; import net.minestom.server.utils.chunk.ChunkUtils; @@ -37,7 +36,7 @@ public void basicJoin(boolean sharedInstance, Env env) { @Test public void renderDistance(Env env) { - final int viewRadius = MinecraftServer.getChunkViewDistance(); + final int viewRadius = env.minecraftServer().getChunkViewDistance(); final int count = ChunkUtils.getChunkCount(viewRadius); var instance = env.createFlatInstance(); var connection = env.createConnection(); diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java index 05c66136165..72d4d9c3782 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java @@ -27,11 +27,11 @@ public void maxDistance(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = MinecraftServer.getEntityViewDistance(); + final int viewDistanceInChunks = env.minecraftServer().getEntityViewDistance(); - final Player viewer = createTestPlayer(); + final Player viewer = createTestPlayer(env.minecraftServer()); final AtomicInteger viewersCount = new AtomicInteger(); - final Entity entity = new Entity(EntityType.ZOMBIE) { + final Entity entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE) { @Override public void updateNewViewer(Player player) { viewersCount.incrementAndGet(); @@ -59,11 +59,11 @@ public void cornerInstanceSwap(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = MinecraftServer.getEntityViewDistance(); + final int viewDistanceInChunks = env.minecraftServer().getEntityViewDistance(); - final Player viewer = createTestPlayer(); + final Player viewer = createTestPlayer(env.minecraftServer()); final AtomicInteger viewersCount = new AtomicInteger(); - final Entity entity = new Entity(EntityType.ZOMBIE) { + final Entity entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE) { @Override public void updateNewViewer(Player player) { viewersCount.incrementAndGet(); @@ -129,8 +129,8 @@ public void viewableShared(Env env) { assertEquals(1, viewable.getViewers().size()); } - private Player createTestPlayer() { - return new Player(UUID.randomUUID(), "TestPlayer", new PlayerConnection() { + private Player createTestPlayer(MinecraftServer minecraftServer) { + return new Player(minecraftServer, UUID.randomUUID(), "TestPlayer", new PlayerConnection(minecraftServer) { @Override public void sendPacket(@NotNull SendablePacket packet) { // nothing diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java index 45508ef388c..a28e626c52c 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -14,7 +15,8 @@ public class EntityTrackerTest { @Test public void register() { - var ent1 = new Entity(EntityType.ZOMBIE); + MinecraftServer minecraftServer = new MinecraftServer(); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -28,7 +30,7 @@ public void remove(@NotNull Entity entity) { fail("No other entity should be registered yet"); } }; - EntityTracker tracker = EntityTracker.newTracker(); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); assertTrue(chunkEntities.isEmpty()); @@ -41,7 +43,8 @@ public void remove(@NotNull Entity entity) { @Test public void move() { - var ent1 = new Entity(EntityType.ZOMBIE); + MinecraftServer minecraftServer = new MinecraftServer(); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -54,7 +57,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, updater); assertEquals(1, tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES).size()); @@ -66,10 +69,11 @@ public void remove(@NotNull Entity entity) { @Test public void tracking() { - var ent1 = new Entity(EntityType.ZOMBIE); - var ent2 = new Entity(EntityType.ZOMBIE); + MinecraftServer minecraftServer = new MinecraftServer(); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); - EntityTracker tracker = EntityTracker.newTracker(); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -125,9 +129,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearby() { - var ent1 = new Entity(EntityType.ZOMBIE); - var ent2 = new Entity(EntityType.ZOMBIE); - var ent3 = new Entity(EntityType.ZOMBIE); + MinecraftServer minecraftServer = new MinecraftServer(); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent3 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -140,7 +145,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent2, new Vec(5, 0, 0), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(50, 0, 0), EntityTracker.Target.ENTITIES, updater); @@ -178,9 +183,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearbySingleChunk() { - var ent1 = new Entity(EntityType.ZOMBIE); - var ent2 = new Entity(EntityType.ZOMBIE); - var ent3 = new Entity(EntityType.ZOMBIE); + MinecraftServer minecraftServer = new MinecraftServer(); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent3 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -193,7 +199,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent1, new Vec(5, 0, 5), EntityTracker.Target.ENTITIES, updater); tracker.register(ent2, new Vec(8, 0, 8), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(17, 0, 17), EntityTracker.Target.ENTITIES, updater); @@ -218,7 +224,8 @@ public void remove(@NotNull Entity entity) { @Test public void collectionView() { - var ent1 = new Entity(EntityType.ZOMBIE); + MinecraftServer minecraftServer = new MinecraftServer(); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -233,7 +240,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); var entities = tracker.entities(); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); @@ -243,7 +250,7 @@ public void remove(@NotNull Entity entity) { assertEquals(1, entities.size()); assertEquals(1, chunkEntities.size()); - assertThrows(Exception.class, () -> entities.add(new Entity(EntityType.ZOMBIE))); - assertThrows(Exception.class, () -> chunkEntities.add(new Entity(EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> entities.add(new Entity(minecraftServer, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> chunkEntities.add(new Entity(minecraftServer, EntityType.ZOMBIE))); } } diff --git a/src/test/java/net/minestom/server/instance/GeneratorTest.java b/src/test/java/net/minestom/server/instance/GeneratorTest.java index 4a53ede725c..f64d0dfcd06 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -29,12 +30,13 @@ public class GeneratorTest { @Test public void unitSize() { - assertDoesNotThrow(() -> dummyUnit(Vec.ZERO, new Vec(16))); - assertDoesNotThrow(() -> dummyUnit(new Vec(16), new Vec(32))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(new Vec(15), Vec.ZERO)); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(new Vec(15), new Vec(32))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(new Vec(15), new Vec(31))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(Vec.ZERO, new Vec(15))); + MinecraftServer minecraftServer = new MinecraftServer(); + assertDoesNotThrow(() -> dummyUnit(minecraftServer, Vec.ZERO, new Vec(16))); + assertDoesNotThrow(() -> dummyUnit(minecraftServer, new Vec(16), new Vec(32))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, new Vec(15), Vec.ZERO)); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, new Vec(15), new Vec(32))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, new Vec(15), new Vec(31))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, Vec.ZERO, new Vec(15))); } @ParameterizedTest @@ -77,13 +79,14 @@ private static Stream sectionCeilParam() { @Test public void chunkSize() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); assertEquals(new Vec(16, sectionCount * 16, 16), chunk.size()); assertEquals(new Vec(chunkX * 16, minSection * 16, chunkZ * 16), chunk.absoluteStart()); @@ -92,13 +95,14 @@ public void chunkSize() { @Test public void chunkSizeNeg() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); assertEquals(new Vec(16, sectionCount * 16, 16), chunk.size()); assertEquals(new Vec(chunkX * 16, minSection * 16, chunkZ * 16), chunk.absoluteStart()); @@ -107,10 +111,11 @@ public void chunkSizeNeg() { @Test public void sectionSize() { + MinecraftServer minecraftServer = new MinecraftServer(); final int sectionX = 3; final int sectionY = -5; final int sectionZ = -2; - GenerationUnit section = GeneratorImpl.section(new Section(), sectionX, sectionY, sectionZ); + GenerationUnit section = GeneratorImpl.section(minecraftServer, new Section(minecraftServer), sectionX, sectionY, sectionZ); assertEquals(new Vec(16), section.size()); assertEquals(new Vec(sectionX * 16, sectionY * 16, sectionZ * 16), section.absoluteStart()); assertEquals(new Vec(sectionX * 16 + 16, sectionY * 16 + 16, sectionZ * 16 + 16), section.absoluteEnd()); @@ -118,13 +123,14 @@ public void sectionSize() { @Test public void chunkSubdivide() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); var subUnits = chunk.subdivide(); assertEquals(sectionCount, subUnits.size()); @@ -138,13 +144,14 @@ public void chunkSubdivide() { @Test public void chunkAbsolute() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); @@ -159,13 +166,14 @@ public void chunkAbsolute() { @Test public void chunkAbsoluteAll() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); @@ -187,13 +195,14 @@ public void chunkAbsoluteAll() { @Test public void chunkRelative() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); @@ -214,13 +223,14 @@ public void chunkRelative() { @Test public void chunkRelativeAll() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); @@ -243,13 +253,14 @@ public void chunkRelativeAll() { @Test public void chunkBiomeSet() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); @@ -264,13 +275,14 @@ public void chunkBiomeSet() { @Test public void chunkBiomeFill() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); @@ -285,11 +297,12 @@ public void chunkBiomeFill() { @Test public void chunkFillHeightExact() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), 3, -2); Generator generator = chunk -> chunk.modifier().fillHeight(0, 32, Block.STONE); generator.generate(chunkUnits); @@ -309,11 +322,12 @@ public void chunkFillHeightExact() { @Test public void chunkFillHeightOneOff() { + MinecraftServer minecraftServer = new MinecraftServer(); final int minSection = -1; final int maxSection = 5; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section()); + Arrays.setAll(sections, i -> new Section(minecraftServer)); var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), 3, -2); Generator generator = chunk -> chunk.modifier().fillHeight(1, 33, Block.STONE); generator.generate(chunkUnits); @@ -347,15 +361,16 @@ public void chunkFillHeightOneOff() { @Test public void sectionFill() { - Section section = new Section(); - var chunkUnit = GeneratorImpl.section(section, -1, -1, 0); + MinecraftServer minecraftServer = new MinecraftServer(); + Section section = new Section(minecraftServer); + var chunkUnit = GeneratorImpl.section(minecraftServer, section, -1, -1, 0); Generator generator = chunk -> chunk.modifier().fill(Block.STONE); generator.generate(chunkUnit); section.blockPalette().getAll((x, y, z, value) -> assertEquals(Block.STONE.stateId(), value)); } - static GenerationUnit dummyUnit(Point start, Point end) { - return unit(null, start, end, null); + static GenerationUnit dummyUnit(MinecraftServer minecraftServer, Point start, Point end) { + return unit(minecraftServer,null, start, end, null); } } diff --git a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java index cddafc32a96..a03ff5469e9 100644 --- a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.MinecraftServer; import net.minestom.server.tag.Tag; import net.minestom.server.world.DimensionType; import net.minestom.server.world.DimensionTypeManager; @@ -17,8 +18,9 @@ public class InstanceContainerTest { @Test public void copyPreservesTag() { + MinecraftServer minecraftServer = new MinecraftServer(); var tag = Tag.String("test"); - var instance = new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD); + var instance = new InstanceContainer(minecraftServer, UUID.randomUUID(), DimensionType.OVERWORLD); instance.setTag(tag, "123"); var copyInstance = instance.copy(); diff --git a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java index 728614c48b6..050f517bf6a 100644 --- a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java @@ -86,7 +86,7 @@ public void chunkGC(Env env) { @Test public void testGCWithEventsLambda(Env env) { - var ref = new WeakReference<>(new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD)); + var ref = new WeakReference<>(new InstanceContainer(env.minecraftServer(), UUID.randomUUID(), DimensionType.OVERWORLD)); env.process().getInstanceManager().registerInstance(ref.get()); tmp(ref.get()); diff --git a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java index 3f6e054985e..fbe5b180bf3 100644 --- a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java +++ b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance.light; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.palette.Palette; @@ -17,7 +18,8 @@ public class BlockLightTest { @Test public void empty() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); var result = LightCompute.compute(palette); for (byte light : result.light()) { assertEquals(0, light); @@ -26,7 +28,8 @@ public void empty() { @Test public void glowstone() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -37,7 +40,8 @@ public void glowstone() { @Test public void doubleGlowstone() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); @@ -51,7 +55,8 @@ public void doubleGlowstone() { @Test public void glowstoneBorder() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -69,7 +74,8 @@ public void glowstoneBorder() { @Test public void glowstoneBlock() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(0, 1, 1, Block.STONE.stateId()); var result = LightCompute.compute(palette); @@ -81,7 +87,8 @@ public void glowstoneBlock() { @Test public void isolated() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.STONE.stateId()); @@ -108,7 +115,8 @@ public void isolated() { @Test public void isolatedStair() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "east", @@ -130,7 +138,8 @@ public void isolatedStair() { @Test public void isolatedStairOpposite() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -157,7 +166,8 @@ public void isolatedStairOpposite() { @Test public void isolatedStairWest() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -187,7 +197,8 @@ public void isolatedStairWest() { @Test public void isolatedStairSouth() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "south", diff --git a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java index cae1ba4c6b5..c40f20c732b 100644 --- a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance.light; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.*; import net.minestom.server.instance.block.Block; @@ -29,12 +30,12 @@ public class LightParityIntegrationTest { @Test public void test(Env env) throws URISyntaxException, IOException, AnvilException { - Map sections = retrieveSections(); + Map sections = retrieveSections(env.minecraftServer()); // Generate our own light InstanceContainer instance = (InstanceContainer) env.createFlatInstance(); instance.setChunkSupplier(LightingChunk::new); - instance.setChunkLoader(new AnvilLoader(Path.of("./src/test/resources/net/minestom/server/instance/lighting"))); + instance.setChunkLoader(new AnvilLoader(env.minecraftServer(), Path.of("./src/test/resources/net/minestom/server/instance/lighting"))); List> futures = new ArrayList<>(); @@ -126,7 +127,7 @@ public void test(Env env) throws URISyntaxException, IOException, AnvilException record SectionEntry(Palette blocks, byte[] sky, byte[] block) { } - private static Map retrieveSections() throws IOException, URISyntaxException, AnvilException { + private static Map retrieveSections(MinecraftServer minecraftServer) throws IOException, URISyntaxException, AnvilException { URL defaultImage = LightParityIntegrationTest.class.getResource("/net/minestom/server/instance/lighting/region/r.0.0.mca"); assert defaultImage != null; File imageFile = new File(defaultImage.toURI()); @@ -142,7 +143,7 @@ private static Map retrieveSections() throws IOException, URI for (int yLevel = chunk.getMinY(); yLevel <= chunk.getMaxY(); yLevel += 16) { var section = chunk.getSection((byte) (yLevel/16)); - var palette = loadBlocks(section); + var palette = loadBlocks(minecraftServer, section); var sky = section.getSkyLights(); var block = section.getBlockLights(); sections.put(new Vec(x, section.getY(), z), new SectionEntry(palette, sky, block)); @@ -152,8 +153,8 @@ private static Map retrieveSections() throws IOException, URI return sections; } - private static Palette loadBlocks(ChunkSection section) throws AnvilException { - var palette = Palette.blocks(); + private static Palette loadBlocks(MinecraftServer minecraftServer, ChunkSection section) throws AnvilException { + var palette = Palette.blocks(minecraftServer); for (int x = 0; x < Chunk.CHUNK_SECTION_SIZE; x++) { for (int z = 0; z < Chunk.CHUNK_SECTION_SIZE; z++) { for (int y = 0; y < Chunk.CHUNK_SECTION_SIZE; y++) { diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java index 9916d52ab23..1105482df76 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance.palette; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.NetworkBuffer; import org.junit.jupiter.api.Test; @@ -12,21 +13,24 @@ public class PaletteOptimizationTest { @Test public void empty() { - var palette = createPalette(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = createPalette(minecraftServer); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void single() { - var palette = createPalette(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = createPalette(minecraftServer); palette.set(0, 0, 0, 1); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void random() { + MinecraftServer minecraftServer = new MinecraftServer(); var random = new Random(12345); - var palette = createPalette(); + var palette = createPalette(minecraftServer); palette.setAll((x, y, z) -> random.nextInt(256)); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> random.nextInt(2)); @@ -35,7 +39,8 @@ public void random() { @Test public void manualFill() { - var palette = createPalette(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = createPalette(minecraftServer); palette.setAll((x, y, z) -> 1); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> 2); @@ -44,8 +49,8 @@ public void manualFill() { paletteEquals(palette.palette, palette.optimizedPalette()); } - AdaptivePalette createPalette() { - return (AdaptivePalette) Palette.blocks(); + AdaptivePalette createPalette(MinecraftServer minecraftServer) { + return (AdaptivePalette) Palette.blocks(minecraftServer); } void paletteEquals(Palette palette, Palette optimized) { diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java index 3372ade4565..2f075cd764f 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java @@ -1,5 +1,6 @@ package net.minestom.server.instance.palette; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import org.junit.jupiter.api.Test; @@ -15,14 +16,16 @@ public class PaletteTest { @Test public void singlePlacement() { - var palette = Palette.blocks(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.blocks(minecraftServer); palette.set(0, 0, 1, 1); assertEquals(1, palette.get(0, 0, 1)); } @Test public void placement() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { final int dimension = palette.dimension(); assertEquals(0, palette.get(0, 0, 0), "Default value should be 0"); @@ -57,8 +60,9 @@ public void placement() { @Test public void placementHighValue() { + MinecraftServer minecraftServer = new MinecraftServer(); final int value = 250_000; - for (Palette palette : testPalettes()) { + for (Palette palette : testPalettes(minecraftServer)) { palette.set(0, 0, 1, value); assertEquals(value, palette.get(0, 0, 1)); } @@ -66,7 +70,8 @@ public void placementHighValue() { @Test public void negPlacement() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { assertThrows(IllegalArgumentException.class, () -> palette.set(-1, 0, 0, 64)); assertThrows(IllegalArgumentException.class, () -> palette.set(0, -1, 0, 64)); @@ -80,7 +85,8 @@ public void negPlacement() { @Test public void resize() { - Palette palette = Palette.newPalette(16, 5, 2); + MinecraftServer minecraftServer = new MinecraftServer(); + Palette palette = Palette.newPalette(minecraftServer,16, 5, 2); palette.set(0, 0, 0, 1); assertEquals(2, palette.bitsPerEntry()); palette.set(0, 0, 1, 2); @@ -99,7 +105,8 @@ public void resize() { @Test public void fill() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { assertEquals(0, palette.count()); palette.set(0, 0, 0, 5); @@ -130,7 +137,8 @@ public void fill() { @Test public void bulk() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { final int dimension = palette.dimension(); // Place @@ -155,7 +163,8 @@ public void bulk() { @Test public void bulkAll() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { // Fill all entries palette.setAll((x, y, z) -> x + y + z + 1); @@ -173,7 +182,8 @@ public void bulkAll() { @Test public void bulkAllOrder() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { AtomicInteger count = new AtomicInteger(); @@ -211,7 +221,8 @@ public void bulkAllOrder() { @Test public void setAllConstant() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.setAll((x, y, z) -> 1); palette.getAll((x, y, z, value) -> assertEquals(1, value)); @@ -220,7 +231,8 @@ public void setAllConstant() { @Test public void getAllPresent() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.getAllPresent((x, y, z, value) -> fail("The palette should be empty")); palette.set(0, 0, 1, 1); @@ -235,7 +247,8 @@ public void getAllPresent() { @Test public void replaceAll() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.setAll((x, y, z) -> x + y + z + 1); palette.replaceAll((x, y, z, value) -> { @@ -248,7 +261,8 @@ public void replaceAll() { @Test public void replace() { - var palettes = testPalettes(); + MinecraftServer minecraftServer = new MinecraftServer(); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.set(0, 0, 0, 1); palette.replace(0, 0, 0, operand -> { @@ -261,7 +275,8 @@ public void replace() { @Test public void replaceLoop() { - var palette = Palette.newPalette(2, 15, 4); + MinecraftServer minecraftServer = new MinecraftServer(); + var palette = Palette.newPalette(minecraftServer,2, 15, 4); palette.setAll((x, y, z) -> x + y + z); final int dimension = palette.dimension(); for (int x = 0; x < dimension; x++) { @@ -275,21 +290,22 @@ public void replaceLoop() { @Test public void dimension() { - assertThrows(Exception.class, () -> Palette.newPalette(-4, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(0, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(1, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(2, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(3, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(4, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(6, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(16, 5, 3)); + MinecraftServer minecraftServer = new MinecraftServer(); + assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,-4, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,0, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,1, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(minecraftServer,2, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,3, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(minecraftServer,4, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,6, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(minecraftServer,16, 5, 3)); } - private static List testPalettes() { + private static List testPalettes(MinecraftServer minecraftServer) { return List.of( - Palette.newPalette(2, 5, 3), - Palette.newPalette(4, 5, 3), - Palette.newPalette(8, 5, 3), - Palette.newPalette(16, 5, 3)); + Palette.newPalette(minecraftServer,2, 5, 3), + Palette.newPalette(minecraftServer,4, 5, 3), + Palette.newPalette(minecraftServer,8, 5, 3), + Palette.newPalette(minecraftServer,16, 5, 3)); } } diff --git a/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java b/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java index 21d92088f43..11bd3dfe3f1 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java @@ -22,7 +22,7 @@ public void doNotReceiveClosePacketFromServerWhenSendingClientCloseWindowPacket( assertEquals(instance, player.getInstance()); var packetTracker = connection.trackIncoming(CloseWindowPacket.class); - var inventory = new Inventory(InventoryType.CHEST_2_ROW, Component.text("Test")); + var inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_2_ROW, Component.text("Test")); player.openInventory(inventory); player.closeInventory(); // Closes the inventory server-side, should send a CloseWindowPacket player.openInventory(inventory); diff --git a/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java b/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java index d0df75b49e8..d2040caca1f 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java @@ -1,8 +1,6 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.item.ItemDropEvent; import net.minestom.server.item.ItemStack; @@ -10,6 +8,8 @@ import net.minestom.server.network.packet.server.play.EntityEquipmentPacket; import net.minestom.server.network.packet.server.play.SetSlotPacket; import net.minestom.server.network.packet.server.play.WindowItemsPacket; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @@ -26,7 +26,7 @@ public void setSlotDuplicateTest(Env env) { var player = connection.connect(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, player.getInstance()); - Inventory inventory = new Inventory(InventoryType.CHEST_6_ROW, Component.empty()); + Inventory inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_6_ROW, Component.empty()); player.openInventory(inventory); assertEquals(inventory, player.getOpenInventory()); @@ -50,7 +50,7 @@ public void setCursorItemDuplicateTest(Env env) { var player = connection.connect(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, player.getInstance()); - Inventory inventory = new Inventory(InventoryType.CHEST_6_ROW, Component.empty()); + Inventory inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_6_ROW, Component.empty()); player.openInventory(inventory); assertEquals(inventory, player.getOpenInventory()); @@ -74,7 +74,7 @@ public void clearInventoryTest(Env env) { var player = connection.connect(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, player.getInstance()); - Inventory inventory = new Inventory(InventoryType.CHEST_6_ROW, Component.empty()); + Inventory inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_6_ROW, Component.empty()); player.openInventory(inventory); assertEquals(inventory, player.getOpenInventory()); @@ -115,7 +115,7 @@ public void closeInventoryTest(Env env) { var instance = env.createFlatInstance(); var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 42, 0)).join(); - final var inventory = new Inventory(InventoryType.CHEST_1_ROW, "title"); + final var inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_1_ROW, "title"); player.openInventory(inventory); assertSame(inventory, player.getOpenInventory()); player.closeInventory(); @@ -128,7 +128,7 @@ public void openInventoryOnItemDropFromInventoryClosingTest(Env env) { var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 42, 0)).join(); var listener = env.listen(ItemDropEvent.class); - final var firstInventory = new Inventory(InventoryType.CHEST_1_ROW, "title"); + final var firstInventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_1_ROW, "title"); player.openInventory(firstInventory); assertSame(firstInventory, player.getOpenInventory()); firstInventory.setCursorItem(player, ItemStack.of(Material.STONE)); @@ -139,7 +139,7 @@ public void openInventoryOnItemDropFromInventoryClosingTest(Env env) { player.openInventory(firstInventory); firstInventory.setCursorItem(player, ItemStack.of(Material.STONE)); - final var secondInventory = new Inventory(InventoryType.CHEST_1_ROW, "title"); + final var secondInventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_1_ROW, "title"); listener.followup(event -> event.getPlayer().openInventory(secondInventory)); player.closeInventory(); assertSame(secondInventory, player.getOpenInventory()); diff --git a/src/test/java/net/minestom/server/inventory/InventoryTest.java b/src/test/java/net/minestom/server/inventory/InventoryTest.java index 612e3b162f3..1a8688e7f71 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryTest.java @@ -10,14 +10,16 @@ public class InventoryTest { + private static MinecraftServer minecraftServer = new MinecraftServer(); + static { // Required to prevent initialization error during event call - MinecraftServer.init(); + minecraftServer.init(); } @Test public void testCreation() { - Inventory inventory = new Inventory(InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); assertEquals(InventoryType.CHEST_1_ROW, inventory.getInventoryType()); assertEquals(Component.text("title"), inventory.getTitle()); @@ -30,7 +32,7 @@ public void testEntry() { var item1 = ItemStack.of(Material.DIAMOND); var item2 = ItemStack.of(Material.GOLD_INGOT); - Inventory inventory = new Inventory(InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); assertSame(ItemStack.AIR, inventory.getItemStack(0)); inventory.setItemStack(0, item1); assertSame(item1, inventory.getItemStack(0)); @@ -54,7 +56,7 @@ public void testEntry() { @Test public void testTake() { ItemStack item = ItemStack.of(Material.DIAMOND, 32); - Inventory inventory = new Inventory(InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); inventory.setItemStack(0, item); assertTrue(inventory.takeItemStack(item, TransactionOption.DRY_RUN)); assertTrue(inventory.takeItemStack(item.withAmount(31), TransactionOption.DRY_RUN)); @@ -67,7 +69,7 @@ public void testTake() { @Test public void testAdd() { - Inventory inventory = new Inventory(InventoryType.HOPPER, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.HOPPER, "title"); assertTrue(inventory.addItemStack(ItemStack.of(Material.DIAMOND, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.GOLD_BLOCK, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.MAP, 32), TransactionOption.ALL_OR_NOTHING)); @@ -79,7 +81,7 @@ public void testAdd() { @Test public void testIds() { for (int i = 0; i <= 1000; ++i) { - final byte windowId = new Inventory(InventoryType.CHEST_1_ROW, "title").getWindowId(); + final byte windowId = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title").getWindowId(); assertTrue(windowId > 0); } } diff --git a/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java b/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java index 18ac2c3261b..a60172c67cb 100644 --- a/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java @@ -99,7 +99,7 @@ public void heldSelf(Env env) { public void heldExternal(Env env) { var instance = env.createFlatInstance(); var player = env.createPlayer(instance, new Pos(0, 40, 0)); - var inventory = new Inventory(InventoryType.HOPPER, "test"); + var inventory = new Inventory(env.minecraftServer(), InventoryType.HOPPER, "test"); var playerInv = player.getInventory(); player.openInventory(inventory); var listener = env.listen(InventoryPreClickEvent.class); diff --git a/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java b/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java index af9d31a48dd..904a00d2a44 100644 --- a/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java @@ -85,7 +85,7 @@ public void leftSelf(Env env) { public void leftExternal(Env env) { var instance = env.createFlatInstance(); var player = env.createPlayer(instance, new Pos(0, 40, 0)); - var inventory = new Inventory(InventoryType.HOPPER, "test"); + var inventory = new Inventory(env.minecraftServer(), InventoryType.HOPPER, "test"); player.openInventory(inventory); var listener = env.listen(InventoryPreClickEvent.class); inventory.setItemStack(1, ItemStack.of(Material.DIAMOND)); diff --git a/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java b/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java index 98d2be50417..e61fcfdf578 100644 --- a/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java @@ -107,7 +107,7 @@ public void rightSelf(Env env) { public void rightExternal(Env env) { var instance = env.createFlatInstance(); var player = env.createPlayer(instance, new Pos(0, 40, 0)); - var inventory = new Inventory(InventoryType.HOPPER, "test"); + var inventory = new Inventory(env.minecraftServer(), InventoryType.HOPPER, "test"); player.openInventory(inventory); var listener = env.listen(InventoryPreClickEvent.class); inventory.setItemStack(1, ItemStack.of(Material.DIAMOND)); diff --git a/src/test/java/net/minestom/server/network/SendablePacketTest.java b/src/test/java/net/minestom/server/network/SendablePacketTest.java index c7d046a6c5e..261905ed86f 100644 --- a/src/test/java/net/minestom/server/network/SendablePacketTest.java +++ b/src/test/java/net/minestom/server/network/SendablePacketTest.java @@ -1,6 +1,7 @@ package net.minestom.server.network; import net.kyori.adventure.text.Component; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.LazyPacket; import net.minestom.server.network.packet.server.play.SystemChatPacket; @@ -28,11 +29,12 @@ public void lazy() { @Test public void cached() { + MinecraftServer minecraftServer = new MinecraftServer(); var packet = new SystemChatPacket(Component.text("Hello World!"), false); - var cached = new CachedPacket(packet); + var cached = new CachedPacket(minecraftServer, packet); assertSame(packet, cached.packet(ConnectionState.PLAY)); - var buffer = PacketUtils.allocateTrimmedPacket(ConnectionState.PLAY, packet); + var buffer = PacketUtils.allocateTrimmedPacket(minecraftServer, ConnectionState.PLAY, packet); var cachedBuffer = cached.body(ConnectionState.PLAY); assertEquals(buffer.body(), cachedBuffer); // May fail in the very unlikely case where soft references are cleared diff --git a/src/test/java/net/minestom/server/network/SocketWriteTest.java b/src/test/java/net/minestom/server/network/SocketWriteTest.java index 7c7356a3774..ea7bbb4ee51 100644 --- a/src/test/java/net/minestom/server/network/SocketWriteTest.java +++ b/src/test/java/net/minestom/server/network/SocketWriteTest.java @@ -1,5 +1,6 @@ package net.minestom.server.network; +import net.minestom.server.MinecraftServer; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.PacketUtils; @@ -42,10 +43,11 @@ public int getId(@NotNull ConnectionState state) { @Test public void writeSingleUncompressed() { + MinecraftServer minecraftServer = new MinecraftServer(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, false); // 3 bytes length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -54,11 +56,12 @@ public void writeSingleUncompressed() { @Test public void writeMultiUncompressed() { + MinecraftServer minecraftServer = new MinecraftServer(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, false); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, false); // 3 bytes length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -67,6 +70,7 @@ public void writeMultiUncompressed() { @Test public void writeSingleCompressed() { + MinecraftServer minecraftServer = new MinecraftServer(); var string = "Hello world!".repeat(200); var stringLength = string.getBytes(StandardCharsets.UTF_8).length; var lengthLength = Utils.getVarIntSize(stringLength); @@ -74,7 +78,7 @@ public void writeSingleCompressed() { var packet = new CompressiblePacket(string); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + payload // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -83,10 +87,11 @@ public void writeSingleCompressed() { @Test public void writeSingleCompressedSmall() { + MinecraftServer minecraftServer = new MinecraftServer(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -95,11 +100,12 @@ public void writeSingleCompressedSmall() { @Test public void writeMultiCompressedSmall() { + MinecraftServer minecraftServer = new MinecraftServer(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, true); - PacketUtils.writeFramedPacket(ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future diff --git a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java index e3d5357e812..d40fa91293b 100644 --- a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java +++ b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java @@ -1,5 +1,6 @@ package net.minestom.server.network.socket; +import net.minestom.server.MinecraftServer; import net.minestom.server.listener.manager.PacketListenerManager; import net.minestom.server.network.PacketProcessor; import org.junit.jupiter.api.Test; @@ -16,11 +17,12 @@ public class ServerAddressTest { @Test public void inetAddressTest() throws IOException { + MinecraftServer minecraftServer = new MinecraftServer(); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 25565); - var server = new Server(new PacketProcessor(new PacketListenerManager())); + var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -32,11 +34,12 @@ public void inetAddressTest() throws IOException { @Test public void inetAddressDynamicTest() throws IOException { + MinecraftServer minecraftServer = new MinecraftServer(); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 0); - var server = new Server(new PacketProcessor(new PacketListenerManager())); + var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -48,11 +51,12 @@ public void inetAddressDynamicTest() throws IOException { @Test public void unixAddressTest() throws IOException { + MinecraftServer minecraftServer = new MinecraftServer(); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); UnixDomainSocketAddress address = UnixDomainSocketAddress.of("minestom.sock"); - var server = new Server(new PacketProcessor(new PacketListenerManager())); + var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); server.init(address); assertTrue(Files.exists(address.getPath())); assertSame(address, server.socketAddress()); @@ -66,7 +70,8 @@ public void unixAddressTest() throws IOException { @Test public void noAddressTest() throws IOException { - var server = new Server(new PacketProcessor(new PacketListenerManager())); + MinecraftServer minecraftServer = new MinecraftServer(); + var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); assertDoesNotThrow(server::stop); } } diff --git a/src/test/java/net/minestom/server/permission/TestPermissions.java b/src/test/java/net/minestom/server/permission/TestPermissions.java index c5604540d92..1b3fe6c77e2 100644 --- a/src/test/java/net/minestom/server/permission/TestPermissions.java +++ b/src/test/java/net/minestom/server/permission/TestPermissions.java @@ -19,11 +19,13 @@ public class TestPermissions { private Player player; private Permission permission1, permission2, permission3, wildcard; + private MinecraftServer minecraftServer; @BeforeEach public void init() { - MinecraftServer.init(); // for entity manager - player = new Player(UUID.randomUUID(), "TestPlayer", null) { + minecraftServer = new MinecraftServer(); + minecraftServer.init(); // for entity manager + player = new Player(minecraftServer, UUID.randomUUID(), "TestPlayer", null) { @Override protected void playerConnectionInit() { } diff --git a/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java b/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java index 6f0809d0cba..cef31ebbf0b 100644 --- a/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java +++ b/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java @@ -1,8 +1,8 @@ package net.minestom.server.snapshot; +import net.minestom.server.instance.block.Block; import net.minestom.testing.Env; import net.minestom.testing.EnvTest; -import net.minestom.server.instance.block.Block; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -14,7 +14,7 @@ public class ChunkSnapshotIntegrationTest { public void blocks(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 0, 0, Block.STONE); - var snapshot = ServerSnapshot.update(); + var snapshot = ServerSnapshot.update(env.minecraftServer()); var inst = snapshot.instances().iterator().next(); assertEquals(Block.STONE, inst.getBlock(0, 0, 0)); diff --git a/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java b/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java index 734b3c88892..f3d85052f6e 100644 --- a/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java +++ b/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java @@ -1,9 +1,9 @@ package net.minestom.server.snapshot; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,9 +15,9 @@ public class EntitySnapshotIntegrationTest { @Test public void basic(Env env) { var instance = env.createFlatInstance(); - var ent = new Entity(EntityType.ZOMBIE); + var ent = new Entity(env.minecraftServer(), EntityType.ZOMBIE); ent.setInstance(instance).join(); - var snapshot = ServerSnapshot.update(); + var snapshot = ServerSnapshot.update(env.minecraftServer()); var inst = snapshot.instances().iterator().next(); var entities = inst.entities(); diff --git a/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java b/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java index 7863e30ea16..bfebc7f0fc4 100644 --- a/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java +++ b/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java @@ -12,7 +12,7 @@ public class InstanceSnapshotIntegrationTest { @Test public void basic(Env env) { env.createFlatInstance(); - var snapshot = ServerSnapshot.update(); + var snapshot = ServerSnapshot.update(env.minecraftServer()); // Ensure that the collection is immutable { diff --git a/src/test/java/net/minestom/server/thread/AcquirableTest.java b/src/test/java/net/minestom/server/thread/AcquirableTest.java index 43753f55874..383f0373fe3 100644 --- a/src/test/java/net/minestom/server/thread/AcquirableTest.java +++ b/src/test/java/net/minestom/server/thread/AcquirableTest.java @@ -1,5 +1,6 @@ package net.minestom.server.thread; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import org.junit.jupiter.api.Test; @@ -13,8 +14,9 @@ public class AcquirableTest { @Test public void assignation() { + MinecraftServer minecraftServer = new MinecraftServer(); AtomicReference tickThread = new AtomicReference<>(); - Entity entity = new Entity(EntityType.ZOMBIE) { + Entity entity = new Entity(minecraftServer, EntityType.ZOMBIE) { @Override public void tick(long time) { super.tick(time); @@ -24,7 +26,7 @@ public void tick(long time) { Object first = new Object(); Object second = new Object(); - ThreadDispatcher dispatcher = ThreadDispatcher.of(ThreadProvider.counter(), 2); + ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer, ThreadProvider.counter(), 2); dispatcher.createPartition(first); dispatcher.createPartition(second); diff --git a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java index 00f7b48addb..44bd5450226 100644 --- a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java +++ b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java @@ -1,5 +1,6 @@ package net.minestom.server.thread; +import net.minestom.server.MinecraftServer; import net.minestom.server.Tickable; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -18,10 +19,11 @@ public class ThreadDispatcherTest { @Test public void elementTick() { + MinecraftServer minecraftServer = new MinecraftServer(); final AtomicInteger counter = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(minecraftServer); assertEquals(1, dispatcher.threads().size()); - assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(1))); + assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(minecraftServer,1))); var partition = new Object(); Tickable element = (time) -> counter.incrementAndGet(); @@ -46,10 +48,11 @@ public void elementTick() { @Test public void partitionTick() { + MinecraftServer minecraftServer = new MinecraftServer(); // Partitions implementing Tickable should be ticked same as elements final AtomicInteger counter1 = new AtomicInteger(); final AtomicInteger counter2 = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(minecraftServer); assertEquals(1, dispatcher.threads().size()); Tickable partition = (time) -> counter1.incrementAndGet(); @@ -75,9 +78,10 @@ public void partitionTick() { @Test public void uniqueThread() { + MinecraftServer minecraftServer = new MinecraftServer(); // Ensure that partitions are properly dispatched across threads final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(ThreadProvider.counter(), threadCount); + ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer, ThreadProvider.counter(), threadCount); assertEquals(threadCount, dispatcher.threads().size()); final AtomicInteger counter = new AtomicInteger(); @@ -104,6 +108,7 @@ public void uniqueThread() { @Test public void threadUpdate() { + MinecraftServer minecraftServer = new MinecraftServer(); // Ensure that partitions threads are properly updated every tick // when RefreshType.ALWAYS is used interface Updater extends Tickable { @@ -111,7 +116,7 @@ interface Updater extends Tickable { } final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(new ThreadProvider<>() { + ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer, new ThreadProvider<>() { @Override public int findThread(@NotNull Updater partition) { return partition.getValue(); diff --git a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java index fe070a1d175..ad7185d7c9d 100644 --- a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java +++ b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java @@ -5,10 +5,10 @@ import net.kyori.adventure.translation.GlobalTranslator; import net.kyori.adventure.translation.TranslationRegistry; import net.minestom.server.adventure.MinestomAdventure; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Pos; import net.minestom.server.network.packet.server.play.SystemChatPacket; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -39,7 +39,7 @@ public void testTranslationEnabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(List.of(player), packet); + PacketUtils.sendGroupedPacket(env.minecraftServer(), List.of(player), packet); // the message should not be changed if translations are enabled. // the translation of the message itself will be proceeded in PlayerConnectionImpl class @@ -58,7 +58,7 @@ public void testTranslationDisabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = false; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(List.of(player), packet); + PacketUtils.sendGroupedPacket(env.minecraftServer(), List.of(player), packet); collector.assertSingle(received -> { assertEquals(message, received.message()); diff --git a/testing/src/main/java/net/minestom/testing/Env.java b/testing/src/main/java/net/minestom/testing/Env.java index 6961f0c1436..3b4716e5c2e 100644 --- a/testing/src/main/java/net/minestom/testing/Env.java +++ b/testing/src/main/java/net/minestom/testing/Env.java @@ -1,5 +1,6 @@ package net.minestom.testing; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; @@ -14,6 +15,7 @@ import java.util.function.BooleanSupplier; public interface Env { + MinecraftServer minecraftServer(); @NotNull ServerProcess process(); @NotNull TestConnection createConnection(); diff --git a/testing/src/main/java/net/minestom/testing/EnvImpl.java b/testing/src/main/java/net/minestom/testing/EnvImpl.java index 851743fe9ce..7e4b9381c35 100644 --- a/testing/src/main/java/net/minestom/testing/EnvImpl.java +++ b/testing/src/main/java/net/minestom/testing/EnvImpl.java @@ -1,5 +1,6 @@ package net.minestom.testing; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.event.Event; import net.minestom.server.event.EventFilter; @@ -16,9 +17,16 @@ final class EnvImpl implements Env { private final ServerProcess process; private final List> listeners = new CopyOnWriteArrayList<>(); + private final MinecraftServer minecraftServer; - public EnvImpl(ServerProcess process) { - this.process = process; + public EnvImpl() { + this.minecraftServer = new MinecraftServer(); + this.process = minecraftServer.updateProcess(); + } + + @Override + public MinecraftServer minecraftServer() { + return minecraftServer; } @Override diff --git a/testing/src/main/java/net/minestom/testing/EnvTest.java b/testing/src/main/java/net/minestom/testing/EnvTest.java index 310e88da11e..79128453e2f 100644 --- a/testing/src/main/java/net/minestom/testing/EnvTest.java +++ b/testing/src/main/java/net/minestom/testing/EnvTest.java @@ -1,6 +1,5 @@ package net.minestom.testing; -import net.minestom.server.MinecraftServer; import org.junit.jupiter.api.extension.*; import org.junit.jupiter.api.extension.support.TypeBasedParameterResolver; @@ -37,7 +36,7 @@ final class EnvParameterResolver extends TypeBasedParameterResolver { @Override public Env resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { - return new EnvImpl(new MinecraftServer().updateProcess()); + return new EnvImpl(); } } } diff --git a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java index 4a41ec57f18..e74bc4480b9 100644 --- a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java @@ -1,6 +1,7 @@ package net.minestom.testing; import net.kyori.adventure.translation.GlobalTranslator; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.coordinate.Pos; @@ -25,13 +26,14 @@ final class TestConnectionImpl implements TestConnection { private final Env env; private final ServerProcess process; - private final PlayerConnectionImpl playerConnection = new PlayerConnectionImpl(); + private final PlayerConnectionImpl playerConnection; private final List> incomingTrackers = new CopyOnWriteArrayList<>(); TestConnectionImpl(Env env) { this.env = env; this.process = env.process(); + this.playerConnection = new PlayerConnectionImpl(env.minecraftServer()); } @Override @@ -62,8 +64,8 @@ final class TestConnectionImpl implements TestConnection { final class PlayerConnectionImpl extends PlayerConnection { - PlayerConnectionImpl() { - super(); + PlayerConnectionImpl(MinecraftServer minecraftServer) { + super(minecraftServer); } @Override diff --git a/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java b/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java index b21aed14a0c..2210cba6428 100644 --- a/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java @@ -9,7 +9,7 @@ public class TestPlayerImpl extends Player { public TestPlayerImpl(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - super(uuid, username, playerConnection); + super(playerConnection.minecraftServer, uuid, username, playerConnection); } @Override From bef47b8b78270040d67c9a5eab0753ba8be988f6 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Mon, 29 Jan 2024 19:24:10 +0300 Subject: [PATCH 06/16] it starts! --- demo/src/main/java/net/minestom/demo/Main.java | 2 +- demo/src/main/java/net/minestom/demo/PlayerInit.java | 3 +-- .../net/minestom/demo/commands/DimensionCommand.java | 4 ++-- .../net/minestom/demo/commands/DisplayCommand.java | 10 ++++------ .../java/net/minestom/demo/commands/HorseCommand.java | 2 +- .../net/minestom/demo/commands/PlayersCommand.java | 6 +----- .../java/net/minestom/demo/commands/SaveCommand.java | 5 ++--- .../java/net/minestom/demo/commands/ShootCommand.java | 8 ++++---- .../java/net/minestom/demo/commands/SummonCommand.java | 9 +++++---- .../net/minestom/demo/commands/TeleportCommand.java | 3 +-- .../java/net/minestom/demo/entity/ChickenCreature.java | 5 +++-- .../java/net/minestom/demo/entity/ZombieCreature.java | 5 +++-- src/main/java/net/minestom/server/MinecraftServer.java | 3 +-- .../java/net/minestom/server/ServerProcessImpl.java | 5 +++-- .../net/minestom/server/network/ConnectionManager.java | 5 +++-- 15 files changed, 35 insertions(+), 40 deletions(-) diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index 2d496200d94..a237e85d4aa 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -40,7 +40,7 @@ public static void main(String[] args) { commandManager.register(new EntitySelectorCommand()); commandManager.register(new HealthCommand()); commandManager.register(new LegacyCommand()); - commandManager.register(new DimensionCommand()); + commandManager.register(new DimensionCommand(minecraftServer)); commandManager.register(new ShutdownCommand(minecraftServer)); commandManager.register(new TeleportCommand()); commandManager.register(new PlayersCommand()); diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index 6680f10b3be..fc6ba86c0bd 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -7,7 +7,6 @@ import net.minestom.server.advancements.notifications.Notification; import net.minestom.server.advancements.notifications.NotificationCenter; import net.minestom.server.adventure.MinestomAdventure; -import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; @@ -225,7 +224,7 @@ public void init() { .append(Component.newline()) .append(Component.text("ACQ TIME: " + MathUtils.round(tickMonitor.getAcquisitionTime(), 2) + "ms")); final Component footer = benchmarkManager.getCpuMonitoringMessage(); - Audiences.players().sendPlayerListHeaderAndFooter(header, footer); + serverProcess.getAudiences().players().sendPlayerListHeaderAndFooter(header, footer); }).repeat(10, TimeUnit.SERVER_TICK); //.schedule(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java index c14d0e0537f..b112d4643e7 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java @@ -10,14 +10,14 @@ public class DimensionCommand extends Command { - public DimensionCommand() { + public DimensionCommand(MinecraftServer minecraftServer) { super("dimensiontest"); setCondition(Conditions::playerOnly); addSyntax((sender, context) -> { final Player player = (Player) sender; final Instance instance = player.getInstance(); - final var instances = MinecraftServer.getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); + final var instances = minecraftServer.process().getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); if (instances.isEmpty()) { player.sendMessage("No instance available"); return; diff --git a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java index 07b3701defd..17a9bdf0b01 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java @@ -1,12 +1,10 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.ArgumentType; -import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.Player; @@ -40,7 +38,7 @@ public void spawnItem(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(EntityType.ITEM_DISPLAY); + var entity = new Entity(sender.getMinecraftServer(), EntityType.ITEM_DISPLAY); var meta = (ItemDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setItemStack(ItemStack.of(Material.STICK)); @@ -55,7 +53,7 @@ public void spawnBlock(@NotNull CommandSender sender, @NotNull CommandContext co if (!(sender instanceof Player player)) return; - var entity = new Entity(EntityType.BLOCK_DISPLAY); + var entity = new Entity(sender.getMinecraftServer(), EntityType.BLOCK_DISPLAY); var meta = (BlockDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBlockState(Block.ORANGE_CANDLE_CAKE.stateId()); @@ -70,7 +68,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(EntityType.TEXT_DISPLAY); + var entity = new Entity(sender.getMinecraftServer(), EntityType.TEXT_DISPLAY); var meta = (TextDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBillboardRenderConstraints(AbstractDisplayMeta.BillboardConstraints.CENTER); @@ -85,7 +83,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con private void startSmoothFollow(@NotNull Entity entity, @NotNull Player player) { // entity.setCustomName(Component.text("MY CUSTOM NAME")); // entity.setCustomNameVisible(true); - MinecraftServer.getSchedulerManager().buildTask(() -> { + entity.getMinecraftServer().process().getSchedulerManager().buildTask(() -> { var meta = (AbstractDisplayMeta) entity.getEntityMeta(); meta.setNotifyAboutChanges(false); meta.setTransformationInterpolationStartDelta(1); diff --git a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java index 2a50173d121..f44a99a0baf 100644 --- a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java @@ -59,7 +59,7 @@ private void onHorseCommand(CommandSender sender, CommandContext context) { boolean baby = context.get("baby"); HorseMeta.Marking marking = context.get("marking"); HorseMeta.Color color = context.get("color"); - var horse = new EntityCreature(EntityType.HORSE); + var horse = new EntityCreature(sender.getMinecraftServer(), EntityType.HORSE); var meta = (HorseMeta) horse.getEntityMeta(); meta.setBaby(baby); meta.setVariant(new HorseMeta.Variant(marking, color)); diff --git a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java index 0c4211c3d96..5a3c271065d 100644 --- a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java @@ -1,14 +1,10 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; -import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionState; -import java.util.Collection; import java.util.List; public class PlayersCommand extends Command { @@ -19,7 +15,7 @@ public PlayersCommand() { } private void usage(CommandSender sender, CommandContext context) { - final var players = List.copyOf(MinecraftServer.getConnectionManager().getOnlinePlayers()); + final var players = List.copyOf(sender.getMinecraftServer().process().getConnectionManager().getOnlinePlayers()); final int playerCount = players.size(); sender.sendMessage(Component.text("Total players: " + playerCount)); diff --git a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java index 6703f8292eb..0dee3f09398 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java @@ -1,6 +1,5 @@ package net.minestom.demo.commands; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -20,12 +19,12 @@ public SaveCommand() { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - for(var instance : MinecraftServer.getInstanceManager().getInstances()) { + for(var instance : commandSender.getMinecraftServer().process().getInstanceManager().getInstances()) { CompletableFuture instanceSave = instance.saveInstance().thenCompose(v -> instance.saveChunksToStorage()); try { instanceSave.get(); } catch (InterruptedException | ExecutionException e) { - MinecraftServer.getExceptionManager().handleException(e); + commandSender.getMinecraftServer().process().getExceptionManager().handleException(e); } } commandSender.sendMessage("Saving done!"); diff --git a/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java index c7692312d1f..0224ffd91e5 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java @@ -7,10 +7,10 @@ import net.minestom.server.command.builder.arguments.ArgumentType; import net.minestom.server.command.builder.condition.Conditions; import net.minestom.server.command.builder.exception.ArgumentSyntaxException; +import net.minestom.server.entity.EntityProjectile; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.Player; import net.minestom.server.entity.metadata.projectile.ArrowMeta; -import net.minestom.server.entity.EntityProjectile; import java.util.concurrent.ThreadLocalRandom; @@ -39,13 +39,13 @@ private void onShootCommand(CommandSender sender, CommandContext context) { EntityProjectile projectile; switch (mode) { case "default": - projectile = new EntityProjectile(player, EntityType.ARROW); + projectile = new EntityProjectile(player.getMinecraftServer(), player, EntityType.ARROW); break; case "spectral": - projectile = new EntityProjectile(player, EntityType.SPECTRAL_ARROW); + projectile = new EntityProjectile(player.getMinecraftServer(), player, EntityType.SPECTRAL_ARROW); break; case "colored": - projectile = new EntityProjectile(player, EntityType.ARROW); + projectile = new EntityProjectile(player.getMinecraftServer(), player, EntityType.ARROW); var meta = (ArrowMeta) projectile.getEntityMeta(); meta.setColor(ThreadLocalRandom.current().nextInt()); break; diff --git a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java index a12dea635d3..804b42b17eb 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java @@ -1,5 +1,6 @@ package net.minestom.demo.commands; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -37,7 +38,7 @@ public SummonCommand() { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - final Entity entity = commandContext.get(entityClass).instantiate(commandContext.get(this.entity)); + final Entity entity = commandContext.get(entityClass).instantiate(commandSender.getMinecraftServer(), commandContext.get(this.entity)); //noinspection ConstantConditions - One couldn't possibly execute a command without being in an instance entity.setInstance(((Player) commandSender).getInstance(), commandContext.get(pos).fromSender(commandSender)); } @@ -53,12 +54,12 @@ enum EntityClass { this.factory = factory; } - public Entity instantiate(EntityType type) { - return factory.newInstance(type); + public Entity instantiate(MinecraftServer minecraftServer, EntityType type) { + return factory.newInstance(minecraftServer, type); } } interface EntityFactory { - Entity newInstance(EntityType type); + Entity newInstance(MinecraftServer minecraftServer, EntityType type); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java index 08e5a822df1..98ee3076e60 100644 --- a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java @@ -1,7 +1,6 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -26,7 +25,7 @@ public TeleportCommand() { private void onPlayerTeleport(CommandSender sender, CommandContext context) { final String playerName = context.get("player"); - Player pl = MinecraftServer.getConnectionManager().getOnlinePlayerByUsername(playerName); + Player pl = sender.getMinecraftServer().process().getConnectionManager().getOnlinePlayerByUsername(playerName); if (sender instanceof Player player) { player.teleport(pl.getPosition()); } diff --git a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java index 6f241e422c3..a6aaee53ef8 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java @@ -1,5 +1,6 @@ package net.minestom.demo.entity; +import net.minestom.server.MinecraftServer; import net.minestom.server.attribute.Attribute; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; @@ -9,8 +10,8 @@ public class ChickenCreature extends EntityCreature { - public ChickenCreature() { - super(EntityType.CHICKEN); + public ChickenCreature(MinecraftServer minecraftServer) { + super(minecraftServer, EntityType.CHICKEN); addAIGroup( List.of( diff --git a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java index ccaa561ea52..e9b89f58fe5 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java @@ -1,5 +1,6 @@ package net.minestom.demo.entity; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.ai.EntityAIGroupBuilder; @@ -7,8 +8,8 @@ public class ZombieCreature extends EntityCreature { - public ZombieCreature() { - super(EntityType.ZOMBIE); + public ZombieCreature(MinecraftServer minecraftServer) { + super(minecraftServer, EntityType.ZOMBIE); addAIGroup( new EntityAIGroupBuilder() .addGoalSelector(new RandomLookAroundGoal(this, 20)) diff --git a/src/main/java/net/minestom/server/MinecraftServer.java b/src/main/java/net/minestom/server/MinecraftServer.java index 5f574954a25..ba18160f255 100644 --- a/src/main/java/net/minestom/server/MinecraftServer.java +++ b/src/main/java/net/minestom/server/MinecraftServer.java @@ -41,7 +41,7 @@ public final class MinecraftServer { public static final int TICK_MS = 1000 / TICK_PER_SECOND; // In-Game Manager - private volatile ServerProcess serverProcess; + volatile ServerProcess serverProcess; private int chunkViewDistance = Integer.getInteger("minestom.chunk-view-distance", 8); private int entityViewDistance = Integer.getInteger("minestom.entity-view-distance", 5); @@ -59,7 +59,6 @@ public ServerProcess updateProcess() { ServerProcess process; try { process = new ServerProcessImpl(this); - serverProcess = process; } catch (IOException e) { throw new RuntimeException(e); } diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java index 35170997b3a..64a921d47b6 100644 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -76,9 +76,9 @@ final class ServerProcessImpl implements ServerProcess { private final MojangAuth mojangAuth; public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { + minecraftServer.serverProcess = this; this.minecraftServer = minecraftServer; this.exceptionManager = new ExceptionManager(minecraftServer); - this.connectionManager = new ConnectionManager(minecraftServer); this.packetListenerManager = new PacketListenerManager(minecraftServer); this.packetProcessor = new PacketProcessor(packetListenerManager); this.instanceManager = new InstanceManager(minecraftServer); @@ -94,9 +94,10 @@ public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { this.advancementManager = new AdvancementManager(minecraftServer); this.bossBarManager = new BossBarManager(minecraftServer); this.tagManager = new TagManager(); + this.connectionManager = new ConnectionManager(minecraftServer, tagManager); this.server = new Server(minecraftServer, packetProcessor); - this.audiences = new Audiences(minecraftServer); this.mojangAuth = new MojangAuth(minecraftServer); + this.audiences = new Audiences(minecraftServer); this.dispatcher = ThreadDispatcher.singleThread(minecraftServer); this.ticker = new TickerImpl(); diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index dba52286a19..b7c4aba91e9 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -8,6 +8,7 @@ import net.minestom.server.entity.damage.DamageType; import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; import net.minestom.server.event.player.AsyncPlayerPreLoginEvent; +import net.minestom.server.gamedata.tags.TagManager; import net.minestom.server.instance.Instance; import net.minestom.server.message.Messenger; import net.minestom.server.network.packet.client.login.ClientLoginStartPacket; @@ -81,10 +82,10 @@ public final class ConnectionManager { private final PlayerProvider defaultPlayerProvider; private volatile PlayerProvider playerProvider; - public ConnectionManager(MinecraftServer minecraftServer) { + public ConnectionManager(MinecraftServer minecraftServer, TagManager tagManager) { this.minecraftServer = minecraftServer; this.serverProcess = minecraftServer.process(); - this.defaultTags = new CachedPacket(minecraftServer, new TagsPacket(serverProcess.getTagManager().getTagMap())); + this.defaultTags = new CachedPacket(minecraftServer, new TagsPacket(tagManager.getTagMap())); defaultPlayerProvider = (uuid, username, connection) -> new Player(minecraftServer, uuid, username, connection); playerProvider = defaultPlayerProvider; } From 2f49b7005b6e7ecfb5b44afd5853dd74e493887f Mon Sep 17 00:00:00 2001 From: MelonHell Date: Tue, 30 Jan 2024 15:26:52 +0300 Subject: [PATCH 07/16] now it looks good --- build.gradle.kts | 2 + .../src/main/java/net/minestom/demo/Main.java | 30 +-- .../java/net/minestom/demo/PlayerInit.java | 17 +- .../demo/commands/DimensionCommand.java | 6 +- .../demo/commands/DisplayCommand.java | 13 +- .../minestom/demo/commands/HorseCommand.java | 2 +- .../demo/commands/PlayersCommand.java | 2 +- .../minestom/demo/commands/SaveCommand.java | 4 +- .../minestom/demo/commands/ShootCommand.java | 6 +- .../demo/commands/ShutdownCommand.java | 10 +- .../demo/commands/SidebarCommand.java | 6 +- .../minestom/demo/commands/SummonCommand.java | 10 +- .../demo/commands/TeleportCommand.java | 2 +- .../minestom/demo/entity/ChickenCreature.java | 6 +- .../minestom/demo/entity/ZombieCreature.java | 6 +- .../net/minestom/server/MinecraftServer.java | 226 ------------------ .../server/MinecraftServerObject.java | 5 - .../net/minestom/server/ServerConsts.java | 12 + .../net/minestom/server/ServerObject.java | 5 + .../net/minestom/server/ServerProcess.java | 13 + .../minestom/server/ServerProcessImpl.java | 51 ++-- .../net/minestom/server/ServerSettings.java | 65 +++++ .../minestom/server/ServerSettingsImpl.java | 122 ++++++++++ .../java/net/minestom/server/Viewable.java | 6 +- .../advancements/AdvancementManager.java | 10 +- .../server/advancements/AdvancementTab.java | 12 +- .../server/adventure/audience/Audiences.java | 14 +- .../audience/IterableAudienceProvider.java | 14 +- .../audience/PacketGroupingAudience.java | 20 +- .../audience/SingleAudienceProvider.java | 18 +- .../adventure/bossbar/BossBarHolder.java | 12 +- .../adventure/bossbar/BossBarListener.java | 18 +- .../adventure/bossbar/BossBarManager.java | 18 +- .../server/command/CommandManager.java | 18 +- .../server/command/CommandSender.java | 6 +- .../server/command/ConsoleSender.java | 12 +- .../minestom/server/command/ServerSender.java | 12 +- .../command/builder/CommandDispatcher.java | 6 +- .../builder/arguments/ArgumentCommand.java | 2 +- .../arguments/minecraft/ArgumentTime.java | 4 +- .../server/crypto/SignatureValidator.java | 6 +- .../net/minestom/server/entity/Entity.java | 78 +++--- .../server/entity/EntityCreature.java | 12 +- .../server/entity/EntityProjectile.java | 14 +- .../minestom/server/entity/EntityView.java | 2 +- .../minestom/server/entity/ExperienceOrb.java | 6 +- .../minestom/server/entity/ItemEntity.java | 17 +- .../minestom/server/entity/LivingEntity.java | 25 +- .../net/minestom/server/entity/Player.java | 105 ++++---- .../server/entity/PlayerProjectile.java | 14 +- .../entity/ai/goal/CombinedAttackGoal.java | 5 +- .../entity/ai/goal/MeleeAttackGoal.java | 5 +- .../entity/ai/goal/RangedAttackGoal.java | 5 +- .../server/entity/fakeplayer/FakePlayer.java | 28 +-- .../server/entity/hologram/Hologram.java | 8 +- .../net/minestom/server/event/EventNode.java | 37 +-- .../minestom/server/event/EventNodeImpl.java | 17 +- .../server/event/EventNodeLazyImpl.java | 6 +- .../server/event/GlobalEventHandler.java | 6 +- .../event/server/ServerListPingEvent.java | 10 +- .../server/exception/ExceptionManager.java | 10 +- .../minestom/server/extras/MojangAuth.java | 12 +- .../minestom/server/extras/lan/OpenToLAN.java | 16 +- .../server/extras/mojangAuth/MojangCrypt.java | 18 +- .../minestom/server/extras/query/Query.java | 15 +- .../extras/query/event/BasicQueryEvent.java | 6 +- .../extras/query/event/FullQueryEvent.java | 8 +- .../query/response/BasicQueryResponse.java | 14 +- .../query/response/FullQueryResponse.java | 16 +- .../extras/query/response/QueryKey.java | 33 ++- .../minestom/server/instance/AnvilLoader.java | 16 +- .../net/minestom/server/instance/Chunk.java | 6 + .../server/instance/DynamicChunk.java | 16 +- .../server/instance/EntityTracker.java | 9 +- .../server/instance/EntityTrackerImpl.java | 25 +- .../minestom/server/instance/Explosion.java | 2 +- .../server/instance/GeneratorImpl.java | 44 ++-- .../server/instance/IChunkLoader.java | 8 +- .../minestom/server/instance/Instance.java | 34 ++- .../server/instance/InstanceContainer.java | 48 ++-- .../server/instance/InstanceManager.java | 20 +- .../server/instance/LightingChunk.java | 4 +- .../net/minestom/server/instance/Section.java | 6 +- .../server/instance/SharedInstance.java | 6 +- .../minestom/server/instance/WorldBorder.java | 2 +- .../instance/palette/AdaptivePalette.java | 12 +- .../instance/palette/FlexiblePalette.java | 16 +- .../server/instance/palette/Palette.java | 14 +- .../server/inventory/AbstractInventory.java | 22 +- .../minestom/server/inventory/Inventory.java | 23 +- .../server/inventory/PlayerInventory.java | 14 +- .../click/InventoryClickProcessor.java | 12 +- .../server/inventory/type/AnvilInventory.java | 10 +- .../inventory/type/BeaconInventory.java | 10 +- .../inventory/type/BrewingStandInventory.java | 10 +- .../type/EnchantmentTableInventory.java | 10 +- .../inventory/type/FurnaceInventory.java | 10 +- .../inventory/type/VillagerInventory.java | 14 +- .../server/listener/AbilitiesListener.java | 4 +- .../listener/AdvancementTabListener.java | 2 +- .../server/listener/AnimationListener.java | 2 +- .../listener/BlockPlacementListener.java | 10 +- .../server/listener/BookListener.java | 2 +- .../server/listener/ChatMessageListener.java | 8 +- .../server/listener/EntityActionListener.java | 10 +- .../server/listener/PlayConfigListener.java | 2 +- .../listener/PlayerDiggingListener.java | 8 +- .../server/listener/PlayerHeldListener.java | 2 +- .../listener/PlayerPositionListener.java | 2 +- .../server/listener/SpectateListener.java | 2 +- .../server/listener/TabCompleteListener.java | 2 +- .../server/listener/UseEntityListener.java | 4 +- .../server/listener/UseItemListener.java | 6 +- .../server/listener/WindowListener.java | 2 +- .../common/PluginMessageListener.java | 2 +- .../listener/common/ResourcePackListener.java | 2 +- .../listener/common/SettingsListener.java | 2 +- .../manager/PacketListenerManager.java | 12 +- .../listener/preplay/ConfigListener.java | 2 +- .../listener/preplay/HandshakeListener.java | 6 +- .../listener/preplay/LoginListener.java | 32 +-- .../listener/preplay/StatusListener.java | 8 +- .../minestom/server/message/Messenger.java | 6 +- .../server/monitoring/BenchmarkManager.java | 20 +- .../server/network/ConnectionManager.java | 24 +- .../network/packet/server/CachedPacket.java | 14 +- .../server/common/PluginMessagePacket.java | 6 +- .../network/player/FakePlayerConnection.java | 6 +- .../network/player/PlayerConnection.java | 25 +- .../player/PlayerSocketConnection.java | 22 +- .../server/network/socket/Server.java | 21 +- .../server/network/socket/Worker.java | 16 +- .../minestom/server/ping/ResponseData.java | 23 +- .../server/ping/ServerListPingType.java | 2 +- .../server/scoreboard/BelowNameTag.java | 18 +- .../minestom/server/scoreboard/Sidebar.java | 20 +- .../minestom/server/scoreboard/TabList.java | 12 +- .../net/minestom/server/scoreboard/Team.java | 20 +- .../server/scoreboard/TeamBuilder.java | 6 +- .../server/scoreboard/TeamManager.java | 14 +- .../server/snapshot/ServerSnapshot.java | 11 +- .../server/snapshot/SnapshotImpl.java | 6 +- .../minestom/server/thread/Acquirable.java | 8 +- .../server/thread/AcquirableCollection.java | 6 +- .../server/thread/ThreadDispatcher.java | 14 +- .../server/thread/TickSchedulerThread.java | 6 +- .../minestom/server/thread/TickThread.java | 15 +- .../minestom/server/utils/PacketUtils.java | 58 ++--- .../net/minestom/server/utils/TickUtils.java | 8 +- .../server/utils/async/AsyncUtils.java | 6 +- .../server/utils/entity/EntityFinder.java | 6 +- .../net/minestom/server/utils/time/Tick.java | 30 ++- .../minestom/server/utils/time/TimeUnit.java | 12 +- .../net/minestom/server/world/Difficulty.java | 5 +- .../minestom/server/ServerProcessTest.java | 5 +- .../EntityBlockPhysicsIntegrationTest.java | 126 +++++----- .../EntityBlockTouchTickIntegrationTest.java | 8 +- ...ityProjectileCollisionIntegrationTest.java | 43 ++-- .../PlacementCollisionIntegrationTest.java | 4 +- .../minestom/server/command/ArgumentTest.java | 17 +- .../server/command/ArgumentTypeTest.java | 34 +-- .../server/command/CommandConditionTest.java | 17 +- .../server/command/CommandManagerTest.java | 19 +- .../command/CommandPacketFilteringTest.java | 7 +- .../server/command/CommandParseTest.java | 7 +- .../server/command/CommandSenderTest.java | 4 +- .../command/CommandSyntaxMultiTest.java | 7 +- .../command/CommandSyntaxSingleTest.java | 7 +- .../minestom/server/command/CommandTest.java | 7 +- .../server/command/SubcommandTest.java | 11 +- .../EntityBoundingBoxIntegrationTest.java | 4 +- .../entity/EntityInstanceIntegrationTest.java | 2 +- .../EntityLineOfSightIntegrationTest.java | 30 +-- .../entity/EntityMetaIntegrationTest.java | 2 +- .../EntityProjectileIntegrationTest.java | 8 +- .../entity/EntityRemovalIntegrationTest.java | 16 +- .../entity/EntityTeleportIntegrationTest.java | 4 +- .../entity/EntityVelocityIntegrationTest.java | 10 +- .../EntityViewDirectionIntegrationTest.java | 12 +- .../entity/EntityViewIntegrationTest.java | 10 +- .../entity/PassengerIntegrationTest.java | 8 +- .../entity/ai/ClosestEntityTargetTest.java | 10 +- .../player/PlayerMovementIntegrationTest.java | 2 +- .../PlayerRespawnChunkIntegrationTest.java | 4 +- .../server/event/EventNodeGraphTest.java | 27 ++- .../server/event/EventNodeMapTest.java | 30 +-- .../server/event/EventNodeQueryTest.java | 37 +-- .../minestom/server/event/EventNodeTest.java | 49 ++-- .../instance/AnvilLoaderIntegrationTest.java | 4 +- .../instance/ChunkViewerIntegrationTest.java | 2 +- .../EntityTrackerIntegrationTest.java | 18 +- .../server/instance/EntityTrackerTest.java | 53 ++-- .../server/instance/GeneratorTest.java | 97 ++++---- .../instance/InstanceContainerTest.java | 7 +- .../InstanceUnregisterIntegrationTest.java | 2 +- .../server/instance/light/BlockLightTest.java | 43 ++-- .../light/LightParityIntegrationTest.java | 14 +- .../palette/PaletteOptimizationTest.java | 23 +- .../server/instance/palette/PaletteTest.java | 87 +++---- .../inventory/InventoryCloseStateTest.java | 2 +- .../inventory/InventoryIntegrationTest.java | 12 +- .../server/inventory/InventoryTest.java | 20 +- .../integration/HeldClickIntegrationTest.java | 2 +- .../integration/LeftClickIntegrationTest.java | 2 +- .../RightClickIntegrationTest.java | 2 +- .../server/network/SendablePacketTest.java | 9 +- .../server/network/SocketWriteTest.java | 27 ++- .../network/socket/ServerAddressTest.java | 21 +- .../server/permission/TestPermissions.java | 10 +- .../ChunkSnapshotIntegrationTest.java | 2 +- .../EntitySnapshotIntegrationTest.java | 4 +- .../InstanceSnapshotIntegrationTest.java | 2 +- .../server/thread/AcquirableTest.java | 9 +- .../server/thread/ThreadDispatcherTest.java | 21 +- .../utils/TranslationIntegrationTest.java | 4 +- .../main/java/net/minestom/testing/Env.java | 3 +- .../java/net/minestom/testing/EnvImpl.java | 11 +- .../minestom/testing/TestConnectionImpl.java | 7 +- .../net/minestom/testing/TestPlayerImpl.java | 2 +- 219 files changed, 1766 insertions(+), 1744 deletions(-) delete mode 100644 src/main/java/net/minestom/server/MinecraftServer.java delete mode 100644 src/main/java/net/minestom/server/MinecraftServerObject.java create mode 100644 src/main/java/net/minestom/server/ServerConsts.java create mode 100644 src/main/java/net/minestom/server/ServerObject.java create mode 100644 src/main/java/net/minestom/server/ServerSettings.java create mode 100644 src/main/java/net/minestom/server/ServerSettingsImpl.java diff --git a/build.gradle.kts b/build.gradle.kts index 0e18d6c9ea6..4233e4b2af5 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -47,6 +47,8 @@ allprojects { tasks.withType { useJUnitPlatform() + maxHeapSize = "2048m" + // Viewable packets make tracking harder. Could be re-enabled later. jvmArgs("-Dminestom.viewable-packet=false") jvmArgs("-Dminestom.inside-test=true") diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index a237e85d4aa..5635b7385fa 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -8,7 +8,8 @@ import net.minestom.demo.block.TestBlockHandler; import net.minestom.demo.block.placement.DripstonePlacementRule; import net.minestom.demo.commands.*; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.CommandManager; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.extras.lan.OpenToLAN; @@ -25,23 +26,22 @@ public class Main { public static void main(String[] args) { System.setProperty("minestom.experiment.pose-updates", "true"); - MinecraftServer minecraftServer = new MinecraftServer(); + ServerSettings serverSettings = ServerSettings.builder().compressionThreshold(0).build(); - minecraftServer.setCompressionThreshold(0); + ServerProcess serverProcess = ServerProcess.of(serverSettings); - minecraftServer.init(); - BlockManager blockManager = minecraftServer.process().getBlockManager(); + BlockManager blockManager = serverProcess.getBlockManager(); blockManager.registerBlockPlacementRule(new DripstonePlacementRule()); blockManager.registerHandler(TestBlockHandler.INSTANCE.getNamespaceId(), () -> TestBlockHandler.INSTANCE); - CommandManager commandManager = minecraftServer.process().getCommandManager(); + CommandManager commandManager = serverProcess.getCommandManager(); commandManager.register(new TestCommand()); commandManager.register(new EntitySelectorCommand()); commandManager.register(new HealthCommand()); commandManager.register(new LegacyCommand()); - commandManager.register(new DimensionCommand(minecraftServer)); - commandManager.register(new ShutdownCommand(minecraftServer)); + commandManager.register(new DimensionCommand(serverProcess)); + commandManager.register(new ShutdownCommand(serverProcess)); commandManager.register(new TeleportCommand()); commandManager.register(new PlayersCommand()); commandManager.register(new FindCommand()); @@ -63,15 +63,15 @@ public static void main(String[] args) { commandManager.register(new NotificationCommand()); commandManager.register(new TestCommand2()); commandManager.register(new ConfigCommand()); - commandManager.register(new SidebarCommand(minecraftServer)); + commandManager.register(new SidebarCommand(serverProcess)); commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED))); - minecraftServer.process().getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); + serverProcess.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); - minecraftServer.process().getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); + serverProcess.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); - minecraftServer.process().getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { + serverProcess.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { ResponseData responseData = event.getResponseData(); responseData.addEntry(NamedAndIdentified.named("The first line is separated from the others")); responseData.addEntry(NamedAndIdentified.named("Could be a name, or a message")); @@ -105,7 +105,7 @@ public static void main(String[] args) { //responseData.setPlayersHidden(true); }); - new PlayerInit(minecraftServer).init(); + new PlayerInit(serverProcess).init(); // VelocityProxy.enable("abcdef"); //BungeeCordProxy.enable(); @@ -113,9 +113,9 @@ public static void main(String[] args) { //MojangAuth.init(); // useful for testing - we don't need to worry about event calls so just set this to a long time - new OpenToLAN(minecraftServer).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); + new OpenToLAN(serverProcess).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); - minecraftServer.start("0.0.0.0", 25565); + serverProcess.start("0.0.0.0", 25565); // minecraftServer.start(java.net.UnixDomainSocketAddress.of("minestom-demo.sock")); //Runtime.getRuntime().addShutdownHook(new Thread(MinecraftServer::stopCleanly)); } diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index fc6ba86c0bd..23b4a4a6b99 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -1,7 +1,6 @@ package net.minestom.demo; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.advancements.FrameType; import net.minestom.server.advancements.notifications.Notification; @@ -47,12 +46,10 @@ public class PlayerInit { - private final MinecraftServer minecraftServer; private final ServerProcess serverProcess; - public PlayerInit(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); + public PlayerInit(ServerProcess serverProcess) { + this.serverProcess = serverProcess; InstanceManager instanceManager = serverProcess.getInstanceManager(); InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); @@ -73,10 +70,10 @@ public PlayerInit(MinecraftServer minecraftServer) { // System.out.println("load end"); // }); - inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, Component.text("Test inventory")); + inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, Component.text("Test inventory")); inventory.setItemStack(3, ItemStack.of(Material.DIAMOND, 34)); - DEMO_NODE = EventNode.all(minecraftServer, "demo") + DEMO_NODE = EventNode.all(serverProcess, "demo") .addListener(EntityAttackEvent.class, event -> { final Entity source = event.getEntity(); final Entity entity = event.getTarget(); @@ -106,13 +103,13 @@ public PlayerInit(MinecraftServer minecraftServer) { ItemStack droppedItem = event.getItemStack(); Pos playerPos = player.getPosition(); - ItemEntity itemEntity = new ItemEntity(minecraftServer, droppedItem); + ItemEntity itemEntity = new ItemEntity(serverProcess, droppedItem); itemEntity.setPickupDelay(Duration.of(500, TimeUnit.MILLISECOND)); itemEntity.setInstance(player.getInstance(), playerPos.withY(y -> y + 1.5)); Vec velocity = playerPos.direction().mul(6); itemEntity.setVelocity(velocity); - FakePlayer.initPlayer(minecraftServer, UUID.randomUUID(), "fake123", fp -> { + FakePlayer.initPlayer(serverProcess, UUID.randomUUID(), "fake123", fp -> { System.out.println("fp = " + fp); }); }) @@ -225,6 +222,6 @@ public void init() { .append(Component.text("ACQ TIME: " + MathUtils.round(tickMonitor.getAcquisitionTime(), 2) + "ms")); final Component footer = benchmarkManager.getCpuMonitoringMessage(); serverProcess.getAudiences().players().sendPlayerListHeaderAndFooter(header, footer); - }).repeat(10, TimeUnit.SERVER_TICK); //.schedule(); + }).repeat(10, TimeUnit.getServerTick(serverProcess.getMinecraftServer())); //.schedule(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java index b112d4643e7..24daa987f84 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.condition.Conditions; import net.minestom.server.entity.Player; @@ -10,14 +10,14 @@ public class DimensionCommand extends Command { - public DimensionCommand(MinecraftServer minecraftServer) { + public DimensionCommand(ServerProcess serverProcess) { super("dimensiontest"); setCondition(Conditions::playerOnly); addSyntax((sender, context) -> { final Player player = (Player) sender; final Instance instance = player.getInstance(); - final var instances = minecraftServer.process().getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); + final var instances = serverProcess.getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); if (instances.isEmpty()) { player.sendMessage("No instance available"); return; diff --git a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java index 17a9bdf0b01..c982c582fea 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java @@ -18,6 +18,8 @@ import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; +import java.time.temporal.TemporalUnit; + public class DisplayCommand extends Command { public DisplayCommand() { @@ -38,7 +40,7 @@ public void spawnItem(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(sender.getMinecraftServer(), EntityType.ITEM_DISPLAY); + var entity = new Entity(sender.getServerProcess(), EntityType.ITEM_DISPLAY); var meta = (ItemDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setItemStack(ItemStack.of(Material.STICK)); @@ -53,7 +55,7 @@ public void spawnBlock(@NotNull CommandSender sender, @NotNull CommandContext co if (!(sender instanceof Player player)) return; - var entity = new Entity(sender.getMinecraftServer(), EntityType.BLOCK_DISPLAY); + var entity = new Entity(sender.getServerProcess(), EntityType.BLOCK_DISPLAY); var meta = (BlockDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBlockState(Block.ORANGE_CANDLE_CAKE.stateId()); @@ -68,7 +70,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(sender.getMinecraftServer(), EntityType.TEXT_DISPLAY); + var entity = new Entity(sender.getServerProcess(), EntityType.TEXT_DISPLAY); var meta = (TextDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBillboardRenderConstraints(AbstractDisplayMeta.BillboardConstraints.CENTER); @@ -83,7 +85,8 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con private void startSmoothFollow(@NotNull Entity entity, @NotNull Player player) { // entity.setCustomName(Component.text("MY CUSTOM NAME")); // entity.setCustomNameVisible(true); - entity.getMinecraftServer().process().getSchedulerManager().buildTask(() -> { + TemporalUnit serverTick = TimeUnit.getServerTick(entity.getServerProcess().getMinecraftServer()); + entity.getServerProcess().getSchedulerManager().buildTask(() -> { var meta = (AbstractDisplayMeta) entity.getEntityMeta(); meta.setNotifyAboutChanges(false); meta.setTransformationInterpolationStartDelta(1); @@ -93,6 +96,6 @@ private void startSmoothFollow(@NotNull Entity entity, @NotNull Player player) { // meta.setScale(new Vec(5, 5, 5)); meta.setTranslation(player.getPosition().sub(entity.getPosition())); meta.setNotifyAboutChanges(true); - }).delay(20, TimeUnit.SERVER_TICK).repeat(20, TimeUnit.SERVER_TICK).schedule(); + }).delay(20, serverTick).repeat(20, serverTick).schedule(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java index f44a99a0baf..617a5c4e6ee 100644 --- a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java @@ -59,7 +59,7 @@ private void onHorseCommand(CommandSender sender, CommandContext context) { boolean baby = context.get("baby"); HorseMeta.Marking marking = context.get("marking"); HorseMeta.Color color = context.get("color"); - var horse = new EntityCreature(sender.getMinecraftServer(), EntityType.HORSE); + var horse = new EntityCreature(sender.getServerProcess(), EntityType.HORSE); var meta = (HorseMeta) horse.getEntityMeta(); meta.setBaby(baby); meta.setVariant(new HorseMeta.Variant(marking, color)); diff --git a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java index 5a3c271065d..2516d9951fd 100644 --- a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java @@ -15,7 +15,7 @@ public PlayersCommand() { } private void usage(CommandSender sender, CommandContext context) { - final var players = List.copyOf(sender.getMinecraftServer().process().getConnectionManager().getOnlinePlayers()); + final var players = List.copyOf(sender.getServerProcess().getConnectionManager().getOnlinePlayers()); final int playerCount = players.size(); sender.sendMessage(Component.text("Total players: " + playerCount)); diff --git a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java index 0dee3f09398..b67b02dc3b4 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java @@ -19,12 +19,12 @@ public SaveCommand() { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - for(var instance : commandSender.getMinecraftServer().process().getInstanceManager().getInstances()) { + for(var instance : commandSender.getServerProcess().getInstanceManager().getInstances()) { CompletableFuture instanceSave = instance.saveInstance().thenCompose(v -> instance.saveChunksToStorage()); try { instanceSave.get(); } catch (InterruptedException | ExecutionException e) { - commandSender.getMinecraftServer().process().getExceptionManager().handleException(e); + commandSender.getServerProcess().getExceptionManager().handleException(e); } } commandSender.sendMessage("Saving done!"); diff --git a/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java index 0224ffd91e5..c54f49fa2c2 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java @@ -39,13 +39,13 @@ private void onShootCommand(CommandSender sender, CommandContext context) { EntityProjectile projectile; switch (mode) { case "default": - projectile = new EntityProjectile(player.getMinecraftServer(), player, EntityType.ARROW); + projectile = new EntityProjectile(player.getServerProcess(), player, EntityType.ARROW); break; case "spectral": - projectile = new EntityProjectile(player.getMinecraftServer(), player, EntityType.SPECTRAL_ARROW); + projectile = new EntityProjectile(player.getServerProcess(), player, EntityType.SPECTRAL_ARROW); break; case "colored": - projectile = new EntityProjectile(player.getMinecraftServer(), player, EntityType.ARROW); + projectile = new EntityProjectile(player.getServerProcess(), player, EntityType.ARROW); var meta = (ArrowMeta) projectile.getEntityMeta(); meta.setColor(ThreadLocalRandom.current().nextInt()); break; diff --git a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java index 99f5bf357cb..56f9f875040 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -11,15 +11,15 @@ */ public class ShutdownCommand extends Command { - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public ShutdownCommand(MinecraftServer minecraftServer) { + public ShutdownCommand(ServerProcess serverProcess) { super("shutdown"); - this.minecraftServer = minecraftServer; + this.serverProcess = serverProcess; addSyntax(this::execute); } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - minecraftServer.stopCleanly(); + serverProcess.stop(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java index 45afe2dd201..46d6e822368 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java @@ -3,7 +3,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -18,10 +18,10 @@ public class SidebarCommand extends Command { private final Sidebar sidebar; private int currentLine = 0; - public SidebarCommand(MinecraftServer minecraftServer) { + public SidebarCommand(ServerProcess serverProcess) { super("sidebar"); - sidebar = new Sidebar(minecraftServer, Component.text("DEMO").decorate(TextDecoration.BOLD)); + sidebar = new Sidebar(serverProcess, Component.text("DEMO").decorate(TextDecoration.BOLD)); addLine("BLANK ", Sidebar.NumberFormat.blank()); addLine("STYLE ", Sidebar.NumberFormat.styled(Component.empty().decorate(TextDecoration.STRIKETHROUGH).color(NamedTextColor.GRAY))); diff --git a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java index 804b42b17eb..ad161344434 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -38,7 +38,7 @@ public SummonCommand() { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - final Entity entity = commandContext.get(entityClass).instantiate(commandSender.getMinecraftServer(), commandContext.get(this.entity)); + final Entity entity = commandContext.get(entityClass).instantiate(commandSender.getServerProcess(), commandContext.get(this.entity)); //noinspection ConstantConditions - One couldn't possibly execute a command without being in an instance entity.setInstance(((Player) commandSender).getInstance(), commandContext.get(pos).fromSender(commandSender)); } @@ -54,12 +54,12 @@ enum EntityClass { this.factory = factory; } - public Entity instantiate(MinecraftServer minecraftServer, EntityType type) { - return factory.newInstance(minecraftServer, type); + public Entity instantiate(ServerProcess serverProcess, EntityType type) { + return factory.newInstance(serverProcess, type); } } interface EntityFactory { - Entity newInstance(MinecraftServer minecraftServer, EntityType type); + Entity newInstance(ServerProcess serverProcess, EntityType type); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java index 98ee3076e60..6a93c83cd8b 100644 --- a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java @@ -25,7 +25,7 @@ public TeleportCommand() { private void onPlayerTeleport(CommandSender sender, CommandContext context) { final String playerName = context.get("player"); - Player pl = sender.getMinecraftServer().process().getConnectionManager().getOnlinePlayerByUsername(playerName); + Player pl = sender.getServerProcess().getConnectionManager().getOnlinePlayerByUsername(playerName); if (sender instanceof Player player) { player.teleport(pl.getPosition()); } diff --git a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java index a6aaee53ef8..4af48478752 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java @@ -1,6 +1,6 @@ package net.minestom.demo.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.attribute.Attribute; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; @@ -10,8 +10,8 @@ public class ChickenCreature extends EntityCreature { - public ChickenCreature(MinecraftServer minecraftServer) { - super(minecraftServer, EntityType.CHICKEN); + public ChickenCreature(ServerProcess serverProcess) { + super(serverProcess, EntityType.CHICKEN); addAIGroup( List.of( diff --git a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java index e9b89f58fe5..810029e8be0 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java @@ -1,6 +1,6 @@ package net.minestom.demo.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.ai.EntityAIGroupBuilder; @@ -8,8 +8,8 @@ public class ZombieCreature extends EntityCreature { - public ZombieCreature(MinecraftServer minecraftServer) { - super(minecraftServer, EntityType.ZOMBIE); + public ZombieCreature(ServerProcess serverProcess) { + super(serverProcess, EntityType.ZOMBIE); addAIGroup( new EntityAIGroupBuilder() .addGoalSelector(new RandomLookAroundGoal(this, 20)) diff --git a/src/main/java/net/minestom/server/MinecraftServer.java b/src/main/java/net/minestom/server/MinecraftServer.java deleted file mode 100644 index ba18160f255..00000000000 --- a/src/main/java/net/minestom/server/MinecraftServer.java +++ /dev/null @@ -1,226 +0,0 @@ -package net.minestom.server; - -import net.kyori.adventure.text.logger.slf4j.ComponentLogger; -import net.minestom.server.network.packet.server.common.PluginMessagePacket; -import net.minestom.server.network.packet.server.play.ServerDifficultyPacket; -import net.minestom.server.thread.TickSchedulerThread; -import net.minestom.server.utils.MathUtils; -import net.minestom.server.utils.PacketUtils; -import net.minestom.server.utils.validate.Check; -import net.minestom.server.world.Difficulty; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.UnknownNullability; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -/** - * The main server class used to start the server and retrieve all the managers. - *

    - * The server needs to be initialized with {@link #init()} and started with {@link #start(String, int)}. - * You should register all of your dimensions, biomes, commands, events, etc... in-between. - */ -public final class MinecraftServer { - - public static final ComponentLogger LOGGER = ComponentLogger.logger(MinecraftServer.class); - - public static final String VERSION_NAME = "1.20.4"; - public static final int PROTOCOL_VERSION = 765; - - // Threads - public static final String THREAD_NAME_BENCHMARK = "Ms-Benchmark"; - - public static final String THREAD_NAME_TICK_SCHEDULER = "Ms-TickScheduler"; - public static final String THREAD_NAME_TICK = "Ms-Tick"; - - // Config - // Can be modified at performance cost when increased - public static final int TICK_PER_SECOND = Integer.getInteger("minestom.tps", 20); - public static final int TICK_MS = 1000 / TICK_PER_SECOND; - - // In-Game Manager - volatile ServerProcess serverProcess; - - private int chunkViewDistance = Integer.getInteger("minestom.chunk-view-distance", 8); - private int entityViewDistance = Integer.getInteger("minestom.entity-view-distance", 5); - private int compressionThreshold = 256; - private boolean terminalEnabled = System.getProperty("minestom.terminal.disabled") == null; - private String brandName = "Minestom"; - private Difficulty difficulty = Difficulty.NORMAL; - - public void init() { - updateProcess(); - } - - @ApiStatus.Internal - public ServerProcess updateProcess() { - ServerProcess process; - try { - process = new ServerProcessImpl(this); - } catch (IOException e) { - throw new RuntimeException(e); - } - return process; - } - - /** - * Gets the current server brand name. - * - * @return the server brand name - */ - @NotNull - public String getBrandName() { - return brandName; - } - - /** - * Changes the server brand name and send the change to all connected players. - * - * @param brandName the server brand name - * @throws NullPointerException if {@code brandName} is null - */ - public void setBrandName(@NotNull String brandName) { - this.brandName = brandName; - PacketUtils.broadcastPlayPacket(this, PluginMessagePacket.getBrandPacket(this)); - } - - /** - * Gets the server difficulty showed in game option. - * - * @return the server difficulty - */ - @NotNull - public Difficulty getDifficulty() { - return difficulty; - } - - /** - * Changes the server difficulty and send the appropriate packet to all connected clients. - * - * @param difficulty the new server difficulty - */ - public void setDifficulty(@NotNull Difficulty difficulty) { - this.difficulty = difficulty; - PacketUtils.broadcastPlayPacket(this, new ServerDifficultyPacket(difficulty, true)); - } - - @ApiStatus.Experimental - public @UnknownNullability ServerProcess process() { - return serverProcess; - } - - /** - * Gets the chunk view distance of the server. - * - * @return the chunk view distance - */ - public int getChunkViewDistance() { - return chunkViewDistance; - } - - /** - * Changes the chunk view distance of the server. - * - * @param chunkViewDistance the new chunk view distance - * @throws IllegalArgumentException if {@code chunkViewDistance} is not between 2 and 32 - * @deprecated should instead be defined with a java property - */ - @Deprecated - public void setChunkViewDistance(int chunkViewDistance) { - Check.stateCondition(serverProcess.isAlive(), "You cannot change the chunk view distance after the server has been started."); - Check.argCondition(!MathUtils.isBetween(chunkViewDistance, 2, 32), - "The chunk view distance must be between 2 and 32"); - this.chunkViewDistance = chunkViewDistance; - } - - /** - * Gets the entity view distance of the server. - * - * @return the entity view distance - */ - public int getEntityViewDistance() { - return entityViewDistance; - } - - /** - * Changes the entity view distance of the server. - * - * @param entityViewDistance the new entity view distance - * @throws IllegalArgumentException if {@code entityViewDistance} is not between 0 and 32 - * @deprecated should instead be defined with a java property - */ - @Deprecated - public void setEntityViewDistance(int entityViewDistance) { - Check.stateCondition(serverProcess.isAlive(), "You cannot change the entity view distance after the server has been started."); - Check.argCondition(!MathUtils.isBetween(entityViewDistance, 0, 32), - "The entity view distance must be between 0 and 32"); - this.entityViewDistance = entityViewDistance; - } - - /** - * Gets the compression threshold of the server. - * - * @return the compression threshold, 0 means that compression is disabled - */ - public int getCompressionThreshold() { - return compressionThreshold; - } - - /** - * Changes the compression threshold of the server. - *

    - * WARNING: this need to be called before {@link #start(SocketAddress)}. - * - * @param compressionThreshold the new compression threshold, 0 to disable compression - * @throws IllegalStateException if this is called after the server started - */ - public void setCompressionThreshold(int compressionThreshold) { - Check.stateCondition(serverProcess != null && serverProcess.isAlive(), "The compression threshold cannot be changed after the server has been started."); - this.compressionThreshold = compressionThreshold; - } - - /** - * Gets if the built in Minestom terminal is enabled. - * - * @return true if the terminal is enabled - */ - public boolean isTerminalEnabled() { - return terminalEnabled; - } - - /** - * Enabled/disables the built in Minestom terminal. - * - * @param enabled true to enable, false to disable - */ - public void setTerminalEnabled(boolean enabled) { - Check.stateCondition(serverProcess.isAlive(), "Terminal settings may not be changed after starting the server."); - terminalEnabled = enabled; - } - - /** - * Starts the server. - *

    - * It should be called after {@link #init()} and probably your own initialization code. - * - * @param address the server address - * @throws IllegalStateException if called before {@link #init()} or if the server is already running - */ - public void start(@NotNull SocketAddress address) { - serverProcess.start(address); - new TickSchedulerThread(serverProcess).start(); - } - - public void start(@NotNull String address, int port) { - start(new InetSocketAddress(address, port)); - } - - /** - * Stops this server properly (saves if needed, kicking players, etc.) - */ - public void stopCleanly() { - serverProcess.stop(); - } -} diff --git a/src/main/java/net/minestom/server/MinecraftServerObject.java b/src/main/java/net/minestom/server/MinecraftServerObject.java deleted file mode 100644 index c1e795323bc..00000000000 --- a/src/main/java/net/minestom/server/MinecraftServerObject.java +++ /dev/null @@ -1,5 +0,0 @@ -package net.minestom.server; - -public interface MinecraftServerObject { - MinecraftServer getMinecraftServer(); -} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/ServerConsts.java b/src/main/java/net/minestom/server/ServerConsts.java new file mode 100644 index 00000000000..b2841664077 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerConsts.java @@ -0,0 +1,12 @@ +package net.minestom.server; + +public interface ServerConsts { + String VERSION_NAME = "1.20.4"; + int PROTOCOL_VERSION = 765; + + // Threads + String THREAD_NAME_BENCHMARK = "Ms-Benchmark"; + + String THREAD_NAME_TICK_SCHEDULER = "Ms-TickScheduler"; + String THREAD_NAME_TICK = "Ms-Tick"; +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/ServerObject.java b/src/main/java/net/minestom/server/ServerObject.java new file mode 100644 index 00000000000..ecbf42c5b53 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerObject.java @@ -0,0 +1,5 @@ +package net.minestom.server; + +public interface ServerObject { + ServerProcess getServerProcess(); +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/ServerProcess.java b/src/main/java/net/minestom/server/ServerProcess.java index 5b589115d2a..7b8f972a336 100644 --- a/src/main/java/net/minestom/server/ServerProcess.java +++ b/src/main/java/net/minestom/server/ServerProcess.java @@ -1,5 +1,6 @@ package net.minestom.server; +import net.kyori.adventure.text.logger.slf4j.ComponentLogger; import net.minestom.server.advancements.AdvancementManager; import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.adventure.bossbar.BossBarManager; @@ -27,11 +28,19 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import java.net.InetSocketAddress; import java.net.SocketAddress; @ApiStatus.Experimental @ApiStatus.NonExtendable public interface ServerProcess extends Snapshotable { + ComponentLogger LOGGER = ComponentLogger.logger(ServerProcess.class); + static ServerProcess of(ServerSettings serverSettings) { + return new ServerProcessImpl(serverSettings); + } + + ServerSettings getMinecraftServer(); + /** * Handles incoming connections/players. */ @@ -136,6 +145,10 @@ public interface ServerProcess extends Snapshotable { void start(@NotNull SocketAddress socketAddress); + default void start(@NotNull String hostname, int port) { + start(new InetSocketAddress(hostname, port)); + } + void stop(); boolean isAlive(); diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java index 64a921d47b6..ac025ebf559 100644 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -26,6 +26,7 @@ import net.minestom.server.snapshot.*; import net.minestom.server.thread.Acquirable; import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.TickSchedulerThread; import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.PropertyUtils; @@ -71,38 +72,42 @@ final class ServerProcessImpl implements ServerProcess { private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); - private final MinecraftServer minecraftServer; + private final ServerSettings serverSettings; private final Audiences audiences; private final MojangAuth mojangAuth; - public ServerProcessImpl(MinecraftServer minecraftServer) throws IOException { - minecraftServer.serverProcess = this; - this.minecraftServer = minecraftServer; - this.exceptionManager = new ExceptionManager(minecraftServer); - this.packetListenerManager = new PacketListenerManager(minecraftServer); + public ServerProcessImpl(ServerSettings serverSettings) { + this.serverSettings = serverSettings; + this.exceptionManager = new ExceptionManager(this); + this.packetListenerManager = new PacketListenerManager(this); this.packetProcessor = new PacketProcessor(packetListenerManager); - this.instanceManager = new InstanceManager(minecraftServer); + this.instanceManager = new InstanceManager(this); this.blockManager = new BlockManager(); - this.commandManager = new CommandManager(minecraftServer); + this.commandManager = new CommandManager(this); this.recipeManager = new RecipeManager(); - this.teamManager = new TeamManager(minecraftServer); - this.globalEventHandler = new GlobalEventHandler(minecraftServer); + this.teamManager = new TeamManager(this); + this.globalEventHandler = new GlobalEventHandler(this); this.schedulerManager = new SchedulerManager(); - this.benchmarkManager = new BenchmarkManager(minecraftServer); + this.benchmarkManager = new BenchmarkManager(this); this.dimensionTypeManager = new DimensionTypeManager(); this.biomeManager = new BiomeManager(); - this.advancementManager = new AdvancementManager(minecraftServer); - this.bossBarManager = new BossBarManager(minecraftServer); + this.advancementManager = new AdvancementManager(this); + this.bossBarManager = new BossBarManager(this); this.tagManager = new TagManager(); - this.connectionManager = new ConnectionManager(minecraftServer, tagManager); - this.server = new Server(minecraftServer, packetProcessor); - this.mojangAuth = new MojangAuth(minecraftServer); - this.audiences = new Audiences(minecraftServer); + this.connectionManager = new ConnectionManager(this, tagManager); + this.server = new Server(this, packetProcessor); + this.mojangAuth = new MojangAuth(this); + this.audiences = new Audiences(this); - this.dispatcher = ThreadDispatcher.singleThread(minecraftServer); + this.dispatcher = ThreadDispatcher.singleThread(this); this.ticker = new TickerImpl(); } + @Override + public ServerSettings getMinecraftServer() { + return serverSettings; + } + @Override public @NotNull ConnectionManager getConnectionManager() { return connectionManager; @@ -209,7 +214,7 @@ public void start(@NotNull SocketAddress socketAddress) { throw new IllegalStateException("Server already started"); } - LOGGER.info("Starting " + minecraftServer.getBrandName() + " server."); + LOGGER.info("Starting " + serverSettings.getBrandName() + " server."); // Init server try { @@ -222,24 +227,26 @@ public void start(@NotNull SocketAddress socketAddress) { // Start server server.start(); - LOGGER.info(minecraftServer.getBrandName() + " server started successfully."); + LOGGER.info(serverSettings.getBrandName() + " server started successfully."); // Stop the server on SIGINT if (SHUTDOWN_ON_SIGNAL) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); + + new TickSchedulerThread(this).start(); } @Override public void stop() { if (!stopped.compareAndSet(false, true)) return; - LOGGER.info("Stopping " + minecraftServer.getBrandName() + " server."); + LOGGER.info("Stopping " + serverSettings.getBrandName() + " server."); schedulerManager.shutdown(); connectionManager.shutdown(); server.stop(); LOGGER.info("Shutting down all thread pools."); benchmarkManager.disable(); dispatcher.shutdown(); - LOGGER.info(minecraftServer.getBrandName() + " server stopped successfully."); + LOGGER.info(serverSettings.getBrandName() + " server stopped successfully."); } @Override diff --git a/src/main/java/net/minestom/server/ServerSettings.java b/src/main/java/net/minestom/server/ServerSettings.java new file mode 100644 index 00000000000..7f45cddbd5d --- /dev/null +++ b/src/main/java/net/minestom/server/ServerSettings.java @@ -0,0 +1,65 @@ +package net.minestom.server; + +import net.minestom.server.world.Difficulty; +import org.jetbrains.annotations.NotNull; + +public interface ServerSettings { + static ServerSettingsImpl.Builder builder() { + return new ServerSettingsImpl.Builder(); + } + + int getTickPerSecond(); + default int getTickMs() { + return 1000 / getTickPerSecond(); + } + + /** + * Gets the current server brand name. + * + * @return the server brand name + */ + @NotNull String getBrandName(); + + /** + * Changes the server brand name and send the change to all connected players. + * + * @param brandName the server brand name + * @throws NullPointerException if {@code brandName} is null + */ + void setBrandName(@NotNull String brandName, @NotNull ServerProcess serverProcess); + + /** + * Gets the server difficulty showed in game option. + * + * @return the server difficulty + */ + @NotNull Difficulty getDifficulty(); + + /** + * Changes the server difficulty and send the appropriate packet to all connected clients. + * + * @param difficulty the new server difficulty + */ + void setDifficulty(@NotNull Difficulty difficulty, @NotNull ServerProcess serverProcess); + + /** + * Gets the chunk view distance of the server. + * + * @return the chunk view distance + */ + int getChunkViewDistance(); + + /** + * Gets the entity view distance of the server. + * + * @return the entity view distance + */ + int getEntityViewDistance(); + + /** + * Gets the compression threshold of the server. + * + * @return the compression threshold, 0 means that compression is disabled + */ + int getCompressionThreshold(); +} diff --git a/src/main/java/net/minestom/server/ServerSettingsImpl.java b/src/main/java/net/minestom/server/ServerSettingsImpl.java new file mode 100644 index 00000000000..804ff9d1bea --- /dev/null +++ b/src/main/java/net/minestom/server/ServerSettingsImpl.java @@ -0,0 +1,122 @@ +package net.minestom.server; + +import net.minestom.server.network.packet.server.common.PluginMessagePacket; +import net.minestom.server.network.packet.server.play.ServerDifficultyPacket; +import net.minestom.server.utils.MathUtils; +import net.minestom.server.utils.PacketUtils; +import net.minestom.server.utils.validate.Check; +import net.minestom.server.world.Difficulty; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Range; + +final class ServerSettingsImpl implements ServerSettings { + private final int chunkViewDistance; + private final int entityViewDistance; + private final int compressionThreshold; + private final int tickPerSecond; + + private @NotNull String brandName; + private @NotNull Difficulty difficulty; + + private ServerSettingsImpl(int chunkViewDistance, int entityViewDistance, int compressionThreshold, int tickPerSecond, @NotNull String brandName, @NotNull Difficulty difficulty) { + this.chunkViewDistance = chunkViewDistance; + this.entityViewDistance = entityViewDistance; + this.compressionThreshold = compressionThreshold; + this.tickPerSecond = tickPerSecond; + this.brandName = brandName; + this.difficulty = difficulty; + } + + @Override + public int getTickPerSecond() { + return tickPerSecond; + } + + @Override + @NotNull + public String getBrandName() { + return brandName; + } + + @Override + public void setBrandName(@NotNull String brandName, @NotNull ServerProcess serverProcess) { + this.brandName = brandName; + PacketUtils.broadcastPlayPacket(serverProcess, PluginMessagePacket.getBrandPacket(this)); + } + + + @NotNull + @Override + public Difficulty getDifficulty() { + return difficulty; + } + + @Override + public void setDifficulty(@NotNull Difficulty difficulty, @NotNull ServerProcess serverProcess) { + this.difficulty = difficulty; + PacketUtils.broadcastPlayPacket(serverProcess, new ServerDifficultyPacket(difficulty, true)); + } + + @Override + public int getChunkViewDistance() { + return chunkViewDistance; + } + + @Override + public int getEntityViewDistance() { + return entityViewDistance; + } + + @Override + public int getCompressionThreshold() { + return compressionThreshold; + } + + public static class Builder { + private int chunkViewDistance = 8; + private int entityViewDistance = 5; + private int compressionThreshold = 256; + private int tickPerSecond = 20; + + private String brandName = "Minestom"; + private Difficulty difficulty = Difficulty.NORMAL; + + @Range(from = 2, to = 32) + public Builder chunkViewDistance(int chunkViewDistance) { + Check.argCondition(!MathUtils.isBetween(chunkViewDistance, 2, 32), "The chunk view distance must be between 2 and 32"); + this.chunkViewDistance = chunkViewDistance; + return this; + } + + @Range(from = 0, to = 32) + public Builder entityViewDistance(int entityViewDistance) { + Check.argCondition(!MathUtils.isBetween(entityViewDistance, 0, 32), "The entity view distance must be between 0 and 32"); + this.entityViewDistance = entityViewDistance; + return this; + } + + public Builder compressionThreshold(int compressionThreshold) { + this.compressionThreshold = compressionThreshold; + return this; + } + + public Builder tickPerSecond(int tickPerSecond) { + this.tickPerSecond = tickPerSecond; + return this; + } + + public Builder brandName(@NotNull String brandName) { + this.brandName = brandName; + return this; + } + + public Builder difficulty(@NotNull Difficulty difficulty) { + this.difficulty = difficulty; + return this; + } + + public ServerSettings build() { + return new ServerSettingsImpl(chunkViewDistance, entityViewDistance, compressionThreshold, tickPerSecond, brandName, difficulty); + } + } +} diff --git a/src/main/java/net/minestom/server/Viewable.java b/src/main/java/net/minestom/server/Viewable.java index 5632e211153..c72962542bc 100644 --- a/src/main/java/net/minestom/server/Viewable.java +++ b/src/main/java/net/minestom/server/Viewable.java @@ -15,7 +15,7 @@ /** * Represents something which can be displayed or hidden to players. */ -public interface Viewable extends MinecraftServerObject { +public interface Viewable extends ServerObject { /** * Adds a viewer. @@ -60,7 +60,7 @@ default boolean isViewer(@NotNull Player player) { */ default void sendPacketToViewers(@NotNull SendablePacket packet) { if (packet instanceof ServerPacket serverPacket) { - PacketUtils.sendGroupedPacket(getMinecraftServer(), getViewers(), serverPacket); + PacketUtils.sendGroupedPacket(getServerProcess(), getViewers(), serverPacket); } else { getViewers().forEach(player -> player.sendPacket(packet)); } @@ -91,7 +91,7 @@ default void sendPacketToViewersAndSelf(@NotNull SendablePacket packet) { * @return the audience */ default @NotNull Audience getViewersAsAudience() { - return PacketGroupingAudience.of(getMinecraftServer(), this.getViewers()); + return PacketGroupingAudience.of(getServerProcess(), this.getViewers()); } /** diff --git a/src/main/java/net/minestom/server/advancements/AdvancementManager.java b/src/main/java/net/minestom/server/advancements/AdvancementManager.java index c6fd29520f0..729c5484edf 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementManager.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementManager.java @@ -1,6 +1,6 @@ package net.minestom.server.advancements; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -18,10 +18,10 @@ public class AdvancementManager { // root identifier = its advancement tab private final Map advancementTabMap = new ConcurrentHashMap<>(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public AdvancementManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public AdvancementManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } /** @@ -36,7 +36,7 @@ public AdvancementManager(MinecraftServer minecraftServer) { public AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root) { Check.stateCondition(advancementTabMap.containsKey(rootIdentifier), "A tab with the identifier '" + rootIdentifier + "' already exists"); - final AdvancementTab advancementTab = new AdvancementTab(minecraftServer, rootIdentifier, root); + final AdvancementTab advancementTab = new AdvancementTab(serverProcess, rootIdentifier, root); this.advancementTabMap.put(rootIdentifier, advancementTab); return advancementTab; } diff --git a/src/main/java/net/minestom/server/advancements/AdvancementTab.java b/src/main/java/net/minestom/server/advancements/AdvancementTab.java index a58b1f88643..128e4030350 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementTab.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementTab.java @@ -1,6 +1,6 @@ package net.minestom.server.advancements; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.AdvancementsPacket; @@ -26,7 +26,7 @@ public class AdvancementTab implements Viewable { private final Set viewers = new HashSet<>(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final AdvancementRoot root; // Advancement -> its parent @@ -36,8 +36,8 @@ public class AdvancementTab implements Viewable { // will never change (since the root identifier is always the same) protected final AdvancementsPacket removePacket; - protected AdvancementTab(MinecraftServer minecraftServer, @NotNull String rootIdentifier, @NotNull AdvancementRoot root) { - this.minecraftServer = minecraftServer; + protected AdvancementTab(ServerProcess serverProcess, @NotNull String rootIdentifier, @NotNull AdvancementRoot root) { + this.serverProcess = serverProcess; this.root = root; cacheAdvancement(rootIdentifier, root, null); this.removePacket = new AdvancementsPacket(false, List.of(), List.of(rootIdentifier), List.of()); @@ -169,7 +169,7 @@ private void removePlayer(@NotNull Player player) { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/adventure/audience/Audiences.java b/src/main/java/net/minestom/server/adventure/audience/Audiences.java index 2eae867359c..99a26fa475c 100644 --- a/src/main/java/net/minestom/server/adventure/audience/Audiences.java +++ b/src/main/java/net/minestom/server/adventure/audience/Audiences.java @@ -3,7 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Keyed; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.NotNull; @@ -15,12 +15,12 @@ */ public class Audiences { - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final SingleAudienceProvider audience; - public Audiences(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - audience = new SingleAudienceProvider(minecraftServer); + public Audiences(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + audience = new SingleAudienceProvider(serverProcess); } /** @@ -68,7 +68,7 @@ public Audiences(MinecraftServer minecraftServer) { * @return all players matching the predicate */ public @NotNull Audience players(ConnectionManager connectionManager, @NotNull Predicate filter) { - return PacketGroupingAudience.of(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); + return PacketGroupingAudience.of(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); } /** @@ -77,7 +77,7 @@ public Audiences(MinecraftServer minecraftServer) { * @return the console */ public @NotNull Audience console() { - return minecraftServer.process().getCommandManager().getConsoleSender(); + return serverProcess.getCommandManager().getConsoleSender(); } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java index df9590db409..3fd9f4880dc 100644 --- a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java @@ -2,7 +2,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.ConsoleSender; import net.minestom.server.entity.Player; import org.jetbrains.annotations.NotNull; @@ -20,11 +20,11 @@ class IterableAudienceProvider implements AudienceProvider> { private final List console; private final AudienceRegistry registry = new AudienceRegistry(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - protected IterableAudienceProvider(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.console = List.of(minecraftServer.process().getCommandManager().getConsoleSender()); + protected IterableAudienceProvider(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + this.console = List.of(serverProcess.getCommandManager().getConsoleSender()); } @Override @@ -38,12 +38,12 @@ protected IterableAudienceProvider(MinecraftServer minecraftServer) { @Override public @NotNull Iterable players() { - return minecraftServer.process().getConnectionManager().getOnlinePlayers(); + return serverProcess.getConnectionManager().getOnlinePlayers(); } @Override public @NotNull Iterable players(@NotNull Predicate filter) { - return minecraftServer.process().getConnectionManager().getOnlinePlayers().stream().filter(filter).toList(); + return serverProcess.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index 9314650e5ec..e48ad8bd016 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -9,8 +9,8 @@ import net.kyori.adventure.sound.SoundStop; import net.kyori.adventure.text.Component; import net.kyori.adventure.title.TitlePart; -import net.minestom.server.MinecraftServer; -import net.minestom.server.MinecraftServerObject; +import net.minestom.server.ServerObject; +import net.minestom.server.ServerProcess; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; @@ -28,7 +28,7 @@ /** * An audience implementation that sends grouped packets if possible. */ -public interface PacketGroupingAudience extends ForwardingAudience, MinecraftServerObject { +public interface PacketGroupingAudience extends ForwardingAudience, ServerObject { /** * Creates a packet grouping audience that copies an iterable of players. The @@ -38,11 +38,11 @@ public interface PacketGroupingAudience extends ForwardingAudience, MinecraftSer * @param players the players * @return the audience */ - static @NotNull PacketGroupingAudience of(MinecraftServer minecraftServer, @NotNull Collection players) { + static @NotNull PacketGroupingAudience of(ServerProcess serverProcess, @NotNull Collection players) { return new PacketGroupingAudience() { @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } @Override @@ -65,12 +65,12 @@ public MinecraftServer getMinecraftServer() { * @param packet the packet to broadcast */ default void sendGroupedPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(getMinecraftServer(), getPlayers(), packet); + PacketUtils.sendGroupedPacket(getServerProcess(), getPlayers(), packet); } @Override default void sendMessage(@NotNull Identity source, @NotNull Component message, @NotNull MessageType type) { - Messenger.sendMessage(getMinecraftServer(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); + Messenger.sendMessage(getServerProcess(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); } @Override @@ -100,12 +100,12 @@ default void resetTitle() { @Override default void showBossBar(@NotNull BossBar bar) { - getMinecraftServer().process().getBossBarManager().addBossBar(this.getPlayers(), bar); + getServerProcess().getBossBarManager().addBossBar(this.getPlayers(), bar); } @Override default void hideBossBar(@NotNull BossBar bar) { - getMinecraftServer().process().getBossBarManager().removeBossBar(this.getPlayers(), bar); + getServerProcess().getBossBarManager().removeBossBar(this.getPlayers(), bar); } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java index 526e164d1ef..94929bc2de5 100644 --- a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java @@ -2,7 +2,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import org.jetbrains.annotations.NotNull; @@ -18,13 +18,13 @@ class SingleAudienceProvider implements AudienceProvider { protected final Audience players; protected final Audience server; @NotNull - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - protected SingleAudienceProvider(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.collection = new IterableAudienceProvider(minecraftServer); - this.players = PacketGroupingAudience.of(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers()); - this.server = Audience.audience(this.players, minecraftServer.process().getCommandManager().getConsoleSender()); + protected SingleAudienceProvider(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + this.collection = new IterableAudienceProvider(serverProcess); + this.players = PacketGroupingAudience.of(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers()); + this.server = Audience.audience(this.players, serverProcess.getCommandManager().getConsoleSender()); } /** @@ -48,12 +48,12 @@ protected SingleAudienceProvider(MinecraftServer minecraftServer) { @Override public @NotNull Audience players(@NotNull Predicate filter) { - return PacketGroupingAudience.of(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); + return PacketGroupingAudience.of(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); } @Override public @NotNull Audience console() { - return minecraftServer.process().getCommandManager().getConsoleSender(); + return serverProcess.getCommandManager().getConsoleSender(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java index fd18c6afb7b..a7ee7e0fda6 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java @@ -2,7 +2,7 @@ import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.entity.Player; @@ -21,11 +21,11 @@ final class BossBarHolder implements Viewable { final UUID uuid = UUID.randomUUID(); final Set players = new CopyOnWriteArraySet<>(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; final BossBar bar; - BossBarHolder(MinecraftServer minecraftServer, @NotNull BossBar bar) { - this.minecraftServer = minecraftServer; + BossBarHolder(ServerProcess serverProcess, @NotNull BossBar bar) { + this.serverProcess = serverProcess; this.bar = bar; } @@ -77,7 +77,7 @@ public boolean removeViewer(@NotNull Player player) { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java index 8583f75bf3c..753446f192f 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java @@ -3,7 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; @@ -17,7 +17,7 @@ * for players. */ class BossBarListener implements BossBar.Listener { - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final BossBarManager manager; /** @@ -25,35 +25,35 @@ class BossBarListener implements BossBar.Listener { * * @param manager the manager instance */ - BossBarListener(MinecraftServer minecraftServer, BossBarManager manager) { - this.minecraftServer = minecraftServer; + BossBarListener(ServerProcess serverProcess, BossBarManager manager) { + this.serverProcess = serverProcess; this.manager = manager; } @Override public void bossBarNameChanged(@NotNull BossBar bar, @NotNull Component oldName, @NotNull Component newName) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createTitleUpdate(newName))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createTitleUpdate(newName))); } @Override public void bossBarProgressChanged(@NotNull BossBar bar, float oldProgress, float newProgress) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createPercentUpdate(newProgress))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createPercentUpdate(newProgress))); } @Override public void bossBarColorChanged(@NotNull BossBar bar, @NotNull BossBar.Color oldColor, @NotNull BossBar.Color newColor) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createColorUpdate(newColor))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createColorUpdate(newColor))); } @Override public void bossBarOverlayChanged(@NotNull BossBar bar, BossBar.@NotNull Overlay oldOverlay, BossBar.@NotNull Overlay newOverlay) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createOverlayUpdate(newOverlay))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createOverlayUpdate(newOverlay))); } @Override public void bossBarFlagsChanged(@NotNull BossBar bar, @NotNull Set flagsAdded, @NotNull Set flagsRemoved) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createFlagsUpdate())); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createFlagsUpdate())); } private void doIfRegistered(@NotNull BossBar bar, @NotNull Consumer consumer) { diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java index 7c0d82da52d..39b0689e20d 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java @@ -2,7 +2,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; @@ -26,14 +26,14 @@ public class BossBarManager { private final BossBarListener listener; private final Map> playerBars = new ConcurrentHashMap<>(); final Map bars = new ConcurrentHashMap<>(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; /** * Creates a new boss bar manager. */ - public BossBarManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.listener = new BossBarListener(minecraftServer,this); + public BossBarManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + this.listener = new BossBarListener(serverProcess,this); } /** @@ -76,7 +76,7 @@ public void addBossBar(@NotNull Collection players, @NotNull BossBar bar BossBarHolder holder = this.getOrCreateHandler(bar); Collection addedPlayers = players.stream().filter(holder::addViewer).toList(); if (!addedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(minecraftServer, addedPlayers, holder.createAddPacket()); + PacketUtils.sendGroupedPacket(serverProcess, addedPlayers, holder.createAddPacket()); } } @@ -91,7 +91,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar if (holder != null) { Collection removedPlayers = players.stream().filter(holder::removeViewer).toList(); if (!removedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(minecraftServer, removedPlayers, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(serverProcess, removedPlayers, holder.createRemovePacket()); } } } @@ -104,7 +104,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar public void destroyBossBar(@NotNull BossBar bossBar) { BossBarHolder holder = this.bars.remove(bossBar); if (holder != null) { - PacketUtils.sendGroupedPacket(minecraftServer, holder.players, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createRemovePacket()); for (Player player : holder.players) { this.removePlayer(player, holder); } @@ -159,7 +159,7 @@ public void removeAllBossBars(@NotNull Player player) { */ private @NotNull BossBarHolder getOrCreateHandler(@NotNull BossBar bar) { return this.bars.computeIfAbsent(bar, bossBar -> { - BossBarHolder holder = new BossBarHolder(minecraftServer, bossBar); + BossBarHolder holder = new BossBarHolder(serverProcess, bossBar); bossBar.addListener(this.listener); return holder; }); diff --git a/src/main/java/net/minestom/server/command/CommandManager.java b/src/main/java/net/minestom/server/command/CommandManager.java index 42e0a94f4aa..6b9573844bc 100644 --- a/src/main/java/net/minestom/server/command/CommandManager.java +++ b/src/main/java/net/minestom/server/command/CommandManager.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.command.builder.CommandResult; @@ -35,12 +35,12 @@ public final class CommandManager { private final Set commands = new HashSet<>(); private CommandCallback unknownCommandCallback; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public CommandManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.serverSender = new ServerSender(minecraftServer); - this.consoleSender = new ConsoleSender(minecraftServer); + public CommandManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + this.serverSender = new ServerSender(serverProcess); + this.consoleSender = new ConsoleSender(serverProcess); } /** @@ -110,7 +110,7 @@ public boolean commandExists(@NotNull String commandName) { // Command event if (sender instanceof Player player) { PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, command); - minecraftServer.process().getGlobalEventHandler().call(playerCommandEvent); + serverProcess.getGlobalEventHandler().call(playerCommandEvent); if (playerCommandEvent.isCancelled()) return CommandResult.of(CommandResult.Type.CANCELLED, command); command = playerCommandEvent.getCommand(); @@ -143,7 +143,7 @@ class Reflection { try { callable.call(); } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } }); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); @@ -151,7 +151,7 @@ class Reflection { return callable.call(); } } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); } } diff --git a/src/main/java/net/minestom/server/command/CommandSender.java b/src/main/java/net/minestom/server/command/CommandSender.java index bcb5595af5e..b0d0a7ef641 100644 --- a/src/main/java/net/minestom/server/command/CommandSender.java +++ b/src/main/java/net/minestom/server/command/CommandSender.java @@ -3,7 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identified; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerObject; import net.minestom.server.entity.Player; import net.minestom.server.permission.PermissionHandler; import net.minestom.server.tag.Taggable; @@ -14,7 +14,7 @@ *

    * Main implementations are {@link Player} and {@link ConsoleSender}. */ -public interface CommandSender extends PermissionHandler, Audience, Taggable, Identified { +public interface CommandSender extends PermissionHandler, Audience, Taggable, Identified, ServerObject { /** * Sends a raw string message. @@ -83,6 +83,4 @@ default Player asPlayer() { default ConsoleSender asConsole() { throw new ClassCastException("CommandSender is not the ConsoleSender"); } - - MinecraftServer getMinecraftServer(); } diff --git a/src/main/java/net/minestom/server/command/ConsoleSender.java b/src/main/java/net/minestom/server/command/ConsoleSender.java index 59d5b5145ed..0b9e2db0494 100644 --- a/src/main/java/net/minestom/server/command/ConsoleSender.java +++ b/src/main/java/net/minestom/server/command/ConsoleSender.java @@ -5,7 +5,7 @@ import net.kyori.adventure.pointer.Pointers; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.logger.slf4j.ComponentLogger; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -27,10 +27,10 @@ public class ConsoleSender implements CommandSender { .withStatic(Identity.UUID, this.identity.uuid()) .build(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public ConsoleSender(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public ConsoleSender(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } @Override @@ -60,8 +60,8 @@ public ConsoleSender asConsole() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } @Override diff --git a/src/main/java/net/minestom/server/command/ServerSender.java b/src/main/java/net/minestom/server/command/ServerSender.java index 5fd671abf72..3080090d05b 100644 --- a/src/main/java/net/minestom/server/command/ServerSender.java +++ b/src/main/java/net/minestom/server/command/ServerSender.java @@ -2,7 +2,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; @@ -24,10 +24,10 @@ public class ServerSender implements CommandSender { private final Set permissions = Collections.unmodifiableSet(new HashSet<>()); private final TagHandler tagHandler = TagHandler.newHandler(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public ServerSender(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public ServerSender(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } @NotNull @@ -47,7 +47,7 @@ public Set getAllPermissions() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java index b6460a4eade..d0edd70c39c 100644 --- a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java +++ b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java @@ -2,7 +2,7 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandParser; import net.minestom.server.command.CommandSender; @@ -26,8 +26,8 @@ public CommandDispatcher(CommandManager manager) { this.manager = manager; } - public CommandDispatcher(MinecraftServer minecraftServer) { - this(new CommandManager(minecraftServer)); + public CommandDispatcher(ServerProcess serverProcess) { + this(new CommandManager(serverProcess)); } /** diff --git a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java index 49ab401e56d..5d565382686 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java @@ -25,7 +25,7 @@ public CommandResult parse(@NotNull CommandSender sender, @NotNull String input) final String commandString = !shortcut.isEmpty() ? shortcut + StringUtils.SPACE + input : input; - CommandDispatcher dispatcher = sender.getMinecraftServer().process().getCommandManager().getDispatcher(); + CommandDispatcher dispatcher = sender.getServerProcess().getCommandManager().getDispatcher(); CommandResult result = dispatcher.parse(sender, commandString); if (onlyCorrect && result.getType() != CommandResult.Type.SUCCESS) diff --git a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java index b7f5e4ee872..d41da9102b7 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java @@ -43,7 +43,7 @@ public Duration parse(@NotNull CommandSender sender, @NotNull String input) thro TemporalUnit timeUnit; if (Character.isDigit(lastChar)) - timeUnit = TimeUnit.SERVER_TICK; + timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getMinecraftServer()); else if (SUFFIXES.contains(lastChar)) { input = input.substring(0, input.length() - 1); @@ -52,7 +52,7 @@ else if (SUFFIXES.contains(lastChar)) { } else if (lastChar == 's') { timeUnit = TimeUnit.SECOND; } else if (lastChar == 't') { - timeUnit = TimeUnit.SERVER_TICK; + timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getMinecraftServer()); } else { throw new ArgumentSyntaxException("Time needs to have the unit d, s, t, or none", input, NO_NUMBER); } diff --git a/src/main/java/net/minestom/server/crypto/SignatureValidator.java b/src/main/java/net/minestom/server/crypto/SignatureValidator.java index 2a8b7f8c8ae..6f5a8da325a 100644 --- a/src/main/java/net/minestom/server/crypto/SignatureValidator.java +++ b/src/main/java/net/minestom/server/crypto/SignatureValidator.java @@ -1,6 +1,6 @@ package net.minestom.server.crypto; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.crypto.KeyUtils; @@ -67,12 +67,12 @@ static SignatureValidator from(PublicKey publicKey, KeyUtils.SignatureAlgorithm private static SignatureValidator createYggdrasilValidator() { try (var stream = SignatureValidator.class.getResourceAsStream("/yggdrasil_session_pubkey.der")) { if (stream == null) { - MinecraftServer.LOGGER.error("Couldn't find Yggdrasil public key, falling back to prohibiting validator!"); + ServerProcess.LOGGER.error("Couldn't find Yggdrasil public key, falling back to prohibiting validator!"); return FAIL; } return from(KeyUtils.publicRSAKeyFrom(stream.readAllBytes()), KeyUtils.SignatureAlgorithm.SHA1withRSA); } catch (Exception e) { - MinecraftServer.LOGGER.error("Exception while reading Yggdrasil public key, falling back to prohibiting validator!", e); + ServerProcess.LOGGER.error("Exception while reading Yggdrasil public key, falling back to prohibiting validator!", e); return FAIL; } } diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index 8d8a91a47c2..e8ab2af5afa 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -5,7 +5,6 @@ import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEvent.ShowEntity; import net.kyori.adventure.text.event.HoverEventSource; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.Viewable; @@ -92,7 +91,7 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev private static final AtomicInteger LAST_ENTITY_ID = new AtomicInteger(); private final CachedPacket destroyPacketCache; - public final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; protected Instance instance; protected Chunk currentChunk; @@ -180,8 +179,8 @@ public void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracke private final Acquirable acquirable = Acquirable.of(this); - public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { - this.minecraftServer = minecraftServer; + public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { + this.serverProcess = serverProcess; this.id = generateId(); this.entityType = entityType; this.uuid = uuid; @@ -199,18 +198,17 @@ public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType enti this.gravityAcceleration = entityType.registry().acceleration(); this.gravityDragPerTick = entityType.registry().drag(); - final ServerProcess process = minecraftServer.process(); - if (process != null) { - this.eventNode = process.getGlobalEventHandler().map(this, EventFilter.ENTITY); + if (serverProcess != null) { + this.eventNode = serverProcess.getGlobalEventHandler().map(this, EventFilter.ENTITY); } else { // Local nodes require a server process this.eventNode = null; } - destroyPacketCache = new CachedPacket(minecraftServer, () -> new DestroyEntitiesPacket(getEntityId())); + destroyPacketCache = new CachedPacket(serverProcess, () -> new DestroyEntitiesPacket(getEntityId())); } - public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { - this(minecraftServer, entityType, UUID.randomUUID()); + public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { + this(serverProcess, entityType, UUID.randomUUID()); } /** @@ -564,7 +562,7 @@ public void tick(long time) { update(time); ticks++; - minecraftServer.process().getGlobalEventHandler().call(new EntityTickEvent(this)); + serverProcess.getGlobalEventHandler().call(new EntityTickEvent(this)); // remove expired effects effectTick(time); @@ -584,7 +582,7 @@ private void velocityTick() { if (!hasVelocity && noGravity) { return; } - final float tps = MinecraftServer.TICK_PER_SECOND; + final float tps = serverProcess.getMinecraftServer().getTickPerSecond(); final Pos positionBeforeMove = getPosition(); final Vec currentVelocity = getVelocity(); final boolean wasOnGround = this.onGround; @@ -683,7 +681,7 @@ protected void updateVelocity(boolean wasOnGround, boolean flying, Pos positionB z * drag )) // Convert from block/tick to block/sec - .mul(MinecraftServer.TICK_PER_SECOND) + .mul(serverProcess.getMinecraftServer().getTickPerSecond()) // Prevent infinitely decreasing velocity .apply(Vec.Operator.EPSILON); } @@ -728,12 +726,12 @@ private void effectTick(long time) { effects.removeIf(timedPotion -> { long duration = timedPotion.getPotion().duration(); if (duration == Potion.INFINITE_DURATION) return false; - final long potionTime = duration * MinecraftServer.TICK_MS; + final long potionTime = duration * serverProcess.getMinecraftServer().getTickMs(); // Remove if the potion should be expired if (time >= timedPotion.getStartingTime() + potionTime) { // Send the packet that the potion should no longer be applied timedPotion.getPotion().sendRemovePacket(this); - minecraftServer.process().getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + serverProcess.getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); return true; } return false; @@ -848,7 +846,7 @@ public void setBoundingBox(BoundingBox boundingBox) { @ApiStatus.Internal protected void refreshCurrentChunk(Chunk currentChunk) { this.currentChunk = currentChunk; - minecraftServer.process().dispatcher().updateElement(this, currentChunk); + serverProcess.dispatcher().updateElement(this, currentChunk); } /** @@ -877,7 +875,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull return teleport(spawnPosition); // Already in the instance, teleport to spawn point } AddEntityToInstanceEvent event = new AddEntityToInstanceEvent(instance, this); - minecraftServer.process().getGlobalEventHandler().call(event); + serverProcess.getGlobalEventHandler().call(event); if (event.isCancelled()) return null; // TODO what to return? if (previousInstance != null) removeFromInstance(previousInstance); @@ -896,9 +894,9 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull } instance.getEntityTracker().register(this, spawnPosition, trackingTarget, trackingUpdate); spawn(); - minecraftServer.process().getGlobalEventHandler().call(new EntitySpawnEvent(this, instance)); + serverProcess.getGlobalEventHandler().call(new EntitySpawnEvent(this, instance)); } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } }); } @@ -921,7 +919,7 @@ public CompletableFuture setInstance(@NotNull Instance instance) { } private void removeFromInstance(Instance instance) { - minecraftServer.process().getGlobalEventHandler().call(new RemoveEntityFromInstanceEvent(instance, this)); + serverProcess.getGlobalEventHandler().call(new RemoveEntityFromInstanceEvent(instance, this)); instance.getEntityTracker().unregister(this, trackingTarget, trackingUpdate); this.viewEngine.forManuals(this::removeViewer); } @@ -944,7 +942,7 @@ private void removeFromInstance(Instance instance) { */ public void setVelocity(@NotNull Vec velocity) { EntityVelocityEvent entityVelocityEvent = new EntityVelocityEvent(this, velocity); - minecraftServer.process().getGlobalEventHandler().callCancellable(entityVelocityEvent, () -> { + serverProcess.getGlobalEventHandler().callCancellable(entityVelocityEvent, () -> { this.velocity = entityVelocityEvent.getVelocity(); sendPacketToViewersAndSelf(getVelocityPacket()); }); @@ -1333,21 +1331,21 @@ public void refreshPosition(@NotNull final Pos newPosition, boolean ignoreView) final Chunk chunk = getChunk(); if (distanceX > 8 || distanceY > 8 || distanceZ > 8) { - PacketUtils.prepareViewablePacket(minecraftServer, chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); + PacketUtils.prepareViewablePacket(serverProcess, chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); } else if (positionChange && viewChange) { - PacketUtils.prepareViewablePacket(minecraftServer, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverProcess, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); // Fix head rotation - PacketUtils.prepareViewablePacket(minecraftServer, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverProcess, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); } else if (positionChange) { // This is a confusing fix for a confusing issue. If rotation is only sent when the entity actually changes, then spawning an entity // on the ground causes the entity not to update its rotation correctly. It works fine if the entity is spawned in the air. Very weird. - PacketUtils.prepareViewablePacket(minecraftServer, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverProcess, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, onGround), this); } else if (viewChange) { - PacketUtils.prepareViewablePacket(minecraftServer, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); - PacketUtils.prepareViewablePacket(minecraftServer,chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverProcess, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverProcess,chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); } this.lastSyncedPosition = position; @@ -1462,7 +1460,7 @@ public void addEffect(@NotNull Potion potion) { removeEffect(potion.effect()); this.effects.add(new TimedPotion(potion, System.currentTimeMillis())); potion.sendAddPacket(this); - minecraftServer.process().getGlobalEventHandler().call(new EntityPotionAddEvent(this, potion)); + serverProcess.getGlobalEventHandler().call(new EntityPotionAddEvent(this, potion)); } /** @@ -1474,7 +1472,7 @@ public void removeEffect(@NotNull PotionEffect effect) { this.effects.removeIf(timedPotion -> { if (timedPotion.getPotion().effect() == effect) { timedPotion.getPotion().sendRemovePacket(this); - minecraftServer.process().getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + serverProcess.getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); return true; } return false; @@ -1517,7 +1515,7 @@ public int getEffectLevel(@NotNull PotionEffect effect) { public void clearEffects() { for (TimedPotion timedPotion : effects) { timedPotion.getPotion().sendRemovePacket(this); - minecraftServer.process().getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + serverProcess.getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); } this.effects.clear(); } @@ -1533,11 +1531,11 @@ public void remove() { protected void remove(boolean permanent) { if (isRemoved()) return; - minecraftServer.process().getGlobalEventHandler().call(new EntityDespawnEvent(this)); + serverProcess.getGlobalEventHandler().call(new EntityDespawnEvent(this)); try { despawn(); } catch (Throwable t) { - minecraftServer.process().getExceptionManager().handleException(t); + serverProcess.getExceptionManager().handleException(t); } // Remove passengers if any (also done with LivingEntity#kill) @@ -1546,7 +1544,7 @@ protected void remove(boolean permanent) { final Entity vehicle = this.vehicle; if (vehicle != null) vehicle.removePassenger(this); - minecraftServer.process().dispatcher().removeElement(this); + serverProcess.dispatcher().removeElement(this); this.removed = true; if (permanent) { Entity.ENTITY_BY_ID.remove(id); @@ -1582,7 +1580,7 @@ public boolean isRemoved() { * @param temporalUnit the unit of the delay */ public void scheduleRemove(long delay, @NotNull TemporalUnit temporalUnit) { - if (temporalUnit == TimeUnit.SERVER_TICK) { + if (temporalUnit.equals(TimeUnit.getServerTick(serverProcess.getMinecraftServer()))) { scheduleRemove(TaskSchedule.tick((int) delay)); } else { scheduleRemove(Duration.of(delay, temporalUnit)); @@ -1603,7 +1601,7 @@ private void scheduleRemove(TaskSchedule schedule) { } protected @NotNull Vec getVelocityForPacket() { - return this.velocity.mul(8000f / MinecraftServer.TICK_PER_SECOND); + return this.velocity.mul(8000f / serverProcess.getMinecraftServer().getTickPerSecond()); } protected @NotNull EntityVelocityPacket getVelocityPacket() { @@ -1632,7 +1630,7 @@ private void scheduleRemove(TaskSchedule schedule) { protected void synchronizePosition(boolean includeSelf) { final Pos posCache = this.position; final ServerPacket packet = new EntityTeleportPacket(getEntityId(), posCache, isOnGround()); - PacketUtils.prepareViewablePacket(minecraftServer, currentChunk, packet, this); + PacketUtils.prepareViewablePacket(serverProcess, currentChunk, packet, this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); this.lastSyncedPosition = posCache; } @@ -1710,9 +1708,9 @@ private Duration getSynchronizationCooldown() { public void takeKnockback(float strength, final double x, final double z) { if (strength > 0) { //TODO check possible side effects of unnatural TPS (other than 20TPS) - strength *= MinecraftServer.TICK_PER_SECOND; + strength *= serverProcess.getMinecraftServer().getTickPerSecond(); final Vec velocityModifier = new Vec(x, z).normalize().mul(strength); - final double verticalLimit = .4d * MinecraftServer.TICK_PER_SECOND; + final double verticalLimit = .4d * serverProcess.getMinecraftServer().getTickPerSecond(); setVelocity(new Vec(velocity.x() / 2d - velocityModifier.x(), onGround ? Math.min(verticalLimit, velocity.y() / 2d + strength) : velocity.y(), @@ -1832,8 +1830,8 @@ public boolean hasCollision() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } public enum Pose { diff --git a/src/main/java/net/minestom/server/entity/EntityCreature.java b/src/main/java/net/minestom/server/entity/EntityCreature.java index 24c995c845f..729702ae7e2 100644 --- a/src/main/java/net/minestom/server/entity/EntityCreature.java +++ b/src/main/java/net/minestom/server/entity/EntityCreature.java @@ -1,7 +1,7 @@ package net.minestom.server.entity; import com.extollit.gaming.ai.path.HydrazinePathFinder; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.ai.EntityAI; import net.minestom.server.entity.ai.EntityAIGroup; @@ -33,13 +33,13 @@ public class EntityCreature extends LivingEntity implements NavigableEntity, Ent /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public EntityCreature(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { - super(minecraftServer, entityType, uuid); + public EntityCreature(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(serverProcess, entityType, uuid); heal(); } - public EntityCreature(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { - this(minecraftServer, entityType, UUID.randomUUID()); + public EntityCreature(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { + this(serverProcess, entityType, UUID.randomUUID()); } @Override @@ -134,7 +134,7 @@ public void attack(@NotNull Entity target, boolean swingHand) { if (swingHand) swingMainHand(); EntityAttackEvent attackEvent = new EntityAttackEvent(this, target); - minecraftServer.process().getGlobalEventHandler().call(attackEvent); + getServerProcess().getGlobalEventHandler().call(attackEvent); } /** diff --git a/src/main/java/net/minestom/server/entity/EntityProjectile.java b/src/main/java/net/minestom/server/entity/EntityProjectile.java index 676af1f2f0b..fbfa494b72e 100644 --- a/src/main/java/net/minestom/server/entity/EntityProjectile.java +++ b/src/main/java/net/minestom/server/entity/EntityProjectile.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.collision.BoundingBox; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; @@ -30,8 +30,8 @@ public class EntityProjectile extends Entity { private final Entity shooter; - public EntityProjectile(@NotNull MinecraftServer minecraftServer, @Nullable Entity shooter, @NotNull EntityType entityType) { - super(minecraftServer, entityType); + public EntityProjectile(@NotNull ServerProcess serverProcess, @Nullable Entity shooter, @NotNull EntityType entityType) { + super(serverProcess, entityType); this.shooter = shooter; setup(); } @@ -50,7 +50,7 @@ public Entity getShooter() { public void shoot(Point to, double power, double spread) { final EntityShootEvent shootEvent = new EntityShootEvent(this.shooter, this, to, power, spread); - minecraftServer.process().getGlobalEventHandler().call(shootEvent); + getServerProcess().getGlobalEventHandler().call(shootEvent); if (shootEvent.isCancelled()) { remove(); return; @@ -105,7 +105,7 @@ public void tick(long time) { } super.onGround = false; setNoGravity(false); - minecraftServer.process().getGlobalEventHandler().call(new ProjectileUncollideEvent(this)); + getServerProcess().getGlobalEventHandler().call(new ProjectileUncollideEvent(this)); } } @@ -147,7 +147,7 @@ private boolean isStuck(Pos pos, Pos posNow) { } if (block.isSolid()) { final ProjectileCollideWithBlockEvent event = new ProjectileCollideWithBlockEvent(this, pos, block); - minecraftServer.process().getGlobalEventHandler().call(event); + getServerProcess().getGlobalEventHandler().call(event); if (!event.isCancelled()) { teleport(pos); return true; @@ -175,7 +175,7 @@ private boolean isStuck(Pos pos, Pos posNow) { if (victimOptional.isPresent()) { final LivingEntity target = victimOptional.get(); final ProjectileCollideWithEntityEvent event = new ProjectileCollideWithEntityEvent(this, pos, target); - minecraftServer.process().getGlobalEventHandler().call(event); + getServerProcess().getGlobalEventHandler().call(event); if (!event.isCancelled()) { return super.onGround; } diff --git a/src/main/java/net/minestom/server/entity/EntityView.java b/src/main/java/net/minestom/server/entity/EntityView.java index 79b1afc0d14..20cbe0eaf66 100644 --- a/src/main/java/net/minestom/server/entity/EntityView.java +++ b/src/main/java/net/minestom/server/entity/EntityView.java @@ -228,7 +228,7 @@ private Collection references() { final Point point = trackedLocation.point(); Int2ObjectOpenHashMap entityMap = new Int2ObjectOpenHashMap<>(lastSize); - instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.minecraftServer.getEntityViewDistance(), target, + instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.getServerProcess().getMinecraftServer().getEntityViewDistance(), target, (entity) -> entityMap.putIfAbsent(entity.getEntityId(), entity)); this.lastSize = entityMap.size(); return entityMap.values(); diff --git a/src/main/java/net/minestom/server/entity/ExperienceOrb.java b/src/main/java/net/minestom/server/entity/ExperienceOrb.java index 5c663e665cb..8b2f737d70b 100644 --- a/src/main/java/net/minestom/server/entity/ExperienceOrb.java +++ b/src/main/java/net/minestom/server/entity/ExperienceOrb.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Vec; import java.util.Comparator; @@ -11,8 +11,8 @@ public class ExperienceOrb extends Entity { private Player target; private long lastTargetUpdateTick; - public ExperienceOrb(MinecraftServer minecraftServer, short experienceCount) { - super(minecraftServer, EntityType.EXPERIENCE_ORB); + public ExperienceOrb(ServerProcess serverProcess, short experienceCount) { + super(serverProcess, EntityType.EXPERIENCE_ORB); setBoundingBox(0.5f, 0.5f, 0.5f); //todo vanilla sets random velocity here? this.experienceCount = experienceCount; diff --git a/src/main/java/net/minestom/server/entity/ItemEntity.java b/src/main/java/net/minestom/server/entity/ItemEntity.java index cbfc139060a..5b00f59644b 100644 --- a/src/main/java/net/minestom/server/entity/ItemEntity.java +++ b/src/main/java/net/minestom/server/entity/ItemEntity.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.metadata.item.ItemEntityMeta; import net.minestom.server.event.entity.EntityItemMergeEvent; import net.minestom.server.instance.EntityTracker; @@ -22,7 +22,7 @@ public class ItemEntity extends Entity { /** * Used to slow down the merge check delay */ - private static Duration mergeDelay = Duration.of(10, TimeUnit.SERVER_TICK); + private Duration mergeDelay; /** * The last time that this item has checked his neighbors for merge @@ -38,10 +38,11 @@ public class ItemEntity extends Entity { private long spawnTime; private long pickupDelay; - public ItemEntity(@NotNull MinecraftServer minecraftServer, @NotNull ItemStack itemStack) { - super(minecraftServer, EntityType.ITEM); + public ItemEntity(@NotNull ServerProcess serverProcess, @NotNull ItemStack itemStack) { + super(serverProcess, EntityType.ITEM); setItemStack(itemStack); setBoundingBox(0.25f, 0.25f, 0.25f); + mergeDelay = Duration.of(10, TimeUnit.getServerTick(serverProcess.getMinecraftServer())); } /** @@ -50,7 +51,7 @@ public ItemEntity(@NotNull MinecraftServer minecraftServer, @NotNull ItemStack i * @return the merge update option */ @Nullable - public static Duration getMergeDelay() { + public Duration getMergeDelay() { return mergeDelay; } @@ -60,8 +61,8 @@ public static Duration getMergeDelay() { * * @param delay the new merge delay */ - public static void setMergeDelay(@Nullable Duration delay) { - ItemEntity.mergeDelay = delay; + public void setMergeDelay(@Nullable Duration delay) { + mergeDelay = delay; } @Override @@ -85,7 +86,7 @@ public void update(long time) { if (!stackingRule.canApply(itemStack, totalAmount)) return; final ItemStack result = stackingRule.apply(itemStack, totalAmount); EntityItemMergeEvent entityItemMergeEvent = new EntityItemMergeEvent(this, itemEntity, result); - minecraftServer.process().getGlobalEventHandler().callCancellable(entityItemMergeEvent, () -> { + getServerProcess().getGlobalEventHandler().callCancellable(entityItemMergeEvent, () -> { setItemStack(entityItemMergeEvent.getResult()); itemEntity.remove(); }); diff --git a/src/main/java/net/minestom/server/entity/LivingEntity.java b/src/main/java/net/minestom/server/entity/LivingEntity.java index f0f64346b7f..70d480896ff 100644 --- a/src/main/java/net/minestom/server/entity/LivingEntity.java +++ b/src/main/java/net/minestom/server/entity/LivingEntity.java @@ -1,7 +1,7 @@ package net.minestom.server.entity; import net.kyori.adventure.sound.Sound.Source; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.attribute.Attribute; import net.minestom.server.attribute.AttributeInstance; import net.minestom.server.collision.BoundingBox; @@ -45,7 +45,7 @@ public class LivingEntity extends Entity implements EquipmentHandler { // ItemStack pickup protected boolean canPickupItem; - protected Cooldown itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.SERVER_TICK)); + protected Cooldown itemPickupCooldown; protected boolean isDead; @@ -86,13 +86,14 @@ public class LivingEntity extends Entity implements EquipmentHandler { /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public LivingEntity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { - super(minecraftServer, entityType, uuid); + public LivingEntity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(serverProcess, entityType, uuid); initEquipments(); + itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(serverProcess.getMinecraftServer()))); } - public LivingEntity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { - this(minecraftServer, entityType, UUID.randomUUID()); + public LivingEntity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { + this(serverProcess, entityType, UUID.randomUUID()); } private void initEquipments() { @@ -179,7 +180,7 @@ public void setBoots(@NotNull ItemStack itemStack) { private ItemStack getEquipmentItem(@NotNull ItemStack itemStack, @NotNull EquipmentSlot slot) { EntityEquipEvent entityEquipEvent = new EntityEquipEvent(this, itemStack, slot); - minecraftServer.process().getGlobalEventHandler().call(entityEquipEvent); + getServerProcess().getGlobalEventHandler().call(entityEquipEvent); return entityEquipEvent.getEquippedItem(); } @@ -199,7 +200,7 @@ public void update(long time) { if (!itemEntity.isPickable()) return; if (expandedBoundingBox.intersectEntity(loweredPosition, itemEntity)) { PickupItemEvent pickupItemEvent = new PickupItemEvent(this, itemEntity); - minecraftServer.process().getGlobalEventHandler().callCancellable(pickupItemEvent, () -> { + getServerProcess().getGlobalEventHandler().callCancellable(pickupItemEvent, () -> { final ItemStack item = itemEntity.getItemStack(); sendPacketToViewersAndSelf(new CollectItemPacket(itemEntity.getEntityId(), getEntityId(), item.amount())); itemEntity.remove(); @@ -267,7 +268,7 @@ public void kill() { } EntityDeathEvent entityDeathEvent = new EntityDeathEvent(this); - minecraftServer.process().getGlobalEventHandler().call(entityDeathEvent); + getServerProcess().getGlobalEventHandler().call(entityDeathEvent); } /** @@ -276,7 +277,7 @@ public void kill() { * @param duration duration in ticks of the effect */ public void setFireForDuration(int duration) { - setFireForDuration(duration, TimeUnit.SERVER_TICK); + setFireForDuration(duration, TimeUnit.getServerTick(getServerProcess().getMinecraftServer())); } /** @@ -301,7 +302,7 @@ public void setFireForDuration(Duration duration) { // Do not start fire event if the fire needs to be removed (< 0 duration) if (duration.toMillis() > 0) { - minecraftServer.process().getGlobalEventHandler().callCancellable(entityFireEvent, () -> { + getServerProcess().getGlobalEventHandler().callCancellable(entityFireEvent, () -> { final long fireTime = entityFireEvent.getFireTime(TimeUnit.MILLISECOND); setOnFire(true); fireExtinguishTime = System.currentTimeMillis() + fireTime; @@ -329,7 +330,7 @@ public boolean damage(@NotNull Damage damage) { } EntityDamageEvent entityDamageEvent = new EntityDamageEvent(this, damage, damage.getSound(this)); - minecraftServer.process().getGlobalEventHandler().callCancellable(entityDamageEvent, () -> { + getServerProcess().getGlobalEventHandler().callCancellable(entityDamageEvent, () -> { // Set the last damage type since the event is not cancelled this.lastDamage = entityDamageEvent.getDamage(); diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index f67dba316d1..92245261c0b 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -19,7 +19,8 @@ import net.kyori.adventure.text.event.HoverEventSource; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.title.TitlePart; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; @@ -145,7 +146,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable, /** * Keeps track of what chunks are sent to the client, this defines the center of the loaded area - * in the range of {@link MinecraftServer#getChunkViewDistance()} + * in the range of {@link ServerSettings#getChunkViewDistance()} */ private Vec chunksLoadedByClient = Vec.ZERO; private final ReentrantLock chunkQueueLock = new ReentrantLock(); @@ -192,7 +193,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable, private final ChunkUpdateLimitChecker chunkUpdateLimitChecker = new ChunkUpdateLimitChecker(6); // Experience orb pickup - protected Cooldown experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.SERVER_TICK)); + protected Cooldown experiencePickupCooldown; private BelowNameTag belowNameTag; @@ -223,8 +224,8 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // The future is non-null when a resource pack is in-flight, and completed when all statuses have been received. private CompletableFuture resourcePackFuture = null; - public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - super(minecraftServer, EntityType.PLAYER, uuid); + public Player(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { + super(serverProcess, EntityType.PLAYER, uuid); this.username = username; this.usernameComponent = Component.text(username); this.playerConnection = playerConnection; @@ -232,7 +233,7 @@ public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @Not setRespawnPoint(Pos.ZERO); this.settings = new PlayerSettings(); - this.inventory = new PlayerInventory(minecraftServer, this); + this.inventory = new PlayerInventory(serverProcess, this); setCanPickupItem(true); // By default @@ -259,8 +260,9 @@ public Player(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @Not chunkRemover = (chunkX, chunkZ) -> { // Unload old chunks sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); - minecraftServer.process().getGlobalEventHandler().call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); + getServerProcess().getGlobalEventHandler().call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); }; + experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(getServerProcess().getMinecraftServer()))); } @ApiStatus.Internal @@ -288,13 +290,13 @@ public CompletableFuture UNSAFE_init() { final JoinGamePacket joinGamePacket = new JoinGamePacket( getEntityId(), this.hardcore, List.of(), 0, - minecraftServer.getChunkViewDistance(), minecraftServer.getChunkViewDistance(), + getServerProcess().getMinecraftServer().getChunkViewDistance(), getServerProcess().getMinecraftServer().getChunkViewDistance(), false, true, false, dimensionType.toString(), spawnInstance.getDimensionName(), 0, gameMode, null, false, levelFlat, deathLocation, portalCooldown); sendPacket(joinGamePacket); // Difficulty - sendPacket(new ServerDifficultyPacket(minecraftServer.getDifficulty(), true)); + sendPacket(new ServerDifficultyPacket(getServerProcess().getMinecraftServer().getDifficulty(), true)); sendPacket(new SpawnPositionPacket(respawnPoint, 0)); @@ -316,12 +318,12 @@ public CompletableFuture UNSAFE_init() { } } PlayerSkinInitEvent skinInitEvent = new PlayerSkinInitEvent(this, profileSkin); - minecraftServer.process().getGlobalEventHandler().call(skinInitEvent); + getServerProcess().getGlobalEventHandler().call(skinInitEvent); this.skin = skinInitEvent.getSkin(); // FIXME: when using Geyser, this line remove the skin of the client - PacketUtils.broadcastPlayPacket(minecraftServer, getAddPlayerToList()); + PacketUtils.broadcastPlayPacket(getServerProcess(), getAddPlayerToList()); - var connectionManager = minecraftServer.process().getConnectionManager(); + var connectionManager = getServerProcess().getConnectionManager(); for (var player : connectionManager.getOnlinePlayers()) { if (player != this) { sendPacket(player.getAddPlayerToList()); @@ -332,7 +334,7 @@ public CompletableFuture UNSAFE_init() { } //Teams - for (Team team : minecraftServer.process().getTeamManager().getTeams()) { + for (Team team : getServerProcess().getTeamManager().getTeams()) { sendPacket(team.createTeamsCreationPacket()); } @@ -341,7 +343,7 @@ public CompletableFuture UNSAFE_init() { // Recipes start { - RecipeManager recipeManager = minecraftServer.process().getRecipeManager(); + RecipeManager recipeManager = getServerProcess().getRecipeManager(); sendPacket(recipeManager.getDeclareRecipesPacket()); List recipesIdentifier = new ArrayList<>(); @@ -385,7 +387,7 @@ public void startConfigurationPhase() { // Remove the player, then send them back to configuration remove(false); - var connectionManager = minecraftServer.process().getConnectionManager(); + var connectionManager = getServerProcess().getConnectionManager(); connectionManager.transitionPlayToConfig(this); } @@ -418,7 +420,7 @@ public void update(long time) { EntityTracker.Target.EXPERIENCE_ORBS, experienceOrb -> { if (expandedBoundingBox.intersectEntity(loweredPosition, experienceOrb)) { PickupExperienceEvent pickupExperienceEvent = new PickupExperienceEvent(this, experienceOrb); - minecraftServer.process().getGlobalEventHandler().callCancellable(pickupExperienceEvent, () -> { + getServerProcess().getGlobalEventHandler().callCancellable(pickupExperienceEvent, () -> { short experienceCount = pickupExperienceEvent.getExperienceCount(); // TODO give to player experienceOrb.remove(); }); @@ -443,7 +445,7 @@ public void update(long time) { if (isFood) { PlayerEatEvent playerEatEvent = new PlayerEatEvent(this, foodItem, eatingHand); - minecraftServer.process().getGlobalEventHandler().call(playerEatEvent); + getServerProcess().getGlobalEventHandler().call(playerEatEvent); } refreshEating(null); @@ -453,7 +455,7 @@ public void update(long time) { if (EXPERIMENT_PERFORM_POSE_UPDATES) updatePose(); // Tick event - minecraftServer.process().getGlobalEventHandler().call(new PlayerTickEvent(this)); + getServerProcess().getGlobalEventHandler().call(new PlayerTickEvent(this)); } @Override @@ -483,7 +485,7 @@ public void kill() { // Call player death event PlayerDeathEvent playerDeathEvent = new PlayerDeathEvent(this, deathText, chatMessage); - minecraftServer.process().getGlobalEventHandler().call(playerDeathEvent); + getServerProcess().getGlobalEventHandler().call(playerDeathEvent); deathText = playerDeathEvent.getDeathText(); chatMessage = playerDeathEvent.getChatMessage(); @@ -495,7 +497,7 @@ public void kill() { // #buildDeathMessage can return null, check here if (chatMessage != null) { - minecraftServer.process().getAudiences().players().sendMessage(chatMessage); + getServerProcess().getAudiences().players().sendMessage(chatMessage); } // Set death location @@ -521,7 +523,7 @@ public void respawn() { 0, gameMode, gameMode, false, levelFlat, deathLocation, portalCooldown, RespawnPacket.COPY_ALL)); PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this); - minecraftServer.process().getGlobalEventHandler().call(respawnEvent); + getServerProcess().getGlobalEventHandler().call(respawnEvent); triggerStatus((byte) (24 + permissionLevel)); // Set permission level refreshIsDead(false); updatePose(); @@ -532,7 +534,7 @@ public void respawn() { ChunkUtils.forChunksInRange(respawnPosition, settings.getEffectiveViewDistance(), chunkAdder); chunksLoadedByClient = new Vec(respawnPosition.chunkX(), respawnPosition.chunkZ()); // Client also needs all entities resent to them, since those are unloaded as well - this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(minecraftServer.getChunkViewDistance(), settings.getViewDistance()), + this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(getServerProcess().getMinecraftServer().getChunkViewDistance(), settings.getViewDistance()), EntityTracker.Target.ENTITIES, entity -> { // Skip refreshing self with a new viewer if (!entity.getUuid().equals(uuid) && entity.isViewer(this)) { @@ -547,7 +549,7 @@ public void respawn() { */ private void refreshClientStateAfterRespawn() { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); - sendPacket(new ServerDifficultyPacket(minecraftServer.getDifficulty(), false)); + sendPacket(new ServerDifficultyPacket(getServerProcess().getMinecraftServer().getDifficulty(), false)); sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation)); sendPacket(new SetExperiencePacket(exp, level, 0)); triggerStatus((byte) (24 + permissionLevel)); // Set permission level @@ -560,7 +562,7 @@ private void refreshClientStateAfterRespawn() { * again, and any changes will be visible to the player. */ public void refreshCommands() { - sendPacket(minecraftServer.process().getCommandManager().createDeclareCommandsPacket(this)); + sendPacket(getServerProcess().getCommandManager().createDeclareCommandsPacket(this)); } @Override @@ -574,14 +576,14 @@ public void remove(boolean permanent) { if (permanent) { this.packets.clear(); - minecraftServer.process().getGlobalEventHandler().call(new PlayerDisconnectEvent(this)); + getServerProcess().getGlobalEventHandler().call(new PlayerDisconnectEvent(this)); } super.remove(permanent); final Inventory currentInventory = getOpenInventory(); if (currentInventory != null) currentInventory.removeViewer(this); - minecraftServer.process().getBossBarManager().removeAllBossBars(this); + getServerProcess().getBossBarManager().removeAllBossBars(this); // Advancement tabs cache { Set advancementTabs = AdvancementTab.getTabs(this); @@ -595,9 +597,9 @@ public void remove(boolean permanent) { final int chunkX = position.chunkX(); final int chunkZ = position.chunkZ(); // Clear all viewable chunks - ChunkUtils.forChunksInRange(chunkX, chunkZ, minecraftServer.getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(chunkX, chunkZ, getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkRemover); // Remove from the tab-list - PacketUtils.broadcastPlayPacket(minecraftServer, getRemovePlayerToList()); + PacketUtils.broadcastPlayPacket(getServerProcess(), getRemovePlayerToList()); // Prevent the player from being stuck in loading screen, or just unable to interact with the server // This should be considered as a bug, since the player will ultimately time out anyway. @@ -647,7 +649,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Ensure that surrounding chunks are loaded List> futures = new ArrayList<>(); - ChunkUtils.forChunksInRange(spawnPosition, minecraftServer.getChunkViewDistance(), (chunkX, chunkZ) -> { + ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getMinecraftServer().getChunkViewDistance(), (chunkX, chunkZ) -> { final CompletableFuture future = instance.loadOptionalChunk(chunkX, chunkZ); if (!future.isDone()) futures.add(future); }); @@ -660,7 +662,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // One or more chunks need to be loaded final Thread runThread = Thread.currentThread(); CountDownLatch latch = new CountDownLatch(1); - Scheduler scheduler = minecraftServer.process().getSchedulerManager(); + Scheduler scheduler = getServerProcess().getSchedulerManager(); CompletableFuture future = new CompletableFuture<>() { @Override public Void join() { @@ -720,7 +722,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, if (!firstSpawn && !dimensionChange) { // Player instance changed, clear current viewable collections if (updateChunks) - ChunkUtils.forChunksInRange(spawnPosition, minecraftServer.getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkRemover); } if (dimensionChange) sendDimension(instance.getDimensionType(), instance.getDimensionName()); @@ -735,7 +737,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new UpdateViewPositionPacket(chunkX, chunkZ)); // Load the nearby chunks and queue them to be sent to them - ChunkUtils.forChunksInRange(spawnPosition, minecraftServer.getChunkViewDistance(), chunkAdder); + ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkAdder); } synchronizePosition(true); // So the player doesn't get stuck @@ -754,7 +756,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); } - minecraftServer.process().getGlobalEventHandler().call(new PlayerSpawnEvent(this, instance, firstSpawn)); + getServerProcess().getGlobalEventHandler().call(new PlayerSpawnEvent(this, instance, firstSpawn)); } @ApiStatus.Internal @@ -802,7 +804,7 @@ private void sendPendingChunks() { if (chunk == null || !chunk.isLoaded()) continue; sendPacket(chunk.getFullDataPacket()); - minecraftServer.process().getGlobalEventHandler().call(new PlayerChunkLoadEvent(this, chunkX, chunkZ)); + getServerProcess().getGlobalEventHandler().call(new PlayerChunkLoadEvent(this, chunkX, chunkZ)); pendingChunkCount -= 1f; batchSize += 1; @@ -976,12 +978,12 @@ public void clearTitle() { @Override public void showBossBar(@NotNull BossBar bar) { - minecraftServer.process().getBossBarManager().addBossBar(this, bar); + getServerProcess().getBossBarManager().addBossBar(this, bar); } @Override public void hideBossBar(@NotNull BossBar bar) { - minecraftServer.process().getBossBarManager().removeBossBar(this, bar); + getServerProcess().getBossBarManager().removeBossBar(this, bar); } @Override @@ -1141,7 +1143,7 @@ public double getEyeHeight() { */ public void setDisplayName(@Nullable Component displayName) { this.displayName = displayName; - PacketUtils.broadcastPlayPacket(minecraftServer, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); + PacketUtils.broadcastPlayPacket(getServerProcess(), new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); } /** @@ -1183,11 +1185,11 @@ public synchronized void setSkin(@Nullable PlayerSkin skin) { { // Remove player - PacketUtils.broadcastPlayPacket(minecraftServer, removePlayerPacket); + PacketUtils.broadcastPlayPacket(getServerProcess(), removePlayerPacket); sendPacketToViewers(destroyEntitiesPacket); // Show player again - PacketUtils.broadcastPlayPacket(minecraftServer, addPlayerPacket); + PacketUtils.broadcastPlayPacket(getServerProcess(), addPlayerPacket); getViewers().forEach(player -> showPlayer(player.getPlayerConnection())); } @@ -1264,7 +1266,7 @@ public void setUsernameField(@NotNull String username) { public boolean dropItem(@NotNull ItemStack item) { if (item.isAir()) return false; ItemDropEvent itemDropEvent = new ItemDropEvent(this, item); - minecraftServer.process().getGlobalEventHandler().call(itemDropEvent); + getServerProcess().getGlobalEventHandler().call(itemDropEvent); return !itemDropEvent.isCancelled(); } @@ -1553,7 +1555,7 @@ public GameMode getGameMode() { */ public boolean setGameMode(@NotNull GameMode gameMode) { PlayerGameModeChangeEvent playerGameModeChangeEvent = new PlayerGameModeChangeEvent(this, gameMode); - minecraftServer.process().getGlobalEventHandler().call(playerGameModeChangeEvent); + getServerProcess().getGlobalEventHandler().call(playerGameModeChangeEvent); if (playerGameModeChangeEvent.isCancelled()) { // Abort return false; @@ -1565,7 +1567,7 @@ public boolean setGameMode(@NotNull GameMode gameMode) { // Condition to prevent sending the packets before spawning the player if (isActive()) { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.CHANGE_GAMEMODE, gameMode.id())); - PacketUtils.broadcastPlayPacket(minecraftServer, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); + PacketUtils.broadcastPlayPacket(getServerProcess(), new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); } // The client updates their abilities based on the GameMode as follows @@ -1701,7 +1703,7 @@ public void setBelowNameTag(BelowNameTag belowNameTag) { public boolean openInventory(@NotNull Inventory inventory) { InventoryOpenEvent inventoryOpenEvent = new InventoryOpenEvent(inventory, this); - minecraftServer.process().getGlobalEventHandler().callCancellable(inventoryOpenEvent, () -> { + getServerProcess().getGlobalEventHandler().callCancellable(inventoryOpenEvent, () -> { Inventory openInventory = getOpenInventory(); if (openInventory != null) { openInventory.removeViewer(this); @@ -2053,7 +2055,7 @@ public void interpretPacketQueue() { kick(Component.text("Too Many Packets", NamedTextColor.RED)); return; } - final PacketListenerManager manager = minecraftServer.process().getPacketListenerManager(); + final PacketListenerManager manager = getServerProcess().getPacketListenerManager(); // This method is NOT thread-safe this.packets.drain(packet -> manager.processClientPacket(packet, playerConnection), PACKET_PER_TICK); } @@ -2066,7 +2068,7 @@ public void interpretPacketQueue() { public void refreshLatency(int latency) { this.latency = latency; if (getPlayerConnection().getConnectionState() == ConnectionState.PLAY) { - PacketUtils.broadcastPlayPacket(minecraftServer, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); + PacketUtils.broadcastPlayPacket(getServerProcess(), new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); } } @@ -2074,7 +2076,7 @@ public void refreshOnGround(boolean onGround) { this.onGround = onGround; if (this.onGround && this.isFlyingWithElytra()) { this.setFlyingWithElytra(false); - minecraftServer.process().getGlobalEventHandler().call(new PlayerStopFlyingWithElytraEvent(this)); + getServerProcess().getGlobalEventHandler().call(new PlayerStopFlyingWithElytraEvent(this)); } } @@ -2148,7 +2150,7 @@ public void refreshEating(@Nullable Hand eatingHand) { return null; ItemUpdateStateEvent itemUpdateStateEvent = new ItemUpdateStateEvent(this, hand, updatedItem); - minecraftServer.process().getGlobalEventHandler().call(itemUpdateStateEvent); + getServerProcess().getGlobalEventHandler().call(itemUpdateStateEvent); return itemUpdateStateEvent; } @@ -2340,11 +2342,6 @@ public Player asPlayer() { return this; } - @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; - } - protected void sendChunkUpdates(Chunk newChunk) { if (chunkUpdateLimitChecker.addToHistory(newChunk)) { final int newX = newChunk.getChunkX(); @@ -2352,7 +2349,7 @@ protected void sendChunkUpdates(Chunk newChunk) { final Vec old = chunksLoadedByClient; sendPacket(new UpdateViewPositionPacket(newX, newZ)); ChunkUtils.forDifferingChunksInRange(newX, newZ, (int) old.x(), (int) old.z(), - minecraftServer.getChunkViewDistance(), chunkAdder, chunkRemover); + getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkAdder, chunkRemover); this.chunksLoadedByClient = new Vec(newX, newZ); } } @@ -2420,7 +2417,7 @@ public byte getViewDistance() { } public int getEffectiveViewDistance() { - return Math.min(getViewDistance(), minecraftServer.getChunkViewDistance()); + return Math.min(getViewDistance(), getServerProcess().getMinecraftServer().getChunkViewDistance()); } /** diff --git a/src/main/java/net/minestom/server/entity/PlayerProjectile.java b/src/main/java/net/minestom/server/entity/PlayerProjectile.java index 85568a872b7..be2b0597a07 100644 --- a/src/main/java/net/minestom/server/entity/PlayerProjectile.java +++ b/src/main/java/net/minestom/server/entity/PlayerProjectile.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.collision.CollisionUtils; import net.minestom.server.collision.PhysicsResult; import net.minestom.server.collision.ShapeImpl; @@ -23,8 +23,8 @@ public class PlayerProjectile extends LivingEntity { private final Entity shooter; private long cooldown = 0; - public PlayerProjectile(MinecraftServer minecraftServer, Entity shooter, EntityType type) { - super(minecraftServer, type); + public PlayerProjectile(ServerProcess serverProcess, Entity shooter, EntityType type) { + super(serverProcess, type); this.shooter = shooter; this.hasCollision = false; setup(); @@ -50,7 +50,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Check if we're inside of a block if (insideBlock != null) { var e = new ProjectileCollideWithBlockEvent(this, Pos.fromPoint(spawnPosition), instance.getBlock(spawnPosition)); - minecraftServer.process().getGlobalEventHandler().call(e); + getServerProcess().getGlobalEventHandler().call(e); } return res; @@ -86,7 +86,7 @@ public void shoot(@NotNull Point from, @NotNull Point to, double power, double s dz += random.nextGaussian() * spread; final EntityShootEvent shootEvent = new EntityShootEvent(this.shooter, this, from, power, spread); - minecraftServer.process().getGlobalEventHandler().call(shootEvent); + getServerProcess().getGlobalEventHandler().call(shootEvent); if (shootEvent.isCancelled()) { remove(); return; @@ -148,7 +148,7 @@ public void tick(long time) { if (collided != null && collided.collisionShapes()[0] != shooter) { if (collided.collisionShapes()[0] instanceof Entity entity) { var e = new ProjectileCollideWithEntityEvent(this, collided.newPosition(), entity); - minecraftServer.process().getGlobalEventHandler().call(e); + getServerProcess().getGlobalEventHandler().call(e); return; } } @@ -172,7 +172,7 @@ public void tick(long time) { if (hitBlock == null) return; var e = new ProjectileCollideWithBlockEvent(this, Pos.fromPoint(hitPoint), hitBlock); - minecraftServer.process().getGlobalEventHandler().call(e); + getServerProcess().getGlobalEventHandler().call(e); } } } diff --git a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java index 8247dab8684..57e1b2616bf 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java @@ -20,7 +20,7 @@ */ public class CombinedAttackGoal extends GoalSelector { - private final Cooldown cooldown = new Cooldown(Duration.of(5, TimeUnit.SERVER_TICK)); + private final Cooldown cooldown; private final int meleeRangeSquared; private final Duration meleeDelay; @@ -127,6 +127,7 @@ public CombinedAttackGoal(@NotNull EntityCreature entityCreature, this.rangedDelay = rangedDelay; this.desirableRangeSquared = desirableRange * desirableRange; this.comeClose = comeClose; + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getMinecraftServer()))); Check.argCondition(desirableRange > rangedRange, "Desirable range can not exceed ranged range!"); } @@ -178,7 +179,7 @@ public void tick(long time) { Function projectileGenerator = this.projectileGenerator; if (projectileGenerator == null) { - projectileGenerator = shooter -> new EntityProjectile(shooter.minecraftServer, shooter, EntityType.ARROW); + projectileGenerator = shooter -> new EntityProjectile(shooter.getServerProcess(), shooter, EntityType.ARROW); } EntityProjectile projectile = projectileGenerator.apply(this.entityCreature); projectile.setInstance(this.entityCreature.getInstance(), this.entityCreature.getPosition()); diff --git a/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java index dc1c86e74f7..ce674031712 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java @@ -1,11 +1,11 @@ package net.minestom.server.entity.ai.goal; +import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.ai.GoalSelector; import net.minestom.server.entity.ai.TargetSelector; import net.minestom.server.entity.pathfinding.Navigator; -import net.minestom.server.coordinate.Point; import net.minestom.server.utils.time.Cooldown; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; @@ -19,7 +19,7 @@ */ public class MeleeAttackGoal extends GoalSelector { - private final Cooldown cooldown = new Cooldown(Duration.of(5, TimeUnit.SERVER_TICK)); + private final Cooldown cooldown; private long lastHit; private final double range; @@ -47,6 +47,7 @@ public MeleeAttackGoal(@NotNull EntityCreature entityCreature, double range, Dur super(entityCreature); this.range = range; this.delay = delay; + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getMinecraftServer()))); } public @NotNull Cooldown getCooldown() { diff --git a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java index 7aeefeb1d0e..27626f904bd 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java @@ -17,7 +17,7 @@ import java.util.function.Function; public class RangedAttackGoal extends GoalSelector { - private final Cooldown cooldown = new Cooldown(Duration.of(5, TimeUnit.SERVER_TICK)); + private final Cooldown cooldown; private long lastShot; private final Duration delay; @@ -63,6 +63,7 @@ public RangedAttackGoal(@NotNull EntityCreature entityCreature, Duration delay, this.comeClose = comeClose; this.power = power; this.spread = spread; + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getMinecraftServer()))); Check.argCondition(desirableRange > attackRange, "Desirable range can not exceed attack range!"); } @@ -84,7 +85,7 @@ public void setProjectileGenerator(Function projectile private ProjectileGenerator getProjectileGeneratorOrDefault() { if (projectileGenerator == null) { - setProjectileGenerator(shooter -> new EntityProjectile(shooter.minecraftServer, shooter, EntityType.ARROW)); + setProjectileGenerator(shooter -> new EntityProjectile(shooter.getServerProcess(), shooter, EntityType.ARROW)); } return projectileGenerator; } diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index 2298eb6c643..cff79573fb5 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -1,7 +1,7 @@ package net.minestom.server.entity.fakeplayer; import com.extollit.gaming.ai.path.HydrazinePathFinder; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.NavigableEntity; @@ -28,7 +28,7 @@ * (events, velocity, gravity, player list, etc...) with the exception that you need to control it server-side * using a {@link FakePlayerController} (see {@link #getController()}). *

    - * You can create one using {@link #initPlayer(MinecraftServer, UUID, String, Consumer)}. Be aware that this really behave exactly like a player + * You can create one using {@link #initPlayer(ServerProcess, UUID, String, Consumer)}. Be aware that this really behave exactly like a player * and this is a feature not a bug, you will need to check at some place if the player is a fake one or not (instanceof) if you want to change it. */ public class FakePlayer extends Player implements NavigableEntity { @@ -50,12 +50,12 @@ public class FakePlayer extends Player implements NavigableEntity { * @param username The username for the fake player. * @param option Any option for the fake player. */ - protected FakePlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, + protected FakePlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - super(minecraftServer, uuid, username, new FakePlayerConnection(minecraftServer)); - this.connectionManager = minecraftServer.process().getConnectionManager(); - this.packetListenerManager = minecraftServer.process().getPacketListenerManager(); + super(serverProcess, uuid, username, new FakePlayerConnection(serverProcess)); + this.connectionManager = serverProcess.getConnectionManager(); + this.packetListenerManager = serverProcess.getPacketListenerManager(); this.option = option; @@ -68,10 +68,10 @@ protected FakePlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uui if (event.getPlayer().equals(this)) if (event.isFirstSpawn()) { spawnCallback.accept(this); - minecraftServer.process().getGlobalEventHandler().removeListener(spawnListener); + serverProcess.getGlobalEventHandler().removeListener(spawnListener); } }).build(); - minecraftServer.process().getGlobalEventHandler().addListener(spawnListener); + serverProcess.getGlobalEventHandler().addListener(spawnListener); } playerConnection.setConnectionState(ConnectionState.LOGIN); @@ -88,23 +88,23 @@ protected FakePlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uui * @param username the FakePlayer username * @param spawnCallback the optional callback called when the fake player first spawn */ - public static void initPlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, + public static void initPlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - new FakePlayer(minecraftServer, uuid, username, option, spawnCallback); + new FakePlayer(serverProcess, uuid, username, option, spawnCallback); } /** * Initializes a new {@link FakePlayer} without adding it in cache. *

    * If you want the fake player to be obtainable with the {@link net.minestom.server.network.ConnectionManager} - * you need to specify it in a {@link FakePlayerOption} and use {@link #initPlayer(MinecraftServer, UUID, String, FakePlayerOption, Consumer)}. + * you need to specify it in a {@link FakePlayerOption} and use {@link #initPlayer(ServerProcess, UUID, String, FakePlayerOption, Consumer)}. * * @param uuid the FakePlayer uuid * @param username the FakePlayer username * @param spawnCallback the optional callback called when the fake player first spawn */ - public static void initPlayer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @Nullable Consumer spawnCallback) { - initPlayer(minecraftServer, uuid, username, new FakePlayerOption(), spawnCallback); + public static void initPlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @Nullable Consumer spawnCallback) { + initPlayer(serverProcess, uuid, username, new FakePlayerOption(), spawnCallback); } /** @@ -166,7 +166,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - minecraftServer.process().getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.SERVER_TICK).schedule(); + getServerProcess().getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(getServerProcess().getMinecraftServer())).schedule(); } } } diff --git a/src/main/java/net/minestom/server/entity/hologram/Hologram.java b/src/main/java/net/minestom/server/entity/hologram/Hologram.java index 3d0bf168457..7735b076dd3 100644 --- a/src/main/java/net/minestom/server/entity/hologram/Hologram.java +++ b/src/main/java/net/minestom/server/entity/hologram/Hologram.java @@ -1,7 +1,7 @@ package net.minestom.server.entity.hologram; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; @@ -62,7 +62,7 @@ public Hologram(Instance instance, Pos spawnPosition, Component text, boolean au * @param autoViewable {@code true}if the hologram should be visible automatically, otherwise {@code false}. */ public Hologram(Instance instance, Pos spawnPosition, Component text, boolean autoViewable, boolean marker) { - this.entity = new Entity(instance.minecraftServer, EntityType.ARMOR_STAND); + this.entity = new Entity(instance.getServerProcess(), EntityType.ARMOR_STAND); ArmorStandMeta armorStandMeta = (ArmorStandMeta) entity.getEntityMeta(); @@ -188,7 +188,7 @@ private void checkRemoved() { } @Override - public MinecraftServer getMinecraftServer() { - return entity.getMinecraftServer(); + public ServerProcess getServerProcess() { + return entity.getServerProcess(); } } diff --git a/src/main/java/net/minestom/server/event/EventNode.java b/src/main/java/net/minestom/server/event/EventNode.java index feffd05be0d..cfa560b5ebf 100644 --- a/src/main/java/net/minestom/server/event/EventNode.java +++ b/src/main/java/net/minestom/server/event/EventNode.java @@ -1,6 +1,7 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerObject; +import net.minestom.server.ServerProcess; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.tag.Tag; import net.minestom.server.tag.TagReadable; @@ -24,7 +25,7 @@ * * @param The event type accepted by this node */ -public sealed interface EventNode permits EventNodeImpl { +public sealed interface EventNode extends ServerObject permits EventNodeImpl { /** * Creates an event node which accepts any event type with no filtering. @@ -33,9 +34,9 @@ public sealed interface EventNode permits EventNodeImpl { * @return An event node with no filtering */ @Contract(value = "_, _ -> new", pure = true) - static @NotNull EventNode all(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode all(@NotNull ServerProcess serverProcess, @NotNull String name) { - return type(minecraftServer, name, EventFilter.ALL); + return type(serverProcess, name, EventFilter.ALL); } /** @@ -53,10 +54,10 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with just an event type filter */ @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode type(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter) { - return create(minecraftServer, name, filter, null); + return create(serverProcess, name, filter, null); } /** @@ -79,11 +80,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode event(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode event(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(minecraftServer, name, filter, (e, h) -> predicate.test(e)); + return create(serverProcess, name, filter, (e, h) -> predicate.test(e)); } /** @@ -108,11 +109,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode type(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @NotNull BiPredicate predicate) { - return create(minecraftServer, name, filter, predicate); + return create(serverProcess, name, filter, predicate); } /** @@ -134,11 +135,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode value(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode value(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(minecraftServer, name, filter, (e, h) -> predicate.test(h)); + return create(serverProcess, name, filter, (e, h) -> predicate.test(h)); } /** @@ -154,11 +155,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a handler with the provided tag */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode tag(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag) { - return create(minecraftServer, name, filter, (e, h) -> h.hasTag(tag)); + return create(serverProcess, name, filter, (e, h) -> h.hasTag(tag)); } /** @@ -173,20 +174,20 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a handler with the provided tag */ @Contract(value = "_, _, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull MinecraftServer minecraftServer, + static @NotNull EventNode tag(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag, @NotNull Predicate<@Nullable V> consumer) { - return create(minecraftServer, name, filter, (e, h) -> consumer.test(h.getTag(tag))); + return create(serverProcess, name, filter, (e, h) -> consumer.test(h.getTag(tag))); } - private static EventNode create(@NotNull MinecraftServer minecraftServer, + private static EventNode create(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { //noinspection unchecked - return new EventNodeImpl<>(minecraftServer, name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); + return new EventNodeImpl<>(serverProcess, name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); } /** diff --git a/src/main/java/net/minestom/server/event/EventNodeImpl.java b/src/main/java/net/minestom/server/event/EventNodeImpl.java index 2a07e96cbb7..7bb70300720 100644 --- a/src/main/java/net/minestom/server/event/EventNodeImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeImpl.java @@ -1,7 +1,7 @@ package net.minestom.server.event; import com.github.benmanes.caffeine.cache.Caffeine; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.event.trait.RecursiveEvent; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.Contract; @@ -30,7 +30,7 @@ non-sealed class EventNodeImpl implements EventNode { final Map> registeredMappedNode = Caffeine.newBuilder() .weakKeys().weakValues().>build().asMap(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; final String name; final EventFilter filter; final BiPredicate predicate; @@ -38,11 +38,11 @@ non-sealed class EventNodeImpl implements EventNode { volatile int priority; volatile EventNodeImpl parent; - EventNodeImpl(@NotNull MinecraftServer minecraftServer, + EventNodeImpl(@NotNull ServerProcess serverProcess, @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { - this.minecraftServer = minecraftServer; + this.serverProcess = serverProcess; this.name = name; this.filter = filter; this.predicate = predicate; @@ -159,7 +159,7 @@ public void removeChildren(@NotNull String name, @NotNull Class eve public @NotNull EventNode map(@NotNull H value, @NotNull EventFilter filter) { EventNodeImpl node; synchronized (GLOBAL_CHILD_LOCK) { - node = new EventNodeLazyImpl<>(minecraftServer,this, value, filter); + node = new EventNodeLazyImpl<>(serverProcess,this, value, filter); Check.stateCondition(node.parent != null, "Node already has a parent"); Check.stateCondition(Objects.equals(parent, node), "Cannot map to self"); EventNodeImpl previous = this.mappedNodeCache.putIfAbsent(value, (EventNodeImpl) node); @@ -260,6 +260,11 @@ private static void genToStringTree(StringBuilder buffer, String prefix, String } } + @Override + public ServerProcess getServerProcess() { + return serverProcess; + } + record Graph(String name, String eventType, int priority, List children) { public Graph { @@ -329,7 +334,7 @@ public void call(@NotNull E event) { try { listener.accept(event); } catch (Throwable e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } diff --git a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java index b47d812c2b1..a965dac578c 100644 --- a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import org.jetbrains.annotations.NotNull; import java.lang.invoke.MethodHandles; @@ -24,9 +24,9 @@ final class EventNodeLazyImpl extends EventNodeImpl { @SuppressWarnings("unused") private boolean mapped; - EventNodeLazyImpl(@NotNull MinecraftServer minecraftServer, @NotNull EventNodeImpl holder, + EventNodeLazyImpl(@NotNull ServerProcess serverProcess, @NotNull EventNodeImpl holder, @NotNull Object owner, @NotNull EventFilter filter) { - super(minecraftServer, owner.toString(), filter, null); + super(serverProcess, owner.toString(), filter, null); this.holder = holder; this.owner = new WeakReference<>(owner); } diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandler.java b/src/main/java/net/minestom/server/event/GlobalEventHandler.java index db85dd75247..3df4cde92ff 100644 --- a/src/main/java/net/minestom/server/event/GlobalEventHandler.java +++ b/src/main/java/net/minestom/server/event/GlobalEventHandler.java @@ -1,12 +1,12 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; /** * Object containing all the global event listeners. */ public final class GlobalEventHandler extends EventNodeImpl { - public GlobalEventHandler(MinecraftServer minecraftServer) { - super(minecraftServer,"global", EventFilter.ALL, null); + public GlobalEventHandler(ServerProcess serverProcess) { + super(serverProcess,"global", EventFilter.ALL, null); } } diff --git a/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java b/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java index 09425ea1943..432af3373f8 100644 --- a/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java +++ b/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.event.server; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.ping.ResponseData; @@ -26,8 +26,8 @@ public class ServerListPingEvent implements CancellableEvent { * * @param type the ping type to respond with */ - public ServerListPingEvent(@NotNull MinecraftServer minecraftServer, @NotNull ServerListPingType type) { - this(minecraftServer, null, type); + public ServerListPingEvent(@NotNull ServerProcess serverProcess, @NotNull ServerListPingType type) { + this(serverProcess, null, type); } /** @@ -36,8 +36,8 @@ public ServerListPingEvent(@NotNull MinecraftServer minecraftServer, @NotNull Se * @param connection the player connection, if the ping type is modern * @param type the ping type to respond with */ - public ServerListPingEvent(@NotNull MinecraftServer minecraftServer, @Nullable PlayerConnection connection, @NotNull ServerListPingType type) { - this.responseData = new ResponseData(minecraftServer); + public ServerListPingEvent(@NotNull ServerProcess serverProcess, @Nullable PlayerConnection connection, @NotNull ServerListPingType type) { + this.responseData = new ResponseData(serverProcess); this.connection = connection; this.type = type; } diff --git a/src/main/java/net/minestom/server/exception/ExceptionManager.java b/src/main/java/net/minestom/server/exception/ExceptionManager.java index 338f0dfb847..52a34b51ce1 100644 --- a/src/main/java/net/minestom/server/exception/ExceptionManager.java +++ b/src/main/java/net/minestom/server/exception/ExceptionManager.java @@ -1,6 +1,6 @@ package net.minestom.server.exception; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import org.jetbrains.annotations.Nullable; /** @@ -9,10 +9,10 @@ public final class ExceptionManager { private ExceptionHandler exceptionHandler; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public ExceptionManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public ExceptionManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } /** @@ -24,7 +24,7 @@ public void handleException(Throwable e) { if (e instanceof OutOfMemoryError) { // OOM should be handled manually e.printStackTrace(); - minecraftServer.stopCleanly(); + serverProcess.stop(); return; } this.getExceptionHandler().handleException(e); diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index 6990fc3a4a0..71d66dd2cb0 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -1,6 +1,6 @@ package net.minestom.server.extras; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.Nullable; @@ -11,12 +11,12 @@ public final class MojangAuth { public final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); private volatile boolean enabled = false; private volatile KeyPair keyPair; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final MojangCrypt mojangCrypt; - public MojangAuth(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.mojangCrypt = new MojangCrypt(minecraftServer); + public MojangAuth(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + this.mojangCrypt = new MojangCrypt(serverProcess); } /** @@ -26,7 +26,7 @@ public MojangAuth(MinecraftServer minecraftServer) { */ public void init() { Check.stateCondition(enabled, "Mojang auth is already enabled!"); - Check.stateCondition(minecraftServer.process().isAlive(), "The server has already been started!"); + Check.stateCondition(serverProcess.isAlive(), "The server has already been started!"); enabled = true; // Generate necessary fields... keyPair = mojangCrypt.generateKeyPair(); diff --git a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java index c9902562a0b..40feb7feaf4 100644 --- a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java +++ b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.lan; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.timer.Task; import net.minestom.server.utils.time.Cooldown; @@ -37,10 +37,10 @@ public class OpenToLAN { private volatile DatagramPacket packet = null; private volatile Task task = null; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public OpenToLAN(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public OpenToLAN(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } /** @@ -70,7 +70,7 @@ public boolean open(@NotNull OpenToLANConfig config) { } eventCooldown = new Cooldown(config.delayBetweenEvent); - task = minecraftServer.process().getSchedulerManager().buildTask(this::ping) + task = serverProcess.getSchedulerManager().buildTask(this::ping) .repeat(config.delayBetweenPings) .schedule(); return true; @@ -104,10 +104,10 @@ public boolean isOpen() { * Performs the ping. */ private void ping() { - if (!minecraftServer.process().getServer().isOpen()) return; + if (!serverProcess.getServer().isOpen()) return; if (packet == null || eventCooldown.isReady(System.currentTimeMillis())) { - final ServerListPingEvent event = new ServerListPingEvent(minecraftServer, OPEN_TO_LAN); - minecraftServer.process().getGlobalEventHandler().call(event); + final ServerListPingEvent event = new ServerListPingEvent(serverProcess, OPEN_TO_LAN); + serverProcess.getGlobalEventHandler().call(event); final byte[] data = OPEN_TO_LAN.getPingResponse(event.getResponseData()).getBytes(StandardCharsets.UTF_8); packet = new DatagramPacket(data, data.length, PING_ADDRESS); diff --git a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java index e9252ba2c0b..44f14a750f3 100644 --- a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java +++ b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.mojangAuth; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,10 +13,10 @@ public final class MojangCrypt { private final Logger LOGGER = LoggerFactory.getLogger(MojangCrypt.class); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public MojangCrypt(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public MojangCrypt(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } public @Nullable KeyPair generateKeyPair() { @@ -25,7 +25,7 @@ public MojangCrypt(MinecraftServer minecraftServer) { keyGen.initialize(1024); return keyGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); LOGGER.error("Key pair generation failed!"); return null; } @@ -35,7 +35,7 @@ public MojangCrypt(MinecraftServer minecraftServer) { try { return digestData("SHA-1", data.getBytes("ISO_8859_1"), secretKey.getEncoded(), publicKey.getEncoded()); } catch (UnsupportedEncodingException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); return null; } } @@ -48,7 +48,7 @@ public MojangCrypt(MinecraftServer minecraftServer) { } return digest.digest(); } catch (NoSuchAlgorithmException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); return null; } } @@ -65,7 +65,7 @@ private byte[] cipherData(int mode, Key key, byte[] data) { try { return setupCipher(mode, key.getAlgorithm(), key).doFinal(data); } catch (IllegalBlockSizeException | BadPaddingException var4) { - minecraftServer.process().getExceptionManager().handleException(var4); + serverProcess.getExceptionManager().handleException(var4); } LOGGER.error("Cipher data failed!"); return null; @@ -77,7 +77,7 @@ private Cipher setupCipher(int mode, String transformation, Key key) { cipher4.init(mode, key); return cipher4; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException var4) { - minecraftServer.process().getExceptionManager().handleException(var4); + serverProcess.getExceptionManager().handleException(var4); } LOGGER.error("Cipher creation failed!"); return null; diff --git a/src/main/java/net/minestom/server/extras/query/Query.java b/src/main/java/net/minestom/server/extras/query/Query.java index cd4d421463d..59f73d4779f 100644 --- a/src/main/java/net/minestom/server/extras/query/Query.java +++ b/src/main/java/net/minestom/server/extras/query/Query.java @@ -3,7 +3,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.extras.query.event.BasicQueryEvent; import net.minestom.server.extras.query.event.FullQueryEvent; @@ -40,12 +39,10 @@ public class Query { private volatile DatagramSocket socket; private volatile Thread thread; private volatile Task task; - private final MinecraftServer minecraftServer; private final ServerProcess serverProcess; - public Query(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); + public Query(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } /** @@ -186,12 +183,12 @@ private void run() { int remaining = data.remaining(); if (remaining == 0) { // basic - BasicQueryEvent event = new BasicQueryEvent(minecraftServer, sender, sessionID); - minecraftServer.process().getGlobalEventHandler().callCancellable(event, () -> + BasicQueryEvent event = new BasicQueryEvent(serverProcess, sender, sessionID); + serverProcess.getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } else if (remaining == 5) { // full - FullQueryEvent event = new FullQueryEvent(minecraftServer, sender, sessionID); - minecraftServer.process().getGlobalEventHandler().callCancellable(event, () -> + FullQueryEvent event = new FullQueryEvent(serverProcess, sender, sessionID); + serverProcess.getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } } diff --git a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java index c0fd8cb172d..216bb12b9ca 100644 --- a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.extras.query.response.BasicQueryResponse; import org.jetbrains.annotations.NotNull; @@ -17,7 +17,7 @@ public class BasicQueryEvent extends QueryEvent { * @param sessionID the session ID * @param sender the sender */ - public BasicQueryEvent(MinecraftServer minecraftServer, @NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new BasicQueryResponse(minecraftServer)); + public BasicQueryEvent(ServerProcess serverProcess, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new BasicQueryResponse(serverProcess)); } } diff --git a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java index 80f82d32264..99c62d6b5dd 100644 --- a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.extras.query.response.FullQueryResponse; import org.jetbrains.annotations.NotNull; @@ -14,11 +14,11 @@ public class FullQueryEvent extends QueryEvent { /** * Creates a new full query event. * - * @param minecraftServer + * @param serverProcess * @param sender the sender * @param sessionID the sessionID */ - public FullQueryEvent(MinecraftServer minecraftServer, @NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new FullQueryResponse(minecraftServer)); + public FullQueryEvent(ServerProcess serverProcess, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new FullQueryResponse(serverProcess)); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java index 1046da512f8..ac4af108663 100644 --- a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.response; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.extras.query.Query; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.Writeable; @@ -13,18 +13,18 @@ */ public class BasicQueryResponse implements Writeable { @NotNull - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private String motd, gametype, map, numPlayers, maxPlayers; /** * Creates a new basic query response with pre-filled default values. */ - public BasicQueryResponse(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public BasicQueryResponse(ServerProcess serverProcess) { + this.serverProcess = serverProcess; this.motd = "A Minestom Server"; this.gametype = "SMP"; this.map = "world"; - this.numPlayers = String.valueOf(minecraftServer.process().getConnectionManager().getOnlinePlayerCount()); + this.numPlayers = String.valueOf(serverProcess.getConnectionManager().getOnlinePlayerCount()); this.maxPlayers = String.valueOf(Integer.parseInt(this.numPlayers) + 1); } @@ -145,7 +145,7 @@ public void write(@NotNull BinaryWriter writer) { writer.writeNullTerminatedString(this.map, Query.CHARSET); writer.writeNullTerminatedString(this.numPlayers, Query.CHARSET); writer.writeNullTerminatedString(this.maxPlayers, Query.CHARSET); - writer.writeShort((short) minecraftServer.process().getServer().getPort()); // TODO little endian? - writer.writeNullTerminatedString(Objects.requireNonNullElse(minecraftServer.process().getServer().getAddress(), ""), Query.CHARSET); + writer.writeShort((short) serverProcess.getServer().getPort()); // TODO little endian? + writer.writeNullTerminatedString(Objects.requireNonNullElse(serverProcess.getServer().getAddress(), ""), Query.CHARSET); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java index ef614a1cb6c..daedf8dc7b8 100644 --- a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java @@ -1,7 +1,7 @@ package net.minestom.server.extras.query.response; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; import net.minestom.server.ServerProcess; import net.minestom.server.extras.query.Query; import net.minestom.server.utils.binary.BinaryWriter; @@ -17,7 +17,6 @@ public class FullQueryResponse implements Writeable { private static final PlainTextComponentSerializer PLAIN = PlainTextComponentSerializer.plainText(); private static final byte[] PADDING_10 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, PADDING_11 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - private final MinecraftServer minecraftServer; private final ServerProcess serverProcess; private Map kv; @@ -26,14 +25,13 @@ public class FullQueryResponse implements Writeable { /** * Creates a new full query response with default values set. */ - public FullQueryResponse(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); + public FullQueryResponse(ServerProcess serverProcess) { + this.serverProcess = serverProcess; this.kv = new HashMap<>(); // populate defaults for (QueryKey key : QueryKey.VALUES) { - this.kv.put(key.getKey(), key.getValue(minecraftServer)); + this.kv.put(key.getKey(), key.getValue(serverProcess)); } this.players = serverProcess.getConnectionManager().getOnlinePlayers() @@ -122,10 +120,10 @@ public void setPlayers(@NotNull List players) { * * @return the string result */ - public static String generatePluginsValue(MinecraftServer minecraftServer) { - StringBuilder builder = new StringBuilder(minecraftServer.getBrandName()) + public static String generatePluginsValue(ServerProcess serverProcess) { + StringBuilder builder = new StringBuilder(serverProcess.getMinecraftServer().getBrandName()) .append(' ') - .append(MinecraftServer.VERSION_NAME); + .append(ServerConsts.VERSION_NAME); return builder.toString(); } diff --git a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java index 6a8d1f093cb..8bb4dc24a2b 100644 --- a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java +++ b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java @@ -1,40 +1,39 @@ package net.minestom.server.extras.query.response; -import net.minestom.server.MinecraftServer; -import net.minestom.server.network.ConnectionState; +import net.minestom.server.ServerConsts; +import net.minestom.server.ServerProcess; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; import java.util.Objects; import java.util.function.Function; -import java.util.function.Supplier; /** * An enum of default query keys. */ public enum QueryKey { - HOSTNAME((minecraftServer) -> "A Minestom Server"), - GAME_TYPE((minecraftServer) -> "SMP"), - GAME_ID("game_id", (minecraftServer) -> "MINECRAFT"), - VERSION((minecraftServer) -> MinecraftServer.VERSION_NAME), + HOSTNAME((serverProcess) -> "A Minestom Server"), + GAME_TYPE((serverProcess) -> "SMP"), + GAME_ID("game_id", (serverProcess) -> "MINECRAFT"), + VERSION((serverProcess) -> ServerConsts.VERSION_NAME), PLUGINS(FullQueryResponse::generatePluginsValue), - MAP((minecraftServer) -> "world"), - NUM_PLAYERS("numplayers", (minecraftServer) -> String.valueOf(minecraftServer.process().getConnectionManager().getOnlinePlayerCount())), - MAX_PLAYERS("maxplayers", (minecraftServer) -> String.valueOf(minecraftServer.process().getConnectionManager().getOnlinePlayerCount() + 1)), - HOST_PORT("hostport", (minecraftServer) -> String.valueOf(minecraftServer.process().getServer().getPort())), - HOST_IP("hostip", (minecraftServer) -> Objects.requireNonNullElse(minecraftServer.process().getServer().getAddress(), "localhost")); + MAP((serverProcess) -> "world"), + NUM_PLAYERS("numplayers", (serverProcess) -> String.valueOf(serverProcess.getConnectionManager().getOnlinePlayerCount())), + MAX_PLAYERS("maxplayers", (serverProcess) -> String.valueOf(serverProcess.getConnectionManager().getOnlinePlayerCount() + 1)), + HOST_PORT("hostport", (serverProcess) -> String.valueOf(serverProcess.getServer().getPort())), + HOST_IP("hostip", (serverProcess) -> Objects.requireNonNullElse(serverProcess.getServer().getAddress(), "localhost")); static QueryKey[] VALUES = QueryKey.values(); private final String key; - private final Function value; + private final Function value; - QueryKey(@NotNull Function value) { + QueryKey(@NotNull Function value) { this(null, value); } - QueryKey(@Nullable String key, @NotNull Function value) { + QueryKey(@Nullable String key, @NotNull Function value) { this.key = Objects.requireNonNullElse(key, this.name().toLowerCase(Locale.ROOT).replace('_', ' ')); this.value = value; } @@ -53,7 +52,7 @@ public enum QueryKey { * * @return the value */ - public @NotNull String getValue(MinecraftServer minecraftServer) { - return this.value.apply(minecraftServer); + public @NotNull String getValue(ServerProcess serverProcess) { + return this.value.apply(serverProcess); } } diff --git a/src/main/java/net/minestom/server/instance/AnvilLoader.java b/src/main/java/net/minestom/server/instance/AnvilLoader.java index 110d5c994a1..40fbb56629e 100644 --- a/src/main/java/net/minestom/server/instance/AnvilLoader.java +++ b/src/main/java/net/minestom/server/instance/AnvilLoader.java @@ -3,7 +3,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.IntIntImmutablePair; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockHandler; @@ -38,7 +37,6 @@ public class AnvilLoader implements IChunkLoader { private static final Biome BIOME = Biome.PLAINS; private final Map alreadyLoaded = new ConcurrentHashMap<>(); - private final MinecraftServer minecraftServer; private final ServerProcess serverProcess; private final Path path; private final Path levelPath; @@ -55,16 +53,15 @@ private static class RegionCache extends ConcurrentHashMap> blockStateId2ObjectCacheTLS = ThreadLocal.withInitial(Int2ObjectArrayMap::new); - public AnvilLoader(@NotNull MinecraftServer minecraftServer, @NotNull Path path) { - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); + public AnvilLoader(@NotNull ServerProcess serverProcess, @NotNull Path path) { + this.serverProcess = serverProcess; this.path = path; this.levelPath = path.resolve("level.dat"); this.regionPath = path.resolve("region"); } - public AnvilLoader(@NotNull MinecraftServer minecraftServer, @NotNull String path) { - this(minecraftServer, Path.of(path)); + public AnvilLoader(@NotNull ServerProcess serverProcess, @NotNull String path) { + this(serverProcess, Path.of(path)); } @Override @@ -482,4 +479,9 @@ public boolean supportsParallelLoading() { public boolean supportsParallelSaving() { return true; } + + @Override + public ServerProcess getServerProcess() { + return serverProcess; + } } diff --git a/src/main/java/net/minestom/server/instance/Chunk.java b/src/main/java/net/minestom/server/instance/Chunk.java index 6d40477eb10..419ddd31629 100644 --- a/src/main/java/net/minestom/server/instance/Chunk.java +++ b/src/main/java/net/minestom/server/instance/Chunk.java @@ -1,5 +1,6 @@ package net.minestom.server.instance; +import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; @@ -315,4 +316,9 @@ public boolean removeViewer(@NotNull Player player) { protected void unload() { this.loaded = false; } + + @Override + public ServerProcess getServerProcess() { + return instance.getServerProcess(); + } } \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java index a718691b16c..6c839c7717d 100644 --- a/src/main/java/net/minestom/server/instance/DynamicChunk.java +++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java @@ -2,7 +2,6 @@ import com.extollit.gaming.ai.path.model.ColumnarOcclusionFieldList; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; @@ -51,15 +50,13 @@ public class DynamicChunk extends Chunk { private long lastChange; final CachedPacket chunkCache; - public final MinecraftServer minecraftServer; public DynamicChunk(@NotNull Instance instance, int chunkX, int chunkZ) { super(instance, chunkX, chunkZ, true); - this.minecraftServer = instance.minecraftServer; var sectionsTemp = new Section[maxSection - minSection]; - Arrays.setAll(sectionsTemp, value -> new Section(minecraftServer)); + Arrays.setAll(sectionsTemp, value -> new Section(getServerProcess())); this.sections = List.of(sectionsTemp); - chunkCache = new CachedPacket(minecraftServer, this::createChunkPacket); + chunkCache = new CachedPacket(getServerProcess(), this::createChunkPacket); } @Override @@ -183,7 +180,7 @@ public void tick(long time) { final Section section = getSectionAt(y); final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return minecraftServer.process().getBiomeManager().getById(id); + return getServerProcess().getBiomeManager().getById(id); } @Override @@ -316,7 +313,7 @@ protected LightData createLightData(boolean sendLater) { clonedSections[i] = sections.get(i).clone(); var entities = instance.getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES); final int[] entityIds = ArrayUtils.mapToIntArray(entities, Entity::getEntityId); - return new SnapshotImpl.Chunk(minecraftServer, minSection, chunkX, chunkZ, + return new SnapshotImpl.Chunk(getServerProcess(), minSection, chunkX, chunkZ, clonedSections, entries.clone(), entityIds, updater.reference(instance), tagHandler().readableCopy()); } @@ -367,9 +364,4 @@ private static long[] encodeBlocks(int[] blocks, int bitsPerEntry) { return data; } - - @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; - } } diff --git a/src/main/java/net/minestom/server/instance/EntityTracker.java b/src/main/java/net/minestom/server/instance/EntityTracker.java index 445b8e8724f..9b9275ec93f 100644 --- a/src/main/java/net/minestom/server/instance/EntityTracker.java +++ b/src/main/java/net/minestom/server/instance/EntityTracker.java @@ -1,6 +1,7 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerObject; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Entity; @@ -23,9 +24,9 @@ * Implementations are expected to be thread-safe. */ @ApiStatus.Experimental -public sealed interface EntityTracker permits EntityTrackerImpl { - static @NotNull EntityTracker newTracker(MinecraftServer minecraftServer) { - return new EntityTrackerImpl(minecraftServer); +public sealed interface EntityTracker extends ServerObject permits EntityTrackerImpl { + static @NotNull EntityTracker newTracker(ServerProcess serverProcess) { + return new EntityTrackerImpl(serverProcess); } /** diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index 98492b80b1c..a18ab70c6f5 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -1,7 +1,7 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -28,7 +28,7 @@ final class EntityTrackerImpl implements EntityTracker { - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; static final AtomicInteger TARGET_COUNTER = new AtomicInteger(); // Store all data associated to a Target @@ -36,8 +36,8 @@ final class EntityTrackerImpl implements EntityTracker { final TargetEntry[] entries = EntityTracker.Target.TARGETS.stream().map((Function, TargetEntry>) TargetEntry::new).toArray(TargetEntry[]::new); private final Int2ObjectSyncMap entityPositions = Int2ObjectSyncMap.hashmap(); - EntityTrackerImpl(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + EntityTrackerImpl(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } @Override @@ -54,7 +54,7 @@ public void register(@NotNull Entity entity, @NotNull Point p } if (update != null) { update.referenceUpdate(point, this); - nearbyEntitiesByChunkRange(point, minecraftServer.getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverProcess.getMinecraftServer().getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.add(newEntity); }); @@ -75,7 +75,7 @@ public void unregister(@NotNull Entity entity, } if (update != null) { update.referenceUpdate(point, null); - nearbyEntitiesByChunkRange(point, minecraftServer.getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverProcess.getMinecraftServer().getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.remove(newEntity); }); @@ -187,7 +187,7 @@ private void difference(Point oldPoint, Point newPoint, @NotNull Target target, @NotNull Update update) { final TargetEntry entry = entries[target.ordinal()]; forDifferingChunksInRange(newPoint.chunkX(), newPoint.chunkZ(), oldPoint.chunkX(), oldPoint.chunkZ(), - minecraftServer.getEntityViewDistance(), (chunkX, chunkZ) -> { + serverProcess.getMinecraftServer().getEntityViewDistance(), (chunkX, chunkZ) -> { // Add final List entities = entry.chunkEntities.get(getChunkIndex(chunkX, chunkZ)); if (entities == null || entities.isEmpty()) return; @@ -200,6 +200,11 @@ private void difference(Point oldPoint, Point newPoint, }); } + @Override + public ServerProcess getServerProcess() { + return serverProcess; + } + record ChunkViewKey(List sharedInstances, int chunkX, int chunkZ) { @Override public boolean equals(Object obj) { @@ -281,13 +286,13 @@ private Collection references() { } private void collectPlayers(EntityTracker tracker, Int2ObjectOpenHashMap map) { - tracker.nearbyEntitiesByChunkRange(point, minecraftServer.getChunkViewDistance(), + tracker.nearbyEntitiesByChunkRange(point, serverProcess.getMinecraftServer().getChunkViewDistance(), EntityTracker.Target.PLAYERS, (player) -> map.putIfAbsent(player.getEntityId(), player)); } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } final class SetImpl extends AbstractSet { diff --git a/src/main/java/net/minestom/server/instance/Explosion.java b/src/main/java/net/minestom/server/instance/Explosion.java index 4c179791c19..f1cbc9bc120 100644 --- a/src/main/java/net/minestom/server/instance/Explosion.java +++ b/src/main/java/net/minestom/server/instance/Explosion.java @@ -73,7 +73,7 @@ public void apply(@NotNull Instance instance) { ExplosionPacket packet = new ExplosionPacket(centerX, centerY, centerZ, strength, records, 0, 0, 0); postExplosion(instance, blocks, packet); - PacketUtils.sendGroupedPacket(instance.getMinecraftServer(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getServerProcess(), instance.getPlayers(), packet); postSend(instance, blocks); } diff --git a/src/main/java/net/minestom/server/instance/GeneratorImpl.java b/src/main/java/net/minestom/server/instance/GeneratorImpl.java index 7a6b495a74d..d0aa5b5f56c 100644 --- a/src/main/java/net/minestom/server/instance/GeneratorImpl.java +++ b/src/main/java/net/minestom/server/instance/GeneratorImpl.java @@ -2,7 +2,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -23,25 +23,25 @@ final class GeneratorImpl { private static final Vec SECTION_SIZE = new Vec(16); - static GenerationUnit section(MinecraftServer minecraftServer, Section section, int sectionX, int sectionY, int sectionZ, + static GenerationUnit section(ServerProcess serverProcess, Section section, int sectionX, int sectionY, int sectionZ, boolean fork) { final Vec start = SECTION_SIZE.mul(sectionX, sectionY, sectionZ); final Vec end = start.add(SECTION_SIZE); final UnitModifier modifier = new SectionModifierImpl(SECTION_SIZE, start, end, section.blockPalette(), section.biomePalette(), new Int2ObjectOpenHashMap<>(0), fork); - return unit(minecraftServer, modifier, start, end, null); + return unit(serverProcess, modifier, start, end, null); } - static GenerationUnit section(MinecraftServer minecraftServer, Section section, int sectionX, int sectionY, int sectionZ) { - return section(minecraftServer, section, sectionX, sectionY, sectionZ, false); + static GenerationUnit section(ServerProcess serverProcess, Section section, int sectionX, int sectionY, int sectionZ) { + return section(serverProcess, section, sectionX, sectionY, sectionZ, false); } - static UnitImpl chunk(Chunk chunk, int minSection, int maxSection, + static UnitImpl chunk(ServerProcess serverProcess, Chunk chunk, int minSection, int maxSection, List

    chunkSections, int chunkX, int chunkZ) { final int minY = minSection * 16; AtomicInteger sectionCounterY = new AtomicInteger(minSection); List sections = chunkSections.stream() - .map(section -> section(chunk.instance.minecraftServer, section, chunkX, sectionCounterY.getAndIncrement(), chunkZ)) + .map(section -> section(serverProcess, section, chunkX, sectionCounterY.getAndIncrement(), chunkZ)) .toList(); final Vec size = new Vec(16, (maxSection - minSection) * 16, 16); @@ -49,19 +49,19 @@ static UnitImpl chunk(Chunk chunk, int minSection, int maxSection, final Vec end = new Vec(chunkX * 16 + 16, size.y() + minY, chunkZ * 16 + 16); final UnitModifier modifier = new AreaModifierImpl(chunk, size, start, end, 1, sections.size(), 1, sections); - return unit(chunk.instance.minecraftServer, modifier, start, end, sections); + return unit(serverProcess, modifier, start, end, sections); } - static UnitImpl chunk(int minSection, int maxSection, + static UnitImpl chunk(ServerProcess serverProcess, int minSection, int maxSection, List
    chunkSections, int chunkX, int chunkZ) { - return chunk(null, minSection, maxSection, chunkSections, chunkX, chunkZ); + return chunk(serverProcess, null, minSection, maxSection, chunkSections, chunkX, chunkZ); } static UnitImpl chunk(Chunk chunk) { - return chunk(chunk, chunk.minSection, chunk.maxSection, chunk.getSections(), chunk.getChunkX(), chunk.getChunkZ()); + return chunk(chunk.getServerProcess(), chunk, chunk.minSection, chunk.maxSection, chunk.getSections(), chunk.getChunkX(), chunk.getChunkZ()); } - static UnitImpl unit(MinecraftServer minecraftServer, UnitModifier modifier, Point start, Point end, + static UnitImpl unit(ServerProcess serverProcess, UnitModifier modifier, Point start, Point end, List divided) { if (start.x() > end.x() || start.y() > end.y() || start.z() > end.z()) { throw new IllegalArgumentException("absoluteStart must be before absoluteEnd"); @@ -73,7 +73,7 @@ static UnitImpl unit(MinecraftServer minecraftServer, UnitModifier modifier, Poi throw new IllegalArgumentException("absoluteEnd must be a multiple of 16"); } final Point size = end.sub(start); - return new UnitImpl(minecraftServer, modifier, size, start, end, divided, new CopyOnWriteArrayList<>()); + return new UnitImpl(serverProcess, modifier, size, start, end, divided, new CopyOnWriteArrayList<>()); } static final class DynamicFork implements Block.Setter { @@ -81,10 +81,10 @@ static final class DynamicFork implements Block.Setter { int width, height, depth; List sections; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - DynamicFork(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + DynamicFork(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } @Override @@ -107,7 +107,7 @@ private void resize(int x, int y, int z) { this.width = 1; this.height = 1; this.depth = 1; - this.sections = List.of(section(minecraftServer, new Section(minecraftServer), sectionX, sectionY, sectionZ, true)); + this.sections = List.of(section(serverProcess, new Section(serverProcess), sectionX, sectionY, sectionZ, true)); } else if (x < minSection.x() || y < minSection.y() || z < minSection.z() || x >= minSection.x() + width * 16 || y >= minSection.y() + height * 16 || z >= minSection.z() + depth * 16) { // Resize necessary @@ -141,7 +141,7 @@ private void resize(int x, int y, int z) { final int newX = coordinates.blockX() + startX; final int newY = coordinates.blockY() + startY; final int newZ = coordinates.blockZ() + startZ; - final GenerationUnit unit = section(minecraftServer, new Section(minecraftServer), newX, newY, newZ, true); + final GenerationUnit unit = section(serverProcess, new Section(serverProcess), newX, newY, newZ, true); newSections[i] = unit; } } @@ -154,7 +154,7 @@ private void resize(int x, int y, int z) { } } - record UnitImpl(MinecraftServer minecraftServer, UnitModifier modifier, Point size, + record UnitImpl(ServerProcess serverProcess, UnitModifier modifier, Point size, Point absoluteStart, Point absoluteEnd, List divided, List forks) implements GenerationUnit { @@ -177,7 +177,7 @@ record UnitImpl(MinecraftServer minecraftServer, UnitModifier modifier, Point si for (int sectionX = minSectionX; sectionX < maxSectionX; sectionX++) { for (int sectionY = minSectionY; sectionY < maxSectionY; sectionY++) { for (int sectionZ = minSectionZ; sectionZ < maxSectionZ; sectionZ++) { - final GenerationUnit unit = section(minecraftServer, new Section(minecraftServer), sectionX, sectionY, sectionZ, true); + final GenerationUnit unit = section(serverProcess, new Section(serverProcess), sectionX, sectionY, sectionZ, true); units[index++] = unit; } } @@ -189,7 +189,7 @@ record UnitImpl(MinecraftServer minecraftServer, UnitModifier modifier, Point si @Override public void fork(@NotNull Consumer consumer) { - DynamicFork dynamicFork = new DynamicFork(minecraftServer); + DynamicFork dynamicFork = new DynamicFork(serverProcess); consumer.accept(dynamicFork); final Point startSection = dynamicFork.minSection; if (startSection == null) @@ -212,7 +212,7 @@ private GenerationUnit registerFork(Point start, List sections, final Point size = end.sub(start); final AreaModifierImpl modifier = new AreaModifierImpl(null, size, start, end, width, height, depth, sections); - final UnitImpl fork = new UnitImpl(minecraftServer, modifier, size, start, end, sections, forks); + final UnitImpl fork = new UnitImpl(serverProcess, modifier, size, start, end, sections, forks); forks.add(fork); return fork; } diff --git a/src/main/java/net/minestom/server/instance/IChunkLoader.java b/src/main/java/net/minestom/server/instance/IChunkLoader.java index 4fa5e3d17f9..c02250ab139 100644 --- a/src/main/java/net/minestom/server/instance/IChunkLoader.java +++ b/src/main/java/net/minestom/server/instance/IChunkLoader.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerObject; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -16,7 +16,7 @@ *

    * See {@link AnvilLoader} for the default implementation used in {@link InstanceContainer}. */ -public interface IChunkLoader { +public interface IChunkLoader extends ServerObject { /** * Loads instance data from the loader. @@ -58,7 +58,7 @@ default void loadInstance(@NotNull Instance instance) { * @return a {@link CompletableFuture} executed when the {@link Chunk} is done saving, * should be called even if the saving failed (you can throw an exception). */ - default @NotNull CompletableFuture saveChunks(MinecraftServer minecraftServer, @NotNull Collection chunks) { + default @NotNull CompletableFuture saveChunks(@NotNull Collection chunks) { if (supportsParallelSaving()) { ExecutorService parallelSavingThreadPool = ForkJoinPool.commonPool(); chunks.forEach(c -> parallelSavingThreadPool.execute(() -> saveChunk(c))); @@ -66,7 +66,7 @@ default void loadInstance(@NotNull Instance instance) { parallelSavingThreadPool.shutdown(); parallelSavingThreadPool.awaitTermination(1L, java.util.concurrent.TimeUnit.DAYS); } catch (InterruptedException e) { - minecraftServer.process().getExceptionManager().handleException(e); + getServerProcess().getExceptionManager().handleException(e); } return AsyncUtils.VOID_FUTURE; } else { diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index e8464845b1c..466684f5d6a 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -3,8 +3,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArraySet; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointers; -import net.minestom.server.MinecraftServer; -import net.minestom.server.MinecraftServerObject; +import net.minestom.server.ServerObject; import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.adventure.audience.PacketGroupingAudience; @@ -65,9 +64,9 @@ * you need to be sure to signal the {@link ThreadDispatcher} of every partition/element changes. */ public abstract class Instance implements Block.Getter, Block.Setter, - Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience, MinecraftServerObject { + Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience, ServerObject { - public final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private boolean registered; private final DimensionType dimensionType; @@ -114,8 +113,8 @@ public abstract class Instance implements Block.Getter, Block.Setter, * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(minecraftServer, uniqueId, dimensionType, dimensionType.getName()); + public Instance(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(serverProcess, uniqueId, dimensionType, dimensionType.getName()); } /** @@ -124,10 +123,10 @@ public Instance(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + public Instance(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { Check.argCondition(!dimensionType.isRegistered(), "The dimension " + dimensionType.getName() + " is not registered! Please use DimensionTypeManager#addDimension"); - this.minecraftServer = minecraftServer; + this.serverProcess = serverProcess; this.uniqueId = uniqueId; this.dimensionType = dimensionType; this.dimensionName = dimensionName.asString(); @@ -138,14 +137,13 @@ public Instance(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId .withDynamic(Identity.UUID, this::getUniqueId) .build(); - final ServerProcess process = minecraftServer.process(); - if (process != null) { - this.eventNode = process.getGlobalEventHandler().map(this, EventFilter.INSTANCE); + if (serverProcess != null) { + this.eventNode = serverProcess.getGlobalEventHandler().map(this, EventFilter.INSTANCE); } else { // Local nodes require a server process this.eventNode = null; } - entityTracker = new EntityTrackerImpl(minecraftServer); + entityTracker = new EntityTrackerImpl(serverProcess); } /** @@ -451,7 +449,7 @@ public long getTime() { */ public void setTime(long time) { this.time = time; - PacketUtils.sendGroupedPacket(minecraftServer, getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverProcess, getPlayers(), createTimePacket()); } /** @@ -666,7 +664,7 @@ public void tick(long time) { this.time += timeRate; // time needs to be sent to players if (timeUpdate != null && !Cooldown.hasCooldown(time, lastTimeUpdate, timeUpdate)) { - PacketUtils.sendGroupedPacket(minecraftServer, getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverProcess, getPlayers(), createTimePacket()); this.lastTimeUpdate = time; } @@ -674,7 +672,7 @@ public void tick(long time) { // Tick event { // Process tick events - minecraftServer.process().getGlobalEventHandler().call(new InstanceTickEvent(this, time, lastTickAge)); + serverProcess.getGlobalEventHandler().call(new InstanceTickEvent(this, time, lastTickAge)); // Set last tick age this.lastTickAge = time; } @@ -701,7 +699,7 @@ public void tick(long time) { public @NotNull InstanceSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) { final Map> chunksMap = updater.referencesMapLong(getChunks(), ChunkUtils::getChunkIndex); final int[] entities = ArrayUtils.mapToIntArray(entityTracker.entities(), Entity::getEntityId); - return new SnapshotImpl.Instance(updater.reference(minecraftServer.process()), + return new SnapshotImpl.Instance(updater.reference(serverProcess), getDimensionType(), getWorldAge(), getTime(), chunksMap, entities, tagHandler.readableCopy()); } @@ -774,7 +772,7 @@ public void setExplosionSupplier(@Nullable ExplosionSupplier supplier) { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index 50352a96e4e..be4c6f52e36 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -1,7 +1,6 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -53,9 +52,6 @@ public class InstanceContainer extends Instance { private static final Logger LOGGER = LoggerFactory.getLogger(InstanceContainer.class); - public final MinecraftServer minecraftServer; - private final ServerProcess serverProcess; - private static final BlockFace[] BLOCK_UPDATE_FACES = new BlockFace[]{ BlockFace.WEST, BlockFace.EAST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.BOTTOM, BlockFace.TOP }; @@ -86,27 +82,25 @@ public class InstanceContainer extends Instance { protected InstanceContainer srcInstance; // only present if this instance has been created using a copy private long lastBlockChangeTime; // Time at which the last block change happened (#setBlock) - public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(minecraftServer, uniqueId, dimensionType, null, dimensionType.getName()); + public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(serverProcess, uniqueId, dimensionType, null, dimensionType.getName()); } - public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { - this(minecraftServer, uniqueId, dimensionType, null, dimensionName); + public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + this(serverProcess, uniqueId, dimensionType, null, dimensionName); } @ApiStatus.Experimental - public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - this(minecraftServer, uniqueId, dimensionType, loader, dimensionType.getName()); + public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + this(serverProcess, uniqueId, dimensionType, loader, dimensionType.getName()); } @ApiStatus.Experimental - public InstanceContainer(@NotNull MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { - super(minecraftServer, uniqueId, dimensionType, dimensionName); + public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { + super(serverProcess, uniqueId, dimensionType, dimensionName); setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(instance, chunkX, chunkZ)); - setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(minecraftServer, "world"))); + setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(getServerProcess(), "world"))); this.chunkLoader.loadInstance(this); - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); } @Override @@ -152,7 +146,7 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in this.currentlyChangingBlocks.put(blockPosition, block); // Change id based on neighbors - final BlockPlacementRule blockPlacementRule = serverProcess.getBlockManager().getBlockPlacementRule(block); + final BlockPlacementRule blockPlacementRule = getServerProcess().getBlockManager().getBlockPlacementRule(block); if (placement != null && blockPlacementRule != null && doBlockUpdates) { BlockPlacementRule.PlacementState rulePlacement; if (placement instanceof BlockHandler.PlayerPlacement pp) { @@ -222,7 +216,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, return false; } PlayerBlockBreakEvent blockBreakEvent = new PlayerBlockBreakEvent(player, block, Block.AIR, blockPosition, blockFace); - minecraftServer.process().getGlobalEventHandler().call(blockBreakEvent); + getServerProcess().getGlobalEventHandler().call(blockBreakEvent); final boolean allowed = !blockBreakEvent.isCancelled(); if (allowed) { // Break or change the broken block based on event result @@ -230,7 +224,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, UNSAFE_setBlock(chunk, x, y, z, resultBlock, null, new BlockHandler.PlayerDestroy(block, this, blockPosition, player), doBlockUpdates, 0); // Send the block break effect packet - PacketUtils.sendGroupedPacket(minecraftServer, chunk.getViewers(), + PacketUtils.sendGroupedPacket(getServerProcess(), chunk.getViewers(), new EffectPacket(2001 /*Block break + block break sound*/, blockPosition, block.stateId(), false), // Prevent the block breaker to play the particles and sound two times (viewer) -> !viewer.equals(player)); @@ -254,7 +248,7 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { final int chunkX = chunk.getChunkX(); final int chunkZ = chunk.getChunkZ(); chunk.sendPacketToViewers(new UnloadChunkPacket(chunkX, chunkZ)); - minecraftServer.process().getGlobalEventHandler().call(new InstanceChunkUnloadEvent(this, chunk)); + getServerProcess().getGlobalEventHandler().call(new InstanceChunkUnloadEvent(this, chunk)); // Remove all entities in chunk getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES).forEach(Entity::remove); // Clear cache @@ -263,7 +257,7 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { if (chunkLoader != null) { chunkLoader.unloadChunk(chunk); } - var dispatcher = serverProcess.dispatcher(); + var dispatcher = getServerProcess().dispatcher(); dispatcher.deletePartition(chunk); } @@ -284,7 +278,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { @Override public @NotNull CompletableFuture saveChunksToStorage() { - return chunkLoader.saveChunks(minecraftServer, getChunks()); + return chunkLoader.saveChunks(getChunks()); } protected @NotNull CompletableFuture<@NotNull Chunk> retrieveChunk(int chunkX, int chunkZ) { @@ -309,13 +303,13 @@ public Chunk getChunk(int chunkX, int chunkZ) { cacheChunk(chunk); chunk.onLoad(); - minecraftServer.process().getGlobalEventHandler().call(new InstanceChunkLoadEvent(this, chunk)); + getServerProcess().getGlobalEventHandler().call(new InstanceChunkLoadEvent(this, chunk)); final CompletableFuture future = this.loadingChunks.remove(index); assert future == completableFuture : "Invalid future: " + future; completableFuture.complete(chunk); }) .exceptionally(throwable -> { - serverProcess.getExceptionManager().handleException(throwable); + getServerProcess().getExceptionManager().handleException(throwable); return null; }); if (loader.supportsParallelLoading()) { @@ -381,7 +375,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { // Apply awaiting forks processFork(chunk); } catch (Throwable e) { - serverProcess.getExceptionManager().handleException(e); + getServerProcess().getExceptionManager().handleException(e); } finally { // End generation refreshLastBlockChangeTime(); @@ -516,7 +510,7 @@ protected void addSharedInstance(SharedInstance sharedInstance) { * @see #getSrcInstance() to retrieve the "creation source" of the copied instance */ public synchronized InstanceContainer copy() { - InstanceContainer copiedInstance = new InstanceContainer(minecraftServer, UUID.randomUUID(), getDimensionType()); + InstanceContainer copiedInstance = new InstanceContainer(getServerProcess(), UUID.randomUUID(), getDimensionType()); copiedInstance.srcInstance = this; copiedInstance.tagHandler = this.tagHandler.copy(); copiedInstance.lastBlockChangeTime = this.lastBlockChangeTime; @@ -640,7 +634,7 @@ private void executeNeighboursBlockPlacementRule(@NotNull Point blockPosition, i final Block neighborBlock = cache.getBlock(neighborX, neighborY, neighborZ, Condition.TYPE); if (neighborBlock == null) continue; - final BlockPlacementRule neighborBlockPlacementRule = serverProcess.getBlockManager().getBlockPlacementRule(neighborBlock); + final BlockPlacementRule neighborBlockPlacementRule = getServerProcess().getBlockManager().getBlockPlacementRule(neighborBlock); if (neighborBlockPlacementRule == null || updateDistance >= neighborBlockPlacementRule.maxUpdateDistance()) continue; final Vec neighborPosition = new Vec(neighborX, neighborY, neighborZ); @@ -670,7 +664,7 @@ private CompletableFuture loadOrRetrieve(int chunkX, int chunkZ, Supplier private void cacheChunk(@NotNull Chunk chunk) { this.chunks.put(getChunkIndex(chunk), chunk); - var dispatcher = serverProcess.dispatcher(); + var dispatcher = getServerProcess().dispatcher(); dispatcher.createPartition(chunk); } } diff --git a/src/main/java/net/minestom/server/instance/InstanceManager.java b/src/main/java/net/minestom/server/instance/InstanceManager.java index beed2d7b751..fb2dac3c1bf 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManager.java +++ b/src/main/java/net/minestom/server/instance/InstanceManager.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.event.instance.InstanceRegisterEvent; import net.minestom.server.event.instance.InstanceUnregisterEvent; import net.minestom.server.utils.validate.Check; @@ -19,12 +19,12 @@ * Used to register {@link Instance}. */ public final class InstanceManager { - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final Set instances = new CopyOnWriteArraySet<>(); - public InstanceManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public InstanceManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } /** @@ -50,7 +50,7 @@ public void registerInstance(@NotNull Instance instance) { */ @ApiStatus.Experimental public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - final InstanceContainer instanceContainer = new InstanceContainer(minecraftServer, UUID.randomUUID(), dimensionType, loader); + final InstanceContainer instanceContainer = new InstanceContainer(serverProcess, UUID.randomUUID(), dimensionType, loader); registerInstance(instanceContainer); return instanceContainer; } @@ -102,7 +102,7 @@ public void registerInstance(@NotNull Instance instance) { Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); - final SharedInstance sharedInstance = new SharedInstance(instanceContainer.minecraftServer, UUID.randomUUID(), instanceContainer); + final SharedInstance sharedInstance = new SharedInstance(serverProcess, UUID.randomUUID(), instanceContainer); return registerSharedInstance(sharedInstance); } @@ -117,12 +117,12 @@ public void unregisterInstance(@NotNull Instance instance) { Check.stateCondition(!instance.getPlayers().isEmpty(), "You cannot unregister an instance with players inside."); synchronized (instance) { InstanceUnregisterEvent event = new InstanceUnregisterEvent(instance); - minecraftServer.process().getGlobalEventHandler().call(event); + serverProcess.getGlobalEventHandler().call(event); // Unload all chunks if (instance instanceof InstanceContainer) { instance.getChunks().forEach(instance::unloadChunk); - var dispatcher = minecraftServer.process().dispatcher(); + var dispatcher = serverProcess.dispatcher(); instance.getChunks().forEach(dispatcher::deletePartition); } // Unregister @@ -164,9 +164,9 @@ public void unregisterInstance(@NotNull Instance instance) { private void UNSAFE_registerInstance(@NotNull Instance instance) { instance.setRegistered(true); this.instances.add(instance); - var dispatcher = minecraftServer.process().dispatcher(); + var dispatcher = serverProcess.dispatcher(); instance.getChunks().forEach(dispatcher::createPartition); InstanceRegisterEvent event = new InstanceRegisterEvent(instance); - minecraftServer.process().getGlobalEventHandler().call(event); + serverProcess.getGlobalEventHandler().call(event); } } diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index b1242d6b7bb..b2602af36eb 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -37,7 +37,7 @@ public class LightingChunk extends DynamicChunk { private static final ExecutorService pool = Executors.newWorkStealingPool(); private int[] heightmap; - final CachedPacket lightCache = new CachedPacket(minecraftServer, this::createLightPacket); + final CachedPacket lightCache = new CachedPacket(getServerProcess(), this::createLightPacket); boolean sendNeighbours = true; boolean chunkLoaded = false; @@ -256,7 +256,7 @@ static void updateAfterGeneration(LightingChunk chunk) { return; } - sendingTask = chunk.minecraftServer.process().getSchedulerManager().scheduleTask(() -> { + sendingTask = chunk.getServerProcess().getSchedulerManager().scheduleTask(() -> { queueLock.lock(); var copy = new ArrayList<>(sendQueue); sendQueue.clear(); diff --git a/src/main/java/net/minestom/server/instance/Section.java b/src/main/java/net/minestom/server/instance/Section.java index 4789cb07224..38a28c4dba7 100644 --- a/src/main/java/net/minestom/server/instance/Section.java +++ b/src/main/java/net/minestom/server/instance/Section.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.instance.light.Light; import net.minestom.server.instance.palette.Palette; import net.minestom.server.network.NetworkBuffer; @@ -28,8 +28,8 @@ private Section(Palette blockPalette, Palette biomePalette, Light skyLight, Ligh this.blockLight = blockLight; } - public Section(MinecraftServer minecraftServer) { - this(Palette.blocks(minecraftServer), Palette.biomes(minecraftServer)); + public Section(ServerProcess serverProcess) { + this(Palette.blocks(serverProcess), Palette.biomes(serverProcess)); } public Palette blockPalette() { diff --git a/src/main/java/net/minestom/server/instance/SharedInstance.java b/src/main/java/net/minestom/server/instance/SharedInstance.java index 6f02c94f7d0..b973f936e79 100644 --- a/src/main/java/net/minestom/server/instance/SharedInstance.java +++ b/src/main/java/net/minestom/server/instance/SharedInstance.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; import net.minestom.server.instance.block.Block; @@ -22,8 +22,8 @@ public class SharedInstance extends Instance { private final InstanceContainer instanceContainer; - public SharedInstance(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { - super(minecraftServer, uniqueId, instanceContainer.getDimensionType()); + public SharedInstance(ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { + super(serverProcess, uniqueId, instanceContainer.getDimensionType()); this.instanceContainer = instanceContainer; } diff --git a/src/main/java/net/minestom/server/instance/WorldBorder.java b/src/main/java/net/minestom/server/instance/WorldBorder.java index 595adb4dac4..49f71159ddf 100644 --- a/src/main/java/net/minestom/server/instance/WorldBorder.java +++ b/src/main/java/net/minestom/server/instance/WorldBorder.java @@ -254,7 +254,7 @@ private void refreshCenter() { } private void sendPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(instance.getMinecraftServer(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getServerProcess(), instance.getPlayers(), packet); } public enum CollisionAxis { diff --git a/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java b/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java index e34dda78703..1133e5aaee4 100644 --- a/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java @@ -2,7 +2,7 @@ import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.MathUtils; import org.jetbrains.annotations.NotNull; @@ -14,11 +14,11 @@ */ final class AdaptivePalette implements Palette, Cloneable { final byte dimension, defaultBitsPerEntry, maxBitsPerEntry; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; SpecializedPalette palette; - AdaptivePalette(MinecraftServer minecraftServer, byte dimension, byte maxBitsPerEntry, byte bitsPerEntry) { - this.minecraftServer = minecraftServer; + AdaptivePalette(ServerProcess serverProcess, byte dimension, byte maxBitsPerEntry, byte bitsPerEntry) { + this.serverProcess = serverProcess; validateDimension(dimension); this.dimension = dimension; this.maxBitsPerEntry = maxBitsPerEntry; @@ -59,7 +59,7 @@ public void fill(int value) { @Override public void setAll(@NotNull EntrySupplier supplier) { - SpecializedPalette newPalette = new FlexiblePalette(minecraftServer, this); + SpecializedPalette newPalette = new FlexiblePalette(serverProcess, this); newPalette.setAll(supplier); this.palette = newPalette; } @@ -142,7 +142,7 @@ SpecializedPalette optimizedPalette() { Palette flexiblePalette() { SpecializedPalette currentPalette = this.palette; if (currentPalette instanceof FilledPalette filledPalette) { - currentPalette = new FlexiblePalette(minecraftServer, this); + currentPalette = new FlexiblePalette(serverProcess, this); currentPalette.fill(filledPalette.value()); this.palette = currentPalette; } diff --git a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java index c9fa96849af..0079666b5e1 100644 --- a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java @@ -2,7 +2,7 @@ import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.MathUtils; import org.jetbrains.annotations.NotNull; @@ -19,7 +19,7 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { private static final ThreadLocal WRITE_CACHE = ThreadLocal.withInitial(() -> new int[4096]); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; // Specific to this palette type private final AdaptivePalette adaptivePalette; private byte bitsPerEntry; @@ -31,8 +31,8 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { // value = palette index private Int2IntOpenHashMap valueToPaletteMap; - FlexiblePalette(MinecraftServer minecraftServer, AdaptivePalette adaptivePalette, byte bitsPerEntry) { - this.minecraftServer = minecraftServer; + FlexiblePalette(ServerProcess serverProcess, AdaptivePalette adaptivePalette, byte bitsPerEntry) { + this.serverProcess = serverProcess; this.adaptivePalette = adaptivePalette; this.bitsPerEntry = bitsPerEntry; @@ -47,8 +47,8 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { this.values = new long[(maxSize() + valuesPerLong - 1) / valuesPerLong]; } - FlexiblePalette(MinecraftServer minecraftServer, AdaptivePalette adaptivePalette) { - this(minecraftServer, adaptivePalette, adaptivePalette.defaultBitsPerEntry); + FlexiblePalette(ServerProcess serverProcess, AdaptivePalette adaptivePalette) { + this(serverProcess, adaptivePalette, adaptivePalette.defaultBitsPerEntry); } @Override @@ -205,7 +205,7 @@ public int dimension() { palette.count = count; return palette; } catch (CloneNotSupportedException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); throw new IllegalStateException("Weird thing happened"); } } @@ -270,7 +270,7 @@ private void updateAll(int[] paletteValues) { void resize(byte newBitsPerEntry) { newBitsPerEntry = newBitsPerEntry > maxBitsPerEntry() ? 15 : newBitsPerEntry; - FlexiblePalette palette = new FlexiblePalette(minecraftServer, adaptivePalette, newBitsPerEntry); + FlexiblePalette palette = new FlexiblePalette(serverProcess, adaptivePalette, newBitsPerEntry); palette.paletteToValueList = paletteToValueList; palette.valueToPaletteMap = valueToPaletteMap; getAll(palette::set); diff --git a/src/main/java/net/minestom/server/instance/palette/Palette.java b/src/main/java/net/minestom/server/instance/palette/Palette.java index 359a570b418..4cc50cf9644 100644 --- a/src/main/java/net/minestom/server/instance/palette/Palette.java +++ b/src/main/java/net/minestom/server/instance/palette/Palette.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.palette; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.NetworkBuffer; import org.jetbrains.annotations.NotNull; @@ -12,16 +12,16 @@ * 0 is the default value. */ public interface Palette extends NetworkBuffer.Writer { - static Palette blocks(MinecraftServer minecraftServer) { - return newPalette(minecraftServer, 16, 8, 4); + static Palette blocks(ServerProcess serverProcess) { + return newPalette(serverProcess, 16, 8, 4); } - static Palette biomes(MinecraftServer minecraftServer) { - return newPalette(minecraftServer, 4, 3, 1); + static Palette biomes(ServerProcess serverProcess) { + return newPalette(serverProcess, 4, 3, 1); } - static Palette newPalette(MinecraftServer minecraftServer, int dimension, int maxBitsPerEntry, int bitsPerEntry) { - return new AdaptivePalette(minecraftServer, (byte) dimension, (byte) maxBitsPerEntry, (byte) bitsPerEntry); + static Palette newPalette(ServerProcess serverProcess, int dimension, int maxBitsPerEntry, int bitsPerEntry) { + return new AdaptivePalette(serverProcess, (byte) dimension, (byte) maxBitsPerEntry, (byte) bitsPerEntry); } int get(int x, int y, int z); diff --git a/src/main/java/net/minestom/server/inventory/AbstractInventory.java b/src/main/java/net/minestom/server/inventory/AbstractInventory.java index 4957d2953a1..12f70d9dee6 100644 --- a/src/main/java/net/minestom/server/inventory/AbstractInventory.java +++ b/src/main/java/net/minestom/server/inventory/AbstractInventory.java @@ -1,6 +1,7 @@ package net.minestom.server.inventory; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerObject; +import net.minestom.server.ServerProcess; import net.minestom.server.event.inventory.InventoryItemChangeEvent; import net.minestom.server.event.inventory.PlayerInventoryItemChangeEvent; import net.minestom.server.inventory.click.InventoryClickProcessor; @@ -23,12 +24,12 @@ /** * Represents an inventory where items can be modified/retrieved. */ -public sealed abstract class AbstractInventory implements InventoryClickHandler, Taggable +public sealed abstract class AbstractInventory implements InventoryClickHandler, Taggable, ServerObject permits Inventory, PlayerInventory { private static final VarHandle ITEM_UPDATER = MethodHandles.arrayElementVarHandle(ItemStack[].class); - public final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final int size; protected final ItemStack[] itemStacks; @@ -39,12 +40,12 @@ public sealed abstract class AbstractInventory implements InventoryClickHandler, private final TagHandler tagHandler = TagHandler.newHandler(); - protected AbstractInventory(@NotNull MinecraftServer minecraftServer, int size) { - this.minecraftServer = minecraftServer; + protected AbstractInventory(@NotNull ServerProcess serverProcess, int size) { + this.serverProcess = serverProcess; this.size = size; this.itemStacks = new ItemStack[getSize()]; Arrays.fill(itemStacks, ItemStack.AIR); - clickProcessor = new InventoryClickProcessor(minecraftServer); + clickProcessor = new InventoryClickProcessor(serverProcess); } /** @@ -82,9 +83,9 @@ protected final void safeItemInsert(int slot, @NotNull ItemStack itemStack, bool UNSAFE_itemInsert(slot, itemStack, sendPacket); } if (this instanceof PlayerInventory inv) { - minecraftServer.process().getGlobalEventHandler().call(new PlayerInventoryItemChangeEvent(inv.player, slot, previous, itemStack)); + serverProcess.getGlobalEventHandler().call(new PlayerInventoryItemChangeEvent(inv.player, slot, previous, itemStack)); } else if (this instanceof Inventory inv) { - minecraftServer.process().getGlobalEventHandler().call(new InventoryItemChangeEvent(inv, slot, previous, itemStack)); + serverProcess.getGlobalEventHandler().call(new InventoryItemChangeEvent(inv, slot, previous, itemStack)); } } @@ -258,4 +259,9 @@ public void copyContents(@NotNull ItemStack[] itemStacks) { public @NotNull TagHandler tagHandler() { return tagHandler; } + + @Override + public ServerProcess getServerProcess() { + return serverProcess; + } } diff --git a/src/main/java/net/minestom/server/inventory/Inventory.java b/src/main/java/net/minestom/server/inventory/Inventory.java index da0a8b373cf..07e11c71e73 100644 --- a/src/main/java/net/minestom/server/inventory/Inventory.java +++ b/src/main/java/net/minestom/server/inventory/Inventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.entity.Player; import net.minestom.server.inventory.click.ClickType; @@ -24,7 +24,7 @@ /** * Represents an inventory which can be viewed by a collection of {@link Player}. *

    - * You can create one with {@link Inventory#Inventory(MinecraftServer, InventoryType, String)} or by making your own subclass. + * You can create one with {@link Inventory#Inventory(ServerProcess, InventoryType, String)} or by making your own subclass. * It can then be opened using {@link Player#openInventory(Inventory)}. */ public non-sealed class Inventory extends AbstractInventory implements Viewable { @@ -45,8 +45,8 @@ public non-sealed class Inventory extends AbstractInventory implements Viewable // (player -> cursor item) map, used by the click listeners private final ConcurrentHashMap cursorPlayersItem = new ConcurrentHashMap<>(); - public Inventory(@NotNull MinecraftServer minecraftServer, @NotNull InventoryType inventoryType, @NotNull Component title) { - super(minecraftServer, inventoryType.getSize()); + public Inventory(@NotNull ServerProcess serverProcess, @NotNull InventoryType inventoryType, @NotNull Component title) { + super(serverProcess, inventoryType.getSize()); this.id = generateId(); this.inventoryType = inventoryType; this.title = title; @@ -54,8 +54,8 @@ public Inventory(@NotNull MinecraftServer minecraftServer, @NotNull InventoryTyp this.offset = getSize(); } - public Inventory(@NotNull MinecraftServer minecraftServer, @NotNull InventoryType inventoryType, @NotNull String title) { - this(minecraftServer, inventoryType, Component.text(title)); + public Inventory(@NotNull ServerProcess serverProcess, @NotNull InventoryType inventoryType, @NotNull String title) { + this(serverProcess, inventoryType, Component.text(title)); } private static byte generateId() { @@ -231,7 +231,7 @@ public boolean leftClick(@NotNull Player player, int slot) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } this.cursorPlayersItem.put(player, clickResult.getCursor()); - callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.LEFT_CLICK, clicked, cursor); + callClickEvent(getServerProcess().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.LEFT_CLICK, clicked, cursor); return true; } @@ -254,7 +254,7 @@ public boolean rightClick(@NotNull Player player, int slot) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } this.cursorPlayersItem.put(player, clickResult.getCursor()); - callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.RIGHT_CLICK, clicked, cursor); + callClickEvent(getServerProcess().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.RIGHT_CLICK, clicked, cursor); return true; } @@ -304,7 +304,7 @@ public boolean changeHeld(@NotNull Player player, int slot, int key) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } playerInventory.setItemStack(convertedKey, clickResult.getCursor()); - callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.CHANGE_HELD, clicked, getCursorItem(player)); + callClickEvent(getServerProcess().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.CHANGE_HELD, clicked, getCursorItem(player)); return true; } @@ -392,9 +392,4 @@ private void updateAll(Player player) { player.getInventory().update(); update(player); } - - @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; - } } diff --git a/src/main/java/net/minestom/server/inventory/PlayerInventory.java b/src/main/java/net/minestom/server/inventory/PlayerInventory.java index a2aa46ab75e..27c45cfe1d6 100644 --- a/src/main/java/net/minestom/server/inventory/PlayerInventory.java +++ b/src/main/java/net/minestom/server/inventory/PlayerInventory.java @@ -1,6 +1,6 @@ package net.minestom.server.inventory; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; import net.minestom.server.event.item.EntityEquipEvent; @@ -25,8 +25,8 @@ public non-sealed class PlayerInventory extends AbstractInventory implements Equ protected final Player player; private ItemStack cursorItem = ItemStack.AIR; - public PlayerInventory(@NotNull MinecraftServer minecraftServer, @NotNull Player player) { - super(minecraftServer, INVENTORY_SIZE); + public PlayerInventory(@NotNull ServerProcess serverProcess, @NotNull Player player) { + super(serverProcess, INVENTORY_SIZE); this.player = player; } @@ -145,7 +145,7 @@ protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean }; if (equipmentSlot != null) { EntityEquipEvent entityEquipEvent = new EntityEquipEvent(player, itemStack, equipmentSlot); - minecraftServer.process().getGlobalEventHandler().call(entityEquipEvent); + getServerProcess().getGlobalEventHandler().call(entityEquipEvent); itemStack = entityEquipEvent.getEquippedItem(); } this.itemStacks[slot] = itemStack; @@ -195,7 +195,7 @@ public boolean leftClick(@NotNull Player player, int slot) { } setItemStack(convertedSlot, clickResult.getClicked()); setCursorItem(clickResult.getCursor()); - callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, null, convertedSlot, ClickType.LEFT_CLICK, clicked, cursor); + callClickEvent(getServerProcess().getGlobalEventHandler(), player, null, convertedSlot, ClickType.LEFT_CLICK, clicked, cursor); return true; } @@ -211,7 +211,7 @@ public boolean rightClick(@NotNull Player player, int slot) { } setItemStack(convertedSlot, clickResult.getClicked()); setCursorItem(clickResult.getCursor()); - callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, null, convertedSlot, ClickType.RIGHT_CLICK, clicked, cursor); + callClickEvent(getServerProcess().getGlobalEventHandler(), player, null, convertedSlot, ClickType.RIGHT_CLICK, clicked, cursor); return true; } @@ -279,7 +279,7 @@ public boolean changeHeld(@NotNull Player player, int slot, int key) { } setItemStack(convertedSlot, clickResult.getClicked()); setItemStack(convertedKey, clickResult.getCursor()); - callClickEvent(minecraftServer.process().getGlobalEventHandler(), player, null, convertedSlot, ClickType.CHANGE_HELD, clicked, cursorItem); + callClickEvent(getServerProcess().getGlobalEventHandler(), player, null, convertedSlot, ClickType.CHANGE_HELD, clicked, cursorItem); return true; } diff --git a/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java b/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java index 70c392885d9..51170481012 100644 --- a/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java +++ b/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java @@ -1,6 +1,6 @@ package net.minestom.server.inventory.click; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; import net.minestom.server.event.inventory.InventoryClickEvent; @@ -31,10 +31,10 @@ public final class InventoryClickProcessor { private final Map> leftDraggingMap = new ConcurrentHashMap<>(); private final Map> rightDraggingMap = new ConcurrentHashMap<>(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public InventoryClickProcessor(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public InventoryClickProcessor(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } public @NotNull InventoryClickResult leftClick(@NotNull Player player, @NotNull AbstractInventory inventory, @@ -433,7 +433,7 @@ public InventoryClickProcessor(MinecraftServer minecraftServer) { { InventoryPreClickEvent inventoryPreClickEvent = new InventoryPreClickEvent(eventInventory, player, slot, clickType, clickResult.getClicked(), clickResult.getCursor()); - minecraftServer.process().getGlobalEventHandler().call(inventoryPreClickEvent); + serverProcess.getGlobalEventHandler().call(inventoryPreClickEvent); clickResult.setCursor(inventoryPreClickEvent.getCursorItem()); clickResult.setClicked(inventoryPreClickEvent.getClickedItem()); if (inventoryPreClickEvent.isCancelled()) { @@ -469,7 +469,7 @@ public InventoryClickProcessor(MinecraftServer minecraftServer) { private void callClickEvent(@NotNull Player player, @Nullable AbstractInventory inventory, int slot, @NotNull ClickType clickType, @NotNull ItemStack clicked, @NotNull ItemStack cursor) { final Inventory eventInventory = inventory instanceof Inventory ? (Inventory) inventory : null; - minecraftServer.process().getGlobalEventHandler().call(new InventoryClickEvent(eventInventory, player, slot, clickType, clicked, cursor)); + serverProcess.getGlobalEventHandler().call(new InventoryClickEvent(eventInventory, player, slot, clickType, clicked, cursor)); } public void clearCache(@NotNull Player player) { diff --git a/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java b/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java index d826bedf32f..55bb753869c 100644 --- a/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -11,12 +11,12 @@ public class AnvilInventory extends Inventory { private short repairCost; - public AnvilInventory(MinecraftServer minecraftServer, @NotNull Component title) { - super(minecraftServer, InventoryType.ANVIL, title); + public AnvilInventory(ServerProcess serverProcess, @NotNull Component title) { + super(serverProcess, InventoryType.ANVIL, title); } - public AnvilInventory(MinecraftServer minecraftServer, @NotNull String title) { - super(minecraftServer, InventoryType.ANVIL, title); + public AnvilInventory(ServerProcess serverProcess, @NotNull String title) { + super(serverProcess, InventoryType.ANVIL, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java b/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java index 47be3963e3b..0f1fa57666a 100644 --- a/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -14,12 +14,12 @@ public class BeaconInventory extends Inventory { private PotionEffect firstPotionEffect; private PotionEffect secondPotionEffect; - public BeaconInventory(MinecraftServer minecraftServer, @NotNull Component title) { - super(minecraftServer, InventoryType.BEACON, title); + public BeaconInventory(ServerProcess serverProcess, @NotNull Component title) { + super(serverProcess, InventoryType.BEACON, title); } - public BeaconInventory(MinecraftServer minecraftServer, @NotNull String title) { - super(minecraftServer, InventoryType.BEACON, title); + public BeaconInventory(ServerProcess serverProcess, @NotNull String title) { + super(serverProcess, InventoryType.BEACON, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java b/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java index 6fa8f2ee3a8..34ac8202440 100644 --- a/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -12,12 +12,12 @@ public class BrewingStandInventory extends Inventory { private short brewTime; private short fuelTime; - public BrewingStandInventory(MinecraftServer minecraftServer, @NotNull Component title) { - super(minecraftServer, InventoryType.BREWING_STAND, title); + public BrewingStandInventory(ServerProcess serverProcess, @NotNull Component title) { + super(serverProcess, InventoryType.BREWING_STAND, title); } - public BrewingStandInventory(MinecraftServer minecraftServer, @NotNull String title) { - super(minecraftServer, InventoryType.BREWING_STAND, title); + public BrewingStandInventory(ServerProcess serverProcess, @NotNull String title) { + super(serverProcess, InventoryType.BREWING_STAND, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java b/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java index 03944333418..fd9b19c7ff3 100644 --- a/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -15,12 +15,12 @@ public class EnchantmentTableInventory extends Inventory { private final short[] enchantmentShown = new short[EnchantmentSlot.values().length]; private final short[] enchantmentLevel = new short[EnchantmentSlot.values().length]; - public EnchantmentTableInventory(MinecraftServer minecraftServer, @NotNull Component title) { - super(minecraftServer, InventoryType.ENCHANTMENT, title); + public EnchantmentTableInventory(ServerProcess serverProcess, @NotNull Component title) { + super(serverProcess, InventoryType.ENCHANTMENT, title); } - public EnchantmentTableInventory(MinecraftServer minecraftServer, @NotNull String title) { - super(minecraftServer, InventoryType.ENCHANTMENT, title); + public EnchantmentTableInventory(ServerProcess serverProcess, @NotNull String title) { + super(serverProcess, InventoryType.ENCHANTMENT, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java b/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java index 47a236ddc6b..07f0f391ecc 100644 --- a/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -14,12 +14,12 @@ public class FurnaceInventory extends Inventory { private short progressArrow; private short maximumProgress; - public FurnaceInventory(MinecraftServer minecraftServer, @NotNull Component title) { - super(minecraftServer, InventoryType.FURNACE, title); + public FurnaceInventory(ServerProcess serverProcess, @NotNull Component title) { + super(serverProcess, InventoryType.FURNACE, title); } - public FurnaceInventory(MinecraftServer minecraftServer, @NotNull String title) { - super(minecraftServer, InventoryType.FURNACE, title); + public FurnaceInventory(ServerProcess serverProcess, @NotNull String title) { + super(serverProcess, InventoryType.FURNACE, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java index 5b8e27481c0..a9962a04266 100644 --- a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; @@ -21,14 +21,14 @@ public class VillagerInventory extends Inventory { private boolean regularVillager; private boolean canRestock; - public VillagerInventory(MinecraftServer minecraftServer, @NotNull Component title) { - super(minecraftServer, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(minecraftServer, this::createTradePacket); + public VillagerInventory(ServerProcess serverProcess, @NotNull Component title) { + super(serverProcess, InventoryType.MERCHANT, title); + tradeCache = new CachedPacket(serverProcess, this::createTradePacket); } - public VillagerInventory(MinecraftServer minecraftServer, @NotNull String title) { - super(minecraftServer, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(minecraftServer, this::createTradePacket); + public VillagerInventory(ServerProcess serverProcess, @NotNull String title) { + super(serverProcess, InventoryType.MERCHANT, title); + tradeCache = new CachedPacket(serverProcess, this::createTradePacket); } public List getTrades() { diff --git a/src/main/java/net/minestom/server/listener/AbilitiesListener.java b/src/main/java/net/minestom/server/listener/AbilitiesListener.java index 78ade72af04..5f066f2b785 100644 --- a/src/main/java/net/minestom/server/listener/AbilitiesListener.java +++ b/src/main/java/net/minestom/server/listener/AbilitiesListener.java @@ -17,10 +17,10 @@ public static void listener(ClientPlayerAbilitiesPacket packet, Player player) { if (isFlying) { PlayerStartFlyingEvent startFlyingEvent = new PlayerStartFlyingEvent(player); - player.minecraftServer.process().getGlobalEventHandler().call(startFlyingEvent); + player.getServerProcess().getGlobalEventHandler().call(startFlyingEvent); } else { PlayerStopFlyingEvent stopFlyingEvent = new PlayerStopFlyingEvent(player); - player.minecraftServer.process().getGlobalEventHandler().call(stopFlyingEvent); + player.getServerProcess().getGlobalEventHandler().call(stopFlyingEvent); } } } diff --git a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java index 7dc78705c2c..22333aa3513 100644 --- a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java +++ b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java @@ -9,7 +9,7 @@ public class AdvancementTabListener { public static void listener(ClientAdvancementTabPacket packet, Player player) { final String tabIdentifier = packet.tabIdentifier(); if (tabIdentifier != null) { - player.getMinecraftServer().process().getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); + player.getServerProcess().getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); } } } diff --git a/src/main/java/net/minestom/server/listener/AnimationListener.java b/src/main/java/net/minestom/server/listener/AnimationListener.java index 6028ea6c20c..1ce605b014e 100644 --- a/src/main/java/net/minestom/server/listener/AnimationListener.java +++ b/src/main/java/net/minestom/server/listener/AnimationListener.java @@ -12,7 +12,7 @@ public static void animationListener(ClientAnimationPacket packet, Player player final ItemStack itemStack = player.getItemInHand(hand); //itemStack.onLeftClick(player, hand); PlayerHandAnimationEvent handAnimationEvent = new PlayerHandAnimationEvent(player, hand); - player.minecraftServer.process().getGlobalEventHandler().callCancellable(handAnimationEvent, () -> { + player.getServerProcess().getGlobalEventHandler().callCancellable(handAnimationEvent, () -> { switch (hand) { case MAIN -> player.swingMainHand(); case OFF -> player.swingOffHand(); diff --git a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java index e8fa0d15aeb..985fa2be729 100644 --- a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java +++ b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java @@ -51,7 +51,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Interact at block // FIXME: onUseOnBlock PlayerBlockInteractEvent playerBlockInteractEvent = new PlayerBlockInteractEvent(player, hand, interactedBlock, blockPosition, cursorPosition, blockFace); - player.minecraftServer.process().getGlobalEventHandler().call(playerBlockInteractEvent); + player.getServerProcess().getGlobalEventHandler().call(playerBlockInteractEvent); boolean blockUse = playerBlockInteractEvent.isBlockingItemUse(); if (!playerBlockInteractEvent.isCancelled()) { final var handler = interactedBlock.handler(); @@ -70,7 +70,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play if (!useMaterial.isBlock()) { // Player didn't try to place a block but interacted with one PlayerUseItemOnBlockEvent event = new PlayerUseItemOnBlockEvent(player, hand, usedItem, blockPosition, cursorPosition, blockFace); - player.minecraftServer.process().getGlobalEventHandler().call(event); + player.getServerProcess().getGlobalEventHandler().call(event); // Ack the block change. This is required to reset the client prediction to the server state. player.sendPacket(new AcknowledgeBlockChangePacket(packet.sequence())); return; @@ -90,7 +90,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Get the newly placed block position //todo it feels like it should be possible to have better replacement rules than this, feels pretty scuffed. Point placementPosition = blockPosition; - var interactedPlacementRule = player.minecraftServer.process().getBlockManager().getBlockPlacementRule(interactedBlock); + var interactedPlacementRule = player.getServerProcess().getBlockManager().getBlockPlacementRule(interactedBlock); if (!interactedBlock.isAir() && (interactedPlacementRule == null || !interactedPlacementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(interactedBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is not replaceable, try to place next to it. @@ -100,7 +100,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play placementPosition = blockPosition.add(offsetX, offsetY, offsetZ); var placementBlock = instance.getBlock(placementPosition); - var placementRule = player.minecraftServer.process().getBlockManager().getBlockPlacementRule(placementBlock); + var placementRule = player.getServerProcess().getBlockManager().getBlockPlacementRule(placementBlock); if (!placementBlock.registry().isReplaceable() && !(placementRule != null && placementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(placementBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is still not replaceable, cancel the placement @@ -149,7 +149,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // BlockPlaceEvent check PlayerBlockPlaceEvent playerBlockPlaceEvent = new PlayerBlockPlaceEvent(player, placedBlock, blockFace, placementPosition, packet.hand()); playerBlockPlaceEvent.consumeBlock(player.getGameMode() != GameMode.CREATIVE); - player.minecraftServer.process().getGlobalEventHandler().call(playerBlockPlaceEvent); + player.getServerProcess().getGlobalEventHandler().call(playerBlockPlaceEvent); if (playerBlockPlaceEvent.isCancelled()) { refresh(player, chunk); return; diff --git a/src/main/java/net/minestom/server/listener/BookListener.java b/src/main/java/net/minestom/server/listener/BookListener.java index 297f774a476..6a204602fdb 100644 --- a/src/main/java/net/minestom/server/listener/BookListener.java +++ b/src/main/java/net/minestom/server/listener/BookListener.java @@ -11,7 +11,7 @@ public class BookListener { public static void listener(ClientEditBookPacket packet, Player player) { int slot = PlayerInventoryUtils.convertClientInventorySlot(packet.slot()); ItemStack itemStack = player.getInventory().getItemStack(slot); - player.minecraftServer.process().getGlobalEventHandler().call(new EditBookEvent(player, itemStack, packet.pages(), packet.title())); + player.getServerProcess().getGlobalEventHandler().call(new EditBookEvent(player, itemStack, packet.pages(), packet.title())); } } diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index 1ddf2f33edc..7e0439734f4 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -18,7 +18,7 @@ public class ChatMessageListener { public static void commandChatListener(ClientCommandChatPacket packet, Player player) { final String command = packet.message(); if (Messenger.canReceiveCommand(player)) { - player.minecraftServer.process().getCommandManager().execute(player, command); + player.getServerProcess().getCommandManager().execute(player, command); } else { Messenger.sendRejectionMessage(player); } @@ -31,11 +31,11 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl return; } - final Collection players = player.minecraftServer.process().getConnectionManager().getOnlinePlayers(); + final Collection players = player.getServerProcess().getConnectionManager().getOnlinePlayers(); PlayerChatEvent playerChatEvent = new PlayerChatEvent(player, players, () -> buildDefaultChatMessage(player, message), message); // Call the event - player.minecraftServer.process().getGlobalEventHandler().callCancellable(playerChatEvent, () -> { + player.getServerProcess().getGlobalEventHandler().callCancellable(playerChatEvent, () -> { final Function formatFunction = playerChatEvent.getChatFormatFunction(); Component textObject; @@ -51,7 +51,7 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl final Collection recipients = playerChatEvent.getRecipients(); if (!recipients.isEmpty()) { // delegate to the messenger to avoid sending messages we shouldn't be - Messenger.sendMessage(player.getMinecraftServer(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); + Messenger.sendMessage(player.getServerProcess(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); } }); } diff --git a/src/main/java/net/minestom/server/listener/EntityActionListener.java b/src/main/java/net/minestom/server/listener/EntityActionListener.java index 45a43262c69..1e84659e2bd 100644 --- a/src/main/java/net/minestom/server/listener/EntityActionListener.java +++ b/src/main/java/net/minestom/server/listener/EntityActionListener.java @@ -24,9 +24,9 @@ private static void setSneaking(Player player, boolean sneaking) { if (oldState != sneaking) { if (sneaking) { - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStartSneakingEvent(player)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerStartSneakingEvent(player)); } else { - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStopSneakingEvent(player)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerStopSneakingEvent(player)); } } } @@ -38,15 +38,15 @@ private static void setSprinting(Player player, boolean sprinting) { if (oldState != sprinting) { if (sprinting) { - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStartSprintingEvent(player)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerStartSprintingEvent(player)); } else { - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStopSprintingEvent(player)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerStopSprintingEvent(player)); } } } private static void startFlyingElytra(Player player) { player.setFlyingWithElytra(true); - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerStartFlyingWithElytraEvent(player)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerStartFlyingWithElytraEvent(player)); } } diff --git a/src/main/java/net/minestom/server/listener/PlayConfigListener.java b/src/main/java/net/minestom/server/listener/PlayConfigListener.java index dde21f91ca9..dca5dfc74cd 100644 --- a/src/main/java/net/minestom/server/listener/PlayConfigListener.java +++ b/src/main/java/net/minestom/server/listener/PlayConfigListener.java @@ -6,6 +6,6 @@ public class PlayConfigListener { public static void configAckListener(@NotNull ClientConfigurationAckPacket packet, @NotNull Player player) { - player.minecraftServer.process().getConnectionManager().doConfiguration(player, false); + player.getServerProcess().getConnectionManager().doConfiguration(player, false); } } diff --git a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java index 4e6f692e84e..248afba081b 100644 --- a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java @@ -82,7 +82,7 @@ private static DiggingResult startDigging(Player player, Instance instance, Poin final boolean instantBreak = player.isInstantBreak() || block.registry().hardness() == 0; if (!instantBreak) { PlayerStartDiggingEvent playerStartDiggingEvent = new PlayerStartDiggingEvent(player, block, blockPosition, blockFace); - player.minecraftServer.process().getGlobalEventHandler().call(playerStartDiggingEvent); + player.getServerProcess().getGlobalEventHandler().call(playerStartDiggingEvent); return new DiggingResult(block, !playerStartDiggingEvent.isCancelled()); } // Client only send a single STARTED_DIGGING when insta-break is enabled @@ -92,7 +92,7 @@ private static DiggingResult startDigging(Player player, Instance instance, Poin private static DiggingResult cancelDigging(Player player, Instance instance, Point blockPosition) { final Block block = instance.getBlock(blockPosition); PlayerCancelDiggingEvent playerCancelDiggingEvent = new PlayerCancelDiggingEvent(player, block, blockPosition); - player.minecraftServer.process().getGlobalEventHandler().call(playerCancelDiggingEvent); + player.getServerProcess().getGlobalEventHandler().call(playerCancelDiggingEvent); return new DiggingResult(block, true); } @@ -104,7 +104,7 @@ private static DiggingResult finishDigging(Player player, Instance instance, Poi } PlayerFinishDiggingEvent playerFinishDiggingEvent = new PlayerFinishDiggingEvent(player, block, blockPosition); - player.minecraftServer.process().getGlobalEventHandler().call(playerFinishDiggingEvent); + player.getServerProcess().getGlobalEventHandler().call(playerFinishDiggingEvent); return breakBlock(instance, player, blockPosition, playerFinishDiggingEvent.getBlock(), blockFace); } @@ -166,7 +166,7 @@ private static void swapItemHand(Player player) { final ItemStack mainHand = inventory.getItemInMainHand(); final ItemStack offHand = inventory.getItemInOffHand(); PlayerSwapItemEvent swapItemEvent = new PlayerSwapItemEvent(player, offHand, mainHand); - player.minecraftServer.process().getGlobalEventHandler().callCancellable(swapItemEvent, () -> { + player.getServerProcess().getGlobalEventHandler().callCancellable(swapItemEvent, () -> { inventory.setItemInMainHand(swapItemEvent.getMainHandItem()); inventory.setItemInOffHand(swapItemEvent.getOffHandItem()); }); diff --git a/src/main/java/net/minestom/server/listener/PlayerHeldListener.java b/src/main/java/net/minestom/server/listener/PlayerHeldListener.java index 292011281fe..8c15fa76501 100644 --- a/src/main/java/net/minestom/server/listener/PlayerHeldListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerHeldListener.java @@ -16,7 +16,7 @@ public static void heldListener(ClientHeldItemChangePacket packet, Player player final byte slot = (byte) packet.slot(); PlayerChangeHeldSlotEvent changeHeldSlotEvent = new PlayerChangeHeldSlotEvent(player, slot); - player.minecraftServer.process().getGlobalEventHandler().call(changeHeldSlotEvent); + player.getServerProcess().getGlobalEventHandler().call(changeHeldSlotEvent); if (!changeHeldSlotEvent.isCancelled()) { // Event hasn't been canceled, process it diff --git a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java index bcb91ac5fab..ef15a749d39 100644 --- a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java @@ -53,7 +53,7 @@ private static void processMovement(@NotNull Player player, @NotNull Pos packetP } PlayerMoveEvent playerMoveEvent = new PlayerMoveEvent(player, packetPosition, onGround); - player.minecraftServer.process().getGlobalEventHandler().call(playerMoveEvent); + player.getServerProcess().getGlobalEventHandler().call(playerMoveEvent); if (!currentPosition.equals(player.getPosition())) { // Player has been teleported in the event return; diff --git a/src/main/java/net/minestom/server/listener/SpectateListener.java b/src/main/java/net/minestom/server/listener/SpectateListener.java index 593ac059fca..cb758f3a1e6 100644 --- a/src/main/java/net/minestom/server/listener/SpectateListener.java +++ b/src/main/java/net/minestom/server/listener/SpectateListener.java @@ -41,7 +41,7 @@ public static void listener(ClientSpectatePacket packet, Player player) { // Despite the name of this packet being spectate, it is sent when the player // uses their hotbar to switch between entities, which actually performs a teleport // instead of a spectate. - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerSpectateEvent(player, target)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerSpectateEvent(player, target)); } } diff --git a/src/main/java/net/minestom/server/listener/TabCompleteListener.java b/src/main/java/net/minestom/server/listener/TabCompleteListener.java index 0d0f973d77d..d8078719f7d 100644 --- a/src/main/java/net/minestom/server/listener/TabCompleteListener.java +++ b/src/main/java/net/minestom/server/listener/TabCompleteListener.java @@ -12,7 +12,7 @@ public class TabCompleteListener { public static void listener(ClientTabCompletePacket packet, Player player) { final String text = packet.text(); - final Suggestion suggestion = getSuggestion(player.minecraftServer.process().getCommandManager(), player, text); + final Suggestion suggestion = getSuggestion(player.getServerProcess().getCommandManager(), player, text); if (suggestion != null) { player.sendPacket(new TabCompletePacket( packet.transactionId(), diff --git a/src/main/java/net/minestom/server/listener/UseEntityListener.java b/src/main/java/net/minestom/server/listener/UseEntityListener.java index 18602993b2f..4722ba77ce8 100644 --- a/src/main/java/net/minestom/server/listener/UseEntityListener.java +++ b/src/main/java/net/minestom/server/listener/UseEntityListener.java @@ -20,10 +20,10 @@ public static void useEntityListener(ClientInteractEntityPacket packet, Player p if (type instanceof ClientInteractEntityPacket.Attack) { if (entity instanceof LivingEntity && ((LivingEntity) entity).isDead()) // Can't attack dead entities return; - player.minecraftServer.process().getGlobalEventHandler().call(new EntityAttackEvent(player, entity)); + player.getServerProcess().getGlobalEventHandler().call(new EntityAttackEvent(player, entity)); } else if (type instanceof ClientInteractEntityPacket.InteractAt interactAt) { Point interactPosition = new Vec(interactAt.targetX(), interactAt.targetY(), interactAt.targetZ()); - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerEntityInteractEvent(player, entity, interactAt.hand(), interactPosition)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerEntityInteractEvent(player, entity, interactAt.hand(), interactPosition)); } } } diff --git a/src/main/java/net/minestom/server/listener/UseItemListener.java b/src/main/java/net/minestom/server/listener/UseItemListener.java index 5b5a522dd34..3abf77e7f6c 100644 --- a/src/main/java/net/minestom/server/listener/UseItemListener.java +++ b/src/main/java/net/minestom/server/listener/UseItemListener.java @@ -18,7 +18,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { ItemStack itemStack = hand == Player.Hand.MAIN ? inventory.getItemInMainHand() : inventory.getItemInOffHand(); //itemStack.onRightClick(player, hand); PlayerUseItemEvent useItemEvent = new PlayerUseItemEvent(player, hand, itemStack); - player.minecraftServer.process().getGlobalEventHandler().call(useItemEvent); + player.getServerProcess().getGlobalEventHandler().call(useItemEvent); final PlayerInventory playerInventory = player.getInventory(); if (useItemEvent.isCancelled()) { @@ -56,7 +56,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { // Eating code, contains the eating time customisation PlayerPreEatEvent playerPreEatEvent = new PlayerPreEatEvent(player, itemStack, hand, player.getDefaultEatingTime()); - player.minecraftServer.process().getGlobalEventHandler().callCancellable(playerPreEatEvent, () -> player.refreshEating(hand, playerPreEatEvent.getEatingTime())); + player.getServerProcess().getGlobalEventHandler().callCancellable(playerPreEatEvent, () -> player.refreshEating(hand, playerPreEatEvent.getEatingTime())); if (playerPreEatEvent.isCancelled()) { cancelAnimation = true; @@ -65,7 +65,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { if (!cancelAnimation && itemAnimationType != null) { PlayerItemAnimationEvent playerItemAnimationEvent = new PlayerItemAnimationEvent(player, itemAnimationType, hand); - player.minecraftServer.process().getGlobalEventHandler().callCancellable(playerItemAnimationEvent, () -> { + player.getServerProcess().getGlobalEventHandler().callCancellable(playerItemAnimationEvent, () -> { player.refreshActiveHand(true, hand == Player.Hand.OFF, false); player.sendPacketToViewers(player.getMetadataPacket()); }); diff --git a/src/main/java/net/minestom/server/listener/WindowListener.java b/src/main/java/net/minestom/server/listener/WindowListener.java index 29065b1e4b1..91b32fa1c91 100644 --- a/src/main/java/net/minestom/server/listener/WindowListener.java +++ b/src/main/java/net/minestom/server/listener/WindowListener.java @@ -85,7 +85,7 @@ public static void pong(ClientPongPacket packet, Player player) { public static void closeWindowListener(ClientCloseWindowPacket packet, Player player) { // if windowId == 0 then it is player's inventory, meaning that they hadn't been any open inventory packet InventoryCloseEvent inventoryCloseEvent = new InventoryCloseEvent(player.getOpenInventory(), player); - player.minecraftServer.process().getGlobalEventHandler().call(inventoryCloseEvent); + player.getServerProcess().getGlobalEventHandler().call(inventoryCloseEvent); player.closeInventory(true); diff --git a/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java b/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java index d3ef8582dc6..0047cea0257 100644 --- a/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java +++ b/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java @@ -8,7 +8,7 @@ public class PluginMessageListener { public static void listener(ClientPluginMessagePacket packet, Player player) { PlayerPluginMessageEvent pluginMessageEvent = new PlayerPluginMessageEvent(player, packet.channel(), packet.data()); - player.minecraftServer.process().getGlobalEventHandler().call(pluginMessageEvent); + player.getServerProcess().getGlobalEventHandler().call(pluginMessageEvent); } } diff --git a/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java b/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java index fae47153dcb..ba30b544c48 100644 --- a/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java +++ b/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java @@ -7,7 +7,7 @@ public class ResourcePackListener { public static void listener(ClientResourcePackStatusPacket packet, Player player) { - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerResourcePackStatusEvent(player, packet.status())); + player.getServerProcess().getGlobalEventHandler().call(new PlayerResourcePackStatusEvent(player, packet.status())); // Run adventure callbacks for the resource pack player.onResourcePackStatus(packet.id(), packet.status()); diff --git a/src/main/java/net/minestom/server/listener/common/SettingsListener.java b/src/main/java/net/minestom/server/listener/common/SettingsListener.java index db3c23ff013..5b68c3fcef9 100644 --- a/src/main/java/net/minestom/server/listener/common/SettingsListener.java +++ b/src/main/java/net/minestom/server/listener/common/SettingsListener.java @@ -9,6 +9,6 @@ public static void listener(ClientSettingsPacket packet, Player player) { Player.PlayerSettings settings = player.getSettings(); // Since viewDistance bounds checking is performed in the refresh function, it is not necessary to check it here settings.refresh(packet.locale(), packet.viewDistance(), packet.chatMessageType(), packet.chatColors(), packet.displayedSkinParts(), packet.mainHand(), packet.enableTextFiltering(), packet.allowsListing()); - player.minecraftServer.process().getGlobalEventHandler().call(new PlayerSettingsChangeEvent(player)); + player.getServerProcess().getGlobalEventHandler().call(new PlayerSettingsChangeEvent(player)); } } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java index d60958aa1db..60d860af90b 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java @@ -1,6 +1,6 @@ package net.minestom.server.listener.manager; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.event.player.PlayerPacketEvent; import net.minestom.server.listener.*; import net.minestom.server.listener.common.KeepAliveListener; @@ -36,10 +36,10 @@ public final class PacketListenerManager { private final static Logger LOGGER = LoggerFactory.getLogger(PacketListenerManager.class); private final Map, PacketPrePlayListenerConsumer>[] listeners = new Map[ConnectionState.values().length]; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public PacketListenerManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public PacketListenerManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; for (int i = 0; i < listeners.length; i++) { listeners[i] = new ConcurrentHashMap<>(); } @@ -119,7 +119,7 @@ public void processClientPacket(@NotNull T packet, @Not // Event if (state == ConnectionState.PLAY) { PlayerPacketEvent playerPacketEvent = new PlayerPacketEvent(connection.getPlayer(), packet); - minecraftServer.process().getGlobalEventHandler().call(playerPacketEvent); + serverProcess.getGlobalEventHandler().call(playerPacketEvent); if (playerPacketEvent.isCancelled()) { return; } @@ -130,7 +130,7 @@ public void processClientPacket(@NotNull T packet, @Not packetListenerConsumer.accept(packet, connection); } catch (Exception e) { // Packet is likely invalid - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java index 983391bb82e..b2430586691 100644 --- a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java @@ -7,6 +7,6 @@ public final class ConfigListener { public static void finishConfigListener(@NotNull ClientFinishConfigurationPacket packet, @NotNull Player player) { - player.minecraftServer.process().getConnectionManager().transitionConfigToPlay(player); + player.getServerProcess().getConnectionManager().transitionConfigToPlay(player); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java b/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java index 13ea23024e7..17ba8bef387 100644 --- a/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java @@ -6,7 +6,7 @@ import com.google.gson.JsonParser; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; import net.minestom.server.extras.bungee.BungeeCordProxy; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; @@ -30,7 +30,7 @@ public final class HandshakeListener { /** * Text sent if a player tries to connect with an invalid version of the client */ - private static final Component INVALID_VERSION_TEXT = Component.text("Invalid Version, please use " + MinecraftServer.VERSION_NAME, NamedTextColor.RED); + private static final Component INVALID_VERSION_TEXT = Component.text("Invalid Version, please use " + ServerConsts.VERSION_NAME, NamedTextColor.RED); /** * Indicates that a BungeeGuard authentication was invalid due to missing, multiple, or invalid tokens. @@ -43,7 +43,7 @@ public static void listener(@NotNull ClientHandshakePacket packet, @NotNull Play case 1 -> connection.setConnectionState(ConnectionState.STATUS); case 2 -> { connection.setConnectionState(ConnectionState.LOGIN); - if (packet.protocolVersion() != MinecraftServer.PROTOCOL_VERSION) { + if (packet.protocolVersion() != ServerConsts.PROTOCOL_VERSION) { // Incorrect client version disconnect(connection, INVALID_VERSION_TEXT); } diff --git a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java index 9ce4b035138..00342cffd73 100644 --- a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java @@ -5,7 +5,7 @@ import com.google.gson.JsonObject; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.extras.MojangAuth; import net.minestom.server.extras.bungee.BungeeCordProxy; @@ -44,7 +44,7 @@ public final class LoginListener { public static final Component INVALID_PROXY_RESPONSE = Component.text("Invalid proxy response!", NamedTextColor.RED); public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @NotNull PlayerConnection connection) { - MojangAuth mojangAuth = connection.minecraftServer.process().getMojangAuth(); + MojangAuth mojangAuth = connection.getServerProcess().getMojangAuth(); final boolean isSocketConnection = connection instanceof PlayerSocketConnection; // Proxy support (only for socket clients) and cache the login username if (isSocketConnection) { @@ -63,7 +63,7 @@ public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @N if (mojangAuth.isEnabled() && isSocketConnection) { // Mojang auth - if (connection.minecraftServer.process().getConnectionManager().getOnlinePlayerByUsername(packet.username()) != null) { + if (connection.getServerProcess().getConnectionManager().getOnlinePlayerByUsername(packet.username()) != null) { connection.sendPacket(new LoginDisconnectPacket(ALREADY_CONNECTED)); connection.disconnect(); return; @@ -80,16 +80,16 @@ public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @N // Offline final UUID playerUuid = bungee && isSocketConnection ? ((PlayerSocketConnection) connection).gameProfile().uuid() : - connection.minecraftServer.process().getConnectionManager().getPlayerConnectionUuid(connection, packet.username()); - connection.minecraftServer.process().getConnectionManager().createPlayer(connection, playerUuid, packet.username()); + connection.getServerProcess().getConnectionManager().getPlayerConnectionUuid(connection, packet.username()); + connection.getServerProcess().getConnectionManager().createPlayer(connection, playerUuid, packet.username()); } } public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResponsePacket packet, @NotNull PlayerConnection connection) { // Encryption is only support for socket connection - MojangAuth mojangAuth = connection.minecraftServer.process().getMojangAuth(); + MojangAuth mojangAuth = connection.getServerProcess().getMojangAuth(); if (!(connection instanceof PlayerSocketConnection socketConnection)) return; - AsyncUtils.runAsync(connection.minecraftServer, () -> { + AsyncUtils.runAsync(connection.getServerProcess(), () -> { final String loginUsername = socketConnection.getLoginUsername(); if (loginUsername == null || loginUsername.isEmpty()) { // Shouldn't happen @@ -101,14 +101,14 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp mojangAuth.getMojangCrypt().decryptUsingKey(mojangAuth.getKeyPair().getPrivate(), packet.encryptedVerifyToken())); if (verificationFailed) { - MinecraftServer.LOGGER.error("Encryption failed for {}", loginUsername); + ServerProcess.LOGGER.error("Encryption failed for {}", loginUsername); return; } final byte[] digestedData = mojangAuth.getMojangCrypt().digestData("", mojangAuth.getKeyPair().getPublic(), getSecretKey(mojangAuth, packet.sharedSecret())); if (digestedData == null) { // Incorrect key, probably because of the client - MinecraftServer.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); + ServerProcess.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); connection.disconnect(); return; } @@ -123,7 +123,7 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp final HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).whenComplete((response, throwable) -> { if (throwable != null) { - connection.minecraftServer.process().getExceptionManager().handleException(throwable); + connection.getServerProcess().getExceptionManager().handleException(throwable); if (socketConnection.getPlayer() != null) { socketConnection.getPlayer().kick(Component.text("Failed to contact Mojang's Session Servers (Are they down?)")); } else { @@ -147,8 +147,8 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp .replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); final String profileName = gameProfile.get("name").getAsString(); - MinecraftServer.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); - connection.minecraftServer.process().getConnectionManager().createPlayer(connection, profileUUID, profileName); + ServerProcess.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); + connection.getServerProcess().getConnectionManager().createPlayer(connection, profileUUID, profileName); List propertyList = new ArrayList<>(); for (JsonElement element : gameProfile.get("properties").getAsJsonArray()) { JsonObject object = element.getAsJsonObject(); @@ -156,7 +156,7 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp } socketConnection.UNSAFE_setProfile(new GameProfile(profileUUID, profileName, propertyList)); } catch (Exception e) { - connection.minecraftServer.process().getExceptionManager().handleException(e); + connection.getServerProcess().getExceptionManager().handleException(e); } }); }); @@ -188,7 +188,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons try { address = InetAddress.getByName(buffer.read(STRING)); } catch (UnknownHostException e) { - connection.minecraftServer.process().getExceptionManager().handleException(e); + connection.getServerProcess().getExceptionManager().handleException(e); return; } final int port = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort(); @@ -201,7 +201,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons if (success) { socketConnection.setRemoteAddress(socketAddress); socketConnection.UNSAFE_setProfile(gameProfile); - connection.minecraftServer.process().getConnectionManager().createPlayer(connection, gameProfile.uuid(), gameProfile.name()); + connection.getServerProcess().getConnectionManager().createPlayer(connection, gameProfile.uuid(), gameProfile.name()); } else { LoginDisconnectPacket disconnectPacket = new LoginDisconnectPacket(INVALID_PROXY_RESPONSE); socketConnection.sendPacket(disconnectPacket); @@ -212,7 +212,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons public static void loginAckListener(@NotNull ClientLoginAcknowledgedPacket ignored, @NotNull PlayerConnection connection) { final Player player = Objects.requireNonNull(connection.getPlayer()); - connection.minecraftServer.process().getConnectionManager().doConfiguration(player, true); + connection.getServerProcess().getConnectionManager().doConfiguration(player, true); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java index 96d6bc3cbc4..b13258db43b 100644 --- a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java @@ -14,14 +14,14 @@ public final class StatusListener { public static void requestListener(@NotNull StatusRequestPacket packet, @NotNull PlayerConnection connection) { final ServerListPingType pingVersion = ServerListPingType.fromModernProtocolVersion(connection.getProtocolVersion()); - final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connection.minecraftServer, connection, pingVersion); - connection.minecraftServer.process().getGlobalEventHandler().callCancellable(statusRequestEvent, () -> + final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connection.getServerProcess(), connection, pingVersion); + connection.getServerProcess().getGlobalEventHandler().callCancellable(statusRequestEvent, () -> connection.sendPacket(new ResponsePacket(pingVersion.getPingResponse(statusRequestEvent.getResponseData())))); } public static void pingListener(@NotNull PingPacket packet, @NotNull PlayerConnection connection) { final ClientPingServerEvent clientPingEvent = new ClientPingServerEvent(connection, packet.number()); - connection.minecraftServer.process().getGlobalEventHandler().call(clientPingEvent); + connection.getServerProcess().getGlobalEventHandler().call(clientPingEvent); if (clientPingEvent.isCancelled()) { connection.disconnect(); @@ -30,7 +30,7 @@ public static void pingListener(@NotNull PingPacket packet, @NotNull PlayerConne connection.sendPacket(new PongPacket(clientPingEvent.getPayload())); connection.disconnect(); } else { - connection.minecraftServer.process().getSchedulerManager().buildTask(() -> { + connection.getServerProcess().getSchedulerManager().buildTask(() -> { connection.sendPacket(new PongPacket(clientPingEvent.getPayload())); connection.disconnect(); }).delay(clientPingEvent.getDelay()).schedule(); diff --git a/src/main/java/net/minestom/server/message/Messenger.java b/src/main/java/net/minestom/server/message/Messenger.java index 42636438e60..69dff6dba25 100644 --- a/src/main/java/net/minestom/server/message/Messenger.java +++ b/src/main/java/net/minestom/server/message/Messenger.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.SystemChatPacket; import net.minestom.server.utils.PacketUtils; @@ -93,9 +93,9 @@ public static boolean sendMessage(@NotNull Player player, @NotNull Component mes * @param position the position * @param uuid the UUID of the sender, if any */ - public static void sendMessage(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull Component message, + public static void sendMessage(ServerProcess serverProcess, @NotNull Collection players, @NotNull Component message, @NotNull ChatPosition position, @Nullable UUID uuid) { - PacketUtils.sendGroupedPacket(minecraftServer, players, new SystemChatPacket(message, false), + PacketUtils.sendGroupedPacket(serverProcess, players, new SystemChatPacket(message, false), player -> getChatMessageType(player).accepts(position)); } diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java index ab669fefc1e..9a16d8c2d56 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java @@ -5,7 +5,8 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; +import net.minestom.server.ServerProcess; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -22,9 +23,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import static net.minestom.server.MinecraftServer.THREAD_NAME_TICK; -import static net.minestom.server.MinecraftServer.THREAD_NAME_TICK_SCHEDULER; - /** * Small monitoring tools that can be used to check the current memory usage and Minestom threads CPU usage. *

    @@ -39,8 +37,8 @@ public final class BenchmarkManager { private static final List THREADS = new ArrayList<>(); static { - THREADS.add(THREAD_NAME_TICK_SCHEDULER); - THREADS.add(THREAD_NAME_TICK); + THREADS.add(ServerConsts.THREAD_NAME_TICK_SCHEDULER); + THREADS.add(ServerConsts.THREAD_NAME_TICK); } private final Long2LongMap lastCpuTimeMap = new Long2LongOpenHashMap(); @@ -52,10 +50,10 @@ public final class BenchmarkManager { private boolean enabled = false; private volatile boolean stop = false; private long time; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public BenchmarkManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public BenchmarkManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; } public void enable(@NotNull Duration duration) { @@ -77,11 +75,11 @@ public void enable(@NotNull Duration duration) { try { Thread.sleep(time); } catch (InterruptedException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } stop = false; - }, MinecraftServer.THREAD_NAME_BENCHMARK); + }, ServerConsts.THREAD_NAME_BENCHMARK); thread.setDaemon(true); thread.start(); diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index b7c4aba91e9..096481be06c 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -2,7 +2,6 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.entity.damage.DamageType; @@ -48,8 +47,6 @@ public final class ConnectionManager { private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class); public final CachedPacket defaultTags; - - private final MinecraftServer minecraftServer; private final ServerProcess serverProcess; private static final long KEEP_ALIVE_DELAY = 10_000; @@ -82,11 +79,10 @@ public final class ConnectionManager { private final PlayerProvider defaultPlayerProvider; private volatile PlayerProvider playerProvider; - public ConnectionManager(MinecraftServer minecraftServer, TagManager tagManager) { - this.minecraftServer = minecraftServer; - this.serverProcess = minecraftServer.process(); - this.defaultTags = new CachedPacket(minecraftServer, new TagsPacket(tagManager.getTagMap())); - defaultPlayerProvider = (uuid, username, connection) -> new Player(minecraftServer, uuid, username, connection); + public ConnectionManager(ServerProcess serverProcess, TagManager tagManager) { + this.serverProcess = serverProcess; + this.defaultTags = new CachedPacket(serverProcess, new TagsPacket(tagManager.getTagMap())); + defaultPlayerProvider = (uuid, username, connection) -> new Player(serverProcess, uuid, username, connection); playerProvider = defaultPlayerProvider; } @@ -231,18 +227,18 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { @ApiStatus.Internal public @NotNull CompletableFuture transitionLoginToConfig(@NotNull Player player) { - return AsyncUtils.runAsync(minecraftServer, () -> { + return AsyncUtils.runAsync(serverProcess, () -> { final PlayerConnection playerConnection = player.getPlayerConnection(); // Compression if (playerConnection instanceof PlayerSocketConnection socketConnection) { - final int threshold = minecraftServer.getCompressionThreshold(); + final int threshold = serverProcess.getMinecraftServer().getCompressionThreshold(); if (threshold > 0) socketConnection.startCompression(); } // Call pre login event AsyncPlayerPreLoginEvent asyncPlayerPreLoginEvent = new AsyncPlayerPreLoginEvent(player); - minecraftServer.process().getGlobalEventHandler().call(asyncPlayerPreLoginEvent); + serverProcess.getGlobalEventHandler().call(asyncPlayerPreLoginEvent); if (!player.isOnline()) return; // Player has been kicked @@ -278,11 +274,11 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { } player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); - CompletableFuture configFuture = AsyncUtils.runAsync(minecraftServer, () -> { - player.sendPacket(PluginMessagePacket.getBrandPacket(minecraftServer)); + CompletableFuture configFuture = AsyncUtils.runAsync(serverProcess, () -> { + player.sendPacket(PluginMessagePacket.getBrandPacket(serverProcess.getMinecraftServer())); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); - minecraftServer.process().getGlobalEventHandler().call(event); + serverProcess.getGlobalEventHandler().call(event); final Instance spawningInstance = event.getSpawningInstance(); Check.notNull(spawningInstance, "You need to specify a spawning instance in the AsyncPlayerConfigurationEvent"); diff --git a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java index fe39482bdec..b64c5f472a7 100644 --- a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java @@ -1,6 +1,6 @@ package net.minestom.server.network.packet.server; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.ApiStatus; @@ -22,15 +22,15 @@ public final class CachedPacket implements SendablePacket { private final Supplier packetSupplier; private volatile SoftReference packet; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; - public CachedPacket(MinecraftServer minecraftServer, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { + public CachedPacket(ServerProcess serverProcess, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { this.packetSupplier = packetSupplier; - this.minecraftServer = minecraftServer; + this.serverProcess = serverProcess; } - public CachedPacket(MinecraftServer minecraftServer, @NotNull ServerPacket packet) { - this(minecraftServer, () -> packet); + public CachedPacket(ServerProcess serverProcess, @NotNull ServerPacket packet) { + this(serverProcess, () -> packet); } public void invalidate() { @@ -53,7 +53,7 @@ public void invalidate() { SoftReference ref = packet; FramedPacket cache; if (ref == null || (cache = ref.get()) == null) { - cache = PacketUtils.allocateTrimmedPacket(minecraftServer, state, packetSupplier.get()); + cache = PacketUtils.allocateTrimmedPacket(serverProcess, state, packetSupplier.get()); this.packet = new SoftReference<>(cache); } return cache; diff --git a/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java b/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java index 2b830804af7..73d2d7d131b 100644 --- a/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/common/PluginMessagePacket.java @@ -1,6 +1,6 @@ package net.minestom.server.network.packet.server.common; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerSettings; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.server.ServerPacket; @@ -38,8 +38,8 @@ public int getId(@NotNull ConnectionState state) { * * @return the current brand name packet */ - public static @NotNull PluginMessagePacket getBrandPacket(MinecraftServer minecraftServer) { - final String brandName = minecraftServer.getBrandName(); + public static @NotNull PluginMessagePacket getBrandPacket(ServerSettings serverSettings) { + final String brandName = serverSettings.getBrandName(); final byte[] data = NetworkBuffer.makeArray(networkBuffer -> networkBuffer.write(STRING, brandName)); return new PluginMessagePacket("minecraft:brand", data); } diff --git a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java index e1d6387cd42..ea935f16761 100644 --- a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java @@ -1,6 +1,6 @@ package net.minestom.server.network.player; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.entity.fakeplayer.FakePlayer; import net.minestom.server.entity.fakeplayer.FakePlayerController; @@ -14,8 +14,8 @@ public class FakePlayerConnection extends PlayerConnection { - public FakePlayerConnection(MinecraftServer minecraftServer) { - super(minecraftServer); + public FakePlayerConnection(ServerProcess serverProcess) { + super(serverProcess); } @Override diff --git a/src/main/java/net/minestom/server/network/player/PlayerConnection.java b/src/main/java/net/minestom/server/network/player/PlayerConnection.java index f44bfd6402e..1083a975781 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerConnection.java @@ -1,6 +1,8 @@ package net.minestom.server.network.player; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; +import net.minestom.server.ServerObject; +import net.minestom.server.ServerProcess; import net.minestom.server.crypto.PlayerPublicKey; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; @@ -18,15 +20,15 @@ * A PlayerConnection is an object needed for all created {@link Player}. * It can be extended to create a new kind of player (NPC for instance). */ -public abstract class PlayerConnection { - public final MinecraftServer minecraftServer; +public abstract class PlayerConnection implements ServerObject { + private final ServerProcess serverProcess; private Player player; private volatile ConnectionState connectionState; private PlayerPublicKey playerPublicKey; volatile boolean online; - public PlayerConnection(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public PlayerConnection(ServerProcess serverProcess) { + this.serverProcess = serverProcess; this.online = true; this.connectionState = ConnectionState.HANDSHAKE; } @@ -74,7 +76,7 @@ public void sendPackets(@NotNull SendablePacket... packets) { * @return the protocol version */ public int getProtocolVersion() { - return MinecraftServer.PROTOCOL_VERSION; + return ServerConsts.PROTOCOL_VERSION; } /** @@ -85,7 +87,7 @@ public int getProtocolVersion() { * @return the server address used */ public @Nullable String getServerAddress() { - return minecraftServer.process().getServer().getAddress(); + return serverProcess.getServer().getAddress(); } @@ -97,7 +99,7 @@ public int getProtocolVersion() { * @return the server port used */ public int getServerPort() { - return minecraftServer.process().getServer().getPort(); + return serverProcess.getServer().getPort(); } /** @@ -105,7 +107,7 @@ public int getServerPort() { */ public void disconnect() { this.online = false; - minecraftServer.process().getConnectionManager().removePlayer(this); + serverProcess.getConnectionManager().removePlayer(this); final Player player = getPlayer(); if (player != null && !player.isRemoved()) { player.scheduleNextTick(Entity::remove); @@ -169,4 +171,9 @@ public String toString() { ", identifier=" + getIdentifier() + '}'; } + + @Override + public ServerProcess getServerProcess() { + return serverProcess; + } } diff --git a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java index e23d4d16a3e..5fc0e7d72a9 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java @@ -1,6 +1,6 @@ package net.minestom.server.network.player; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.entity.Player; import net.minestom.server.event.ListenerHandle; @@ -75,13 +75,13 @@ public class PlayerSocketConnection extends PlayerConnection { private final ListenerHandle outgoing; - public PlayerSocketConnection(@NotNull MinecraftServer minecraftServer, @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { - super(minecraftServer); + public PlayerSocketConnection(@NotNull ServerProcess serverProcess, @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { + super(serverProcess); this.worker = worker; this.workerQueue = worker.queue(); this.channel = channel; this.remoteAddress = remoteAddress; - this.outgoing = minecraftServer.process().getGlobalEventHandler().getHandle(PlayerPacketOutEvent.class); + this.outgoing = serverProcess.getGlobalEventHandler().getHandle(PlayerPacketOutEvent.class); } public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProcessor) { @@ -93,7 +93,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces try { encryptionContext.decrypt().update(input, input.duplicate()); } catch (ShortBufferException e) { - minecraftServer.process().getExceptionManager().handleException(e); + getServerProcess().getExceptionManager().handleException(e); return; } } @@ -109,7 +109,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces packet = packetProcessor.process(this, id, payload); } catch (Exception e) { // Error while reading the packet - minecraftServer.process().getExceptionManager().handleException(e); + getServerProcess().getExceptionManager().handleException(e); } finally { if (payload.position() != payload.limit()) { LOGGER.warn("WARNING: Packet ({}) 0x{} not fully read ({}) {}", getConnectionState(), Integer.toHexString(id), payload, packet); @@ -117,7 +117,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces } }); } catch (DataFormatException e) { - minecraftServer.process().getExceptionManager().handleException(e); + getServerProcess().getExceptionManager().handleException(e); disconnect(); } } @@ -138,7 +138,7 @@ public void consumeCache(BinaryBuffer buffer) { */ public void setEncryptionKey(@NotNull SecretKey secretKey) { Check.stateCondition(encryptionContext != null, "Encryption is already enabled!"); - MojangCrypt mojangCrypt = minecraftServer.process().getMojangAuth().getMojangCrypt(); + MojangCrypt mojangCrypt = getServerProcess().getMojangAuth().getMojangCrypt(); this.encryptionContext = new EncryptionContext(mojangCrypt.getCipher(1, secretKey), mojangCrypt.getCipher(2, secretKey)); } @@ -149,7 +149,7 @@ public void setEncryptionKey(@NotNull SecretKey secretKey) { */ public void startCompression() { Check.stateCondition(compressed, "Compression is already enabled!"); - final int threshold = minecraftServer.getCompressionThreshold(); + final int threshold = getServerProcess().getMinecraftServer().getCompressionThreshold(); Check.stateCondition(threshold == 0, "Compression cannot be enabled because the threshold is equal to 0"); sendPacket(new SetCompressionPacket(threshold)); this.compressed = true; @@ -370,7 +370,7 @@ private void writeServerPacketSync(ServerPacket serverPacket, boolean compressed } } try (var hold = ObjectPool.PACKET_POOL.hold()) { - var buffer = PacketUtils.createFramedPacket(minecraftServer, getConnectionState(), hold.get(), serverPacket, compressed); + var buffer = PacketUtils.createFramedPacket(getServerProcess(), getConnectionState(), hold.get(), serverPacket, compressed); writeBufferSync(buffer, 0, buffer.limit()); } } @@ -385,7 +385,7 @@ private void writeBufferSync(@NotNull ByteBuffer buffer, int index, int length) length = encryptionContext.encrypt().update(buffer.slice(index, length), output); writeBufferSync0(output, 0, length); } catch (ShortBufferException e) { - minecraftServer.process().getExceptionManager().handleException(e); + getServerProcess().getExceptionManager().handleException(e); } return; } diff --git a/src/main/java/net/minestom/server/network/socket/Server.java b/src/main/java/net/minestom/server/network/socket/Server.java index 5f6eb95d55d..b27332b91e7 100644 --- a/src/main/java/net/minestom/server/network/socket/Server.java +++ b/src/main/java/net/minestom/server/network/socket/Server.java @@ -1,6 +1,6 @@ package net.minestom.server.network.socket; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.PacketProcessor; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -25,8 +25,8 @@ public final class Server { private volatile boolean stop; - private final Selector selector = Selector.open(); - private final MinecraftServer minecraftServer; + private final Selector selector; + private final ServerProcess serverProcess; private final PacketProcessor packetProcessor; private final List workers; private int index; @@ -36,12 +36,17 @@ public final class Server { private String address; private int port; - public Server(MinecraftServer minecraftServer, PacketProcessor packetProcessor) throws IOException { - this.minecraftServer = minecraftServer; + public Server(ServerProcess serverProcess, PacketProcessor packetProcessor) { + this.serverProcess = serverProcess; this.packetProcessor = packetProcessor; Worker[] workers = new Worker[WORKER_COUNT]; - Arrays.setAll(workers, value -> new Worker(minecraftServer,this)); + Arrays.setAll(workers, value -> new Worker(serverProcess,this)); this.workers = List.of(workers); + try { + this.selector = Selector.open(); + } catch (IOException e) { + throw new RuntimeException(e); + } } @ApiStatus.Internal @@ -90,7 +95,7 @@ public void start() { } }); } catch (IOException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } }, "Ms-entrypoint").start(); @@ -115,7 +120,7 @@ public void stop() { Files.deleteIfExists(unixDomainSocketAddress.getPath()); } } catch (IOException e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } this.selector.wakeup(); this.workers.forEach(worker -> worker.selector.wakeup()); diff --git a/src/main/java/net/minestom/server/network/socket/Worker.java b/src/main/java/net/minestom/server/network/socket/Worker.java index 7123ebd7c77..a8bcabc4fe9 100644 --- a/src/main/java/net/minestom/server/network/socket/Worker.java +++ b/src/main/java/net/minestom/server/network/socket/Worker.java @@ -1,6 +1,6 @@ package net.minestom.server.network.socket; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.thread.MinestomThread; import net.minestom.server.utils.ObjectPool; @@ -25,13 +25,13 @@ public final class Worker extends MinestomThread { final Selector selector; private final Map connectionMap = new ConcurrentHashMap<>(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final Server server; private final MpscUnboundedXaddArrayQueue queue = new MpscUnboundedXaddArrayQueue<>(1024); - Worker(MinecraftServer minecraftServer, Server server) { + Worker(ServerProcess serverProcess, Server server) { super("Ms-worker-" + COUNTER.getAndIncrement()); - this.minecraftServer = minecraftServer; + this.serverProcess = serverProcess; this.server = server; try { this.selector = Selector.open(); @@ -51,7 +51,7 @@ public void run() { try { this.queue.drain(Runnable::run); } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } // Flush all connections if needed for (PlayerSocketConnection connection : connectionMap.values()) { @@ -88,12 +88,12 @@ public void run() { // TODO print exception? (should ignore disconnection) connection.disconnect(); } catch (Throwable t) { - minecraftServer.process().getExceptionManager().handleException(t); + serverProcess.getExceptionManager().handleException(t); connection.disconnect(); } }); } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } } @@ -113,7 +113,7 @@ public void disconnect(PlayerSocketConnection connection, SocketChannel channel) } void receiveConnection(SocketChannel channel) throws IOException { - this.connectionMap.put(channel, new PlayerSocketConnection(minecraftServer, this, channel, channel.getRemoteAddress())); + this.connectionMap.put(channel, new PlayerSocketConnection(serverProcess, this, channel, channel.getRemoteAddress())); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); if (channel.getLocalAddress() instanceof InetSocketAddress) { diff --git a/src/main/java/net/minestom/server/ping/ResponseData.java b/src/main/java/net/minestom/server/ping/ResponseData.java index 85fb2b3d789..188e7992927 100644 --- a/src/main/java/net/minestom/server/ping/ResponseData.java +++ b/src/main/java/net/minestom/server/ping/ResponseData.java @@ -4,7 +4,8 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.utils.identity.NamedAndIdentified; @@ -22,7 +23,7 @@ public class ResponseData { private final List entries; @NotNull - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private String version; private int protocol; @@ -35,12 +36,12 @@ public class ResponseData { /** * Constructs a new {@link ResponseData}. */ - public ResponseData(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public ResponseData(ServerProcess serverProcess) { + this.serverProcess = serverProcess; this.entries = new ArrayList<>(); - this.version = MinecraftServer.VERSION_NAME; - this.protocol = MinecraftServer.PROTOCOL_VERSION; - this.online = minecraftServer.process().getConnectionManager().getOnlinePlayerCount(); + this.version = ServerConsts.VERSION_NAME; + this.protocol = ServerConsts.PROTOCOL_VERSION; + this.online = serverProcess.getConnectionManager().getOnlinePlayerCount(); this.maxPlayer = this.online + 1; this.description = DEFAULT_DESCRIPTION; this.favicon = ""; @@ -316,6 +317,10 @@ public boolean arePlayersHidden() { return playersHidden; } + public ServerProcess getServerProcess() { + return serverProcess; + } + /** * Converts the response data into a {@link JsonObject}. * @@ -327,10 +332,6 @@ public boolean arePlayersHidden() { return ServerListPingType.getModernPingResponse(this, true); } - public MinecraftServer getMinecraftServer() { - return minecraftServer; - } - /** * Represents a player line in the server list hover. * diff --git a/src/main/java/net/minestom/server/ping/ServerListPingType.java b/src/main/java/net/minestom/server/ping/ServerListPingType.java index 91cfbb1ca09..473a206936d 100644 --- a/src/main/java/net/minestom/server/ping/ServerListPingType.java +++ b/src/main/java/net/minestom/server/ping/ServerListPingType.java @@ -74,7 +74,7 @@ public enum ServerListPingType { * @see OpenToLAN */ public static @NotNull String getOpenToLANPing(@NotNull ResponseData data) { - return String.format(LAN_PING_FORMAT, SECTION.serialize(data.getDescription()), data.getMinecraftServer().process().getServer().getPort()); + return String.format(LAN_PING_FORMAT, SECTION.serialize(data.getDescription()), data.getServerProcess().getServer().getPort()); } /** diff --git a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java index 682807f224d..24755820131 100644 --- a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java +++ b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java @@ -1,7 +1,7 @@ package net.minestom.server.scoreboard; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket; import org.jetbrains.annotations.NotNull; @@ -22,7 +22,7 @@ public class BelowNameTag implements Scoreboard { private final Set viewers = new CopyOnWriteArraySet<>(); private final Set unmodifiableViewers = Collections.unmodifiableSet(viewers); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final String objectiveName; private final ScoreboardObjectivePacket scoreboardObjectivePacket; @@ -32,11 +32,11 @@ public class BelowNameTag implements Scoreboard { * * @param name The objective name of the scoreboard * @param value The value of the scoreboard - * @deprecated Use {@link #BelowNameTag(MinecraftServer, String, Component)} + * @deprecated Use {@link #BelowNameTag(ServerProcess, String, Component)} */ @Deprecated - public BelowNameTag(MinecraftServer minecraftServer, String name, String value) { - this(minecraftServer, name, Component.text(value)); + public BelowNameTag(ServerProcess serverProcess, String name, String value) { + this(serverProcess, name, Component.text(value)); } /** @@ -45,8 +45,8 @@ public BelowNameTag(MinecraftServer minecraftServer, String name, String value) * @param name The objective name of the scoreboard * @param value The value of the scoreboard */ - public BelowNameTag(MinecraftServer minecraftServer, String name, Component value) { - this.minecraftServer = minecraftServer; + public BelowNameTag(ServerProcess serverProcess, String name, Component value) { + this.serverProcess = serverProcess; this.objectiveName = BELOW_NAME_TAG_PREFIX + name; this.scoreboardObjectivePacket = this.getCreationObjectivePacket(value, ScoreboardObjectivePacket.Type.INTEGER); } @@ -84,7 +84,7 @@ public Set getViewers() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/scoreboard/Sidebar.java b/src/main/java/net/minestom/server/scoreboard/Sidebar.java index 8c2a7558e53..de26e753ab5 100644 --- a/src/main/java/net/minestom/server/scoreboard/Sidebar.java +++ b/src/main/java/net/minestom/server/scoreboard/Sidebar.java @@ -3,7 +3,7 @@ import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.server.play.*; @@ -20,7 +20,7 @@ /** * Represents a sidebar which can contain up to 16 {@link ScoreboardLine}. *

    - * In order to use it you need to create a new instance using the constructor {@link #Sidebar(MinecraftServer, String)} and create new lines + * In order to use it you need to create a new instance using the constructor {@link #Sidebar(ServerProcess, String)} and create new lines * with {@link #createLine(ScoreboardLine)}. You can then add a {@link Player} to the viewing list using {@link #addViewer(Player)} * and remove him later with {@link #removeViewer(Player)}. *

    @@ -49,18 +49,18 @@ public class Sidebar implements Scoreboard { private final String objectiveName; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private Component title; /** * Creates a new sidebar * * @param title The title of the sidebar - * @deprecated Use {@link #Sidebar(MinecraftServer, Component)} + * @deprecated Use {@link #Sidebar(ServerProcess, Component)} */ @Deprecated - public Sidebar(MinecraftServer minecraftServer, @NotNull String title) { - this(minecraftServer, Component.text(title)); + public Sidebar(ServerProcess serverProcess, @NotNull String title) { + this(serverProcess, Component.text(title)); } /** @@ -68,8 +68,8 @@ public Sidebar(MinecraftServer minecraftServer, @NotNull String title) { * * @param title The title of the sidebar */ - public Sidebar(MinecraftServer minecraftServer, @NotNull Component title) { - this.minecraftServer = minecraftServer; + public Sidebar(ServerProcess serverProcess, @NotNull Component title) { + this.serverProcess = serverProcess; this.title = title; this.objectiveName = SCOREBOARD_PREFIX + COUNTER.incrementAndGet(); @@ -245,8 +245,8 @@ public Set getViewers() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } /** diff --git a/src/main/java/net/minestom/server/scoreboard/TabList.java b/src/main/java/net/minestom/server/scoreboard/TabList.java index 9c1246082dd..34171d17527 100644 --- a/src/main/java/net/minestom/server/scoreboard/TabList.java +++ b/src/main/java/net/minestom/server/scoreboard/TabList.java @@ -1,7 +1,7 @@ package net.minestom.server.scoreboard; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.PlayerListHeaderAndFooterPacket; import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket; @@ -27,7 +27,7 @@ public class TabList implements Scoreboard { private final Set viewers = new CopyOnWriteArraySet<>(); private final Set unmodifiableViewers = Collections.unmodifiableSet(viewers); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private final String objectiveName; private Component header = Component.empty(); @@ -35,8 +35,8 @@ public class TabList implements Scoreboard { private ScoreboardObjectivePacket.Type type; - public TabList(MinecraftServer minecraftServer, String name, ScoreboardObjectivePacket.Type type) { - this.minecraftServer = minecraftServer; + public TabList(ServerProcess serverProcess, String name, ScoreboardObjectivePacket.Type type) { + this.serverProcess = serverProcess; this.objectiveName = TAB_LIST_PREFIX + name; this.type = type; @@ -102,7 +102,7 @@ public String getObjectiveName() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/scoreboard/Team.java b/src/main/java/net/minestom/server/scoreboard/Team.java index a20d48eada4..8e38a0debf1 100644 --- a/src/main/java/net/minestom/server/scoreboard/Team.java +++ b/src/main/java/net/minestom/server/scoreboard/Team.java @@ -4,7 +4,7 @@ import net.kyori.adventure.pointer.Pointers; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.adventure.audience.PacketGroupingAudience; import net.minestom.server.entity.LivingEntity; import net.minestom.server.entity.Player; @@ -75,15 +75,15 @@ public class Team implements PacketGroupingAudience { // Adventure private final Pointers pointers; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; /** * Default constructor to creates a team. * * @param teamName The registry name for the team */ - protected Team(MinecraftServer minecraftServer, @NotNull String teamName) { - this.minecraftServer = minecraftServer; + protected Team(ServerProcess serverProcess, @NotNull String teamName) { + this.serverProcess = serverProcess; this.teamName = teamName; this.teamDisplayName = Component.empty(); @@ -131,7 +131,7 @@ public void addMembers(@NotNull Collection<@NotNull String> toAdd) { final TeamsPacket addPlayerPacket = new TeamsPacket(teamName, new TeamsPacket.AddEntitiesToTeamAction(toAdd)); // Sends to all online players the add player packet - PacketUtils.broadcastPlayPacket(minecraftServer, addPlayerPacket); + PacketUtils.broadcastPlayPacket(serverProcess, addPlayerPacket); // invalidate player members this.isPlayerMembersUpToDate = false; @@ -162,7 +162,7 @@ public void removeMembers(@NotNull Collection<@NotNull String> toRemove) { final TeamsPacket removePlayerPacket = new TeamsPacket(teamName, new TeamsPacket.RemoveEntitiesToTeamAction(toRemove)); // Sends to all online player the remove player packet - PacketUtils.broadcastPlayPacket(minecraftServer, removePlayerPacket); + PacketUtils.broadcastPlayPacket(getServerProcess(), removePlayerPacket); // Removes the member from the team this.members.removeAll(toRemove); @@ -466,7 +466,7 @@ public Component getSuffix() { public void sendUpdatePacket() { final var info = new TeamsPacket.UpdateTeamAction(teamDisplayName, friendlyFlags, nameTagVisibility, collisionRule, teamColor, prefix, suffix); - PacketUtils.broadcastPlayPacket(minecraftServer, new TeamsPacket(teamName, info)); + PacketUtils.broadcastPlayPacket(serverProcess, new TeamsPacket(teamName, info)); } @Override @@ -475,7 +475,7 @@ public void sendUpdatePacket() { this.playerMembers.clear(); for (String member : this.members) { - Player player = minecraftServer.process().getConnectionManager().getOnlinePlayerByUsername(member); + Player player = getServerProcess().getConnectionManager().getOnlinePlayerByUsername(member); if (player != null) { this.playerMembers.add(player); @@ -494,7 +494,7 @@ public void sendUpdatePacket() { } @Override - public MinecraftServer getMinecraftServer() { - return minecraftServer; + public ServerProcess getServerProcess() { + return serverProcess; } } diff --git a/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java b/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java index ab9ed47ddb0..d5fa2874b02 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.network.packet.server.play.TeamsPacket.CollisionRule; import net.minestom.server.network.packet.server.play.TeamsPacket.NameTagVisibility; @@ -30,8 +30,8 @@ public class TeamBuilder { * @param name The name of the new team * @param teamManager The manager for the team */ - public TeamBuilder(MinecraftServer minecraftServer, String name, TeamManager teamManager) { - this(teamManager.exists(name) ? teamManager.getTeam(name) : new Team(minecraftServer, name), teamManager); + public TeamBuilder(ServerProcess serverProcess, String name, TeamManager teamManager) { + this(teamManager.exists(name) ? teamManager.getTeam(name) : new Team(serverProcess, name), teamManager); } /** diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManager.java b/src/main/java/net/minestom/server/scoreboard/TeamManager.java index 7db8303f397..5523d63afe1 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamManager.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamManager.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.LivingEntity; import net.minestom.server.entity.Player; import net.minestom.server.utils.PacketUtils; @@ -23,13 +23,13 @@ public final class TeamManager { * Represents all registered teams */ private final Set teams; - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; /** * Default constructor */ - public TeamManager(MinecraftServer minecraftServer) { - this.minecraftServer = minecraftServer; + public TeamManager(ServerProcess serverProcess) { + this.serverProcess = serverProcess; this.teams = new CopyOnWriteArraySet<>(); } @@ -40,7 +40,7 @@ public TeamManager(MinecraftServer minecraftServer) { */ protected void registerNewTeam(@NotNull Team team) { this.teams.add(team); - PacketUtils.broadcastPlayPacket(minecraftServer, team.createTeamsCreationPacket()); + PacketUtils.broadcastPlayPacket(serverProcess, team.createTeamsCreationPacket()); } /** @@ -63,7 +63,7 @@ public boolean deleteTeam(@NotNull String registryName) { */ public boolean deleteTeam(@NotNull Team team) { // Sends to all online players a team destroy packet - PacketUtils.broadcastPlayPacket(minecraftServer, team.createTeamDestructionPacket()); + PacketUtils.broadcastPlayPacket(serverProcess, team.createTeamDestructionPacket()); return this.teams.remove(team); } @@ -74,7 +74,7 @@ public boolean deleteTeam(@NotNull Team team) { * @return the team builder */ public TeamBuilder createBuilder(@NotNull String name) { - return new TeamBuilder(minecraftServer, name, this); + return new TeamBuilder(serverProcess, name, this); } /** diff --git a/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java b/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java index 49bd20f4794..6bf75e3e9df 100644 --- a/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java +++ b/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java @@ -1,8 +1,6 @@ - - package net.minestom.server.snapshot; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.UnknownNullability; @@ -12,8 +10,7 @@ /** * Represents the complete state of the server at a given moment. */ -public sealed interface ServerSnapshot extends Snapshot - permits SnapshotImpl.Server { +public sealed interface ServerSnapshot extends Snapshot permits SnapshotImpl.Server { @NotNull Collection<@NotNull InstanceSnapshot> instances(); @NotNull Collection entities(); @@ -21,7 +18,7 @@ public sealed interface ServerSnapshot extends Snapshot @UnknownNullability EntitySnapshot entity(int id); @ApiStatus.Experimental - static ServerSnapshot update(MinecraftServer minecraftServer) { - return SnapshotUpdater.update(minecraftServer.process()); + static ServerSnapshot update(ServerProcess serverProcess) { + return SnapshotUpdater.update(serverProcess); } } diff --git a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java index 3592e350d36..d0fbd45860f 100644 --- a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java +++ b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java @@ -1,7 +1,7 @@ package net.minestom.server.snapshot; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.EntityType; @@ -75,7 +75,7 @@ public record Instance(AtomicReference serverRef, } } - public record Chunk(MinecraftServer minecraftServer, + public record Chunk(ServerProcess serverProcess, int minSection, int chunkX, int chunkZ, Section[] sections, Int2ObjectOpenHashMap blockEntries, @@ -104,7 +104,7 @@ public record Chunk(MinecraftServer minecraftServer, final Section section = sections[getChunkCoordinate(y) - minSection]; final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return minecraftServer.process().getBiomeManager().getById(id); + return serverProcess.getBiomeManager().getById(id); } @Override diff --git a/src/main/java/net/minestom/server/thread/Acquirable.java b/src/main/java/net/minestom/server/thread/Acquirable.java index b0b5ad6ca00..52718866dcd 100644 --- a/src/main/java/net/minestom/server/thread/Acquirable.java +++ b/src/main/java/net/minestom/server/thread/Acquirable.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.entity.Entity; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.ApiStatus; @@ -99,7 +99,7 @@ default boolean isLocal() { * Free if the element is already present in the current thread, blocking otherwise. * * @param consumer the callback to execute once the element has been safely acquired - * @see #async(MinecraftServer, Consumer) + * @see #async(ServerProcess, Consumer) */ default void sync(@NotNull Consumer consumer) { Acquired acquired = lock(); @@ -113,9 +113,9 @@ default void sync(@NotNull Consumer consumer) { * @param consumer the callback to execute once the element has been safely acquired * @see #sync(Consumer) */ - default void async(MinecraftServer minecraftServer, @NotNull Consumer consumer) { + default void async(ServerProcess serverProcess, @NotNull Consumer consumer) { // TODO per-thread list - AsyncUtils.runAsync(minecraftServer, () -> sync(consumer)); + AsyncUtils.runAsync(serverProcess, () -> sync(consumer)); } /** diff --git a/src/main/java/net/minestom/server/thread/AcquirableCollection.java b/src/main/java/net/minestom/server/thread/AcquirableCollection.java index db1946d2dc1..a63ac25e031 100644 --- a/src/main/java/net/minestom/server/thread/AcquirableCollection.java +++ b/src/main/java/net/minestom/server/thread/AcquirableCollection.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -36,8 +36,8 @@ public void acquireSync(@NotNull Consumer consumer) { } } - public void acquireAsync(MinecraftServer minecraftServer, @NotNull Consumer consumer) { - AsyncUtils.runAsync(minecraftServer, () -> acquireSync(consumer)); + public void acquireAsync(ServerProcess serverProcess, @NotNull Consumer consumer) { + AsyncUtils.runAsync(serverProcess, () -> acquireSync(consumer)); } public @NotNull Stream unwrap() { diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java index fb35ea87c6c..80a1bbbc3c9 100644 --- a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; import org.jctools.queues.MessagePassingQueue; @@ -31,20 +31,20 @@ public final class ThreadDispatcher

    { // Requests consumed at the end of each tick private final MessagePassingQueue> updates = new MpscUnboundedArrayQueue<>(1024); - private ThreadDispatcher(MinecraftServer minecraftServer, ThreadProvider

    provider, int threadCount) { + private ThreadDispatcher(ServerProcess serverProcess, ThreadProvider

    provider, int threadCount) { this.provider = provider; TickThread[] threads = new TickThread[threadCount]; - Arrays.setAll(threads, (i) -> new TickThread(minecraftServer, i)); + Arrays.setAll(threads, (i) -> new TickThread(serverProcess, i)); this.threads = List.of(threads); this.threads.forEach(Thread::start); } - public static

    @NotNull ThreadDispatcher

    of(MinecraftServer minecraftServer,@NotNull ThreadProvider

    provider, int threadCount) { - return new ThreadDispatcher<>(minecraftServer, provider, threadCount); + public static

    @NotNull ThreadDispatcher

    of(ServerProcess serverProcess,@NotNull ThreadProvider

    provider, int threadCount) { + return new ThreadDispatcher<>(serverProcess, provider, threadCount); } - public static

    @NotNull ThreadDispatcher

    singleThread(MinecraftServer minecraftServer) { - return of(minecraftServer, ThreadProvider.counter(), 1); + public static

    @NotNull ThreadDispatcher

    singleThread(ServerProcess serverProcess) { + return of(serverProcess, ThreadProvider.counter(), 1); } @Unmodifiable diff --git a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java index a1f0378de5b..7b7bf3595cb 100644 --- a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java +++ b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; import net.minestom.server.ServerProcess; import org.jetbrains.annotations.ApiStatus; @@ -14,13 +14,13 @@ public final class TickSchedulerThread extends MinestomThread { private long tick = 1; public TickSchedulerThread(ServerProcess serverProcess) { - super(MinecraftServer.THREAD_NAME_TICK_SCHEDULER); + super(ServerConsts.THREAD_NAME_TICK_SCHEDULER); this.serverProcess = serverProcess; } @Override public void run() { - final long tickNs = (long) (MinecraftServer.TICK_MS * 1e6); + final long tickNs = (long) (serverProcess.getMinecraftServer().getTickMs() * 1e6); while (serverProcess.isAlive()) { final long tickStart = System.nanoTime(); try { diff --git a/src/main/java/net/minestom/server/thread/TickThread.java b/src/main/java/net/minestom/server/thread/TickThread.java index 1316d8a9b87..e07ce83849f 100644 --- a/src/main/java/net/minestom/server/thread/TickThread.java +++ b/src/main/java/net/minestom/server/thread/TickThread.java @@ -1,6 +1,7 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerConsts; +import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; import net.minestom.server.instance.Chunk; @@ -23,7 +24,7 @@ @ApiStatus.Internal public final class TickThread extends MinestomThread { private final ReentrantLock lock = new ReentrantLock(); - private final MinecraftServer minecraftServer; + private final ServerProcess serverProcess; private volatile boolean stop; private CountDownLatch latch; @@ -31,9 +32,9 @@ public final class TickThread extends MinestomThread { private long tickNum = 0; private final List entries = new ArrayList<>(); - public TickThread(MinecraftServer minecraftServer, int number) { - super(MinecraftServer.THREAD_NAME_TICK + "-" + number); - this.minecraftServer = minecraftServer; + public TickThread(ServerProcess serverProcess, int number) { + super(ServerConsts.THREAD_NAME_TICK + "-" + number); + this.serverProcess = serverProcess; } public static @Nullable TickThread current() { @@ -50,7 +51,7 @@ public void run() { try { tick(); } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } this.lock.unlock(); // #acquire() callbacks @@ -75,7 +76,7 @@ private void tick() { try { element.tick(tickTime); } catch (Throwable e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } } } diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index 58b8159eac6..15b6f81940f 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -10,7 +10,7 @@ import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TranslatableComponent; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.adventure.ComponentHolder; import net.minestom.server.adventure.MinestomAdventure; @@ -67,7 +67,7 @@ private PacketUtils() { *

      *
    1. If {@code audience} is a {@link Player}, send the packet to them.
    2. *
    3. Otherwise, if {@code audience} is a {@link PacketGroupingAudience}, call - * {@link #sendGroupedPacket(MinecraftServer, Collection, ServerPacket)} on the players that the + * {@link #sendGroupedPacket(ServerProcess, Collection, ServerPacket)} on the players that the * grouping audience contains.
    4. *
    5. Otherwise, if {@code audience} is a {@link ForwardingAudience.Single}, * call this method on the single audience inside the forwarding audience.
    6. @@ -80,16 +80,16 @@ private PacketUtils() { * @param packet the packet */ @SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience - public static void sendPacket(MinecraftServer minecraftServer, @NotNull Audience audience, @NotNull ServerPacket packet) { + public static void sendPacket(ServerProcess serverProcess, @NotNull Audience audience, @NotNull ServerPacket packet) { if (audience instanceof Player player) { player.sendPacket(packet); } else if (audience instanceof PacketGroupingAudience groupingAudience) { - PacketUtils.sendGroupedPacket(minecraftServer, groupingAudience.getPlayers(), packet); + PacketUtils.sendGroupedPacket(serverProcess, groupingAudience.getPlayers(), packet); } else if (audience instanceof ForwardingAudience.Single singleAudience) { - PacketUtils.sendPacket(minecraftServer, singleAudience.audience(), packet); + PacketUtils.sendPacket(serverProcess, singleAudience.audience(), packet); } else if (audience instanceof ForwardingAudience forwardingAudience) { for (Audience member : forwardingAudience.audiences()) { - PacketUtils.sendPacket(minecraftServer, member, packet); + PacketUtils.sendPacket(serverProcess, member, packet); } } } @@ -103,9 +103,9 @@ public static void sendPacket(MinecraftServer minecraftServer, @NotNull Audience * @param packet the packet to send to the players * @param predicate predicate to ignore specific players */ - public static void sendGroupedPacket(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull ServerPacket packet, + public static void sendGroupedPacket(ServerProcess serverProcess, @NotNull Collection players, @NotNull ServerPacket packet, @NotNull Predicate predicate) { - final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(minecraftServer, packet) : packet; + final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(serverProcess, packet) : packet; players.forEach(player -> { if (predicate.test(player)) player.sendPacket(sendablePacket); @@ -146,21 +146,21 @@ private static boolean isTranslatable(final @NotNull Component component) { } /** - * Same as {@link #sendGroupedPacket(MinecraftServer, Collection, ServerPacket, Predicate)} + * Same as {@link #sendGroupedPacket(ServerProcess, Collection, ServerPacket, Predicate)} * but with the player validator sets to null. * - * @see #sendGroupedPacket(MinecraftServer, Collection, ServerPacket, Predicate) + * @see #sendGroupedPacket(ServerProcess, Collection, ServerPacket, Predicate) */ - public static void sendGroupedPacket(MinecraftServer minecraftServer, @NotNull Collection players, @NotNull ServerPacket packet) { - sendGroupedPacket(minecraftServer, players, packet, player -> true); + public static void sendGroupedPacket(ServerProcess serverProcess, @NotNull Collection players, @NotNull ServerPacket packet) { + sendGroupedPacket(serverProcess, players, packet, player -> true); } - public static void broadcastPlayPacket(MinecraftServer minecraftServer, @NotNull ServerPacket packet) { - sendGroupedPacket(minecraftServer, minecraftServer.process().getConnectionManager().getOnlinePlayers(), packet); + public static void broadcastPlayPacket(ServerProcess serverProcess, @NotNull ServerPacket packet) { + sendGroupedPacket(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers(), packet); } @ApiStatus.Experimental - public static void prepareViewablePacket(MinecraftServer minecraftServer, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket, + public static void prepareViewablePacket(ServerProcess serverProcess, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket, @Nullable Entity entity) { if (entity != null && !entity.hasPredictableViewers()) { // Operation cannot be optimized @@ -168,17 +168,17 @@ public static void prepareViewablePacket(MinecraftServer minecraftServer, @NotNu return; } if (!VIEWABLE_PACKET) { - sendGroupedPacket(minecraftServer, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); + sendGroupedPacket(serverProcess, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); return; } final Player exception = entity instanceof Player ? (Player) entity : null; ViewableStorage storage = VIEWABLE_STORAGE_MAP.get(viewable, (unused) -> new ViewableStorage()); - storage.append(minecraftServer, viewable, serverPacket, exception); + storage.append(serverProcess, viewable, serverPacket, exception); } @ApiStatus.Experimental - public static void prepareViewablePacket(MinecraftServer minecraftServer, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { - prepareViewablePacket(minecraftServer, viewable, serverPacket, null); + public static void prepareViewablePacket(ServerProcess serverProcess, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { + prepareViewablePacket(serverProcess, viewable, serverPacket, null); } @ApiStatus.Internal @@ -246,13 +246,13 @@ public static void flush() { return remaining; } - public static void writeFramedPacket(MinecraftServer minecraftServer, + public static void writeFramedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { writeFramedPacket(buffer, packet.getId(state), packet, - compression ? minecraftServer.getCompressionThreshold() : 0); + compression ? serverProcess.getMinecraftServer().getCompressionThreshold() : 0); } public static void writeFramedPacket(@NotNull ByteBuffer buffer, @@ -300,20 +300,20 @@ public static void writeFramedPacket(@NotNull ByteBuffer buffer, } @ApiStatus.Internal - public static ByteBuffer createFramedPacket(MinecraftServer minecraftServer, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { - writeFramedPacket(minecraftServer, state, buffer, packet, compression); + public static ByteBuffer createFramedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { + writeFramedPacket(serverProcess, state, buffer, packet, compression); return buffer.flip(); } @ApiStatus.Internal - public static ByteBuffer createFramedPacket(MinecraftServer minecraftServer, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet) { - return createFramedPacket(minecraftServer, state, buffer, packet, minecraftServer.getCompressionThreshold() > 0); + public static ByteBuffer createFramedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet) { + return createFramedPacket(serverProcess, state, buffer, packet, serverProcess.getMinecraftServer().getCompressionThreshold() > 0); } @ApiStatus.Internal - public static FramedPacket allocateTrimmedPacket(MinecraftServer minecraftServer, @NotNull ConnectionState state, @NotNull ServerPacket packet) { + public static FramedPacket allocateTrimmedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ServerPacket packet) { try (var hold = ObjectPool.PACKET_POOL.hold()) { - final ByteBuffer temp = PacketUtils.createFramedPacket(minecraftServer, state, hold.get(), packet); + final ByteBuffer temp = PacketUtils.createFramedPacket(serverProcess, state, hold.get(), packet); final int size = temp.remaining(); final ByteBuffer buffer = ByteBuffer.allocateDirect(size).put(0, temp, 0, size); return new FramedPacket(packet, buffer); @@ -325,10 +325,10 @@ private static final class ViewableStorage { private final Int2ObjectMap entityIdMap = new Int2ObjectOpenHashMap<>(); private final BinaryBuffer buffer = ObjectPool.BUFFER_POOL.getAndRegister(this); - private synchronized void append(MinecraftServer minecraftServer, Viewable viewable, ServerPacket serverPacket, @Nullable Player exception) { + private synchronized void append(ServerProcess serverProcess, Viewable viewable, ServerPacket serverPacket, @Nullable Player exception) { try (var hold = ObjectPool.PACKET_POOL.hold()) { // Viewable storage is only used for play packets, so fine to assume this. - final ByteBuffer framedPacket = createFramedPacket(minecraftServer, ConnectionState.PLAY, hold.get(), serverPacket); + final ByteBuffer framedPacket = createFramedPacket(serverProcess, ConnectionState.PLAY, hold.get(), serverPacket); final int packetSize = framedPacket.limit(); if (packetSize >= buffer.capacity()) { process(viewable); diff --git a/src/main/java/net/minestom/server/utils/TickUtils.java b/src/main/java/net/minestom/server/utils/TickUtils.java index 84ac9ec1436..88b40a5b6fd 100644 --- a/src/main/java/net/minestom/server/utils/TickUtils.java +++ b/src/main/java/net/minestom/server/utils/TickUtils.java @@ -1,6 +1,6 @@ package net.minestom.server.utils; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerSettings; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -21,14 +21,14 @@ public final class TickUtils { public static final int CLIENT_TICK_MS = 50; /** - * Creates a number of ticks from a given duration, based on {@link MinecraftServer#TICK_MS}. + * Creates a number of ticks from a given duration, based on {@link ServerSettings#getTickMs()}. * * @param duration the duration * @return the number of ticks * @throws IllegalArgumentException if duration is negative */ - public static int fromDuration(@NotNull Duration duration) { - return TickUtils.fromDuration(duration, MinecraftServer.TICK_MS); + public static int fromDuration(ServerSettings serverSettings, @NotNull Duration duration) { + return TickUtils.fromDuration(duration, serverSettings.getTickMs()); } /** diff --git a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java index 2d7e5933627..d6b518a898c 100644 --- a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java +++ b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java @@ -1,6 +1,6 @@ package net.minestom.server.utils.async; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -15,12 +15,12 @@ public static CompletableFuture empty() { return (CompletableFuture) VOID_FUTURE; } - public static @NotNull CompletableFuture runAsync(MinecraftServer minecraftServer, @NotNull Runnable runnable) { + public static @NotNull CompletableFuture runAsync(ServerProcess serverProcess, @NotNull Runnable runnable) { return CompletableFuture.runAsync(() -> { try { runnable.run(); } catch (Exception e) { - minecraftServer.process().getExceptionManager().handleException(e); + serverProcess.getExceptionManager().handleException(e); } }); } diff --git a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java index cf9fec518c4..0e6aabd7648 100644 --- a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java +++ b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java @@ -127,7 +127,7 @@ public EntityFinder setDifference(float dx, float dy, float dz) { public @NotNull List<@NotNull Entity> find(@Nullable Instance instance, @Nullable Entity self) { if (targetSelector == TargetSelector.MINESTOM_USERNAME) { Check.notNull(constantName, "The player name should not be null when searching for it"); - final Player player = instance.minecraftServer.process().getConnectionManager().getOnlinePlayerByUsername(constantName); + final Player player = instance.getServerProcess().getConnectionManager().getOnlinePlayerByUsername(constantName); return player != null ? List.of(player) : List.of(); } else if (targetSelector == TargetSelector.MINESTOM_UUID) { Check.notNull(constantUuid, "The UUID should not be null when searching for it"); @@ -306,7 +306,7 @@ private static class ToggleableMap extends Object2BooleanOpenHashMap { private static @NotNull List<@NotNull Entity> findTarget(@Nullable Instance instance, @NotNull TargetSelector targetSelector, @NotNull Point startPosition, @Nullable Entity self) { - final var players = instance != null ? instance.getPlayers() : instance.minecraftServer.process().getConnectionManager().getOnlinePlayers(); + final var players = instance != null ? instance.getPlayers() : instance.getServerProcess().getConnectionManager().getOnlinePlayers(); if (targetSelector == TargetSelector.NEAREST_PLAYER) { return players.stream() .min(Comparator.comparingDouble(p -> p.getPosition().distanceSquared(startPosition))) @@ -322,7 +322,7 @@ private static class ToggleableMap extends Object2BooleanOpenHashMap { return List.copyOf(instance.getEntities()); } // Get entities from every instance - var instances = instance.minecraftServer.process().getInstanceManager().getInstances(); + var instances = instance.getServerProcess().getInstanceManager().getInstances(); List entities = new ArrayList<>(); for (Instance inst : instances) { entities.addAll(inst.getEntities()); diff --git a/src/main/java/net/minestom/server/utils/time/Tick.java b/src/main/java/net/minestom/server/utils/time/Tick.java index e749e201860..180b751f71e 100644 --- a/src/main/java/net/minestom/server/utils/time/Tick.java +++ b/src/main/java/net/minestom/server/utils/time/Tick.java @@ -1,21 +1,16 @@ package net.minestom.server.utils.time; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerSettings; import java.time.Duration; import java.time.temporal.Temporal; import java.time.temporal.TemporalUnit; +import java.util.Objects; /** * A TemporalUnit that represents one tick. */ public final class Tick implements TemporalUnit { - /** - * A TemporalUnit representing the server tick. This is defined using - * {@link MinecraftServer#TICK_MS}. - */ - public static Tick SERVER_TICKS = new Tick(MinecraftServer.TICK_MS); - /** * A TemporalUnit representing the client tick. This is always equal to 50ms. */ @@ -38,14 +33,18 @@ private Tick(long length) { this.tps = Math.toIntExact(Duration.ofSeconds(1).dividedBy(Duration.ofMillis(this.milliseconds))); } + public static Tick serverTick(ServerSettings serverSettings) { + return new Tick(serverSettings.getTickMs()); + } + /** * Creates a duration from an amount of ticks. * * @param ticks the amount of ticks * @return the duration */ - public static Duration server(long ticks) { - return Duration.of(ticks, SERVER_TICKS); + public static Duration server(ServerSettings serverSettings, long ticks) { + return Duration.of(ticks, serverTick(serverSettings)); } /** @@ -109,4 +108,17 @@ public R addTo(R temporal, long amount) { public long between(Temporal start, Temporal end) { return start.until(end, this); } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Tick tick = (Tick) o; + return milliseconds == tick.milliseconds && tps == tick.tps; + } + + @Override + public int hashCode() { + return Objects.hash(milliseconds, tps); + } } \ No newline at end of file diff --git a/src/main/java/net/minestom/server/utils/time/TimeUnit.java b/src/main/java/net/minestom/server/utils/time/TimeUnit.java index 7e181a47c91..7bf502e0257 100644 --- a/src/main/java/net/minestom/server/utils/time/TimeUnit.java +++ b/src/main/java/net/minestom/server/utils/time/TimeUnit.java @@ -1,5 +1,7 @@ package net.minestom.server.utils.time; +import net.minestom.server.ServerSettings; + import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; @@ -9,13 +11,11 @@ public final class TimeUnit { public static final TemporalUnit MINUTE = ChronoUnit.MINUTES; public static final TemporalUnit SECOND = ChronoUnit.SECONDS; public static final TemporalUnit MILLISECOND = ChronoUnit.MILLIS; - public static final TemporalUnit SERVER_TICK = Tick.SERVER_TICKS; public static final TemporalUnit CLIENT_TICK = Tick.CLIENT_TICKS; - /** - * @deprecated Please use either {@link #SERVER_TICK} or {@link #CLIENT_TICK} - */ - @Deprecated(forRemoval = true) - public static final TemporalUnit TICK = CLIENT_TICK; + + public static TemporalUnit getServerTick(ServerSettings serverSettings) { + return Tick.serverTick(serverSettings); + } private TimeUnit() { } diff --git a/src/main/java/net/minestom/server/world/Difficulty.java b/src/main/java/net/minestom/server/world/Difficulty.java index 514209e3207..64e2c4a6af1 100644 --- a/src/main/java/net/minestom/server/world/Difficulty.java +++ b/src/main/java/net/minestom/server/world/Difficulty.java @@ -1,9 +1,12 @@ package net.minestom.server.world; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; + /** * Those are all the difficulties which can be displayed in the player menu. *

      - * Sets with {@link net.minestom.server.MinecraftServer#setDifficulty(Difficulty)}. + * Sets with {@link ServerSettings#setDifficulty(Difficulty, ServerProcess)}. */ public enum Difficulty { diff --git a/src/test/java/net/minestom/server/ServerProcessTest.java b/src/test/java/net/minestom/server/ServerProcessTest.java index b5ab64efce0..9e9a2e1a28c 100644 --- a/src/test/java/net/minestom/server/ServerProcessTest.java +++ b/src/test/java/net/minestom/server/ServerProcessTest.java @@ -17,7 +17,7 @@ public void init() { assumeTrue(System.getenv("GITHUB_ACTIONS") == null); AtomicReference process = new AtomicReference<>(); - assertDoesNotThrow(() -> process.set(new MinecraftServer().updateProcess())); + assertDoesNotThrow(() -> process.set(ServerProcess.of(ServerSettings.builder().build()))); assertDoesNotThrow(() -> process.get().start(new InetSocketAddress("localhost", 25565))); assertThrows(Exception.class, () -> process.get().start(new InetSocketAddress("localhost", 25566))); assertDoesNotThrow(() -> process.get().stop()); @@ -28,8 +28,7 @@ public void tick() { // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); - - var process = new MinecraftServer().updateProcess(); + var process = ServerProcess.of(ServerSettings.builder().build()); process.start(new InetSocketAddress("localhost", 25565)); var ticker = process.ticker(); assertDoesNotThrow(() -> ticker.tick(System.currentTimeMillis())); diff --git a/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java index eac29525498..cda9c77675c 100644 --- a/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityBlockPhysicsIntegrationTest.java @@ -49,7 +49,7 @@ public void entityPhysicsCheckCollision(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 43, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -67,7 +67,7 @@ public void entityPhysicsCheckSlab(Env env) { instance.setBlock(0, 42, 0, Block.STONE_SLAB); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 44, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -80,7 +80,7 @@ public void entityPhysicsCheckShallowAngle(Env env) { var instance = env.createFlatInstance(); instance.setBlock(13, 99, 16, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(12.812, 100.0, 16.498)).join(); PhysicsResult res = CollisionUtils.handlePhysics(entity, new Vec(0.273, -0.0784, 0.0)); @@ -95,7 +95,7 @@ public void entityPhysicsCheckFallFence(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.OAK_FENCE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -114,7 +114,7 @@ public void entityPhysicsCheckFallHitCarpet(Env env) { instance.setBlock(0, 42, 0, Block.OAK_FENCE); instance.setBlock(0, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 54.0625, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -128,7 +128,7 @@ public void entityPhysicsCheckFallHitFence(Env env) { instance.setBlock(0, 42, 0, Block.OAK_FENCE); instance.setBlock(0, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 54.0625, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -141,7 +141,7 @@ public void entityPhysicsCheckHorizontalFence(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 0, Block.OAK_FENCE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.25, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -155,7 +155,7 @@ public void entityPhysicsCheckMultipleBlocksPassFirst(Env env) { instance.setBlock(4, 40, -1, Block.SANDSTONE_STAIRS); instance.setBlock(16, 40, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.0, 40.51, 0.0)).join(); assertEquals(instance, entity.getInstance()); @@ -171,7 +171,7 @@ public void entityPhysicsCheckMultipleBlocksHitFirst(Env env) { instance.loadChunk(0, -1).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.0, 40.51, 0.0)).join(); assertEquals(instance, entity.getInstance()); @@ -186,7 +186,7 @@ public void entityPhysicsCheckHorizontalCarpetedFence(Env env) { instance.setBlock(1, 42, 0, Block.OAK_FENCE); instance.setBlock(1, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.25, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -205,7 +205,7 @@ public void entityPhysicsCheckDiagonalCarpetedFenceX(Env env) { instance.setBlock(1, 42, 0, Block.OAK_FENCE); instance.setBlock(1, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.075, 44.0625, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -224,7 +224,7 @@ public void entityPhysicsCheckDiagonalCarpetedFenceZ(Env env) { instance.setBlock(0, 42, 1, Block.OAK_FENCE); instance.setBlock(0, 43, 1, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 44.0625, 0.075)).join(); assertEquals(instance, entity.getInstance()); @@ -248,7 +248,7 @@ public void entityPhysicsCheckDiagonalCarpetedFenceXZ(Env env) { instance.setBlock(0, 43, 0, Block.BROWN_CARPET); instance.setBlock(-1, 43, 1, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(-0.925, 44.0625, 0.075)).join(); assertEquals(instance, entity.getInstance()); @@ -269,7 +269,7 @@ public void entityPhysicsCheckFallHitFenceLongMove(Env env) { instance.setBlock(0, 42, 0, Block.OAK_FENCE); instance.setBlock(0, 43, 0, Block.BROWN_CARPET); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 54.0625, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -283,7 +283,7 @@ public void entityPhysicsCheckFenceAboveHead(Env env) { instance.setBlock(0, 45, 0, Block.OAK_FENCE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.0, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -297,7 +297,7 @@ public void entityPhysicsCheckDiagonal(Env env) { instance.setBlock(1, 43, 1, Block.STONE); instance.setBlock(1, 43, 2, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -313,7 +313,7 @@ public void entityPhysicsCheckDirectSlide(Env env) { instance.setBlock(1, 43, 1, Block.STONE); instance.setBlock(1, 43, 2, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.69, 42, 0.69)).join(); assertEquals(instance, entity.getInstance()); @@ -328,7 +328,7 @@ public void entityPhysicsCheckCorner(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); instance.setBlock(5, 43, -5, Block.STONE); @@ -349,7 +349,7 @@ public void entityPhysicsCheckEnclosedHit(Env env) { instance.setBlock(8, 42, 8, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.SLIME); + var entity = new Entity(env.process(), EntityType.SLIME); SlimeMeta meta = (SlimeMeta) entity.getEntityMeta(); meta.setSize(20); @@ -371,7 +371,7 @@ public void entityPhysicsCheckEnclosedHitSubBlock(Env env) { instance.setBlock(8, 42, 8, Block.LANTERN); - var entity = new Entity(env.minecraftServer(), EntityType.SLIME); + var entity = new Entity(env.process(), EntityType.SLIME); SlimeMeta meta = (SlimeMeta) entity.getEntityMeta(); meta.setSize(20); @@ -389,7 +389,7 @@ public void entityPhysicsCheckEnclosedMiss(Env env) { var instance = env.createFlatInstance(); instance.setBlock(11, 43, 11, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.SLIME); + var entity = new Entity(env.process(), EntityType.SLIME); SlimeMeta meta = (SlimeMeta) entity.getEntityMeta(); meta.setSize(5); @@ -408,7 +408,7 @@ public void entityPhysicsCheckEntityHit(Env env) { Point z3 = new Pos(11, 0, 0); Point movement = new Pos(20, 1, 0); - BoundingBox bb = new Entity(env.minecraftServer(), EntityType.ZOMBIE).getBoundingBox(); + BoundingBox bb = new Entity(env.process(), EntityType.ZOMBIE).getBoundingBox(); SweepResult sweepResultFinal = new SweepResult(1, 0, 0, 0, null, null); @@ -424,7 +424,7 @@ public void entityPhysicsCheckEdgeClip(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0.7)).join(); assertEquals(instance, entity.getInstance()); @@ -437,7 +437,7 @@ public void entityPhysicsCheckEdgeClipSmall(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.6999, 42, 0.6999)).join(); PhysicsResult res = CollisionUtils.handlePhysics(entity, new Vec(0.702, 0, 0.702)); @@ -453,7 +453,7 @@ public void entityPhysicsCheckDoorSubBlockNorth(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -468,7 +468,7 @@ public void entityPhysicsCheckDoorSubBlockSouth(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -483,7 +483,7 @@ public void entityPhysicsCheckDoorSubBlockWest(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -498,7 +498,7 @@ public void entityPhysicsCheckDoorSubBlockEast(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -513,7 +513,7 @@ public void entityPhysicsCheckDoorSubBlockUp(Env env) { instance.setBlock(0, 44, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.7, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -528,7 +528,7 @@ public void entityPhysicsCheckDoorSubBlockDown(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.2, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -541,7 +541,7 @@ public void entityPhysicsCheckOnGround(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 40, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 50, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -554,7 +554,7 @@ public void entityPhysicsCheckStairTop(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.ACACIA_STAIRS); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.4, 42.5, 0.9)).join(); assertEquals(instance, entity.getInstance()); @@ -567,7 +567,7 @@ public void entityPhysicsCheckStairTopSmall(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.ACACIA_STAIRS); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.4, 42.5, 0.9)).join(); assertEquals(instance, entity.getInstance()); @@ -583,7 +583,7 @@ public void entityPhysicsCheckNotOnGround(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 50, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -596,7 +596,7 @@ public void entityPhysicsCheckNotOnGroundHitUp(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 60, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 50, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -611,7 +611,7 @@ public void entityPhysicsCheckSlide(Env env) { instance.setBlock(1, 43, 2, Block.STONE); instance.setBlock(1, 43, 3, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -624,7 +624,7 @@ public void entityPhysicsSmallMoveCollide(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.6, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -638,7 +638,7 @@ public void entityPhysicsSmallMoveC0(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.7, 42, 0.5)).join(); @@ -653,7 +653,7 @@ public void entityPhysicsSmallMoveC1(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.5, 42, 0.7)).join(); @@ -668,7 +668,7 @@ public void entityPhysicsSmallMoveC2(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.8, 42, 1.3)).join(); @@ -683,7 +683,7 @@ public void entityPhysicsSmallMoveC3(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.7, 42, 1.1)).join(); @@ -698,7 +698,7 @@ public void entityPhysicsSmallMoveC4(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.1, 42, 1.3)).join(); @@ -713,7 +713,7 @@ public void entityPhysicsSmallMoveC5(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.3, 42, 1.1)).join(); @@ -728,7 +728,7 @@ public void entityPhysicsSmallMoveC6(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.1, 42, 0.7)).join(); @@ -743,7 +743,7 @@ public void entityPhysicsSmallMoveC7(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 42, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(1.3, 42, 0.8)).join(); @@ -759,7 +759,7 @@ public void entityPhysicsSmallMoveC0E(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.51, 42.51, 0.5)).join(); @@ -774,7 +774,7 @@ public void entityPhysicsSmallMoveC1E(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 43, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.50, 42.51, 0.51)).join(); @@ -789,7 +789,7 @@ public void entityPhysicsSmallMoveC2E(Env env) { var instance = env.createFlatInstance(); instance.setBlock(1, 43, 1, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setBoundingBox(BoundingBox.ZERO); entity.setInstance(instance, new Pos(0.51, 42.50, 0.51)).join(); @@ -808,7 +808,7 @@ public void entityPhysicsCheckNoCollision(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -822,7 +822,7 @@ public void entityPhysicsCheckBlockMiss(Env env) { instance.setBlock(0, 43, 2, Block.STONE); instance.setBlock(2, 43, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -843,7 +843,7 @@ public void entityPhysicsCheckBlockDirections(Env env) { instance.setBlock(0, 41, 0, Block.STONE); instance.setBlock(0, 44, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -867,7 +867,7 @@ public void entityPhysicsCheckBlockDirections(Env env) { @Test public void entityPhysicsCheckLargeVelocityMiss(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -882,7 +882,7 @@ public void entityPhysicsCheckLargeVelocityMiss(Env env) { @Test public void entityPhysicsCheckLargeVelocityHit(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -899,7 +899,7 @@ public void entityPhysicsCheckLargeVelocityHit(Env env) { @Test public void entityPhysicsCheckNoMove(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(5, 42, 5)).join(); assertEquals(instance, entity.getInstance()); @@ -925,7 +925,7 @@ public void entityPhysicsRepeatedCollision(Env env) { instance.setBlock(0, 43, -1, Block.STONE); instance.setBlock(-1, 43, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 43.1, 0.5)).join(); PhysicsResult res = CollisionUtils.handlePhysics(entity, new Vec(0, 0, 0)); @@ -943,7 +943,7 @@ public void entityPhysicsRepeatedCollision(Env env) { @Test public void entityPhysicsCheckNoMoveCache(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(5, 42, 5)).join(); assertEquals(instance, entity.getInstance()); @@ -957,7 +957,7 @@ public void entityPhysicsCheckNoMoveCache(Env env) { @Test public void entityPhysicsCheckNoMoveLargeVelocityHit(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -976,7 +976,7 @@ public void entityPhysicsCheckNoMoveLargeVelocityHit(Env env) { @Test public void entityPhysicsCheckLargeVelocityHitNoMove(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); final int distance = 20; for (int x = 0; x < distance; ++x) instance.loadChunk(x, 0).join(); @@ -999,7 +999,7 @@ public void entityPhysicsCheckDoorSubBlockSouthRepeat(Env env) { instance.setBlock(0, 42, 0, b); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0.5, 42.5, 0.5)).join(); assertEquals(instance, entity.getInstance()); @@ -1019,7 +1019,7 @@ public void entityPhysicsCheckCollisionDownCache(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -1039,7 +1039,7 @@ public void entityPhysicsCheckGravityCached(Env env) { for (int j = -2; j <= 2; ++j) instance.loadChunk(i, j).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); @@ -1066,7 +1066,7 @@ public void entityBlockPositionTestSlightlyAbove(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 43.00001, 0)); var deltaPos = new Vec(0.0, -10, 0.0); @@ -1081,7 +1081,7 @@ public void entityBlockPositionTestFarAbove(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 42, 0, Block.STONE); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 43.5, 0)); var deltaPos = new Vec(0.0, -10, 0.0); diff --git a/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java index 91c3917bfe4..ac20b269a5d 100644 --- a/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityBlockTouchTickIntegrationTest.java @@ -46,7 +46,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(1, 42, 0, Block.STONE.withHandler(handler)); instance.setBlock(0, 42, 10, Block.STONE.withHandler(handler)); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0.7)).join(); entity.tick(0); @@ -85,7 +85,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(1001, 42, 1000, Block.STONE.withHandler(handler)); instance.setBlock(1000, 42, 1010, Block.STONE.withHandler(handler)); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(1000, 42, 1000.7)).join(); entity.tick(0); @@ -130,7 +130,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(1001, 42, 1000, Block.STONE.withHandler(handler)); instance.setBlock(1000, 42, 1010, Block.STONE.withHandler(handler)); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(1000.699, 42, 1000)).join(); entity.tick(0); @@ -178,7 +178,7 @@ public void onTouch(@NotNull Touch touch) { instance.setBlock(-1001, 42, -1000, Block.STONE.withHandler(handler)); instance.setBlock(-1000, 42, -1010, Block.STONE.withHandler(handler)); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(-1000.301, 42, -1000)).join(); entity.tick(0); diff --git a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java index 34ca2978433..491d789dc3e 100644 --- a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java @@ -1,6 +1,5 @@ package net.minestom.server.collision; -import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; @@ -31,10 +30,10 @@ public void blockShootAndBlockRemoval(Env env) { final Instance instance = env.createFlatInstance(); instance.getWorldBorder().setDiameter(1000.0); - final Entity shooter = new Entity(env.minecraftServer(), EntityType.SKELETON); + final Entity shooter = new Entity(env.process(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 40, 0)).join(); - final EntityProjectile projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); + final EntityProjectile projectile = new EntityProjectile(env.process(), shooter, EntityType.ARROW); projectile.setInstance(instance, shooter.getPosition().withY(y -> y + shooter.getEyeHeight())).join(); final Point blockPosition = new Vec(5, 40, 0); @@ -43,10 +42,10 @@ public void blockShootAndBlockRemoval(Env env) { projectile.shoot(blockPosition, 1, 0); final var eventRef = new AtomicReference(); - env.minecraftServer().process().getGlobalEventHandler().addListener(ProjectileCollideWithBlockEvent.class, eventRef::set); + env.process().getGlobalEventHandler().addListener(ProjectileCollideWithBlockEvent.class, eventRef::set); - final long tick = TimeUnit.SERVER_TICK.getDuration().toMillis(); - for (int i = 0; i < MinecraftServer.TICK_PER_SECOND; ++i) { + final long tick = TimeUnit.getServerTick(env.process().getMinecraftServer()).getDuration().toMillis(); + for (int i = 0; i < env.process().getMinecraftServer().getTickPerSecond(); ++i) { projectile.tick(i * tick); } @@ -56,12 +55,12 @@ public void blockShootAndBlockRemoval(Env env) { assertEquals(block, event.getBlock()); final var eventRef2 = new AtomicReference(); - env.minecraftServer().process().getGlobalEventHandler().addListener(ProjectileUncollideEvent.class, eventRef2::set); + env.process().getGlobalEventHandler().addListener(ProjectileUncollideEvent.class, eventRef2::set); eventRef.set(null); instance.setBlock(blockPosition, Block.AIR); - for (int i = 0; i < MinecraftServer.TICK_PER_SECOND; ++i) { - projectile.tick((MinecraftServer.TICK_PER_SECOND + i) * tick); + for (int i = 0; i < env.process().getMinecraftServer().getTickPerSecond(); ++i) { + projectile.tick((env.process().getMinecraftServer().getTickPerSecond() + i) * tick); } event = eventRef.get(); final var event2 = eventRef2.get(); @@ -75,7 +74,7 @@ public void entityShoot(Env env) { final Instance instance = env.createFlatInstance(); instance.getWorldBorder().setDiameter(1000.0); - final Entity shooter = new Entity(env.minecraftServer(), EntityType.SKELETON); + final Entity shooter = new Entity(env.process(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 40, 0)).join(); for (double dx = 1; dx <= 3; dx += .2) { @@ -88,24 +87,24 @@ private void singleEntityShoot( Entity shooter, final Point targetPosition ) { - final EntityProjectile projectile = new EntityProjectile(shooter.getMinecraftServer(), shooter, EntityType.ARROW); + final EntityProjectile projectile = new EntityProjectile(shooter.getServerProcess(), shooter, EntityType.ARROW); projectile.setInstance(instance, shooter.getPosition().withY(y -> y + shooter.getEyeHeight())).join(); - final LivingEntity target = new LivingEntity(shooter.getMinecraftServer(), EntityType.RABBIT); + final LivingEntity target = new LivingEntity(shooter.getServerProcess(), EntityType.RABBIT); target.setInstance(instance, Pos.fromPoint(targetPosition)).join(); projectile.shoot(targetPosition, 1, 0); final var eventRef = new AtomicReference(); - final var eventNode = EventNode.all(shooter.getMinecraftServer(), "projectile-test"); + final var eventNode = EventNode.all(shooter.getServerProcess(), "projectile-test"); eventNode.addListener(ProjectileCollideWithEntityEvent.class, event -> { event.getEntity().remove(); eventRef.set(event); - shooter.getMinecraftServer().process().getGlobalEventHandler().removeChild(eventNode); + shooter.getServerProcess().getGlobalEventHandler().removeChild(eventNode); }); - shooter.getMinecraftServer().process().getGlobalEventHandler().addChild(eventNode); + shooter.getServerProcess().getGlobalEventHandler().addChild(eventNode); - final long tick = TimeUnit.SERVER_TICK.getDuration().toMillis(); - for (int i = 0; i < MinecraftServer.TICK_PER_SECOND; ++i) { + final long tick = TimeUnit.getServerTick(instance.getServerProcess().getMinecraftServer()).getDuration().toMillis(); + for (int i = 0; i < instance.getServerProcess().getMinecraftServer().getTickPerSecond(); ++i) { if (!projectile.isRemoved()) { projectile.tick(i * tick); } @@ -123,22 +122,22 @@ public void entitySelfShoot(Env env) { final Instance instance = env.createFlatInstance(); instance.getWorldBorder().setDiameter(1000.0); - final LivingEntity shooter = new LivingEntity(env.minecraftServer(), EntityType.SKELETON); + final LivingEntity shooter = new LivingEntity(env.process(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 40, 0)).join(); - final EntityProjectile projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); + final EntityProjectile projectile = new EntityProjectile(env.process(), shooter, EntityType.ARROW); projectile.setInstance(instance, shooter.getPosition().withY(y -> y + shooter.getEyeHeight())).join(); projectile.shoot(new Vec(0, 60, 0), 1, 0); final var eventRef = new AtomicReference(); - env.minecraftServer().process().getGlobalEventHandler().addListener(ProjectileCollideWithEntityEvent.class, event -> { + env.process().getGlobalEventHandler().addListener(ProjectileCollideWithEntityEvent.class, event -> { event.getEntity().remove(); eventRef.set(event); }); - final long tick = TimeUnit.SERVER_TICK.getDuration().toMillis(); - for (int i = 0; i < MinecraftServer.TICK_PER_SECOND * 5; ++i) { + final long tick = TimeUnit.getServerTick(env.process().getMinecraftServer()).getDuration().toMillis(); + for (int i = 0; i < env.process().getMinecraftServer().getTickPerSecond() * 5; ++i) { if (!projectile.isRemoved()) { projectile.tick(i * tick); } diff --git a/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java b/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java index 089049a6f05..e122aa8e9e1 100644 --- a/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/PlacementCollisionIntegrationTest.java @@ -24,14 +24,14 @@ public void empty(Env env) { @Test public void entityBlock(Env env) { var instance = env.createFlatInstance(); - new Entity(env.minecraftServer(), EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40, 0)).join(); + new Entity(env.process(), EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40, 0)).join(); assertNotNull(BlockCollision.canPlaceBlockAt(instance, new Vec(0, 40, 0), Block.STONE)); } @Test public void slab(Env env) { var instance = env.createFlatInstance(); - new Entity(env.minecraftServer(), EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40.75, 0)).join(); + new Entity(env.process(), EntityType.ZOMBIE).setInstance(instance, new Pos(0, 40.75, 0)).join(); assertNull(BlockCollision.canPlaceBlockAt(instance, new Vec(0, 40, 0), Block.STONE_SLAB)); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTest.java b/src/test/java/net/minestom/server/command/ArgumentTest.java index fe5fb17e8dd..c80c87d62b2 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -16,9 +17,9 @@ public class ArgumentTest { @Test public void testParseSelf() { - MinecraftServer minecraftServer = new MinecraftServer(); - assertEquals("example", Argument.parse(new ServerSender(minecraftServer), ArgumentType.String("example"))); - assertEquals(55, Argument.parse(new ServerSender(minecraftServer), ArgumentType.Integer("55"))); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertEquals("example", Argument.parse(new ServerSender(serverProcess), ArgumentType.String("example"))); + assertEquals(55, Argument.parse(new ServerSender(serverProcess), ArgumentType.Integer("55"))); } @Test @@ -33,18 +34,18 @@ public void testCallback() { @Test public void testDefaultValue() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var arg = ArgumentType.String("id"); assertFalse(arg.isOptional()); arg.setDefaultValue("default value"); assertTrue(arg.isOptional()); - assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(minecraftServer))); + assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(serverProcess))); } @Test public void testSuggestionCallback() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var arg = ArgumentType.String("id"); assertFalse(arg.hasSuggestion()); @@ -53,7 +54,7 @@ public void testSuggestionCallback() { assertTrue(arg.hasSuggestion()); Suggestion suggestion = new Suggestion("input", 2, 4); - arg.getSuggestionCallback().apply(new ServerSender(minecraftServer), new CommandContext("input"), suggestion); + arg.getSuggestionCallback().apply(new ServerSender(serverProcess), new CommandContext("input"), suggestion); assertEquals(suggestion.getEntries(), List.of(new SuggestionEntry("entry"))); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java index 5015cc3e2dd..f9a2466546d 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java @@ -5,7 +5,8 @@ import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentEnum; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -221,9 +222,10 @@ public void testArgumentResourceOrTag() { @Test public void testArgumentTime() { + ServerSettings serverSettings = ServerSettings.builder().build(); var arg = ArgumentType.Time("time"); - assertArg(arg, Duration.of(20, TimeUnit.SERVER_TICK), "20"); - assertArg(arg, Duration.of(40, TimeUnit.SERVER_TICK), "40t"); + assertArg(arg, Duration.of(20, TimeUnit.getServerTick(serverSettings)), "20"); + assertArg(arg, Duration.of(40, TimeUnit.getServerTick(serverSettings)), "40t"); assertArg(arg, Duration.of(60, TimeUnit.SECOND), "60s"); assertArg(arg, Duration.of(80, TimeUnit.DAY), "80d"); @@ -376,17 +378,17 @@ enum ExampleEnum {FIRST, SECOND, Third, fourth} @Test public void testArgumentGroup() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var arg = ArgumentType.Group("group", ArgumentType.Integer("integer"), ArgumentType.String("string"), ArgumentType.Double("double")); // Test normal input - var context1 = arg.parse(new ServerSender(minecraftServer), "1234 1234 1234"); + var context1 = arg.parse(new ServerSender(serverProcess), "1234 1234 1234"); assertEquals(1234, context1.get("integer")); assertEquals("1234", context1.get("string")); assertEquals(1234.0, context1.get("double")); // Test different input + trailing spaces - var context2 = arg.parse(new ServerSender(minecraftServer), "1234 abcd 1234.5678 "); + var context2 = arg.parse(new ServerSender(serverProcess), "1234 abcd 1234.5678 "); assertEquals(1234, context2.get("integer")); assertEquals("abcd", context2.get("string")); assertEquals(1234.5678, context2.get("double")); @@ -453,8 +455,8 @@ public void testArgumentWord() { @Test public void testArgumentMapWithSender() { - MinecraftServer minecraftServer = new MinecraftServer(); - var serverSender = new ServerSender(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var serverSender = new ServerSender(serverProcess); var arg = ArgumentType.Word("word").from("word1", "word2", "word3") .map((sender, s) -> { @@ -466,22 +468,22 @@ public void testArgumentMapWithSender() { } private static void assertArg(Argument arg, T expected, String input) { - MinecraftServer minecraftServer = new MinecraftServer(); - assertEquals(expected, arg.parse(new ServerSender(minecraftServer), input)); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertEquals(expected, arg.parse(new ServerSender(serverProcess), input)); } private static void assertArrayArg(Argument arg, T[] expected, String input) { - MinecraftServer minecraftServer = new MinecraftServer(); - assertArrayEquals(expected, arg.parse(new ServerSender(minecraftServer), input)); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertArrayEquals(expected, arg.parse(new ServerSender(serverProcess), input)); } private static void assertValidArg(Argument arg, String input) { - MinecraftServer minecraftServer = new MinecraftServer(); - assertDoesNotThrow(() -> arg.parse(new ServerSender(minecraftServer), input)); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertDoesNotThrow(() -> arg.parse(new ServerSender(serverProcess), input)); } private static void assertInvalidArg(Argument arg, String input) { - MinecraftServer minecraftServer = new MinecraftServer(); - assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(minecraftServer), input)); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(serverProcess), input)); } } diff --git a/src/test/java/net/minestom/server/command/CommandConditionTest.java b/src/test/java/net/minestom/server/command/CommandConditionTest.java index 36fbfb2d629..d3c020b557c 100644 --- a/src/test/java/net/minestom/server/command/CommandConditionTest.java +++ b/src/test/java/net/minestom/server/command/CommandConditionTest.java @@ -1,7 +1,8 @@ package net.minestom.server.command; import net.kyori.adventure.identity.Identity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.permission.Permission; @@ -18,8 +19,8 @@ public class CommandConditionTest { @Test public void mainCondition() { - MinecraftServer minecraftServer = new MinecraftServer(); - var dispatcher = new CommandDispatcher(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(serverProcess); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -42,8 +43,8 @@ public void mainCondition() { @Test public void subCondition() { - MinecraftServer minecraftServer = new MinecraftServer(); - var dispatcher = new CommandDispatcher(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(serverProcess); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -87,8 +88,8 @@ public void subCondition() { @Test public void subConditionOverride() { - MinecraftServer minecraftServer = new MinecraftServer(); - var dispatcher = new CommandDispatcher(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(serverProcess); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -146,7 +147,7 @@ private static final class Sender implements CommandSender { } @Override - public MinecraftServer getMinecraftServer() { + public ServerProcess getServerProcess() { return null; } } diff --git a/src/test/java/net/minestom/server/command/CommandManagerTest.java b/src/test/java/net/minestom/server/command/CommandManagerTest.java index ad084bd8434..8074fa46e80 100644 --- a/src/test/java/net/minestom/server/command/CommandManagerTest.java +++ b/src/test/java/net/minestom/server/command/CommandManagerTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandResult; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -15,8 +16,8 @@ public class CommandManagerTest { @Test public void testCommandRegistration() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); var command = new Command("name1", "name2"); @@ -35,8 +36,8 @@ public void testCommandRegistration() { @Test public void testUnknownCommandCallback() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); AtomicBoolean check = new AtomicBoolean(false); manager.setUnknownCommandCallback((sender, command) -> check.set(true)); @@ -52,8 +53,8 @@ public void testUnknownCommandCallback() { @Test public void testSharedArgumentSyntaxABFirst() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); @@ -81,8 +82,8 @@ public void testSharedArgumentSyntaxABFirst() { @Test public void testSharedArgumentSyntaxAFirst() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java index 04e1b8efad4..adf151c0da7 100644 --- a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java +++ b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentType; import net.minestom.server.entity.Player; @@ -12,8 +13,8 @@ @SuppressWarnings("ConstantConditions") public class CommandPacketFilteringTest { - private static final MinecraftServer minecraftServer = new MinecraftServer(); - private static final Player PLAYER = new Player(minecraftServer, UUID.randomUUID(), "", null); + private static final ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + private static final Player PLAYER = new Player(serverProcess, UUID.randomUUID(), "", null); @Test public void singleCommandFilteredFalse() { diff --git a/src/test/java/net/minestom/server/command/CommandParseTest.java b/src/test/java/net/minestom/server/command/CommandParseTest.java index 5bda34def5a..eb5a0f19a5c 100644 --- a/src/test/java/net/minestom/server/command/CommandParseTest.java +++ b/src/test/java/net/minestom/server/command/CommandParseTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.arguments.ArgumentType; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -144,8 +145,8 @@ private static void assertValid(Graph graph, String input, AtomicBoolean executo } private static CommandParser.Result parseCommand(Graph graph, String input) { - MinecraftServer minecraftServer = new MinecraftServer(); - return CommandParser.parser().parse(new ServerSender(minecraftServer), graph, input); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + return CommandParser.parser().parse(new ServerSender(serverProcess), graph, input); } @NotNull diff --git a/src/test/java/net/minestom/server/command/CommandSenderTest.java b/src/test/java/net/minestom/server/command/CommandSenderTest.java index 7f579a901b1..1297886c450 100644 --- a/src/test/java/net/minestom/server/command/CommandSenderTest.java +++ b/src/test/java/net/minestom/server/command/CommandSenderTest.java @@ -4,7 +4,7 @@ import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -85,7 +85,7 @@ public void sendMessage(@NotNull Identity source, @NotNull Component message, @N } @Override - public MinecraftServer getMinecraftServer() { + public ServerProcess getServerProcess() { return null; } } diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java index b7ff0ae8d20..7441b1f069d 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.Argument; import org.junit.jupiter.api.Test; @@ -45,10 +46,10 @@ public void similarArgs() { } private static void assertSyntax(List>> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final String commandName = "name"; - var manager = new CommandManager(minecraftServer); + var manager = new CommandManager(serverProcess); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java index ed2550d23cd..adcd7bc0cb1 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.Argument; @@ -147,10 +148,10 @@ public void singleLoopDoubleGroup() { } private static void assertSyntax(List> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final String commandName = "name"; - var manager = new CommandManager(minecraftServer); + var manager = new CommandManager(serverProcess); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandTest.java b/src/test/java/net/minestom/server/command/CommandTest.java index d6f674a8d8d..e8fdcec81a9 100644 --- a/src/test/java/net/minestom/server/command/CommandTest.java +++ b/src/test/java/net/minestom/server/command/CommandTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; import org.jetbrains.annotations.NotNull; @@ -29,8 +30,8 @@ public void testNames() { @Test public void testGlobalListener() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); AtomicBoolean hasRun = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/SubcommandTest.java b/src/test/java/net/minestom/server/command/SubcommandTest.java index 2139add221b..8365100946d 100644 --- a/src/test/java/net/minestom/server/command/SubcommandTest.java +++ b/src/test/java/net/minestom/server/command/SubcommandTest.java @@ -1,6 +1,7 @@ package net.minestom.server.command; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import org.junit.jupiter.api.Test; @@ -13,8 +14,8 @@ public class SubcommandTest { @Test public void testSubCommands() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); var parent = new Command("parent"); var child = new Command("child"); @@ -36,8 +37,8 @@ public void testSubCommands() { @Test public void testSubCommandConditions() { - MinecraftServer minecraftServer = new MinecraftServer(); - var manager = new CommandManager(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var manager = new CommandManager(serverProcess); var parent = new Command("parent"); var child = new Command("child"); diff --git a/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java index 22d38f18524..636ea498f9a 100644 --- a/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityBoundingBoxIntegrationTest.java @@ -58,7 +58,7 @@ public void pickupItem(Env env) { final var instance = env.createFlatInstance(); final var listener = env.listen(PickupItemEvent.class); final var spawnPos = new Pos(0, 42, 0); - final var entity = new LivingEntity(env.minecraftServer(), EntityType.ZOMBIE); + final var entity = new LivingEntity(env.process(), EntityType.ZOMBIE); entity.setCanPickupItem(true); entity.setInstance(instance, spawnPos).join(); @@ -74,7 +74,7 @@ public void pickupItem(Env env) { } private void dropItem(final Instance instance, final Pos position) { - final var entity = new ItemEntity(instance.getMinecraftServer(), ItemStack.of(Material.STONE)); + final var entity = new ItemEntity(instance.getServerProcess(), ItemStack.of(Material.STONE)); entity.hasPhysics = false; entity.setNoGravity(true); entity.setInstance(instance, position).join(); diff --git a/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java index 484bb2b3a47..85f034004ac 100644 --- a/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityInstanceIntegrationTest.java @@ -16,7 +16,7 @@ public class EntityInstanceIntegrationTest { @Test public void entityJoin(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); assertEquals(new Pos(0, 42, 0), entity.getPosition()); diff --git a/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java index 4e6c5bf5899..a900da478c5 100644 --- a/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityLineOfSightIntegrationTest.java @@ -14,11 +14,11 @@ public class EntityLineOfSightIntegrationTest { public void entityPhysicsCheckLineOfSight(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0)).join(); assertEquals(entity2, entity.getLineOfSightEntity(20, (e) -> true)); @@ -38,11 +38,11 @@ public void entityPhysicsCheckLineOfSight(Env env) { public void entityPhysicsCheckLineOfSightBehind(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(-10, 42, 0)).join(); assertNull(entity.getLineOfSightEntity(20, (e) -> true)); @@ -62,11 +62,11 @@ public void entityPhysicsCheckLineOfSightBehind(Env env) { public void entityPhysicsCheckLineOfSightNearMiss(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0.31)).join(); assertNull(entity.getLineOfSightEntity(20, (e) -> true)); @@ -86,11 +86,11 @@ public void entityPhysicsCheckLineOfSightNearMiss(Env env) { public void entityPhysicsCheckLineOfSightNearHit(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0.3)).join(); assertEquals(entity2, entity.getLineOfSightEntity(20, (e) -> true)); @@ -112,14 +112,14 @@ public void entityPhysicsCheckLineOfSightNearHit(Env env) { public void entityPhysicsCheckLineOfSightCorrectOrder(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 0)).join(); - var entity3 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity3 = new Entity(env.process(), EntityTypes.ZOMBIE); entity3.setInstance(instance, new Pos(5, 42, 0)).join(); assertEquals(entity3, entity.getLineOfSightEntity(20, (e) -> true)); @@ -133,11 +133,11 @@ public void entityPhysicsCheckLineOfSightCorrectOrder(Env env) { public void entityPhysicsCheckLineOfSightBigMiss(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(10, 42, 10)).join(); assertNull(entity.getLineOfSightEntity(20, (e) -> true)); @@ -148,11 +148,11 @@ public void entityPhysicsCheckLineOfSightBigMiss(Env env) { public void entityPhysicsCheckLineOfSightLargeBoundingBox(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); entity.setView(-90, 0); - var entity2 = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity2 = new Entity(env.process(), EntityTypes.ZOMBIE); entity2.setInstance(instance, new Pos(6, 42, 0)).join(); entity2.setBoundingBox(4.0, 2.0, 4.0); diff --git a/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java index 6d61e5e274f..14e4f889301 100644 --- a/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityMetaIntegrationTest.java @@ -92,7 +92,7 @@ public void customName(Env env) { var incomingPackets = connection.trackIncoming(EntityMetaDataPacket.class); //Creates entity and name. - Entity entity = new Entity(env.minecraftServer(), EntityType.BEE); + Entity entity = new Entity(env.process(), EntityType.BEE); entity.setAutoViewable(false); entity.getEntityMeta().setNotifyAboutChanges(false); entity.setCustomName(Component.text("Custom Name")); diff --git a/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java index 74d32489015..da31ad6775d 100644 --- a/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityProjectileIntegrationTest.java @@ -12,9 +12,9 @@ public class EntityProjectileIntegrationTest { @Test public void gravityVelocity(Env env) { var instance = env.createFlatInstance(); - var shooter = new EntityCreature(env.minecraftServer(), EntityType.SKELETON); + var shooter = new EntityCreature(env.process(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 42, 0)).join(); - var projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); + var projectile = new EntityProjectile(env.process(), shooter, EntityType.ARROW); var from = new Pos(0, 42, 0).add(0, shooter.getEyeHeight(), shooter.getPosition().direction().z()); var target = from.add(0, 0, 10); @@ -44,9 +44,9 @@ public void gravityVelocity(Env env) { @Test public void noGravityVelocity(Env env) { var instance = env.createFlatInstance(); - var shooter = new EntityCreature(env.minecraftServer(), EntityType.SKELETON); + var shooter = new EntityCreature(env.process(), EntityType.SKELETON); shooter.setInstance(instance, new Pos(0, 42, 0)).join(); - var projectile = new EntityProjectile(env.minecraftServer(), shooter, EntityType.ARROW); + var projectile = new EntityProjectile(env.process(), shooter, EntityType.ARROW); var from = new Pos(0, 42, 0).add(0, shooter.getEyeHeight(), shooter.getPosition().direction().z()); var target = from.add(0, 0, 10); diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index c3db8a2a387..31a69751899 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.entity.EntityTickEvent; import net.minestom.server.network.packet.server.play.DestroyEntitiesPacket; @@ -25,7 +25,7 @@ public void destructionPacket(Env env) { var connection = env.createConnection(); connection.connect(instance, new Pos(0, 40, 0)).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); var tracker = connection.trackIncoming(DestroyEntitiesPacket.class); @@ -36,7 +36,7 @@ public void destructionPacket(Env env) { @Test public void instanceRemoval(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); assertFalse(entity.isRemoved()); @@ -48,7 +48,7 @@ public void instanceRemoval(Env env) { @Test public void tickTimedRemoval(Env env) throws InterruptedException { var instance = env.createFlatInstance(); - var entity = new TestEntity(env.minecraftServer(), 2, TimeUnit.SERVER_TICK); + var entity = new TestEntity(env.process(), 2, TimeUnit.getServerTick(env.process().getMinecraftServer())); entity.setInstance(instance, new Pos(0, 40, 0)).join(); assertFalse(entity.isRemoved()); @@ -69,7 +69,7 @@ public void tickTimedRemoval(Env env) throws InterruptedException { public void entityGC(Env env) { // Ensure that entities do not stay in memory after they are removed var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); entity.remove(); @@ -84,7 +84,7 @@ public void entityGC(Env env) { public void entityNodeGC(Env env) { // Ensure that the entities GCed when a local listener is present var node = env.process().getGlobalEventHandler(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.eventNode().addListener(EntityTickEvent.class, event -> { }); node.call(new EntityTickEvent(entity)); @@ -98,8 +98,8 @@ public void entityNodeGC(Env env) { } static final class TestEntity extends Entity { - public TestEntity(MinecraftServer minecraftServer, long delay, TemporalUnit unit) { - super(minecraftServer, EntityType.ZOMBIE); + public TestEntity(ServerProcess serverProcess, long delay, TemporalUnit unit) { + super(serverProcess, EntityType.ZOMBIE); scheduleRemove(delay, unit); } } diff --git a/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java index 9ea0035cf99..dfc9a29cd3a 100644 --- a/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityTeleportIntegrationTest.java @@ -16,7 +16,7 @@ public class EntityTeleportIntegrationTest { @Test public void entityChunkTeleport(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); assertEquals(new Pos(0, 42, 0), entity.getPosition()); @@ -28,7 +28,7 @@ public void entityChunkTeleport(Env env) { @Test public void entityTeleport(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, entity.getInstance()); assertEquals(new Pos(0, 42, 0), entity.getPosition()); diff --git a/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java index 1e9e80adebd..468ecd4b47f 100644 --- a/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityVelocityIntegrationTest.java @@ -21,7 +21,7 @@ public void gravity(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 42, 0)).join(); env.tick(); // Ensure velocity downwards is present @@ -40,7 +40,7 @@ public void singleKnockback(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); env.tick(); env.tick(); // Ensures the entity is onGround @@ -71,7 +71,7 @@ public void doubleKnockback(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(env.minecraftServer(), EntityTypes.ZOMBIE); + var entity = new Entity(env.process(), EntityTypes.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); env.tick(); env.tick(); // Ensures the entity is onGround @@ -145,7 +145,7 @@ public void testHasVelocity(Env env) { var instance = env.createFlatInstance(); loadChunks(instance); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); // Should be false because the new entity should have no velocity assertFalse(entity.hasVelocity()); @@ -170,7 +170,7 @@ public void countVelocityPackets(Env env) { var instance = env.createFlatInstance(); var viewerConnection = env.createConnection(); viewerConnection.connect(instance, new Pos(1, 40, 1)).join(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0,40,0)).join(); AtomicInteger i = new AtomicInteger(); diff --git a/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java index 4802b2c05a8..a45b4723ddb 100644 --- a/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityViewDirectionIntegrationTest.java @@ -15,7 +15,7 @@ public class EntityViewDirectionIntegrationTest { @Test public void viewYawAndPitch(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 0)).join(); entity.setView(0, 0); assertEquals(0, entity.getPosition().yaw()); @@ -50,7 +50,7 @@ public void viewYawAndPitch(Env env) { @Test public void lookAtPos(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); double eyeHeight = entity.getEyeHeight(); // adding this to some position Y coordinates, to look horizontally entity.setInstance(instance, new Pos(0, 40, 0)).join(); @@ -90,8 +90,8 @@ public void lookAtPos(Env env) { public void lookAtEntitySameType(Env env) { var instance = env.createFlatInstance(); // same type, same eye height - var e1 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); - var e2 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var e1 = new Entity(env.process(), EntityType.ZOMBIE); + var e2 = new Entity(env.process(), EntityType.ZOMBIE); e1.setInstance(instance, new Pos(0, 40, 0)).join(); e2.setInstance(instance, new Pos(0, 40, 0)).join(); @@ -124,9 +124,9 @@ public void lookAtEntitySameType(Env env) { public void lookAtEntityDifferentType(Env env) { var instance = env.createFlatInstance(); // same type, same eye height - var e1 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var e1 = new Entity(env.process(), EntityType.ZOMBIE); // a chicken has a lower eye height than a zombie - var e2 = new Entity(env.minecraftServer(), EntityType.CHICKEN); + var e2 = new Entity(env.process(), EntityType.CHICKEN); e1.setInstance(instance, new Pos(0, 40, 0)).join(); e2.setInstance(instance, new Pos(0, 40, 0)).join(); diff --git a/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java index 8815a9b5cec..0b6045606d9 100644 --- a/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityViewIntegrationTest.java @@ -14,7 +14,7 @@ public class EntityViewIntegrationTest { @Test public void emptyEntity(Env env) { var instance = env.createFlatInstance(); - var entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var entity = new Entity(env.process(), EntityType.ZOMBIE); entity.setInstance(instance, new Pos(0, 40, 42)).join(); assertEquals(0, entity.getViewers().size()); } @@ -128,8 +128,8 @@ public void livingVehicle(Env env) { var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 40, 0)).join(); - var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); - var passenger = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var vehicle = new Entity(env.process(), EntityType.ZOMBIE); + var passenger = new Entity(env.process(), EntityType.ZOMBIE); var tracker = connection.trackIncoming(SpawnEntityPacket.class); @@ -158,11 +158,11 @@ public void vehicleInheritance(Env env) { var p1 = env.createPlayer(instance, new Pos(0, 40, 0)); var p2 = env.createPlayer(instance, new Pos(0, 40, 0)); - var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var vehicle = new Entity(env.process(), EntityType.ZOMBIE); vehicle.setInstance(instance, new Pos(0, 40, 0)).join(); vehicle.addPassenger(p1); - var vehicle2 = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var vehicle2 = new Entity(env.process(), EntityType.ZOMBIE); vehicle2.setInstance(instance, new Pos(0, 40, 0)).join(); vehicle2.addPassenger(p2); diff --git a/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java b/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java index edb9b2b3588..5b7bfcf4876 100644 --- a/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/PassengerIntegrationTest.java @@ -13,8 +13,8 @@ public class PassengerIntegrationTest { @Test public void passenger(Env env) { var instance = env.createFlatInstance(); - var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); - var passenger = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var vehicle = new Entity(env.process(), EntityType.ZOMBIE); + var passenger = new Entity(env.process(), EntityType.ZOMBIE); vehicle.setInstance(instance, new Pos(0, 40, 0)).join(); passenger.setInstance(instance, new Pos(0, 40, 0)).join(); @@ -30,8 +30,8 @@ public void passenger(Env env) { @Test public void passengerTeleport(Env env) { var instance = env.createFlatInstance(); - var vehicle = new Entity(env.minecraftServer(), EntityType.ZOMBIE); - var passenger = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var vehicle = new Entity(env.process(), EntityType.ZOMBIE); + var passenger = new Entity(env.process(), EntityType.ZOMBIE); vehicle.setInstance(instance, new Pos(0, 40, 0)).join(); passenger.setInstance(instance, new Pos(0, 40, 5000)).join(); diff --git a/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java b/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java index 5a6f7ee3267..e4a023cf5c9 100644 --- a/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java +++ b/src/test/java/net/minestom/server/entity/ai/ClosestEntityTargetTest.java @@ -18,19 +18,19 @@ public class ClosestEntityTargetTest { public void validFindTarget(Env env) { var instance = env.createFlatInstance(); - var self = new EntityCreature(env.minecraftServer(), EntityType.ZOMBIE); + var self = new EntityCreature(env.process(), EntityType.ZOMBIE); self.setInstance(instance, new Pos(0, 42, 0)).join(); - var spider = new EntityCreature(env.minecraftServer(), EntityType.SPIDER); + var spider = new EntityCreature(env.process(), EntityType.SPIDER); spider.setInstance(instance, new Pos(-3, 42, -3)).join(); - var secondSpider = new EntityCreature(env.minecraftServer(), EntityType.SPIDER); + var secondSpider = new EntityCreature(env.process(), EntityType.SPIDER); secondSpider.setInstance(instance, new Pos(-4, 42, -4)).join(); - var skeleton = new EntityCreature(env.minecraftServer(), EntityType.SKELETON); + var skeleton = new EntityCreature(env.process(), EntityType.SKELETON); skeleton.setInstance(instance, new Pos(5, 42, 5)).join(); - var zombie = new EntityCreature(env.minecraftServer(), EntityType.ZOMBIE); + var zombie = new EntityCreature(env.process(), EntityType.ZOMBIE); zombie.setInstance(instance, new Pos(10, 42, -10)).join(); assertEquals(5, instance.getEntities().size(), "Not all entities are in the instance"); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java index eec6054981f..fc04e2402ea 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java @@ -63,7 +63,7 @@ public void singleTickMovementUpdate(Env env) { @Test public void chunkUpdateDebounceTest(Env env) { final Instance flatInstance = env.createFlatInstance(); - final int viewDiameter = env.minecraftServer().getChunkViewDistance() * 2 + 1; + final int viewDiameter = env.process().getMinecraftServer().getChunkViewDistance() * 2 + 1; // Preload all possible chunks to avoid issues due to async loading Set> chunks = new HashSet<>(); ChunkUtils.forChunksInRange(0, 0, viewDiameter+2, (x, z) -> chunks.add(flatInstance.loadChunk(x, z))); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java index 219866ebf74..e14f5c808ae 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java @@ -45,7 +45,7 @@ public void testChunkReloadCount(Env env) { player.setHealth(0); player.respawn(); // Player should have all their chunks reloaded - int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.minecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance())); + int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.process().getMinecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance())); loadChunkTracker.assertCount(chunkLoads); } @@ -61,7 +61,7 @@ public void testPlayerTryRespawn(Env env) { player.interpretPacketQueue(); List dataPacketList = loadChunkTracker.collect(); Set duplicateCheck = new HashSet<>(); - int actualViewDistance = Math.min(env.minecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance()); + int actualViewDistance = Math.min(env.process().getMinecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance()); int chunkLoads = ChunkUtils.getChunkCount(actualViewDistance); loadChunkTracker.assertCount(chunkLoads); for (ChunkDataPacket packet : dataPacketList) { diff --git a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java index 1f20afbfb29..cf352b0220d 100644 --- a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java @@ -1,6 +1,7 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import org.junit.jupiter.api.Test; import java.util.List; @@ -11,16 +12,16 @@ public class EventNodeGraphTest { @Test public void single() { - MinecraftServer minecraftServer = new MinecraftServer(); - EventNode node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + EventNode node = EventNode.all(serverProcess,"main"); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of())); } @Test public void singleChild() { - MinecraftServer minecraftServer = new MinecraftServer(); - EventNode node = EventNode.all(minecraftServer,"main"); - node.addChild(EventNode.all(minecraftServer,"child")); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + EventNode node = EventNode.all(serverProcess,"main"); + node.addChild(EventNode.all(serverProcess,"child")); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child", "Event", 0, List.of()) ))); @@ -28,20 +29,20 @@ public void singleChild() { @Test public void childrenPriority() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); { - EventNode node = EventNode.all(minecraftServer,"main"); - node.addChild(EventNode.all(minecraftServer,"child1").setPriority(5)); - node.addChild(EventNode.all(minecraftServer,"child2").setPriority(10)); + EventNode node = EventNode.all(serverProcess,"main"); + node.addChild(EventNode.all(serverProcess,"child1").setPriority(5)); + node.addChild(EventNode.all(serverProcess,"child2").setPriority(10)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) ))); } { - EventNode node = EventNode.all(minecraftServer, "main"); - node.addChild(EventNode.all(minecraftServer,"child2").setPriority(10)); - node.addChild(EventNode.all(minecraftServer,"child1").setPriority(5)); + EventNode node = EventNode.all(serverProcess, "main"); + node.addChild(EventNode.all(serverProcess,"child2").setPriority(10)); + node.addChild(EventNode.all(serverProcess,"child1").setPriority(5)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) diff --git a/src/test/java/net/minestom/server/event/EventNodeMapTest.java b/src/test/java/net/minestom/server/event/EventNodeMapTest.java index 5a8517d5831..528da5d6672 100644 --- a/src/test/java/net/minestom/server/event/EventNodeMapTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeMapTest.java @@ -1,6 +1,7 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import net.minestom.server.item.ItemStack; @@ -17,9 +18,9 @@ public class EventNodeMapTest { @Test public void uniqueMapping() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(minecraftServer,"main"); + var node = EventNode.all(serverProcess,"main"); var itemNode1 = node.map(item, EventFilter.ITEM); var itemNode2 = node.map(item, EventFilter.ITEM); assertNotNull(itemNode1); @@ -33,9 +34,9 @@ public void uniqueMapping() { @Test public void lazyRegistration() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all(minecraftServer,"main"); + var node = (EventNodeImpl) EventNode.all(serverProcess,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertFalse(node.registeredMappedNode.containsKey(item)); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { @@ -45,9 +46,9 @@ public void lazyRegistration() { @Test public void secondMap() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all(minecraftServer,"main"); + var node = (EventNodeImpl) EventNode.all(serverProcess,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertSame(itemNode, itemNode.map(item, EventFilter.ITEM)); assertThrows(Exception.class, () -> itemNode.map(ItemStack.AIR, EventFilter.ITEM)); @@ -55,9 +56,9 @@ public void secondMap() { @Test public void map() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(minecraftServer, "main"); + var node = EventNode.all(serverProcess, "main"); AtomicBoolean result = new AtomicBoolean(false); var itemNode = node.map(item, EventFilter.ITEM); @@ -81,10 +82,9 @@ public void map() { @Test public void entityLocal() { - MinecraftServer minecraftServer = new MinecraftServer(); - var process = minecraftServer.updateProcess(); - var node = process.getGlobalEventHandler(); - var entity = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = serverProcess.getGlobalEventHandler(); + var entity = new Entity(serverProcess, EntityType.ZOMBIE); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventNodeTest.EntityTestEvent.class, event -> result.set(true)); @@ -108,10 +108,10 @@ public void entityLocal() { @Test public void ownerGC() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // Ensure that the mapped object gets GCed var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(minecraftServer,"main"); + var node = EventNode.all(serverProcess,"main"); var itemNode = node.map(item, EventFilter.ITEM); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { }); diff --git a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java index 052c2cd7922..49044e3fbc2 100644 --- a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java @@ -1,6 +1,7 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.event.trait.EntityEvent; import net.minestom.server.event.trait.PlayerEvent; import org.junit.jupiter.api.Test; @@ -14,13 +15,13 @@ public class EventNodeQueryTest { @Test public void find() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer, "main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess, "main"); assertEquals(List.of(), node.findChildren("test")); - var child1 = EventNode.all(minecraftServer,"test"); - var child2 = EventNode.all(minecraftServer,"test"); - var child3 = EventNode.all(minecraftServer,"test3"); + var child1 = EventNode.all(serverProcess,"test"); + var child2 = EventNode.all(serverProcess,"test"); + var child3 = EventNode.all(serverProcess,"test3"); node.addChild(child1); node.addChild(child2); @@ -36,13 +37,13 @@ public void find() { @Test public void findType() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); assertEquals(List.of(), node.findChildren("test", Event.class)); - var child1 = EventNode.type(minecraftServer, "test", EventFilter.PLAYER); - var child2 = EventNode.type(minecraftServer, "test", EventFilter.ENTITY); - var child3 = EventNode.type(minecraftServer, "test3", EventFilter.ENTITY); + var child1 = EventNode.type(serverProcess, "test", EventFilter.PLAYER); + var child2 = EventNode.type(serverProcess, "test", EventFilter.ENTITY); + var child3 = EventNode.type(serverProcess, "test3", EventFilter.ENTITY); node.addChild(child1); node.addChild(child2); @@ -62,19 +63,19 @@ public void findType() { @Test public void replace() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); - var child1 = EventNode.all(minecraftServer,"test"); - var child2 = EventNode.all(minecraftServer,"test"); - var child3 = EventNode.all(minecraftServer,"test3"); + var child1 = EventNode.all(serverProcess,"test"); + var child2 = EventNode.all(serverProcess,"test"); + var child3 = EventNode.all(serverProcess,"test3"); node.addChild(child1); node.addChild(child2); node.addChild(child3); - var tmp1 = EventNode.all(minecraftServer,"tmp1"); - var tmp2 = EventNode.all(minecraftServer,"tmp2"); + var tmp1 = EventNode.all(serverProcess,"tmp1"); + var tmp2 = EventNode.all(serverProcess,"tmp2"); node.replaceChildren("test", tmp1); assertEqualsIgnoreOrder(List.of(child2), node.findChildren("test")); diff --git a/src/test/java/net/minestom/server/event/EventNodeTest.java b/src/test/java/net/minestom/server/event/EventNodeTest.java index 58dab585b74..055f498fc1b 100644 --- a/src/test/java/net/minestom/server/event/EventNodeTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeTest.java @@ -1,6 +1,7 @@ package net.minestom.server.event; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.event.trait.EntityEvent; @@ -59,8 +60,8 @@ record EntityTestEvent(Entity entity) implements EntityEvent { @Test public void testCall() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventTest.class, eventTest -> result.set(true)); node.addListener(listener); @@ -77,8 +78,8 @@ public void testCall() { @Test public void testHandle() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); var handle = node.getHandle(EventTest.class); assertSame(handle, node.getHandle(EventTest.class)); @@ -88,8 +89,8 @@ public void testHandle() { @Test public void testCancellable() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.builder(CancellableTest.class) .handler(event -> { @@ -108,8 +109,8 @@ public void testCancellable() { @Test public void recursiveSub() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); AtomicBoolean result1 = new AtomicBoolean(false); AtomicBoolean result2 = new AtomicBoolean(false); var listener1 = EventListener.of(Recursive1.class, event -> result1.set(true)); @@ -150,15 +151,15 @@ public void recursiveSub() { @Test public void testChildren() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); AtomicInteger result = new AtomicInteger(0); - var child1 = EventNode.all(minecraftServer,"child1").setPriority(1) + var child1 = EventNode.all(serverProcess,"child1").setPriority(1) .addListener(EventTest.class, eventTest -> { assertEquals(0, result.get(), "child1 should be called before child2"); result.set(1); }); - var child2 = EventNode.all(minecraftServer,"child2").setPriority(2) + var child2 = EventNode.all(serverProcess,"child2").setPriority(2) .addListener(EventTest.class, eventTest -> { assertEquals(1, result.get(), "child2 should be called after child1"); result.set(2); @@ -185,13 +186,13 @@ public void testChildren() { @Test public void testFiltering() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); AtomicBoolean result = new AtomicBoolean(false); AtomicBoolean childResult = new AtomicBoolean(false); - var node = EventNode.type(minecraftServer,"item_node", EventFilter.ITEM, + var node = EventNode.type(serverProcess,"item_node", EventFilter.ITEM, (event, item) -> item.material() == Material.DIAMOND); - var child = EventNode.type(minecraftServer,"item_node2", EventFilter.ITEM) + var child = EventNode.type(serverProcess,"item_node2", EventFilter.ITEM) .addListener(ItemTestEvent.class, event -> childResult.set(true)); node.addChild(child); @@ -210,8 +211,8 @@ public void testFiltering() { @Test public void testBinding() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); AtomicBoolean result = new AtomicBoolean(false); var binding = EventBinding.filtered(EventFilter.ITEM, itemStack -> itemStack.material() == Material.DIAMOND) @@ -233,8 +234,8 @@ public void testBinding() { @Test public void nodeEmptyGC() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); var ref = new WeakReference<>(node); //noinspection UnusedAssignment @@ -244,8 +245,8 @@ public void nodeEmptyGC() { @Test public void nodeGC() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); var ref = new WeakReference<>(node); node.addListener(EventTest.class, event -> { }); @@ -272,8 +273,8 @@ public void nodeGC() { @Test public void nodeMapGC() { - MinecraftServer minecraftServer = new MinecraftServer(); - var node = EventNode.all(minecraftServer,"main"); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var node = EventNode.all(serverProcess,"main"); var handler = ItemStack.AIR; var mapped = node.map(handler, EventFilter.ITEM); diff --git a/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java b/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java index 395dd776f5e..20656932cd3 100644 --- a/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/AnvilLoaderIntegrationTest.java @@ -51,7 +51,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) public void loadHouse(Env env) { // load a world that contains only a basic house and make sure it is loaded properly - AnvilLoader chunkLoader = new AnvilLoader(env.minecraftServer(), worldFolder) { + AnvilLoader chunkLoader = new AnvilLoader(env.process(), worldFolder) { // Force loads inside current thread @Override public boolean supportsParallelLoading() { @@ -146,7 +146,7 @@ public boolean supportsParallelSaving() { @Test public void loadAndSaveChunk(Env env) throws InterruptedException { - Instance instance = env.createFlatInstance(new AnvilLoader(env.minecraftServer(), worldFolder) { + Instance instance = env.createFlatInstance(new AnvilLoader(env.process(), worldFolder) { // Force loads inside current thread @Override public boolean supportsParallelLoading() { diff --git a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java index 468e7affe42..b2905a70845 100644 --- a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java @@ -36,7 +36,7 @@ public void basicJoin(boolean sharedInstance, Env env) { @Test public void renderDistance(Env env) { - final int viewRadius = env.minecraftServer().getChunkViewDistance(); + final int viewRadius = env.process().getMinecraftServer().getChunkViewDistance(); final int count = ChunkUtils.getChunkCount(viewRadius); var instance = env.createFlatInstance(); var connection = env.createConnection(); diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java index 72d4d9c3782..90a841eeb53 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -27,11 +27,11 @@ public void maxDistance(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = env.minecraftServer().getEntityViewDistance(); + final int viewDistanceInChunks = env.process().getMinecraftServer().getEntityViewDistance(); - final Player viewer = createTestPlayer(env.minecraftServer()); + final Player viewer = createTestPlayer(env.process()); final AtomicInteger viewersCount = new AtomicInteger(); - final Entity entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE) { + final Entity entity = new Entity(env.process(), EntityType.ZOMBIE) { @Override public void updateNewViewer(Player player) { viewersCount.incrementAndGet(); @@ -59,11 +59,11 @@ public void cornerInstanceSwap(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = env.minecraftServer().getEntityViewDistance(); + final int viewDistanceInChunks = env.process().getMinecraftServer().getEntityViewDistance(); - final Player viewer = createTestPlayer(env.minecraftServer()); + final Player viewer = createTestPlayer(env.process()); final AtomicInteger viewersCount = new AtomicInteger(); - final Entity entity = new Entity(env.minecraftServer(), EntityType.ZOMBIE) { + final Entity entity = new Entity(env.process(), EntityType.ZOMBIE) { @Override public void updateNewViewer(Player player) { viewersCount.incrementAndGet(); @@ -129,8 +129,8 @@ public void viewableShared(Env env) { assertEquals(1, viewable.getViewers().size()); } - private Player createTestPlayer(MinecraftServer minecraftServer) { - return new Player(minecraftServer, UUID.randomUUID(), "TestPlayer", new PlayerConnection(minecraftServer) { + private Player createTestPlayer(ServerProcess serverProcess) { + return new Player(serverProcess, UUID.randomUUID(), "TestPlayer", new PlayerConnection(serverProcess) { @Override public void sendPacket(@NotNull SendablePacket packet) { // nothing diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java index a28e626c52c..294906238ac 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java @@ -1,6 +1,7 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -15,8 +16,8 @@ public class EntityTrackerTest { @Test public void register() { - MinecraftServer minecraftServer = new MinecraftServer(); - var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -30,7 +31,7 @@ public void remove(@NotNull Entity entity) { fail("No other entity should be registered yet"); } }; - EntityTracker tracker = EntityTracker.newTracker(minecraftServer); + EntityTracker tracker = EntityTracker.newTracker(serverProcess); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); assertTrue(chunkEntities.isEmpty()); @@ -43,8 +44,8 @@ public void remove(@NotNull Entity entity) { @Test public void move() { - MinecraftServer minecraftServer = new MinecraftServer(); - var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -57,7 +58,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(minecraftServer); + EntityTracker tracker = EntityTracker.newTracker(serverProcess); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, updater); assertEquals(1, tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES).size()); @@ -69,11 +70,11 @@ public void remove(@NotNull Entity entity) { @Test public void tracking() { - MinecraftServer minecraftServer = new MinecraftServer(); - var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); - var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); + var ent2 = new Entity(serverProcess, EntityType.ZOMBIE); - EntityTracker tracker = EntityTracker.newTracker(minecraftServer); + EntityTracker tracker = EntityTracker.newTracker(serverProcess); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -129,10 +130,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearby() { - MinecraftServer minecraftServer = new MinecraftServer(); - var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); - var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); - var ent3 = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); + var ent2 = new Entity(serverProcess, EntityType.ZOMBIE); + var ent3 = new Entity(serverProcess, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -145,7 +146,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(minecraftServer); + EntityTracker tracker = EntityTracker.newTracker(serverProcess); tracker.register(ent2, new Vec(5, 0, 0), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(50, 0, 0), EntityTracker.Target.ENTITIES, updater); @@ -183,10 +184,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearbySingleChunk() { - MinecraftServer minecraftServer = new MinecraftServer(); - var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); - var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); - var ent3 = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); + var ent2 = new Entity(serverProcess, EntityType.ZOMBIE); + var ent3 = new Entity(serverProcess, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -199,7 +200,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(minecraftServer); + EntityTracker tracker = EntityTracker.newTracker(serverProcess); tracker.register(ent1, new Vec(5, 0, 5), EntityTracker.Target.ENTITIES, updater); tracker.register(ent2, new Vec(8, 0, 8), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(17, 0, 17), EntityTracker.Target.ENTITIES, updater); @@ -224,8 +225,8 @@ public void remove(@NotNull Entity entity) { @Test public void collectionView() { - MinecraftServer minecraftServer = new MinecraftServer(); - var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -240,7 +241,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(minecraftServer); + EntityTracker tracker = EntityTracker.newTracker(serverProcess); var entities = tracker.entities(); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); @@ -250,7 +251,7 @@ public void remove(@NotNull Entity entity) { assertEquals(1, entities.size()); assertEquals(1, chunkEntities.size()); - assertThrows(Exception.class, () -> entities.add(new Entity(minecraftServer, EntityType.ZOMBIE))); - assertThrows(Exception.class, () -> chunkEntities.add(new Entity(minecraftServer, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> entities.add(new Entity(serverProcess, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> chunkEntities.add(new Entity(serverProcess, EntityType.ZOMBIE))); } } diff --git a/src/test/java/net/minestom/server/instance/GeneratorTest.java b/src/test/java/net/minestom/server/instance/GeneratorTest.java index f64d0dfcd06..91dfeecb58b 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorTest.java @@ -1,6 +1,7 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -30,13 +31,13 @@ public class GeneratorTest { @Test public void unitSize() { - MinecraftServer minecraftServer = new MinecraftServer(); - assertDoesNotThrow(() -> dummyUnit(minecraftServer, Vec.ZERO, new Vec(16))); - assertDoesNotThrow(() -> dummyUnit(minecraftServer, new Vec(16), new Vec(32))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, new Vec(15), Vec.ZERO)); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, new Vec(15), new Vec(32))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, new Vec(15), new Vec(31))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(minecraftServer, Vec.ZERO, new Vec(15))); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertDoesNotThrow(() -> dummyUnit(serverProcess, Vec.ZERO, new Vec(16))); + assertDoesNotThrow(() -> dummyUnit(serverProcess, new Vec(16), new Vec(32))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, new Vec(15), Vec.ZERO)); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, new Vec(15), new Vec(32))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, new Vec(15), new Vec(31))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, Vec.ZERO, new Vec(15))); } @ParameterizedTest @@ -79,15 +80,15 @@ private static Stream sectionCeilParam() { @Test public void chunkSize() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + GenerationUnit chunk = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); assertEquals(new Vec(16, sectionCount * 16, 16), chunk.size()); assertEquals(new Vec(chunkX * 16, minSection * 16, chunkZ * 16), chunk.absoluteStart()); assertEquals(new Vec(chunkX * 16 + 16, maxSection * 16, chunkZ * 16 + 16), chunk.absoluteEnd()); @@ -95,15 +96,15 @@ public void chunkSize() { @Test public void chunkSizeNeg() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + GenerationUnit chunk = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); assertEquals(new Vec(16, sectionCount * 16, 16), chunk.size()); assertEquals(new Vec(chunkX * 16, minSection * 16, chunkZ * 16), chunk.absoluteStart()); assertEquals(new Vec(chunkX * 16 + 16, maxSection * 16, chunkZ * 16 + 16), chunk.absoluteEnd()); @@ -111,11 +112,11 @@ public void chunkSizeNeg() { @Test public void sectionSize() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int sectionX = 3; final int sectionY = -5; final int sectionZ = -2; - GenerationUnit section = GeneratorImpl.section(minecraftServer, new Section(minecraftServer), sectionX, sectionY, sectionZ); + GenerationUnit section = GeneratorImpl.section(serverProcess, new Section(serverProcess), sectionX, sectionY, sectionZ); assertEquals(new Vec(16), section.size()); assertEquals(new Vec(sectionX * 16, sectionY * 16, sectionZ * 16), section.absoluteStart()); assertEquals(new Vec(sectionX * 16 + 16, sectionY * 16 + 16, sectionZ * 16 + 16), section.absoluteEnd()); @@ -123,15 +124,15 @@ public void sectionSize() { @Test public void chunkSubdivide() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + GenerationUnit chunk = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); var subUnits = chunk.subdivide(); assertEquals(sectionCount, subUnits.size()); for (int i = 0; i < sectionCount; i++) { @@ -144,15 +145,15 @@ public void chunkSubdivide() { @Test public void chunkAbsolute() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); assertThrows(Exception.class, () -> modifier.setBlock(0, 0, 0, Block.STONE), "Block outside of chunk"); @@ -166,15 +167,15 @@ public void chunkAbsolute() { @Test public void chunkAbsoluteAll() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); Set points = new HashSet<>(); @@ -195,15 +196,15 @@ public void chunkAbsoluteAll() { @Test public void chunkRelative() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); assertThrows(Exception.class, () -> modifier.setRelative(-1, 0, 0, Block.STONE)); @@ -223,15 +224,15 @@ public void chunkRelative() { @Test public void chunkRelativeAll() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); Set points = new HashSet<>(); @@ -253,15 +254,15 @@ public void chunkRelativeAll() { @Test public void chunkBiomeSet() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); modifier.setBiome(48, 0, -32, Biome.PLAINS); @@ -275,15 +276,15 @@ public void chunkBiomeSet() { @Test public void chunkBiomeFill() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); modifier.fillBiome(Biome.PLAINS); @@ -297,13 +298,13 @@ public void chunkBiomeFill() { @Test public void chunkFillHeightExact() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), 3, -2); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), 3, -2); Generator generator = chunk -> chunk.modifier().fillHeight(0, 32, Block.STONE); generator.generate(chunkUnits); @@ -322,13 +323,13 @@ public void chunkFillHeightExact() { @Test public void chunkFillHeightOneOff() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(minecraftServer)); - var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), 3, -2); + Arrays.setAll(sections, i -> new Section(serverProcess)); + var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), 3, -2); Generator generator = chunk -> chunk.modifier().fillHeight(1, 33, Block.STONE); generator.generate(chunkUnits); @@ -361,16 +362,16 @@ public void chunkFillHeightOneOff() { @Test public void sectionFill() { - MinecraftServer minecraftServer = new MinecraftServer(); - Section section = new Section(minecraftServer); - var chunkUnit = GeneratorImpl.section(minecraftServer, section, -1, -1, 0); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + Section section = new Section(serverProcess); + var chunkUnit = GeneratorImpl.section(serverProcess, section, -1, -1, 0); Generator generator = chunk -> chunk.modifier().fill(Block.STONE); generator.generate(chunkUnit); section.blockPalette().getAll((x, y, z, value) -> assertEquals(Block.STONE.stateId(), value)); } - static GenerationUnit dummyUnit(MinecraftServer minecraftServer, Point start, Point end) { - return unit(minecraftServer,null, start, end, null); + static GenerationUnit dummyUnit(ServerProcess serverProcess, Point start, Point end) { + return unit(serverProcess,null, start, end, null); } } diff --git a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java index a03ff5469e9..e9e9cb2d2e6 100644 --- a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java @@ -1,6 +1,7 @@ package net.minestom.server.instance; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.tag.Tag; import net.minestom.server.world.DimensionType; import net.minestom.server.world.DimensionTypeManager; @@ -18,9 +19,9 @@ public class InstanceContainerTest { @Test public void copyPreservesTag() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var tag = Tag.String("test"); - var instance = new InstanceContainer(minecraftServer, UUID.randomUUID(), DimensionType.OVERWORLD); + var instance = new InstanceContainer(serverProcess, UUID.randomUUID(), DimensionType.OVERWORLD); instance.setTag(tag, "123"); var copyInstance = instance.copy(); diff --git a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java index 050f517bf6a..7eb99953b75 100644 --- a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java @@ -86,7 +86,7 @@ public void chunkGC(Env env) { @Test public void testGCWithEventsLambda(Env env) { - var ref = new WeakReference<>(new InstanceContainer(env.minecraftServer(), UUID.randomUUID(), DimensionType.OVERWORLD)); + var ref = new WeakReference<>(new InstanceContainer(env.process(), UUID.randomUUID(), DimensionType.OVERWORLD)); env.process().getInstanceManager().registerInstance(ref.get()); tmp(ref.get()); diff --git a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java index fbe5b180bf3..903ddb446b7 100644 --- a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java +++ b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java @@ -1,6 +1,7 @@ package net.minestom.server.instance.light; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.palette.Palette; @@ -18,8 +19,8 @@ public class BlockLightTest { @Test public void empty() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); var result = LightCompute.compute(palette); for (byte light : result.light()) { assertEquals(0, light); @@ -28,8 +29,8 @@ public void empty() { @Test public void glowstone() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -40,8 +41,8 @@ public void glowstone() { @Test public void doubleGlowstone() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); @@ -55,8 +56,8 @@ public void doubleGlowstone() { @Test public void glowstoneBorder() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -74,8 +75,8 @@ public void glowstoneBorder() { @Test public void glowstoneBlock() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(0, 1, 1, Block.STONE.stateId()); var result = LightCompute.compute(palette); @@ -87,8 +88,8 @@ public void glowstoneBlock() { @Test public void isolated() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.STONE.stateId()); @@ -115,8 +116,8 @@ public void isolated() { @Test public void isolatedStair() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "east", @@ -138,8 +139,8 @@ public void isolatedStair() { @Test public void isolatedStairOpposite() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -166,8 +167,8 @@ public void isolatedStairOpposite() { @Test public void isolatedStairWest() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -197,8 +198,8 @@ public void isolatedStairWest() { @Test public void isolatedStairSouth() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "south", diff --git a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java index c40f20c732b..03c54f70fa2 100644 --- a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.*; import net.minestom.server.instance.block.Block; @@ -30,12 +30,12 @@ public class LightParityIntegrationTest { @Test public void test(Env env) throws URISyntaxException, IOException, AnvilException { - Map sections = retrieveSections(env.minecraftServer()); + Map sections = retrieveSections(env.process()); // Generate our own light InstanceContainer instance = (InstanceContainer) env.createFlatInstance(); instance.setChunkSupplier(LightingChunk::new); - instance.setChunkLoader(new AnvilLoader(env.minecraftServer(), Path.of("./src/test/resources/net/minestom/server/instance/lighting"))); + instance.setChunkLoader(new AnvilLoader(env.process(), Path.of("./src/test/resources/net/minestom/server/instance/lighting"))); List> futures = new ArrayList<>(); @@ -127,7 +127,7 @@ public void test(Env env) throws URISyntaxException, IOException, AnvilException record SectionEntry(Palette blocks, byte[] sky, byte[] block) { } - private static Map retrieveSections(MinecraftServer minecraftServer) throws IOException, URISyntaxException, AnvilException { + private static Map retrieveSections(ServerProcess serverProcess) throws IOException, URISyntaxException, AnvilException { URL defaultImage = LightParityIntegrationTest.class.getResource("/net/minestom/server/instance/lighting/region/r.0.0.mca"); assert defaultImage != null; File imageFile = new File(defaultImage.toURI()); @@ -143,7 +143,7 @@ private static Map retrieveSections(MinecraftServer minecraft for (int yLevel = chunk.getMinY(); yLevel <= chunk.getMaxY(); yLevel += 16) { var section = chunk.getSection((byte) (yLevel/16)); - var palette = loadBlocks(minecraftServer, section); + var palette = loadBlocks(serverProcess, section); var sky = section.getSkyLights(); var block = section.getBlockLights(); sections.put(new Vec(x, section.getY(), z), new SectionEntry(palette, sky, block)); @@ -153,8 +153,8 @@ private static Map retrieveSections(MinecraftServer minecraft return sections; } - private static Palette loadBlocks(MinecraftServer minecraftServer, ChunkSection section) throws AnvilException { - var palette = Palette.blocks(minecraftServer); + private static Palette loadBlocks(ServerProcess serverProcess, ChunkSection section) throws AnvilException { + var palette = Palette.blocks(serverProcess); for (int x = 0; x < Chunk.CHUNK_SECTION_SIZE; x++) { for (int z = 0; z < Chunk.CHUNK_SECTION_SIZE; z++) { for (int y = 0; y < Chunk.CHUNK_SECTION_SIZE; y++) { diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java index 1105482df76..60dab1b3f5f 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java @@ -1,6 +1,7 @@ package net.minestom.server.instance.palette; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.network.NetworkBuffer; import org.junit.jupiter.api.Test; @@ -13,24 +14,24 @@ public class PaletteOptimizationTest { @Test public void empty() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = createPalette(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = createPalette(serverProcess); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void single() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = createPalette(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = createPalette(serverProcess); palette.set(0, 0, 0, 1); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void random() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var random = new Random(12345); - var palette = createPalette(minecraftServer); + var palette = createPalette(serverProcess); palette.setAll((x, y, z) -> random.nextInt(256)); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> random.nextInt(2)); @@ -39,8 +40,8 @@ public void random() { @Test public void manualFill() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = createPalette(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = createPalette(serverProcess); palette.setAll((x, y, z) -> 1); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> 2); @@ -49,8 +50,8 @@ public void manualFill() { paletteEquals(palette.palette, palette.optimizedPalette()); } - AdaptivePalette createPalette(MinecraftServer minecraftServer) { - return (AdaptivePalette) Palette.blocks(minecraftServer); + AdaptivePalette createPalette(ServerProcess serverProcess) { + return (AdaptivePalette) Palette.blocks(serverProcess); } void paletteEquals(Palette palette, Palette optimized) { diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java index 2f075cd764f..30bb0833cbb 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java @@ -1,6 +1,7 @@ package net.minestom.server.instance.palette; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import org.junit.jupiter.api.Test; @@ -16,16 +17,16 @@ public class PaletteTest { @Test public void singlePlacement() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.blocks(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverProcess); palette.set(0, 0, 1, 1); assertEquals(1, palette.get(0, 0, 1)); } @Test public void placement() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { final int dimension = palette.dimension(); assertEquals(0, palette.get(0, 0, 0), "Default value should be 0"); @@ -60,9 +61,9 @@ public void placement() { @Test public void placementHighValue() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int value = 250_000; - for (Palette palette : testPalettes(minecraftServer)) { + for (Palette palette : testPalettes(serverProcess)) { palette.set(0, 0, 1, value); assertEquals(value, palette.get(0, 0, 1)); } @@ -70,8 +71,8 @@ public void placementHighValue() { @Test public void negPlacement() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { assertThrows(IllegalArgumentException.class, () -> palette.set(-1, 0, 0, 64)); assertThrows(IllegalArgumentException.class, () -> palette.set(0, -1, 0, 64)); @@ -85,8 +86,8 @@ public void negPlacement() { @Test public void resize() { - MinecraftServer minecraftServer = new MinecraftServer(); - Palette palette = Palette.newPalette(minecraftServer,16, 5, 2); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + Palette palette = Palette.newPalette(serverProcess,16, 5, 2); palette.set(0, 0, 0, 1); assertEquals(2, palette.bitsPerEntry()); palette.set(0, 0, 1, 2); @@ -105,8 +106,8 @@ public void resize() { @Test public void fill() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { assertEquals(0, palette.count()); palette.set(0, 0, 0, 5); @@ -137,8 +138,8 @@ public void fill() { @Test public void bulk() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { final int dimension = palette.dimension(); // Place @@ -163,8 +164,8 @@ public void bulk() { @Test public void bulkAll() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { // Fill all entries palette.setAll((x, y, z) -> x + y + z + 1); @@ -182,8 +183,8 @@ public void bulkAll() { @Test public void bulkAllOrder() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { AtomicInteger count = new AtomicInteger(); @@ -221,8 +222,8 @@ public void bulkAllOrder() { @Test public void setAllConstant() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { palette.setAll((x, y, z) -> 1); palette.getAll((x, y, z, value) -> assertEquals(1, value)); @@ -231,8 +232,8 @@ public void setAllConstant() { @Test public void getAllPresent() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { palette.getAllPresent((x, y, z, value) -> fail("The palette should be empty")); palette.set(0, 0, 1, 1); @@ -247,8 +248,8 @@ public void getAllPresent() { @Test public void replaceAll() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { palette.setAll((x, y, z) -> x + y + z + 1); palette.replaceAll((x, y, z, value) -> { @@ -261,8 +262,8 @@ public void replaceAll() { @Test public void replace() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palettes = testPalettes(minecraftServer); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverProcess); for (Palette palette : palettes) { palette.set(0, 0, 0, 1); palette.replace(0, 0, 0, operand -> { @@ -275,8 +276,8 @@ public void replace() { @Test public void replaceLoop() { - MinecraftServer minecraftServer = new MinecraftServer(); - var palette = Palette.newPalette(minecraftServer,2, 15, 4); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var palette = Palette.newPalette(serverProcess,2, 15, 4); palette.setAll((x, y, z) -> x + y + z); final int dimension = palette.dimension(); for (int x = 0; x < dimension; x++) { @@ -290,22 +291,22 @@ public void replaceLoop() { @Test public void dimension() { - MinecraftServer minecraftServer = new MinecraftServer(); - assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,-4, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,0, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,1, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(minecraftServer,2, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,3, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(minecraftServer,4, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(minecraftServer,6, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(minecraftServer,16, 5, 3)); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,-4, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,0, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,1, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(serverProcess,2, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,3, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(serverProcess,4, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,6, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(serverProcess,16, 5, 3)); } - private static List testPalettes(MinecraftServer minecraftServer) { + private static List testPalettes(ServerProcess serverProcess) { return List.of( - Palette.newPalette(minecraftServer,2, 5, 3), - Palette.newPalette(minecraftServer,4, 5, 3), - Palette.newPalette(minecraftServer,8, 5, 3), - Palette.newPalette(minecraftServer,16, 5, 3)); + Palette.newPalette(serverProcess,2, 5, 3), + Palette.newPalette(serverProcess,4, 5, 3), + Palette.newPalette(serverProcess,8, 5, 3), + Palette.newPalette(serverProcess,16, 5, 3)); } } diff --git a/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java b/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java index 11bd3dfe3f1..df1b6a598cf 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryCloseStateTest.java @@ -22,7 +22,7 @@ public void doNotReceiveClosePacketFromServerWhenSendingClientCloseWindowPacket( assertEquals(instance, player.getInstance()); var packetTracker = connection.trackIncoming(CloseWindowPacket.class); - var inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_2_ROW, Component.text("Test")); + var inventory = new Inventory(env.process(), InventoryType.CHEST_2_ROW, Component.text("Test")); player.openInventory(inventory); player.closeInventory(); // Closes the inventory server-side, should send a CloseWindowPacket player.openInventory(inventory); diff --git a/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java b/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java index d2040caca1f..89bfb95426a 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryIntegrationTest.java @@ -26,7 +26,7 @@ public void setSlotDuplicateTest(Env env) { var player = connection.connect(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, player.getInstance()); - Inventory inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_6_ROW, Component.empty()); + Inventory inventory = new Inventory(env.process(), InventoryType.CHEST_6_ROW, Component.empty()); player.openInventory(inventory); assertEquals(inventory, player.getOpenInventory()); @@ -50,7 +50,7 @@ public void setCursorItemDuplicateTest(Env env) { var player = connection.connect(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, player.getInstance()); - Inventory inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_6_ROW, Component.empty()); + Inventory inventory = new Inventory(env.process(), InventoryType.CHEST_6_ROW, Component.empty()); player.openInventory(inventory); assertEquals(inventory, player.getOpenInventory()); @@ -74,7 +74,7 @@ public void clearInventoryTest(Env env) { var player = connection.connect(instance, new Pos(0, 42, 0)).join(); assertEquals(instance, player.getInstance()); - Inventory inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_6_ROW, Component.empty()); + Inventory inventory = new Inventory(env.process(), InventoryType.CHEST_6_ROW, Component.empty()); player.openInventory(inventory); assertEquals(inventory, player.getOpenInventory()); @@ -115,7 +115,7 @@ public void closeInventoryTest(Env env) { var instance = env.createFlatInstance(); var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 42, 0)).join(); - final var inventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_1_ROW, "title"); + final var inventory = new Inventory(env.process(), InventoryType.CHEST_1_ROW, "title"); player.openInventory(inventory); assertSame(inventory, player.getOpenInventory()); player.closeInventory(); @@ -128,7 +128,7 @@ public void openInventoryOnItemDropFromInventoryClosingTest(Env env) { var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 42, 0)).join(); var listener = env.listen(ItemDropEvent.class); - final var firstInventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_1_ROW, "title"); + final var firstInventory = new Inventory(env.process(), InventoryType.CHEST_1_ROW, "title"); player.openInventory(firstInventory); assertSame(firstInventory, player.getOpenInventory()); firstInventory.setCursorItem(player, ItemStack.of(Material.STONE)); @@ -139,7 +139,7 @@ public void openInventoryOnItemDropFromInventoryClosingTest(Env env) { player.openInventory(firstInventory); firstInventory.setCursorItem(player, ItemStack.of(Material.STONE)); - final var secondInventory = new Inventory(env.minecraftServer(), InventoryType.CHEST_1_ROW, "title"); + final var secondInventory = new Inventory(env.process(), InventoryType.CHEST_1_ROW, "title"); listener.followup(event -> event.getPlayer().openInventory(secondInventory)); player.closeInventory(); assertSame(secondInventory, player.getOpenInventory()); diff --git a/src/test/java/net/minestom/server/inventory/InventoryTest.java b/src/test/java/net/minestom/server/inventory/InventoryTest.java index 1a8688e7f71..377d701ebef 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryTest.java @@ -1,7 +1,8 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import org.junit.jupiter.api.Test; @@ -10,16 +11,11 @@ public class InventoryTest { - private static MinecraftServer minecraftServer = new MinecraftServer(); - - static { - // Required to prevent initialization error during event call - minecraftServer.init(); - } + private static ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); @Test public void testCreation() { - Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title"); assertEquals(InventoryType.CHEST_1_ROW, inventory.getInventoryType()); assertEquals(Component.text("title"), inventory.getTitle()); @@ -32,7 +28,7 @@ public void testEntry() { var item1 = ItemStack.of(Material.DIAMOND); var item2 = ItemStack.of(Material.GOLD_INGOT); - Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title"); assertSame(ItemStack.AIR, inventory.getItemStack(0)); inventory.setItemStack(0, item1); assertSame(item1, inventory.getItemStack(0)); @@ -56,7 +52,7 @@ public void testEntry() { @Test public void testTake() { ItemStack item = ItemStack.of(Material.DIAMOND, 32); - Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title"); inventory.setItemStack(0, item); assertTrue(inventory.takeItemStack(item, TransactionOption.DRY_RUN)); assertTrue(inventory.takeItemStack(item.withAmount(31), TransactionOption.DRY_RUN)); @@ -69,7 +65,7 @@ public void testTake() { @Test public void testAdd() { - Inventory inventory = new Inventory(minecraftServer, InventoryType.HOPPER, "title"); + Inventory inventory = new Inventory(serverProcess, InventoryType.HOPPER, "title"); assertTrue(inventory.addItemStack(ItemStack.of(Material.DIAMOND, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.GOLD_BLOCK, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.MAP, 32), TransactionOption.ALL_OR_NOTHING)); @@ -81,7 +77,7 @@ public void testAdd() { @Test public void testIds() { for (int i = 0; i <= 1000; ++i) { - final byte windowId = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title").getWindowId(); + final byte windowId = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title").getWindowId(); assertTrue(windowId > 0); } } diff --git a/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java b/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java index a60172c67cb..341e6a796a8 100644 --- a/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/click/integration/HeldClickIntegrationTest.java @@ -99,7 +99,7 @@ public void heldSelf(Env env) { public void heldExternal(Env env) { var instance = env.createFlatInstance(); var player = env.createPlayer(instance, new Pos(0, 40, 0)); - var inventory = new Inventory(env.minecraftServer(), InventoryType.HOPPER, "test"); + var inventory = new Inventory(env.process(), InventoryType.HOPPER, "test"); var playerInv = player.getInventory(); player.openInventory(inventory); var listener = env.listen(InventoryPreClickEvent.class); diff --git a/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java b/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java index 904a00d2a44..538902b8edf 100644 --- a/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/click/integration/LeftClickIntegrationTest.java @@ -85,7 +85,7 @@ public void leftSelf(Env env) { public void leftExternal(Env env) { var instance = env.createFlatInstance(); var player = env.createPlayer(instance, new Pos(0, 40, 0)); - var inventory = new Inventory(env.minecraftServer(), InventoryType.HOPPER, "test"); + var inventory = new Inventory(env.process(), InventoryType.HOPPER, "test"); player.openInventory(inventory); var listener = env.listen(InventoryPreClickEvent.class); inventory.setItemStack(1, ItemStack.of(Material.DIAMOND)); diff --git a/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java b/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java index e61fcfdf578..e8c4c25b5c8 100644 --- a/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java +++ b/src/test/java/net/minestom/server/inventory/click/integration/RightClickIntegrationTest.java @@ -107,7 +107,7 @@ public void rightSelf(Env env) { public void rightExternal(Env env) { var instance = env.createFlatInstance(); var player = env.createPlayer(instance, new Pos(0, 40, 0)); - var inventory = new Inventory(env.minecraftServer(), InventoryType.HOPPER, "test"); + var inventory = new Inventory(env.process(), InventoryType.HOPPER, "test"); player.openInventory(inventory); var listener = env.listen(InventoryPreClickEvent.class); inventory.setItemStack(1, ItemStack.of(Material.DIAMOND)); diff --git a/src/test/java/net/minestom/server/network/SendablePacketTest.java b/src/test/java/net/minestom/server/network/SendablePacketTest.java index 261905ed86f..0d10c0abe60 100644 --- a/src/test/java/net/minestom/server/network/SendablePacketTest.java +++ b/src/test/java/net/minestom/server/network/SendablePacketTest.java @@ -1,7 +1,8 @@ package net.minestom.server.network; import net.kyori.adventure.text.Component; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.LazyPacket; import net.minestom.server.network.packet.server.play.SystemChatPacket; @@ -29,12 +30,12 @@ public void lazy() { @Test public void cached() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var packet = new SystemChatPacket(Component.text("Hello World!"), false); - var cached = new CachedPacket(minecraftServer, packet); + var cached = new CachedPacket(serverProcess, packet); assertSame(packet, cached.packet(ConnectionState.PLAY)); - var buffer = PacketUtils.allocateTrimmedPacket(minecraftServer, ConnectionState.PLAY, packet); + var buffer = PacketUtils.allocateTrimmedPacket(serverProcess, ConnectionState.PLAY, packet); var cachedBuffer = cached.body(ConnectionState.PLAY); assertEquals(buffer.body(), cachedBuffer); // May fail in the very unlikely case where soft references are cleared diff --git a/src/test/java/net/minestom/server/network/SocketWriteTest.java b/src/test/java/net/minestom/server/network/SocketWriteTest.java index ea7bbb4ee51..65eacb1a7f8 100644 --- a/src/test/java/net/minestom/server/network/SocketWriteTest.java +++ b/src/test/java/net/minestom/server/network/SocketWriteTest.java @@ -1,6 +1,7 @@ package net.minestom.server.network; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.PacketUtils; @@ -43,11 +44,11 @@ public int getId(@NotNull ConnectionState state) { @Test public void writeSingleUncompressed() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, false); // 3 bytes length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -56,12 +57,12 @@ public void writeSingleUncompressed() { @Test public void writeMultiUncompressed() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, false); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, false); // 3 bytes length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -70,7 +71,7 @@ public void writeMultiUncompressed() { @Test public void writeSingleCompressed() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var string = "Hello world!".repeat(200); var stringLength = string.getBytes(StandardCharsets.UTF_8).length; var lengthLength = Utils.getVarIntSize(stringLength); @@ -78,7 +79,7 @@ public void writeSingleCompressed() { var packet = new CompressiblePacket(string); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + payload // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -87,11 +88,11 @@ public void writeSingleCompressed() { @Test public void writeSingleCompressedSmall() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -100,12 +101,12 @@ public void writeSingleCompressedSmall() { @Test public void writeMultiCompressedSmall() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); - PacketUtils.writeFramedPacket(minecraftServer, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future diff --git a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java index d40fa91293b..a7c20bfb041 100644 --- a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java +++ b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java @@ -1,6 +1,7 @@ package net.minestom.server.network.socket; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.listener.manager.PacketListenerManager; import net.minestom.server.network.PacketProcessor; import org.junit.jupiter.api.Test; @@ -17,12 +18,12 @@ public class ServerAddressTest { @Test public void inetAddressTest() throws IOException { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 25565); - var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); + var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -34,12 +35,12 @@ public void inetAddressTest() throws IOException { @Test public void inetAddressDynamicTest() throws IOException { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 0); - var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); + var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -51,12 +52,12 @@ public void inetAddressDynamicTest() throws IOException { @Test public void unixAddressTest() throws IOException { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); UnixDomainSocketAddress address = UnixDomainSocketAddress.of("minestom.sock"); - var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); + var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); server.init(address); assertTrue(Files.exists(address.getPath())); assertSame(address, server.socketAddress()); @@ -69,9 +70,9 @@ public void unixAddressTest() throws IOException { } @Test - public void noAddressTest() throws IOException { - MinecraftServer minecraftServer = new MinecraftServer(); - var server = new Server(minecraftServer, new PacketProcessor(new PacketListenerManager(minecraftServer))); + public void noAddressTest() { + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); assertDoesNotThrow(server::stop); } } diff --git a/src/test/java/net/minestom/server/permission/TestPermissions.java b/src/test/java/net/minestom/server/permission/TestPermissions.java index 1b3fe6c77e2..dafc4280267 100644 --- a/src/test/java/net/minestom/server/permission/TestPermissions.java +++ b/src/test/java/net/minestom/server/permission/TestPermissions.java @@ -1,6 +1,7 @@ package net.minestom.server.permission; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import org.jglrxavpok.hephaistos.nbt.NBT; import org.junit.jupiter.api.AfterEach; @@ -19,13 +20,12 @@ public class TestPermissions { private Player player; private Permission permission1, permission2, permission3, wildcard; - private MinecraftServer minecraftServer; + private ServerProcess serverProcess; @BeforeEach public void init() { - minecraftServer = new MinecraftServer(); - minecraftServer.init(); // for entity manager - player = new Player(minecraftServer, UUID.randomUUID(), "TestPlayer", null) { + serverProcess = ServerProcess.of(ServerSettings.builder().build()); + player = new Player(serverProcess, UUID.randomUUID(), "TestPlayer", null) { @Override protected void playerConnectionInit() { } diff --git a/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java b/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java index cef31ebbf0b..a1e302a826a 100644 --- a/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java +++ b/src/test/java/net/minestom/server/snapshot/ChunkSnapshotIntegrationTest.java @@ -14,7 +14,7 @@ public class ChunkSnapshotIntegrationTest { public void blocks(Env env) { var instance = env.createFlatInstance(); instance.setBlock(0, 0, 0, Block.STONE); - var snapshot = ServerSnapshot.update(env.minecraftServer()); + var snapshot = ServerSnapshot.update(env.process()); var inst = snapshot.instances().iterator().next(); assertEquals(Block.STONE, inst.getBlock(0, 0, 0)); diff --git a/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java b/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java index f3d85052f6e..44cc8cd904d 100644 --- a/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java +++ b/src/test/java/net/minestom/server/snapshot/EntitySnapshotIntegrationTest.java @@ -15,9 +15,9 @@ public class EntitySnapshotIntegrationTest { @Test public void basic(Env env) { var instance = env.createFlatInstance(); - var ent = new Entity(env.minecraftServer(), EntityType.ZOMBIE); + var ent = new Entity(env.process(), EntityType.ZOMBIE); ent.setInstance(instance).join(); - var snapshot = ServerSnapshot.update(env.minecraftServer()); + var snapshot = ServerSnapshot.update(env.process()); var inst = snapshot.instances().iterator().next(); var entities = inst.entities(); diff --git a/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java b/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java index bfebc7f0fc4..96e17c85a47 100644 --- a/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java +++ b/src/test/java/net/minestom/server/snapshot/InstanceSnapshotIntegrationTest.java @@ -12,7 +12,7 @@ public class InstanceSnapshotIntegrationTest { @Test public void basic(Env env) { env.createFlatInstance(); - var snapshot = ServerSnapshot.update(env.minecraftServer()); + var snapshot = ServerSnapshot.update(env.process()); // Ensure that the collection is immutable { diff --git a/src/test/java/net/minestom/server/thread/AcquirableTest.java b/src/test/java/net/minestom/server/thread/AcquirableTest.java index 383f0373fe3..d46fd1df09a 100644 --- a/src/test/java/net/minestom/server/thread/AcquirableTest.java +++ b/src/test/java/net/minestom/server/thread/AcquirableTest.java @@ -1,6 +1,7 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import org.junit.jupiter.api.Test; @@ -14,9 +15,9 @@ public class AcquirableTest { @Test public void assignation() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); AtomicReference tickThread = new AtomicReference<>(); - Entity entity = new Entity(minecraftServer, EntityType.ZOMBIE) { + Entity entity = new Entity(serverProcess, EntityType.ZOMBIE) { @Override public void tick(long time) { super.tick(time); @@ -26,7 +27,7 @@ public void tick(long time) { Object first = new Object(); Object second = new Object(); - ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer, ThreadProvider.counter(), 2); + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess, ThreadProvider.counter(), 2); dispatcher.createPartition(first); dispatcher.createPartition(second); diff --git a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java index 44bd5450226..0db30aa4d41 100644 --- a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java +++ b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java @@ -1,6 +1,7 @@ package net.minestom.server.thread; -import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Tickable; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -19,11 +20,11 @@ public class ThreadDispatcherTest { @Test public void elementTick() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final AtomicInteger counter = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(minecraftServer); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess); assertEquals(1, dispatcher.threads().size()); - assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(minecraftServer,1))); + assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(serverProcess,1))); var partition = new Object(); Tickable element = (time) -> counter.incrementAndGet(); @@ -48,11 +49,11 @@ public void elementTick() { @Test public void partitionTick() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // Partitions implementing Tickable should be ticked same as elements final AtomicInteger counter1 = new AtomicInteger(); final AtomicInteger counter2 = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(minecraftServer); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess); assertEquals(1, dispatcher.threads().size()); Tickable partition = (time) -> counter1.incrementAndGet(); @@ -78,10 +79,10 @@ public void partitionTick() { @Test public void uniqueThread() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // Ensure that partitions are properly dispatched across threads final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer, ThreadProvider.counter(), threadCount); + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess, ThreadProvider.counter(), threadCount); assertEquals(threadCount, dispatcher.threads().size()); final AtomicInteger counter = new AtomicInteger(); @@ -108,7 +109,7 @@ public void uniqueThread() { @Test public void threadUpdate() { - MinecraftServer minecraftServer = new MinecraftServer(); + ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // Ensure that partitions threads are properly updated every tick // when RefreshType.ALWAYS is used interface Updater extends Tickable { @@ -116,7 +117,7 @@ interface Updater extends Tickable { } final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer, new ThreadProvider<>() { + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess, new ThreadProvider<>() { @Override public int findThread(@NotNull Updater partition) { return partition.getValue(); diff --git a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java index ad7185d7c9d..47654e154fd 100644 --- a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java +++ b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java @@ -39,7 +39,7 @@ public void testTranslationEnabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(env.minecraftServer(), List.of(player), packet); + PacketUtils.sendGroupedPacket(env.process(), List.of(player), packet); // the message should not be changed if translations are enabled. // the translation of the message itself will be proceeded in PlayerConnectionImpl class @@ -58,7 +58,7 @@ public void testTranslationDisabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = false; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(env.minecraftServer(), List.of(player), packet); + PacketUtils.sendGroupedPacket(env.process(), List.of(player), packet); collector.assertSingle(received -> { assertEquals(message, received.message()); diff --git a/testing/src/main/java/net/minestom/testing/Env.java b/testing/src/main/java/net/minestom/testing/Env.java index 3b4716e5c2e..46c64bb79be 100644 --- a/testing/src/main/java/net/minestom/testing/Env.java +++ b/testing/src/main/java/net/minestom/testing/Env.java @@ -1,6 +1,5 @@ package net.minestom.testing; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; @@ -15,7 +14,7 @@ import java.util.function.BooleanSupplier; public interface Env { - MinecraftServer minecraftServer(); + @NotNull ServerProcess process(); @NotNull TestConnection createConnection(); diff --git a/testing/src/main/java/net/minestom/testing/EnvImpl.java b/testing/src/main/java/net/minestom/testing/EnvImpl.java index 7e4b9381c35..a2a1ccc3438 100644 --- a/testing/src/main/java/net/minestom/testing/EnvImpl.java +++ b/testing/src/main/java/net/minestom/testing/EnvImpl.java @@ -1,7 +1,7 @@ package net.minestom.testing; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.event.Event; import net.minestom.server.event.EventFilter; import net.minestom.server.event.EventListener; @@ -17,16 +17,9 @@ final class EnvImpl implements Env { private final ServerProcess process; private final List> listeners = new CopyOnWriteArrayList<>(); - private final MinecraftServer minecraftServer; public EnvImpl() { - this.minecraftServer = new MinecraftServer(); - this.process = minecraftServer.updateProcess(); - } - - @Override - public MinecraftServer minecraftServer() { - return minecraftServer; + this.process = ServerProcess.of(ServerSettings.builder().build()); } @Override diff --git a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java index e74bc4480b9..857c30374ca 100644 --- a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java @@ -1,7 +1,6 @@ package net.minestom.testing; import net.kyori.adventure.translation.GlobalTranslator; -import net.minestom.server.MinecraftServer; import net.minestom.server.ServerProcess; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.coordinate.Pos; @@ -33,7 +32,7 @@ final class TestConnectionImpl implements TestConnection { TestConnectionImpl(Env env) { this.env = env; this.process = env.process(); - this.playerConnection = new PlayerConnectionImpl(env.minecraftServer()); + this.playerConnection = new PlayerConnectionImpl(env.process()); } @Override @@ -64,8 +63,8 @@ final class TestConnectionImpl implements TestConnection { final class PlayerConnectionImpl extends PlayerConnection { - PlayerConnectionImpl(MinecraftServer minecraftServer) { - super(minecraftServer); + PlayerConnectionImpl(ServerProcess serverProcess) { + super(serverProcess); } @Override diff --git a/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java b/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java index 2210cba6428..7565b8e679e 100644 --- a/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestPlayerImpl.java @@ -9,7 +9,7 @@ public class TestPlayerImpl extends Player { public TestPlayerImpl(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - super(playerConnection.minecraftServer, uuid, username, playerConnection); + super(playerConnection.getServerProcess(), uuid, username, playerConnection); } @Override From 5ad4b14814903c36f88210656abd7b6975ba105d Mon Sep 17 00:00:00 2001 From: MelonHell Date: Tue, 30 Jan 2024 16:50:14 +0300 Subject: [PATCH 08/16] little changes --- .../java/net/minestom/demo/PlayerInit.java | 4 +- .../demo/commands/DisplayCommand.java | 2 +- .../minestom/demo/commands/SaveCommand.java | 2 +- .../net/minestom/server/ServerProcess.java | 6 +-- .../minestom/server/ServerProcessImpl.java | 39 ++++++++------ .../java/net/minestom/server/Viewable.java | 2 +- .../server/adventure/audience/Audiences.java | 5 +- .../audience/IterableAudienceProvider.java | 5 +- .../audience/PacketGroupingAudience.java | 4 +- .../audience/SingleAudienceProvider.java | 10 ++-- .../adventure/bossbar/BossBarListener.java | 10 ++-- .../adventure/bossbar/BossBarManager.java | 6 +-- .../server/command/CommandManager.java | 4 +- .../arguments/minecraft/ArgumentTime.java | 4 +- .../net/minestom/server/entity/Entity.java | 34 ++++++------ .../minestom/server/entity/EntityView.java | 2 +- .../minestom/server/entity/ItemEntity.java | 2 +- .../minestom/server/entity/LivingEntity.java | 4 +- .../net/minestom/server/entity/Player.java | 22 ++++---- .../entity/ai/goal/CombinedAttackGoal.java | 2 +- .../entity/ai/goal/MeleeAttackGoal.java | 2 +- .../entity/ai/goal/RangedAttackGoal.java | 2 +- .../server/entity/fakeplayer/FakePlayer.java | 2 +- .../net/minestom/server/event/EventNode.java | 5 +- .../minestom/server/event/EventNodeImpl.java | 17 +++--- .../server/event/EventNodeLazyImpl.java | 6 +-- .../server/event/GlobalEventHandler.java | 6 +-- .../server/exception/ExceptionHandler.java | 4 +- .../exception/ExceptionHandlerImpl.java | 21 ++++++++ .../server/exception/ExceptionManager.java | 50 ----------------- .../minestom/server/extras/MojangAuth.java | 5 +- .../server/extras/mojangAuth/MojangCrypt.java | 18 +++---- .../query/response/FullQueryResponse.java | 2 +- .../minestom/server/instance/AnvilLoader.java | 14 ++--- .../server/instance/DynamicChunk.java | 2 +- .../server/instance/EntityTrackerImpl.java | 8 +-- .../minestom/server/instance/Explosion.java | 2 +- .../server/instance/IChunkLoader.java | 2 +- .../minestom/server/instance/Instance.java | 4 +- .../server/instance/InstanceContainer.java | 6 +-- .../server/instance/InstanceManager.java | 35 ++++++------ .../server/instance/LightingChunk.java | 2 +- .../minestom/server/instance/WorldBorder.java | 2 +- .../instance/palette/FlexiblePalette.java | 2 +- .../inventory/type/VillagerInventory.java | 4 +- .../server/listener/ChatMessageListener.java | 2 +- .../manager/PacketListenerManager.java | 16 ++++-- .../listener/preplay/LoginListener.java | 6 +-- .../minestom/server/message/Messenger.java | 6 +-- .../server/monitoring/BenchmarkManager.java | 10 ++-- .../server/network/ConnectionManager.java | 9 ++-- .../network/packet/server/CachedPacket.java | 14 ++--- .../player/PlayerSocketConnection.java | 12 ++--- .../server/network/socket/Server.java | 4 +- .../server/network/socket/Worker.java | 6 +-- .../server/thread/ThreadDispatcher.java | 14 ++--- .../server/thread/TickSchedulerThread.java | 4 +- .../minestom/server/thread/TickThread.java | 12 ++--- .../minestom/server/utils/PacketUtils.java | 54 ++++++++++--------- .../server/utils/async/AsyncUtils.java | 2 +- ...ityProjectileCollisionIntegrationTest.java | 16 +++--- .../entity/EntityRemovalIntegrationTest.java | 2 +- .../entity/player/PlayerIntegrationTest.java | 4 +- .../player/PlayerMovementIntegrationTest.java | 2 +- .../PlayerRespawnChunkIntegrationTest.java | 4 +- .../instance/ChunkViewerIntegrationTest.java | 4 +- .../EntityTrackerIntegrationTest.java | 8 +-- .../GeneratorForkConsumerIntegrationTest.java | 18 +++---- .../GeneratorForkIntegrationTest.java | 16 +++--- .../instance/GeneratorIntegrationTest.java | 19 +++---- .../InstanceEventsIntegrationTest.java | 2 +- .../InstanceUnregisterIntegrationTest.java | 8 +-- .../light/WorldRelightIntegrationTest.java | 2 +- .../server/network/SendablePacketTest.java | 7 ++- .../server/network/SocketWriteTest.java | 26 ++++----- .../server/thread/AcquirableTest.java | 2 +- .../server/thread/ThreadDispatcherTest.java | 10 ++-- .../utils/TranslationIntegrationTest.java | 4 +- .../main/java/net/minestom/testing/Env.java | 2 +- 79 files changed, 356 insertions(+), 363 deletions(-) create mode 100644 src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java delete mode 100644 src/main/java/net/minestom/server/exception/ExceptionManager.java diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index 23b4a4a6b99..c6ac9c0f41b 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -52,7 +52,7 @@ public PlayerInit(ServerProcess serverProcess) { this.serverProcess = serverProcess; InstanceManager instanceManager = serverProcess.getInstanceManager(); - InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); + InstanceContainer instanceContainer = instanceManager.createInstanceContainer(serverProcess, DimensionType.OVERWORLD); instanceContainer.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); instanceContainer.setChunkSupplier(LightingChunk::new); @@ -222,6 +222,6 @@ public void init() { .append(Component.text("ACQ TIME: " + MathUtils.round(tickMonitor.getAcquisitionTime(), 2) + "ms")); final Component footer = benchmarkManager.getCpuMonitoringMessage(); serverProcess.getAudiences().players().sendPlayerListHeaderAndFooter(header, footer); - }).repeat(10, TimeUnit.getServerTick(serverProcess.getMinecraftServer())); //.schedule(); + }).repeat(10, TimeUnit.getServerTick(serverProcess.getServerSetting())); //.schedule(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java index c982c582fea..4f8861df67e 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java @@ -85,7 +85,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con private void startSmoothFollow(@NotNull Entity entity, @NotNull Player player) { // entity.setCustomName(Component.text("MY CUSTOM NAME")); // entity.setCustomNameVisible(true); - TemporalUnit serverTick = TimeUnit.getServerTick(entity.getServerProcess().getMinecraftServer()); + TemporalUnit serverTick = TimeUnit.getServerTick(entity.getServerProcess().getServerSetting()); entity.getServerProcess().getSchedulerManager().buildTask(() -> { var meta = (AbstractDisplayMeta) entity.getEntityMeta(); meta.setNotifyAboutChanges(false); diff --git a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java index b67b02dc3b4..c2877c51d54 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java @@ -24,7 +24,7 @@ private void execute(@NotNull CommandSender commandSender, @NotNull CommandConte try { instanceSave.get(); } catch (InterruptedException | ExecutionException e) { - commandSender.getServerProcess().getExceptionManager().handleException(e); + commandSender.getServerProcess().getExceptionHandler().handleException(e); } } commandSender.sendMessage("Saving done!"); diff --git a/src/main/java/net/minestom/server/ServerProcess.java b/src/main/java/net/minestom/server/ServerProcess.java index 7b8f972a336..ab009748cc3 100644 --- a/src/main/java/net/minestom/server/ServerProcess.java +++ b/src/main/java/net/minestom/server/ServerProcess.java @@ -6,7 +6,7 @@ import net.minestom.server.adventure.bossbar.BossBarManager; import net.minestom.server.command.CommandManager; import net.minestom.server.event.GlobalEventHandler; -import net.minestom.server.exception.ExceptionManager; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.extras.MojangAuth; import net.minestom.server.gamedata.tags.TagManager; import net.minestom.server.instance.Chunk; @@ -39,7 +39,7 @@ static ServerProcess of(ServerSettings serverSettings) { return new ServerProcessImpl(serverSettings); } - ServerSettings getMinecraftServer(); + ServerSettings getServerSetting(); /** * Handles incoming connections/players. @@ -114,7 +114,7 @@ static ServerProcess of(ServerSettings serverSettings) { /** * Handles all thrown exceptions from the server. */ - @NotNull ExceptionManager getExceptionManager(); + @NotNull ExceptionHandler getExceptionHandler(); /** * Handles incoming packets. diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java index ac025ebf559..4f53f84ad02 100644 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -8,7 +8,8 @@ import net.minestom.server.entity.Entity; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ServerTickMonitorEvent; -import net.minestom.server.exception.ExceptionManager; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerImpl; import net.minestom.server.extras.MojangAuth; import net.minestom.server.gamedata.tags.TagManager; import net.minestom.server.instance.Chunk; @@ -34,6 +35,7 @@ import net.minestom.server.world.DimensionTypeManager; import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,6 +43,7 @@ import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -48,7 +51,7 @@ final class ServerProcessImpl implements ServerProcess { private static final Logger LOGGER = LoggerFactory.getLogger(ServerProcessImpl.class); private static final Boolean SHUTDOWN_ON_SIGNAL = PropertyUtils.getBoolean("minestom.shutdown-on-signal", true); - private final ExceptionManager exceptionManager; + private final ExceptionHandler exceptionHandler; private final ConnectionManager connectionManager; private final PacketListenerManager packetListenerManager; private final PacketProcessor packetProcessor; @@ -77,34 +80,38 @@ final class ServerProcessImpl implements ServerProcess { private final MojangAuth mojangAuth; public ServerProcessImpl(ServerSettings serverSettings) { + this(serverSettings, null); + } + + public ServerProcessImpl(ServerSettings serverSettings, @Nullable ExceptionHandler exceptionHandler) { this.serverSettings = serverSettings; - this.exceptionManager = new ExceptionManager(this); - this.packetListenerManager = new PacketListenerManager(this); + this.exceptionHandler = Objects.requireNonNullElseGet(exceptionHandler, () -> new ExceptionHandlerImpl(this)); + this.globalEventHandler = new GlobalEventHandler(exceptionHandler); + this.packetListenerManager = new PacketListenerManager(globalEventHandler, exceptionHandler); this.packetProcessor = new PacketProcessor(packetListenerManager); - this.instanceManager = new InstanceManager(this); + this.dispatcher = ThreadDispatcher.singleThread(exceptionHandler); + this.instanceManager = new InstanceManager(dispatcher, globalEventHandler); this.blockManager = new BlockManager(); this.commandManager = new CommandManager(this); this.recipeManager = new RecipeManager(); this.teamManager = new TeamManager(this); - this.globalEventHandler = new GlobalEventHandler(this); this.schedulerManager = new SchedulerManager(); - this.benchmarkManager = new BenchmarkManager(this); + this.benchmarkManager = new BenchmarkManager(exceptionHandler); this.dimensionTypeManager = new DimensionTypeManager(); this.biomeManager = new BiomeManager(); this.advancementManager = new AdvancementManager(this); this.bossBarManager = new BossBarManager(this); this.tagManager = new TagManager(); - this.connectionManager = new ConnectionManager(this, tagManager); + this.connectionManager = new ConnectionManager(this, serverSettings, tagManager); this.server = new Server(this, packetProcessor); - this.mojangAuth = new MojangAuth(this); - this.audiences = new Audiences(this); + this.mojangAuth = new MojangAuth(this, exceptionHandler); + this.audiences = new Audiences(this, connectionManager, commandManager); - this.dispatcher = ThreadDispatcher.singleThread(this); this.ticker = new TickerImpl(); } @Override - public ServerSettings getMinecraftServer() { + public ServerSettings getServerSetting() { return serverSettings; } @@ -179,8 +186,8 @@ public ServerSettings getMinecraftServer() { } @Override - public @NotNull ExceptionManager getExceptionManager() { - return exceptionManager; + public @NotNull ExceptionHandler getExceptionHandler() { + return exceptionHandler; } @Override @@ -220,7 +227,7 @@ public void start(@NotNull SocketAddress socketAddress) { try { server.init(socketAddress); } catch (IOException e) { - exceptionManager.handleException(e); + exceptionHandler.handleException(e); throw new RuntimeException(e); } @@ -311,7 +318,7 @@ private void serverTick(long tickStart) { try { instance.tick(tickStart); } catch (Exception e) { - getExceptionManager().handleException(e); + getExceptionHandler().handleException(e); } } // Tick all chunks (and entities inside) diff --git a/src/main/java/net/minestom/server/Viewable.java b/src/main/java/net/minestom/server/Viewable.java index c72962542bc..733e5a80f9e 100644 --- a/src/main/java/net/minestom/server/Viewable.java +++ b/src/main/java/net/minestom/server/Viewable.java @@ -60,7 +60,7 @@ default boolean isViewer(@NotNull Player player) { */ default void sendPacketToViewers(@NotNull SendablePacket packet) { if (packet instanceof ServerPacket serverPacket) { - PacketUtils.sendGroupedPacket(getServerProcess(), getViewers(), serverPacket); + PacketUtils.sendGroupedPacket(getServerProcess().getServerSetting(), getViewers(), serverPacket); } else { getViewers().forEach(player -> player.sendPacket(packet)); } diff --git a/src/main/java/net/minestom/server/adventure/audience/Audiences.java b/src/main/java/net/minestom/server/adventure/audience/Audiences.java index 99a26fa475c..94c6db6652f 100644 --- a/src/main/java/net/minestom/server/adventure/audience/Audiences.java +++ b/src/main/java/net/minestom/server/adventure/audience/Audiences.java @@ -4,6 +4,7 @@ import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Keyed; import net.minestom.server.ServerProcess; +import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.NotNull; @@ -18,9 +19,9 @@ public class Audiences { private final ServerProcess serverProcess; private final SingleAudienceProvider audience; - public Audiences(ServerProcess serverProcess) { + public Audiences(ServerProcess serverProcess, ConnectionManager connectionManager, CommandManager commandManager) { this.serverProcess = serverProcess; - audience = new SingleAudienceProvider(serverProcess); + audience = new SingleAudienceProvider(serverProcess, connectionManager, commandManager); } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java index 3fd9f4880dc..fda720adcc5 100644 --- a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java @@ -3,6 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.minestom.server.ServerProcess; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.ConsoleSender; import net.minestom.server.entity.Player; import org.jetbrains.annotations.NotNull; @@ -22,9 +23,9 @@ class IterableAudienceProvider implements AudienceProvider(), CopyOnWriteArrayList::new); private final ServerProcess serverProcess; - protected IterableAudienceProvider(ServerProcess serverProcess) { + protected IterableAudienceProvider(ServerProcess serverProcess, CommandManager commandManager) { this.serverProcess = serverProcess; - this.console = List.of(serverProcess.getCommandManager().getConsoleSender()); + this.console = List.of(commandManager.getConsoleSender()); } @Override diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index e48ad8bd016..2ee3e40f82d 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -65,12 +65,12 @@ public ServerProcess getServerProcess() { * @param packet the packet to broadcast */ default void sendGroupedPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(getServerProcess(), getPlayers(), packet); + PacketUtils.sendGroupedPacket(getServerProcess().getServerSetting(), getPlayers(), packet); } @Override default void sendMessage(@NotNull Identity source, @NotNull Component message, @NotNull MessageType type) { - Messenger.sendMessage(getServerProcess(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); + Messenger.sendMessage(getServerProcess().getServerSetting(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); } @Override diff --git a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java index 94929bc2de5..88389a8ef0d 100644 --- a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java @@ -3,7 +3,9 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.minestom.server.ServerProcess; +import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; +import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.NotNull; import java.util.function.Predicate; @@ -20,11 +22,11 @@ class SingleAudienceProvider implements AudienceProvider { @NotNull private final ServerProcess serverProcess; - protected SingleAudienceProvider(ServerProcess serverProcess) { + protected SingleAudienceProvider(ServerProcess serverProcess, ConnectionManager connectionManager, CommandManager commandManager) { this.serverProcess = serverProcess; - this.collection = new IterableAudienceProvider(serverProcess); - this.players = PacketGroupingAudience.of(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers()); - this.server = Audience.audience(this.players, serverProcess.getCommandManager().getConsoleSender()); + this.collection = new IterableAudienceProvider(serverProcess, commandManager); + this.players = PacketGroupingAudience.of(serverProcess, connectionManager.getOnlinePlayers()); + this.server = Audience.audience(this.players, commandManager.getConsoleSender()); } /** diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java index 753446f192f..df20f1977ef 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java @@ -32,28 +32,28 @@ class BossBarListener implements BossBar.Listener { @Override public void bossBarNameChanged(@NotNull BossBar bar, @NotNull Component oldName, @NotNull Component newName) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createTitleUpdate(newName))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createTitleUpdate(newName))); } @Override public void bossBarProgressChanged(@NotNull BossBar bar, float oldProgress, float newProgress) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createPercentUpdate(newProgress))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createPercentUpdate(newProgress))); } @Override public void bossBarColorChanged(@NotNull BossBar bar, @NotNull BossBar.Color oldColor, @NotNull BossBar.Color newColor) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createColorUpdate(newColor))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createColorUpdate(newColor))); } @Override public void bossBarOverlayChanged(@NotNull BossBar bar, BossBar.@NotNull Overlay oldOverlay, BossBar.@NotNull Overlay newOverlay) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createOverlayUpdate(newOverlay))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createOverlayUpdate(newOverlay))); } @Override public void bossBarFlagsChanged(@NotNull BossBar bar, @NotNull Set flagsAdded, @NotNull Set flagsRemoved) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createFlagsUpdate())); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createFlagsUpdate())); } private void doIfRegistered(@NotNull BossBar bar, @NotNull Consumer consumer) { diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java index 39b0689e20d..95f1c38d74a 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java @@ -76,7 +76,7 @@ public void addBossBar(@NotNull Collection players, @NotNull BossBar bar BossBarHolder holder = this.getOrCreateHandler(bar); Collection addedPlayers = players.stream().filter(holder::addViewer).toList(); if (!addedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(serverProcess, addedPlayers, holder.createAddPacket()); + PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), addedPlayers, holder.createAddPacket()); } } @@ -91,7 +91,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar if (holder != null) { Collection removedPlayers = players.stream().filter(holder::removeViewer).toList(); if (!removedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(serverProcess, removedPlayers, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), removedPlayers, holder.createRemovePacket()); } } } @@ -104,7 +104,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar public void destroyBossBar(@NotNull BossBar bossBar) { BossBarHolder holder = this.bars.remove(bossBar); if (holder != null) { - PacketUtils.sendGroupedPacket(serverProcess, holder.players, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createRemovePacket()); for (Player player : holder.players) { this.removePlayer(player, holder); } diff --git a/src/main/java/net/minestom/server/command/CommandManager.java b/src/main/java/net/minestom/server/command/CommandManager.java index 6b9573844bc..2c785c6d694 100644 --- a/src/main/java/net/minestom/server/command/CommandManager.java +++ b/src/main/java/net/minestom/server/command/CommandManager.java @@ -143,7 +143,7 @@ class Reflection { try { callable.call(); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } }); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); @@ -151,7 +151,7 @@ class Reflection { return callable.call(); } } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); } } diff --git a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java index d41da9102b7..fb197c8fcec 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java @@ -43,7 +43,7 @@ public Duration parse(@NotNull CommandSender sender, @NotNull String input) thro TemporalUnit timeUnit; if (Character.isDigit(lastChar)) - timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getMinecraftServer()); + timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getServerSetting()); else if (SUFFIXES.contains(lastChar)) { input = input.substring(0, input.length() - 1); @@ -52,7 +52,7 @@ else if (SUFFIXES.contains(lastChar)) { } else if (lastChar == 's') { timeUnit = TimeUnit.SECOND; } else if (lastChar == 't') { - timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getMinecraftServer()); + timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getServerSetting()); } else { throw new ArgumentSyntaxException("Time needs to have the unit d, s, t, or none", input, NO_NUMBER); } diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index e8ab2af5afa..8046bf55817 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -204,7 +204,7 @@ public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityTy // Local nodes require a server process this.eventNode = null; } - destroyPacketCache = new CachedPacket(serverProcess, () -> new DestroyEntitiesPacket(getEntityId())); + destroyPacketCache = new CachedPacket(serverProcess.getServerSetting(), () -> new DestroyEntitiesPacket(getEntityId())); } public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { @@ -582,7 +582,7 @@ private void velocityTick() { if (!hasVelocity && noGravity) { return; } - final float tps = serverProcess.getMinecraftServer().getTickPerSecond(); + final float tps = serverProcess.getServerSetting().getTickPerSecond(); final Pos positionBeforeMove = getPosition(); final Vec currentVelocity = getVelocity(); final boolean wasOnGround = this.onGround; @@ -681,7 +681,7 @@ protected void updateVelocity(boolean wasOnGround, boolean flying, Pos positionB z * drag )) // Convert from block/tick to block/sec - .mul(serverProcess.getMinecraftServer().getTickPerSecond()) + .mul(serverProcess.getServerSetting().getTickPerSecond()) // Prevent infinitely decreasing velocity .apply(Vec.Operator.EPSILON); } @@ -726,7 +726,7 @@ private void effectTick(long time) { effects.removeIf(timedPotion -> { long duration = timedPotion.getPotion().duration(); if (duration == Potion.INFINITE_DURATION) return false; - final long potionTime = duration * serverProcess.getMinecraftServer().getTickMs(); + final long potionTime = duration * serverProcess.getServerSetting().getTickMs(); // Remove if the potion should be expired if (time >= timedPotion.getStartingTime() + potionTime) { // Send the packet that the potion should no longer be applied @@ -896,7 +896,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull spawn(); serverProcess.getGlobalEventHandler().call(new EntitySpawnEvent(this, instance)); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } }); } @@ -1331,21 +1331,21 @@ public void refreshPosition(@NotNull final Pos newPosition, boolean ignoreView) final Chunk chunk = getChunk(); if (distanceX > 8 || distanceY > 8 || distanceZ > 8) { - PacketUtils.prepareViewablePacket(serverProcess, chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); } else if (positionChange && viewChange) { - PacketUtils.prepareViewablePacket(serverProcess, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); // Fix head rotation - PacketUtils.prepareViewablePacket(serverProcess, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); } else if (positionChange) { // This is a confusing fix for a confusing issue. If rotation is only sent when the entity actually changes, then spawning an entity // on the ground causes the entity not to update its rotation correctly. It works fine if the entity is spawned in the air. Very weird. - PacketUtils.prepareViewablePacket(serverProcess, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, onGround), this); } else if (viewChange) { - PacketUtils.prepareViewablePacket(serverProcess, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); - PacketUtils.prepareViewablePacket(serverProcess,chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(),chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); } this.lastSyncedPosition = position; @@ -1535,7 +1535,7 @@ protected void remove(boolean permanent) { try { despawn(); } catch (Throwable t) { - serverProcess.getExceptionManager().handleException(t); + serverProcess.getExceptionHandler().handleException(t); } // Remove passengers if any (also done with LivingEntity#kill) @@ -1580,7 +1580,7 @@ public boolean isRemoved() { * @param temporalUnit the unit of the delay */ public void scheduleRemove(long delay, @NotNull TemporalUnit temporalUnit) { - if (temporalUnit.equals(TimeUnit.getServerTick(serverProcess.getMinecraftServer()))) { + if (temporalUnit.equals(TimeUnit.getServerTick(serverProcess.getServerSetting()))) { scheduleRemove(TaskSchedule.tick((int) delay)); } else { scheduleRemove(Duration.of(delay, temporalUnit)); @@ -1601,7 +1601,7 @@ private void scheduleRemove(TaskSchedule schedule) { } protected @NotNull Vec getVelocityForPacket() { - return this.velocity.mul(8000f / serverProcess.getMinecraftServer().getTickPerSecond()); + return this.velocity.mul(8000f / serverProcess.getServerSetting().getTickPerSecond()); } protected @NotNull EntityVelocityPacket getVelocityPacket() { @@ -1630,7 +1630,7 @@ private void scheduleRemove(TaskSchedule schedule) { protected void synchronizePosition(boolean includeSelf) { final Pos posCache = this.position; final ServerPacket packet = new EntityTeleportPacket(getEntityId(), posCache, isOnGround()); - PacketUtils.prepareViewablePacket(serverProcess, currentChunk, packet, this); + PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), currentChunk, packet, this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); this.lastSyncedPosition = posCache; } @@ -1708,9 +1708,9 @@ private Duration getSynchronizationCooldown() { public void takeKnockback(float strength, final double x, final double z) { if (strength > 0) { //TODO check possible side effects of unnatural TPS (other than 20TPS) - strength *= serverProcess.getMinecraftServer().getTickPerSecond(); + strength *= serverProcess.getServerSetting().getTickPerSecond(); final Vec velocityModifier = new Vec(x, z).normalize().mul(strength); - final double verticalLimit = .4d * serverProcess.getMinecraftServer().getTickPerSecond(); + final double verticalLimit = .4d * serverProcess.getServerSetting().getTickPerSecond(); setVelocity(new Vec(velocity.x() / 2d - velocityModifier.x(), onGround ? Math.min(verticalLimit, velocity.y() / 2d + strength) : velocity.y(), diff --git a/src/main/java/net/minestom/server/entity/EntityView.java b/src/main/java/net/minestom/server/entity/EntityView.java index 20cbe0eaf66..1e39fbeb0be 100644 --- a/src/main/java/net/minestom/server/entity/EntityView.java +++ b/src/main/java/net/minestom/server/entity/EntityView.java @@ -228,7 +228,7 @@ private Collection references() { final Point point = trackedLocation.point(); Int2ObjectOpenHashMap entityMap = new Int2ObjectOpenHashMap<>(lastSize); - instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.getServerProcess().getMinecraftServer().getEntityViewDistance(), target, + instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.getServerProcess().getServerSetting().getEntityViewDistance(), target, (entity) -> entityMap.putIfAbsent(entity.getEntityId(), entity)); this.lastSize = entityMap.size(); return entityMap.values(); diff --git a/src/main/java/net/minestom/server/entity/ItemEntity.java b/src/main/java/net/minestom/server/entity/ItemEntity.java index 5b00f59644b..c87381d1718 100644 --- a/src/main/java/net/minestom/server/entity/ItemEntity.java +++ b/src/main/java/net/minestom/server/entity/ItemEntity.java @@ -42,7 +42,7 @@ public ItemEntity(@NotNull ServerProcess serverProcess, @NotNull ItemStack itemS super(serverProcess, EntityType.ITEM); setItemStack(itemStack); setBoundingBox(0.25f, 0.25f, 0.25f); - mergeDelay = Duration.of(10, TimeUnit.getServerTick(serverProcess.getMinecraftServer())); + mergeDelay = Duration.of(10, TimeUnit.getServerTick(serverProcess.getServerSetting())); } /** diff --git a/src/main/java/net/minestom/server/entity/LivingEntity.java b/src/main/java/net/minestom/server/entity/LivingEntity.java index 70d480896ff..e1e54ac83cb 100644 --- a/src/main/java/net/minestom/server/entity/LivingEntity.java +++ b/src/main/java/net/minestom/server/entity/LivingEntity.java @@ -89,7 +89,7 @@ public class LivingEntity extends Entity implements EquipmentHandler { public LivingEntity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { super(serverProcess, entityType, uuid); initEquipments(); - itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(serverProcess.getMinecraftServer()))); + itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(serverProcess.getServerSetting()))); } public LivingEntity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { @@ -277,7 +277,7 @@ public void kill() { * @param duration duration in ticks of the effect */ public void setFireForDuration(int duration) { - setFireForDuration(duration, TimeUnit.getServerTick(getServerProcess().getMinecraftServer())); + setFireForDuration(duration, TimeUnit.getServerTick(getServerProcess().getServerSetting())); } /** diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 92245261c0b..eed1160098b 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -262,7 +262,7 @@ public Player(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); getServerProcess().getGlobalEventHandler().call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); }; - experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(getServerProcess().getMinecraftServer()))); + experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(getServerProcess().getServerSetting()))); } @ApiStatus.Internal @@ -290,13 +290,13 @@ public CompletableFuture UNSAFE_init() { final JoinGamePacket joinGamePacket = new JoinGamePacket( getEntityId(), this.hardcore, List.of(), 0, - getServerProcess().getMinecraftServer().getChunkViewDistance(), getServerProcess().getMinecraftServer().getChunkViewDistance(), + getServerProcess().getServerSetting().getChunkViewDistance(), getServerProcess().getServerSetting().getChunkViewDistance(), false, true, false, dimensionType.toString(), spawnInstance.getDimensionName(), 0, gameMode, null, false, levelFlat, deathLocation, portalCooldown); sendPacket(joinGamePacket); // Difficulty - sendPacket(new ServerDifficultyPacket(getServerProcess().getMinecraftServer().getDifficulty(), true)); + sendPacket(new ServerDifficultyPacket(getServerProcess().getServerSetting().getDifficulty(), true)); sendPacket(new SpawnPositionPacket(respawnPoint, 0)); @@ -534,7 +534,7 @@ public void respawn() { ChunkUtils.forChunksInRange(respawnPosition, settings.getEffectiveViewDistance(), chunkAdder); chunksLoadedByClient = new Vec(respawnPosition.chunkX(), respawnPosition.chunkZ()); // Client also needs all entities resent to them, since those are unloaded as well - this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(getServerProcess().getMinecraftServer().getChunkViewDistance(), settings.getViewDistance()), + this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(getServerProcess().getServerSetting().getChunkViewDistance(), settings.getViewDistance()), EntityTracker.Target.ENTITIES, entity -> { // Skip refreshing self with a new viewer if (!entity.getUuid().equals(uuid) && entity.isViewer(this)) { @@ -549,7 +549,7 @@ public void respawn() { */ private void refreshClientStateAfterRespawn() { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); - sendPacket(new ServerDifficultyPacket(getServerProcess().getMinecraftServer().getDifficulty(), false)); + sendPacket(new ServerDifficultyPacket(getServerProcess().getServerSetting().getDifficulty(), false)); sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation)); sendPacket(new SetExperiencePacket(exp, level, 0)); triggerStatus((byte) (24 + permissionLevel)); // Set permission level @@ -597,7 +597,7 @@ public void remove(boolean permanent) { final int chunkX = position.chunkX(); final int chunkZ = position.chunkZ(); // Clear all viewable chunks - ChunkUtils.forChunksInRange(chunkX, chunkZ, getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(chunkX, chunkZ, getServerProcess().getServerSetting().getChunkViewDistance(), chunkRemover); // Remove from the tab-list PacketUtils.broadcastPlayPacket(getServerProcess(), getRemovePlayerToList()); @@ -649,7 +649,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Ensure that surrounding chunks are loaded List> futures = new ArrayList<>(); - ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getMinecraftServer().getChunkViewDistance(), (chunkX, chunkZ) -> { + ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getServerSetting().getChunkViewDistance(), (chunkX, chunkZ) -> { final CompletableFuture future = instance.loadOptionalChunk(chunkX, chunkZ); if (!future.isDone()) futures.add(future); }); @@ -722,7 +722,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, if (!firstSpawn && !dimensionChange) { // Player instance changed, clear current viewable collections if (updateChunks) - ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getServerSetting().getChunkViewDistance(), chunkRemover); } if (dimensionChange) sendDimension(instance.getDimensionType(), instance.getDimensionName()); @@ -737,7 +737,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new UpdateViewPositionPacket(chunkX, chunkZ)); // Load the nearby chunks and queue them to be sent to them - ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkAdder); + ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getServerSetting().getChunkViewDistance(), chunkAdder); } synchronizePosition(true); // So the player doesn't get stuck @@ -2349,7 +2349,7 @@ protected void sendChunkUpdates(Chunk newChunk) { final Vec old = chunksLoadedByClient; sendPacket(new UpdateViewPositionPacket(newX, newZ)); ChunkUtils.forDifferingChunksInRange(newX, newZ, (int) old.x(), (int) old.z(), - getServerProcess().getMinecraftServer().getChunkViewDistance(), chunkAdder, chunkRemover); + getServerProcess().getServerSetting().getChunkViewDistance(), chunkAdder, chunkRemover); this.chunksLoadedByClient = new Vec(newX, newZ); } } @@ -2417,7 +2417,7 @@ public byte getViewDistance() { } public int getEffectiveViewDistance() { - return Math.min(getViewDistance(), getServerProcess().getMinecraftServer().getChunkViewDistance()); + return Math.min(getViewDistance(), getServerProcess().getServerSetting().getChunkViewDistance()); } /** diff --git a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java index 57e1b2616bf..5bfc7271051 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java @@ -127,7 +127,7 @@ public CombinedAttackGoal(@NotNull EntityCreature entityCreature, this.rangedDelay = rangedDelay; this.desirableRangeSquared = desirableRange * desirableRange; this.comeClose = comeClose; - this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getMinecraftServer()))); + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getServerSetting()))); Check.argCondition(desirableRange > rangedRange, "Desirable range can not exceed ranged range!"); } diff --git a/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java index ce674031712..85585f1c653 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java @@ -47,7 +47,7 @@ public MeleeAttackGoal(@NotNull EntityCreature entityCreature, double range, Dur super(entityCreature); this.range = range; this.delay = delay; - this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getMinecraftServer()))); + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getServerSetting()))); } public @NotNull Cooldown getCooldown() { diff --git a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java index 27626f904bd..dfef4ec7c45 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java @@ -63,7 +63,7 @@ public RangedAttackGoal(@NotNull EntityCreature entityCreature, Duration delay, this.comeClose = comeClose; this.power = power; this.spread = spread; - this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getMinecraftServer()))); + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getServerSetting()))); Check.argCondition(desirableRange > attackRange, "Desirable range can not exceed attack range!"); } diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index cff79573fb5..d6c727dad86 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -166,7 +166,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - getServerProcess().getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(getServerProcess().getMinecraftServer())).schedule(); + getServerProcess().getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(getServerProcess().getServerSetting())).schedule(); } } } diff --git a/src/main/java/net/minestom/server/event/EventNode.java b/src/main/java/net/minestom/server/event/EventNode.java index cfa560b5ebf..4d51f2f96d4 100644 --- a/src/main/java/net/minestom/server/event/EventNode.java +++ b/src/main/java/net/minestom/server/event/EventNode.java @@ -1,6 +1,5 @@ package net.minestom.server.event; -import net.minestom.server.ServerObject; import net.minestom.server.ServerProcess; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.tag.Tag; @@ -25,7 +24,7 @@ * * @param The event type accepted by this node */ -public sealed interface EventNode extends ServerObject permits EventNodeImpl { +public sealed interface EventNode permits EventNodeImpl { /** * Creates an event node which accepts any event type with no filtering. @@ -187,7 +186,7 @@ private static EventNode create(@NotNull ServerProcess s @NotNull EventFilter filter, @Nullable BiPredicate predicate) { //noinspection unchecked - return new EventNodeImpl<>(serverProcess, name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); + return new EventNodeImpl<>(serverProcess.getExceptionHandler(), name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); } /** diff --git a/src/main/java/net/minestom/server/event/EventNodeImpl.java b/src/main/java/net/minestom/server/event/EventNodeImpl.java index 7bb70300720..90a3a1db636 100644 --- a/src/main/java/net/minestom/server/event/EventNodeImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeImpl.java @@ -1,8 +1,8 @@ package net.minestom.server.event; import com.github.benmanes.caffeine.cache.Caffeine; -import net.minestom.server.ServerProcess; import net.minestom.server.event.trait.RecursiveEvent; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -30,7 +30,7 @@ non-sealed class EventNodeImpl implements EventNode { final Map> registeredMappedNode = Caffeine.newBuilder() .weakKeys().weakValues().>build().asMap(); - private final ServerProcess serverProcess; + private final ExceptionHandler exceptionHandler; final String name; final EventFilter filter; final BiPredicate predicate; @@ -38,11 +38,11 @@ non-sealed class EventNodeImpl implements EventNode { volatile int priority; volatile EventNodeImpl parent; - EventNodeImpl(@NotNull ServerProcess serverProcess, + EventNodeImpl(@NotNull ExceptionHandler exceptionHandler, @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { - this.serverProcess = serverProcess; + this.exceptionHandler = exceptionHandler; this.name = name; this.filter = filter; this.predicate = predicate; @@ -159,7 +159,7 @@ public void removeChildren(@NotNull String name, @NotNull Class eve public @NotNull EventNode map(@NotNull H value, @NotNull EventFilter filter) { EventNodeImpl node; synchronized (GLOBAL_CHILD_LOCK) { - node = new EventNodeLazyImpl<>(serverProcess,this, value, filter); + node = new EventNodeLazyImpl<>(exceptionHandler,this, value, filter); Check.stateCondition(node.parent != null, "Node already has a parent"); Check.stateCondition(Objects.equals(parent, node), "Cannot map to self"); EventNodeImpl previous = this.mappedNodeCache.putIfAbsent(value, (EventNodeImpl) node); @@ -260,11 +260,6 @@ private static void genToStringTree(StringBuilder buffer, String prefix, String } } - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } - record Graph(String name, String eventType, int priority, List children) { public Graph { @@ -334,7 +329,7 @@ public void call(@NotNull E event) { try { listener.accept(event); } catch (Throwable e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); } } diff --git a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java index a965dac578c..0d0abfd212f 100644 --- a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import org.jetbrains.annotations.NotNull; import java.lang.invoke.MethodHandles; @@ -24,9 +24,9 @@ final class EventNodeLazyImpl extends EventNodeImpl { @SuppressWarnings("unused") private boolean mapped; - EventNodeLazyImpl(@NotNull ServerProcess serverProcess, @NotNull EventNodeImpl holder, + EventNodeLazyImpl(@NotNull ExceptionHandler exceptionHandler, @NotNull EventNodeImpl holder, @NotNull Object owner, @NotNull EventFilter filter) { - super(serverProcess, owner.toString(), filter, null); + super(exceptionHandler, owner.toString(), filter, null); this.holder = holder; this.owner = new WeakReference<>(owner); } diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandler.java b/src/main/java/net/minestom/server/event/GlobalEventHandler.java index 3df4cde92ff..55e649ce765 100644 --- a/src/main/java/net/minestom/server/event/GlobalEventHandler.java +++ b/src/main/java/net/minestom/server/event/GlobalEventHandler.java @@ -1,12 +1,12 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; /** * Object containing all the global event listeners. */ public final class GlobalEventHandler extends EventNodeImpl { - public GlobalEventHandler(ServerProcess serverProcess) { - super(serverProcess,"global", EventFilter.ALL, null); + public GlobalEventHandler(ExceptionHandler exceptionHandler) { + super(exceptionHandler, "global", EventFilter.ALL, null); } } diff --git a/src/main/java/net/minestom/server/exception/ExceptionHandler.java b/src/main/java/net/minestom/server/exception/ExceptionHandler.java index ce22931ec5d..9786d383e96 100644 --- a/src/main/java/net/minestom/server/exception/ExceptionHandler.java +++ b/src/main/java/net/minestom/server/exception/ExceptionHandler.java @@ -2,14 +2,12 @@ /** * Used when you want to implement your own exception handling, instead of just printing the stack trace. - *

      - * Sets with {@link ExceptionManager#setExceptionHandler(ExceptionHandler)}. */ @FunctionalInterface public interface ExceptionHandler { /** - * Called when a exception was caught. + * Called when an exception was caught. * * @param e the thrown exception */ diff --git a/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java b/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java new file mode 100644 index 00000000000..62f676534b7 --- /dev/null +++ b/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java @@ -0,0 +1,21 @@ +package net.minestom.server.exception; + +import net.minestom.server.ServerProcess; + +public final class ExceptionHandlerImpl implements ExceptionHandler { + + private final ServerProcess serverProcess; + + public ExceptionHandlerImpl(ServerProcess serverProcess) { + this.serverProcess = serverProcess; + } + + @Override + public void handleException(Throwable e) { + e.printStackTrace(); + if (e instanceof OutOfMemoryError) { + // OOM should be handled manually + serverProcess.stop(); + } + } +} diff --git a/src/main/java/net/minestom/server/exception/ExceptionManager.java b/src/main/java/net/minestom/server/exception/ExceptionManager.java deleted file mode 100644 index 52a34b51ce1..00000000000 --- a/src/main/java/net/minestom/server/exception/ExceptionManager.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.minestom.server.exception; - -import net.minestom.server.ServerProcess; -import org.jetbrains.annotations.Nullable; - -/** - * Manages the handling of exceptions. - */ -public final class ExceptionManager { - - private ExceptionHandler exceptionHandler; - private final ServerProcess serverProcess; - - public ExceptionManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } - - /** - * Handles an exception, if no {@link ExceptionHandler} is set, it just prints the stack trace. - * - * @param e the occurred exception - */ - public void handleException(Throwable e) { - if (e instanceof OutOfMemoryError) { - // OOM should be handled manually - e.printStackTrace(); - serverProcess.stop(); - return; - } - this.getExceptionHandler().handleException(e); - } - - /** - * Changes the exception handler, to allow custom exception handling. - * - * @param exceptionHandler the new {@link ExceptionHandler}, can be set to null to apply the default provider - */ - public void setExceptionHandler(@Nullable ExceptionHandler exceptionHandler) { - this.exceptionHandler = exceptionHandler; - } - - /** - * Retrieves the current {@link ExceptionHandler}, can be the default one if none is defined. - * - * @return the current {@link ExceptionHandler} - */ - public ExceptionHandler getExceptionHandler() { - return this.exceptionHandler == null ? exceptionHandler = Throwable::printStackTrace : this.exceptionHandler; - } -} diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index 71d66dd2cb0..5ed0abb92a8 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -1,6 +1,7 @@ package net.minestom.server.extras; import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.Nullable; @@ -14,9 +15,9 @@ public final class MojangAuth { private final ServerProcess serverProcess; private final MojangCrypt mojangCrypt; - public MojangAuth(ServerProcess serverProcess) { + public MojangAuth(ServerProcess serverProcess, ExceptionHandler exceptionHandler) { this.serverProcess = serverProcess; - this.mojangCrypt = new MojangCrypt(serverProcess); + this.mojangCrypt = new MojangCrypt(exceptionHandler); } /** diff --git a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java index 44f14a750f3..6856ab7527e 100644 --- a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java +++ b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.mojangAuth; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,10 +13,10 @@ public final class MojangCrypt { private final Logger LOGGER = LoggerFactory.getLogger(MojangCrypt.class); - private final ServerProcess serverProcess; + private final ExceptionHandler exceptionHandler; - public MojangCrypt(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public MojangCrypt(ExceptionHandler exceptionHandler) { + this.exceptionHandler = exceptionHandler; } public @Nullable KeyPair generateKeyPair() { @@ -25,7 +25,7 @@ public MojangCrypt(ServerProcess serverProcess) { keyGen.initialize(1024); return keyGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); LOGGER.error("Key pair generation failed!"); return null; } @@ -35,7 +35,7 @@ public MojangCrypt(ServerProcess serverProcess) { try { return digestData("SHA-1", data.getBytes("ISO_8859_1"), secretKey.getEncoded(), publicKey.getEncoded()); } catch (UnsupportedEncodingException e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); return null; } } @@ -48,7 +48,7 @@ public MojangCrypt(ServerProcess serverProcess) { } return digest.digest(); } catch (NoSuchAlgorithmException e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); return null; } } @@ -65,7 +65,7 @@ private byte[] cipherData(int mode, Key key, byte[] data) { try { return setupCipher(mode, key.getAlgorithm(), key).doFinal(data); } catch (IllegalBlockSizeException | BadPaddingException var4) { - serverProcess.getExceptionManager().handleException(var4); + exceptionHandler.handleException(var4); } LOGGER.error("Cipher data failed!"); return null; @@ -77,7 +77,7 @@ private Cipher setupCipher(int mode, String transformation, Key key) { cipher4.init(mode, key); return cipher4; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException var4) { - serverProcess.getExceptionManager().handleException(var4); + exceptionHandler.handleException(var4); } LOGGER.error("Cipher creation failed!"); return null; diff --git a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java index daedf8dc7b8..f34884eae02 100644 --- a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java @@ -121,7 +121,7 @@ public void setPlayers(@NotNull List players) { * @return the string result */ public static String generatePluginsValue(ServerProcess serverProcess) { - StringBuilder builder = new StringBuilder(serverProcess.getMinecraftServer().getBrandName()) + StringBuilder builder = new StringBuilder(serverProcess.getServerSetting().getBrandName()) .append(' ') .append(ServerConsts.VERSION_NAME); diff --git a/src/main/java/net/minestom/server/instance/AnvilLoader.java b/src/main/java/net/minestom/server/instance/AnvilLoader.java index 40fbb56629e..883e5593b6a 100644 --- a/src/main/java/net/minestom/server/instance/AnvilLoader.java +++ b/src/main/java/net/minestom/server/instance/AnvilLoader.java @@ -74,7 +74,7 @@ public void loadInstance(@NotNull Instance instance) { Files.copy(levelPath, path.resolve("level.dat_old"), StandardCopyOption.REPLACE_EXISTING); instance.tagHandler().updateContent(tag); } catch (IOException | NBTException e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } } @@ -87,7 +87,7 @@ public void loadInstance(@NotNull Instance instance) { try { return loadMCA(instance, chunkX, chunkZ); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } return CompletableFuture.completedFuture(null); } @@ -153,7 +153,7 @@ public void loadInstance(@NotNull Instance instance) { } return new RegionFile(new RandomAccessFile(regionPath.toFile(), "rw"), regionX, regionZ, instance.getDimensionType().getMinY(), instance.getDimensionType().getMaxY() - 1); } catch (IOException | AnvilException e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); return null; } }); @@ -266,7 +266,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { chunk.setBlock(x, y + yOffset, z, block); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } } } @@ -343,7 +343,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { alreadyLoaded.put(n, mcaFile); } catch (AnvilException | IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); return AsyncUtils.VOID_FUTURE; } } @@ -355,7 +355,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { mcaFile.writeColumnData(writer.toNBT(), chunk.getChunkX(), chunk.getChunkZ()); } catch (IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); return AsyncUtils.VOID_FUTURE; } return AsyncUtils.VOID_FUTURE; @@ -462,7 +462,7 @@ public void unloadChunk(Chunk chunk) { try { regionFile.close(); } catch (IOException e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } } } diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java index 6c839c7717d..3e3c099d3ef 100644 --- a/src/main/java/net/minestom/server/instance/DynamicChunk.java +++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java @@ -56,7 +56,7 @@ public DynamicChunk(@NotNull Instance instance, int chunkX, int chunkZ) { var sectionsTemp = new Section[maxSection - minSection]; Arrays.setAll(sectionsTemp, value -> new Section(getServerProcess())); this.sections = List.of(sectionsTemp); - chunkCache = new CachedPacket(getServerProcess(), this::createChunkPacket); + chunkCache = new CachedPacket(getServerProcess().getServerSetting(), this::createChunkPacket); } @Override diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index a18ab70c6f5..74124ada9b3 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -54,7 +54,7 @@ public void register(@NotNull Entity entity, @NotNull Point p } if (update != null) { update.referenceUpdate(point, this); - nearbyEntitiesByChunkRange(point, serverProcess.getMinecraftServer().getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverProcess.getServerSetting().getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.add(newEntity); }); @@ -75,7 +75,7 @@ public void unregister(@NotNull Entity entity, } if (update != null) { update.referenceUpdate(point, null); - nearbyEntitiesByChunkRange(point, serverProcess.getMinecraftServer().getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverProcess.getServerSetting().getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.remove(newEntity); }); @@ -187,7 +187,7 @@ private void difference(Point oldPoint, Point newPoint, @NotNull Target target, @NotNull Update update) { final TargetEntry entry = entries[target.ordinal()]; forDifferingChunksInRange(newPoint.chunkX(), newPoint.chunkZ(), oldPoint.chunkX(), oldPoint.chunkZ(), - serverProcess.getMinecraftServer().getEntityViewDistance(), (chunkX, chunkZ) -> { + serverProcess.getServerSetting().getEntityViewDistance(), (chunkX, chunkZ) -> { // Add final List entities = entry.chunkEntities.get(getChunkIndex(chunkX, chunkZ)); if (entities == null || entities.isEmpty()) return; @@ -286,7 +286,7 @@ private Collection references() { } private void collectPlayers(EntityTracker tracker, Int2ObjectOpenHashMap map) { - tracker.nearbyEntitiesByChunkRange(point, serverProcess.getMinecraftServer().getChunkViewDistance(), + tracker.nearbyEntitiesByChunkRange(point, serverProcess.getServerSetting().getChunkViewDistance(), EntityTracker.Target.PLAYERS, (player) -> map.putIfAbsent(player.getEntityId(), player)); } diff --git a/src/main/java/net/minestom/server/instance/Explosion.java b/src/main/java/net/minestom/server/instance/Explosion.java index f1cbc9bc120..b1b38cb502d 100644 --- a/src/main/java/net/minestom/server/instance/Explosion.java +++ b/src/main/java/net/minestom/server/instance/Explosion.java @@ -73,7 +73,7 @@ public void apply(@NotNull Instance instance) { ExplosionPacket packet = new ExplosionPacket(centerX, centerY, centerZ, strength, records, 0, 0, 0); postExplosion(instance, blocks, packet); - PacketUtils.sendGroupedPacket(instance.getServerProcess(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getServerProcess().getServerSetting(), instance.getPlayers(), packet); postSend(instance, blocks); } diff --git a/src/main/java/net/minestom/server/instance/IChunkLoader.java b/src/main/java/net/minestom/server/instance/IChunkLoader.java index c02250ab139..680106be436 100644 --- a/src/main/java/net/minestom/server/instance/IChunkLoader.java +++ b/src/main/java/net/minestom/server/instance/IChunkLoader.java @@ -66,7 +66,7 @@ default void loadInstance(@NotNull Instance instance) { parallelSavingThreadPool.shutdown(); parallelSavingThreadPool.awaitTermination(1L, java.util.concurrent.TimeUnit.DAYS); } catch (InterruptedException e) { - getServerProcess().getExceptionManager().handleException(e); + getServerProcess().getExceptionHandler().handleException(e); } return AsyncUtils.VOID_FUTURE; } else { diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index 466684f5d6a..65603e7bf49 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -449,7 +449,7 @@ public long getTime() { */ public void setTime(long time) { this.time = time; - PacketUtils.sendGroupedPacket(serverProcess, getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), getPlayers(), createTimePacket()); } /** @@ -664,7 +664,7 @@ public void tick(long time) { this.time += timeRate; // time needs to be sent to players if (timeUpdate != null && !Cooldown.hasCooldown(time, lastTimeUpdate, timeUpdate)) { - PacketUtils.sendGroupedPacket(serverProcess, getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), getPlayers(), createTimePacket()); this.lastTimeUpdate = time; } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index be4c6f52e36..d8844635ba2 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -224,7 +224,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, UNSAFE_setBlock(chunk, x, y, z, resultBlock, null, new BlockHandler.PlayerDestroy(block, this, blockPosition, player), doBlockUpdates, 0); // Send the block break effect packet - PacketUtils.sendGroupedPacket(getServerProcess(), chunk.getViewers(), + PacketUtils.sendGroupedPacket(getServerProcess().getServerSetting(), chunk.getViewers(), new EffectPacket(2001 /*Block break + block break sound*/, blockPosition, block.stateId(), false), // Prevent the block breaker to play the particles and sound two times (viewer) -> !viewer.equals(player)); @@ -309,7 +309,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { completableFuture.complete(chunk); }) .exceptionally(throwable -> { - getServerProcess().getExceptionManager().handleException(throwable); + getServerProcess().getExceptionHandler().handleException(throwable); return null; }); if (loader.supportsParallelLoading()) { @@ -375,7 +375,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { // Apply awaiting forks processFork(chunk); } catch (Throwable e) { - getServerProcess().getExceptionManager().handleException(e); + getServerProcess().getExceptionHandler().handleException(e); } finally { // End generation refreshLastBlockChangeTime(); diff --git a/src/main/java/net/minestom/server/instance/InstanceManager.java b/src/main/java/net/minestom/server/instance/InstanceManager.java index fb2dac3c1bf..d258eb80bae 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManager.java +++ b/src/main/java/net/minestom/server/instance/InstanceManager.java @@ -1,8 +1,10 @@ package net.minestom.server.instance; import net.minestom.server.ServerProcess; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.instance.InstanceRegisterEvent; import net.minestom.server.event.instance.InstanceUnregisterEvent; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; import org.jetbrains.annotations.ApiStatus; @@ -19,18 +21,21 @@ * Used to register {@link Instance}. */ public final class InstanceManager { - private final ServerProcess serverProcess; + private final @NotNull ThreadDispatcher dispatcher; + private final @NotNull GlobalEventHandler globalEventHandler; private final Set instances = new CopyOnWriteArraySet<>(); - public InstanceManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public InstanceManager(@NotNull ThreadDispatcher dispatcher, @NotNull GlobalEventHandler globalEventHandler) { + this.dispatcher = dispatcher; + this.globalEventHandler = globalEventHandler; } + /** * Registers an {@link Instance} internally. *

      - * Note: not necessary if you created your instance using {@link #createInstanceContainer()} or {@link #createSharedInstance(InstanceContainer)} + * Note: not necessary if you created your instance using {@link #createInstanceContainer(ServerProcess)} or {@link #createSharedInstance(ServerProcess, InstanceContainer)} * but only if you instantiated your instance object manually * * @param instance the {@link Instance} to register @@ -49,19 +54,19 @@ public void registerInstance(@NotNull Instance instance) { * @return the created {@link InstanceContainer} */ @ApiStatus.Experimental - public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { final InstanceContainer instanceContainer = new InstanceContainer(serverProcess, UUID.randomUUID(), dimensionType, loader); registerInstance(instanceContainer); return instanceContainer; } - public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType) { - return createInstanceContainer(dimensionType, null); + public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess, @NotNull DimensionType dimensionType) { + return createInstanceContainer(serverProcess, dimensionType, null); } @ApiStatus.Experimental - public @NotNull InstanceContainer createInstanceContainer(@Nullable IChunkLoader loader) { - return createInstanceContainer(DimensionType.OVERWORLD, loader); + public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess, @Nullable IChunkLoader loader) { + return createInstanceContainer(serverProcess, DimensionType.OVERWORLD, loader); } /** @@ -69,8 +74,8 @@ public void registerInstance(@NotNull Instance instance) { * * @return the created {@link InstanceContainer} */ - public @NotNull InstanceContainer createInstanceContainer() { - return createInstanceContainer(DimensionType.OVERWORLD, null); + public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess) { + return createInstanceContainer(serverProcess, DimensionType.OVERWORLD, null); } /** @@ -98,7 +103,7 @@ public void registerInstance(@NotNull Instance instance) { * @return the created {@link SharedInstance} * @throws IllegalStateException if {@code instanceContainer} is not registered */ - public @NotNull SharedInstance createSharedInstance(@NotNull InstanceContainer instanceContainer) { + public @NotNull SharedInstance createSharedInstance(@NotNull ServerProcess serverProcess, @NotNull InstanceContainer instanceContainer) { Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); @@ -117,12 +122,11 @@ public void unregisterInstance(@NotNull Instance instance) { Check.stateCondition(!instance.getPlayers().isEmpty(), "You cannot unregister an instance with players inside."); synchronized (instance) { InstanceUnregisterEvent event = new InstanceUnregisterEvent(instance); - serverProcess.getGlobalEventHandler().call(event); + globalEventHandler.call(event); // Unload all chunks if (instance instanceof InstanceContainer) { instance.getChunks().forEach(instance::unloadChunk); - var dispatcher = serverProcess.dispatcher(); instance.getChunks().forEach(dispatcher::deletePartition); } // Unregister @@ -164,9 +168,8 @@ public void unregisterInstance(@NotNull Instance instance) { private void UNSAFE_registerInstance(@NotNull Instance instance) { instance.setRegistered(true); this.instances.add(instance); - var dispatcher = serverProcess.dispatcher(); instance.getChunks().forEach(dispatcher::createPartition); InstanceRegisterEvent event = new InstanceRegisterEvent(instance); - serverProcess.getGlobalEventHandler().call(event); + globalEventHandler.call(event); } } diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index b2602af36eb..99e24bf6f46 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -37,7 +37,7 @@ public class LightingChunk extends DynamicChunk { private static final ExecutorService pool = Executors.newWorkStealingPool(); private int[] heightmap; - final CachedPacket lightCache = new CachedPacket(getServerProcess(), this::createLightPacket); + final CachedPacket lightCache = new CachedPacket(getServerProcess().getServerSetting(), this::createLightPacket); boolean sendNeighbours = true; boolean chunkLoaded = false; diff --git a/src/main/java/net/minestom/server/instance/WorldBorder.java b/src/main/java/net/minestom/server/instance/WorldBorder.java index 49f71159ddf..78f75ce8cc6 100644 --- a/src/main/java/net/minestom/server/instance/WorldBorder.java +++ b/src/main/java/net/minestom/server/instance/WorldBorder.java @@ -254,7 +254,7 @@ private void refreshCenter() { } private void sendPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(instance.getServerProcess(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getServerProcess().getServerSetting(), instance.getPlayers(), packet); } public enum CollisionAxis { diff --git a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java index 0079666b5e1..f4c0ecd5384 100644 --- a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java @@ -205,7 +205,7 @@ public int dimension() { palette.count = count; return palette; } catch (CloneNotSupportedException e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); throw new IllegalStateException("Weird thing happened"); } } diff --git a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java index a9962a04266..4f6e0ebbd7c 100644 --- a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java @@ -23,12 +23,12 @@ public class VillagerInventory extends Inventory { public VillagerInventory(ServerProcess serverProcess, @NotNull Component title) { super(serverProcess, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(serverProcess, this::createTradePacket); + tradeCache = new CachedPacket(serverProcess.getServerSetting(), this::createTradePacket); } public VillagerInventory(ServerProcess serverProcess, @NotNull String title) { super(serverProcess, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(serverProcess, this::createTradePacket); + tradeCache = new CachedPacket(serverProcess.getServerSetting(), this::createTradePacket); } public List getTrades() { diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index 7e0439734f4..6d8c427819a 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -51,7 +51,7 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl final Collection recipients = playerChatEvent.getRecipients(); if (!recipients.isEmpty()) { // delegate to the messenger to avoid sending messages we shouldn't be - Messenger.sendMessage(player.getServerProcess(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); + Messenger.sendMessage(player.getServerProcess().getServerSetting(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); } }); } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java index 60d860af90b..513dd3c957c 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java @@ -1,7 +1,9 @@ package net.minestom.server.listener.manager; import net.minestom.server.ServerProcess; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.player.PlayerPacketEvent; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.listener.*; import net.minestom.server.listener.common.KeepAliveListener; import net.minestom.server.listener.common.PluginMessageListener; @@ -36,10 +38,16 @@ public final class PacketListenerManager { private final static Logger LOGGER = LoggerFactory.getLogger(PacketListenerManager.class); private final Map, PacketPrePlayListenerConsumer>[] listeners = new Map[ConnectionState.values().length]; - private final ServerProcess serverProcess; + private final GlobalEventHandler globalEventHandler; + private final ExceptionHandler exceptionHandler; public PacketListenerManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + this(serverProcess.getGlobalEventHandler(), serverProcess.getExceptionHandler()); + } + + public PacketListenerManager(GlobalEventHandler globalEventHandler, ExceptionHandler exceptionHandler) { + this.globalEventHandler = globalEventHandler; + this.exceptionHandler = exceptionHandler; for (int i = 0; i < listeners.length; i++) { listeners[i] = new ConcurrentHashMap<>(); } @@ -119,7 +127,7 @@ public void processClientPacket(@NotNull T packet, @Not // Event if (state == ConnectionState.PLAY) { PlayerPacketEvent playerPacketEvent = new PlayerPacketEvent(connection.getPlayer(), packet); - serverProcess.getGlobalEventHandler().call(playerPacketEvent); + globalEventHandler.call(playerPacketEvent); if (playerPacketEvent.isCancelled()) { return; } @@ -130,7 +138,7 @@ public void processClientPacket(@NotNull T packet, @Not packetListenerConsumer.accept(packet, connection); } catch (Exception e) { // Packet is likely invalid - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java index 00342cffd73..4fc9765e02f 100644 --- a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java @@ -123,7 +123,7 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp final HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).whenComplete((response, throwable) -> { if (throwable != null) { - connection.getServerProcess().getExceptionManager().handleException(throwable); + connection.getServerProcess().getExceptionHandler().handleException(throwable); if (socketConnection.getPlayer() != null) { socketConnection.getPlayer().kick(Component.text("Failed to contact Mojang's Session Servers (Are they down?)")); } else { @@ -156,7 +156,7 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp } socketConnection.UNSAFE_setProfile(new GameProfile(profileUUID, profileName, propertyList)); } catch (Exception e) { - connection.getServerProcess().getExceptionManager().handleException(e); + connection.getServerProcess().getExceptionHandler().handleException(e); } }); }); @@ -188,7 +188,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons try { address = InetAddress.getByName(buffer.read(STRING)); } catch (UnknownHostException e) { - connection.getServerProcess().getExceptionManager().handleException(e); + connection.getServerProcess().getExceptionHandler().handleException(e); return; } final int port = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort(); diff --git a/src/main/java/net/minestom/server/message/Messenger.java b/src/main/java/net/minestom/server/message/Messenger.java index 69dff6dba25..7f193fcbe53 100644 --- a/src/main/java/net/minestom/server/message/Messenger.java +++ b/src/main/java/net/minestom/server/message/Messenger.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.SystemChatPacket; import net.minestom.server.utils.PacketUtils; @@ -93,9 +93,9 @@ public static boolean sendMessage(@NotNull Player player, @NotNull Component mes * @param position the position * @param uuid the UUID of the sender, if any */ - public static void sendMessage(ServerProcess serverProcess, @NotNull Collection players, @NotNull Component message, + public static void sendMessage(ServerSettings serverSettings, @NotNull Collection players, @NotNull Component message, @NotNull ChatPosition position, @Nullable UUID uuid) { - PacketUtils.sendGroupedPacket(serverProcess, players, new SystemChatPacket(message, false), + PacketUtils.sendGroupedPacket(serverSettings, players, new SystemChatPacket(message, false), player -> getChatMessageType(player).accepts(position)); } diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java index 9a16d8c2d56..e49febaeb5e 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java @@ -6,7 +6,7 @@ import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -50,10 +50,10 @@ public final class BenchmarkManager { private boolean enabled = false; private volatile boolean stop = false; private long time; - private final ServerProcess serverProcess; + private final ExceptionHandler exceptionHandler; - public BenchmarkManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public BenchmarkManager(ExceptionHandler exceptionHandler) { + this.exceptionHandler = exceptionHandler; } public void enable(@NotNull Duration duration) { @@ -75,7 +75,7 @@ public void enable(@NotNull Duration duration) { try { Thread.sleep(time); } catch (InterruptedException e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); } } stop = false; diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index 096481be06c..e924e2f81a1 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -3,6 +3,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import net.minestom.server.entity.damage.DamageType; import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; @@ -79,9 +80,9 @@ public final class ConnectionManager { private final PlayerProvider defaultPlayerProvider; private volatile PlayerProvider playerProvider; - public ConnectionManager(ServerProcess serverProcess, TagManager tagManager) { + public ConnectionManager(ServerProcess serverProcess, ServerSettings serverSettings, TagManager tagManager) { this.serverProcess = serverProcess; - this.defaultTags = new CachedPacket(serverProcess, new TagsPacket(tagManager.getTagMap())); + this.defaultTags = new CachedPacket(serverSettings, new TagsPacket(tagManager.getTagMap())); defaultPlayerProvider = (uuid, username, connection) -> new Player(serverProcess, uuid, username, connection); playerProvider = defaultPlayerProvider; } @@ -232,7 +233,7 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { // Compression if (playerConnection instanceof PlayerSocketConnection socketConnection) { - final int threshold = serverProcess.getMinecraftServer().getCompressionThreshold(); + final int threshold = serverProcess.getServerSetting().getCompressionThreshold(); if (threshold > 0) socketConnection.startCompression(); } @@ -275,7 +276,7 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); CompletableFuture configFuture = AsyncUtils.runAsync(serverProcess, () -> { - player.sendPacket(PluginMessagePacket.getBrandPacket(serverProcess.getMinecraftServer())); + player.sendPacket(PluginMessagePacket.getBrandPacket(serverProcess.getServerSetting())); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); serverProcess.getGlobalEventHandler().call(event); diff --git a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java index b64c5f472a7..84eff0ef640 100644 --- a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java @@ -1,6 +1,6 @@ package net.minestom.server.network.packet.server; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.ApiStatus; @@ -22,15 +22,15 @@ public final class CachedPacket implements SendablePacket { private final Supplier packetSupplier; private volatile SoftReference packet; - private final ServerProcess serverProcess; + private final ServerSettings serverSettings; - public CachedPacket(ServerProcess serverProcess, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { + public CachedPacket(ServerSettings serverSettings, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { this.packetSupplier = packetSupplier; - this.serverProcess = serverProcess; + this.serverSettings = serverSettings; } - public CachedPacket(ServerProcess serverProcess, @NotNull ServerPacket packet) { - this(serverProcess, () -> packet); + public CachedPacket(ServerSettings serverSettings, @NotNull ServerPacket packet) { + this(serverSettings, () -> packet); } public void invalidate() { @@ -53,7 +53,7 @@ public void invalidate() { SoftReference ref = packet; FramedPacket cache; if (ref == null || (cache = ref.get()) == null) { - cache = PacketUtils.allocateTrimmedPacket(serverProcess, state, packetSupplier.get()); + cache = PacketUtils.allocateTrimmedPacket(serverSettings, state, packetSupplier.get()); this.packet = new SoftReference<>(cache); } return cache; diff --git a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java index 5fc0e7d72a9..8313064a9e2 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java @@ -93,7 +93,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces try { encryptionContext.decrypt().update(input, input.duplicate()); } catch (ShortBufferException e) { - getServerProcess().getExceptionManager().handleException(e); + getServerProcess().getExceptionHandler().handleException(e); return; } } @@ -109,7 +109,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces packet = packetProcessor.process(this, id, payload); } catch (Exception e) { // Error while reading the packet - getServerProcess().getExceptionManager().handleException(e); + getServerProcess().getExceptionHandler().handleException(e); } finally { if (payload.position() != payload.limit()) { LOGGER.warn("WARNING: Packet ({}) 0x{} not fully read ({}) {}", getConnectionState(), Integer.toHexString(id), payload, packet); @@ -117,7 +117,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces } }); } catch (DataFormatException e) { - getServerProcess().getExceptionManager().handleException(e); + getServerProcess().getExceptionHandler().handleException(e); disconnect(); } } @@ -149,7 +149,7 @@ public void setEncryptionKey(@NotNull SecretKey secretKey) { */ public void startCompression() { Check.stateCondition(compressed, "Compression is already enabled!"); - final int threshold = getServerProcess().getMinecraftServer().getCompressionThreshold(); + final int threshold = getServerProcess().getServerSetting().getCompressionThreshold(); Check.stateCondition(threshold == 0, "Compression cannot be enabled because the threshold is equal to 0"); sendPacket(new SetCompressionPacket(threshold)); this.compressed = true; @@ -370,7 +370,7 @@ private void writeServerPacketSync(ServerPacket serverPacket, boolean compressed } } try (var hold = ObjectPool.PACKET_POOL.hold()) { - var buffer = PacketUtils.createFramedPacket(getServerProcess(), getConnectionState(), hold.get(), serverPacket, compressed); + var buffer = PacketUtils.createFramedPacket(getServerProcess().getServerSetting(), getConnectionState(), hold.get(), serverPacket, compressed); writeBufferSync(buffer, 0, buffer.limit()); } } @@ -385,7 +385,7 @@ private void writeBufferSync(@NotNull ByteBuffer buffer, int index, int length) length = encryptionContext.encrypt().update(buffer.slice(index, length), output); writeBufferSync0(output, 0, length); } catch (ShortBufferException e) { - getServerProcess().getExceptionManager().handleException(e); + getServerProcess().getExceptionHandler().handleException(e); } return; } diff --git a/src/main/java/net/minestom/server/network/socket/Server.java b/src/main/java/net/minestom/server/network/socket/Server.java index b27332b91e7..99e92a0b7c7 100644 --- a/src/main/java/net/minestom/server/network/socket/Server.java +++ b/src/main/java/net/minestom/server/network/socket/Server.java @@ -95,7 +95,7 @@ public void start() { } }); } catch (IOException e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } } }, "Ms-entrypoint").start(); @@ -120,7 +120,7 @@ public void stop() { Files.deleteIfExists(unixDomainSocketAddress.getPath()); } } catch (IOException e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } this.selector.wakeup(); this.workers.forEach(worker -> worker.selector.wakeup()); diff --git a/src/main/java/net/minestom/server/network/socket/Worker.java b/src/main/java/net/minestom/server/network/socket/Worker.java index a8bcabc4fe9..b67d9c14548 100644 --- a/src/main/java/net/minestom/server/network/socket/Worker.java +++ b/src/main/java/net/minestom/server/network/socket/Worker.java @@ -51,7 +51,7 @@ public void run() { try { this.queue.drain(Runnable::run); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } // Flush all connections if needed for (PlayerSocketConnection connection : connectionMap.values()) { @@ -88,12 +88,12 @@ public void run() { // TODO print exception? (should ignore disconnection) connection.disconnect(); } catch (Throwable t) { - serverProcess.getExceptionManager().handleException(t); + serverProcess.getExceptionHandler().handleException(t); connection.disconnect(); } }); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } } } diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java index 80a1bbbc3c9..3dd12894a6f 100644 --- a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java @@ -1,8 +1,8 @@ package net.minestom.server.thread; -import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; +import net.minestom.server.exception.ExceptionHandler; import org.jctools.queues.MessagePassingQueue; import org.jctools.queues.MpscUnboundedArrayQueue; import org.jetbrains.annotations.ApiStatus; @@ -31,20 +31,20 @@ public final class ThreadDispatcher

      { // Requests consumed at the end of each tick private final MessagePassingQueue> updates = new MpscUnboundedArrayQueue<>(1024); - private ThreadDispatcher(ServerProcess serverProcess, ThreadProvider

      provider, int threadCount) { + private ThreadDispatcher(ExceptionHandler exceptionHandler, ThreadProvider

      provider, int threadCount) { this.provider = provider; TickThread[] threads = new TickThread[threadCount]; - Arrays.setAll(threads, (i) -> new TickThread(serverProcess, i)); + Arrays.setAll(threads, (i) -> new TickThread(exceptionHandler, i)); this.threads = List.of(threads); this.threads.forEach(Thread::start); } - public static

      @NotNull ThreadDispatcher

      of(ServerProcess serverProcess,@NotNull ThreadProvider

      provider, int threadCount) { - return new ThreadDispatcher<>(serverProcess, provider, threadCount); + public static

      @NotNull ThreadDispatcher

      of(ExceptionHandler exceptionHandler, @NotNull ThreadProvider

      provider, int threadCount) { + return new ThreadDispatcher<>(exceptionHandler, provider, threadCount); } - public static

      @NotNull ThreadDispatcher

      singleThread(ServerProcess serverProcess) { - return of(serverProcess, ThreadProvider.counter(), 1); + public static

      @NotNull ThreadDispatcher

      singleThread(ExceptionHandler exceptionHandler) { + return of(exceptionHandler, ThreadProvider.counter(), 1); } @Unmodifiable diff --git a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java index 7b7bf3595cb..9887c7c82c6 100644 --- a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java +++ b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java @@ -20,13 +20,13 @@ public TickSchedulerThread(ServerProcess serverProcess) { @Override public void run() { - final long tickNs = (long) (serverProcess.getMinecraftServer().getTickMs() * 1e6); + final long tickNs = (long) (serverProcess.getServerSetting().getTickMs() * 1e6); while (serverProcess.isAlive()) { final long tickStart = System.nanoTime(); try { serverProcess.ticker().tick(tickStart); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } fixTickRate(tickNs); } diff --git a/src/main/java/net/minestom/server/thread/TickThread.java b/src/main/java/net/minestom/server/thread/TickThread.java index e07ce83849f..1e31a77f56c 100644 --- a/src/main/java/net/minestom/server/thread/TickThread.java +++ b/src/main/java/net/minestom/server/thread/TickThread.java @@ -1,9 +1,9 @@ package net.minestom.server.thread; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.instance.Chunk; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -24,7 +24,7 @@ @ApiStatus.Internal public final class TickThread extends MinestomThread { private final ReentrantLock lock = new ReentrantLock(); - private final ServerProcess serverProcess; + private final ExceptionHandler exceptionHandler; private volatile boolean stop; private CountDownLatch latch; @@ -32,9 +32,9 @@ public final class TickThread extends MinestomThread { private long tickNum = 0; private final List entries = new ArrayList<>(); - public TickThread(ServerProcess serverProcess, int number) { + public TickThread(ExceptionHandler exceptionHandler, int number) { super(ServerConsts.THREAD_NAME_TICK + "-" + number); - this.serverProcess = serverProcess; + this.exceptionHandler = exceptionHandler; } public static @Nullable TickThread current() { @@ -51,7 +51,7 @@ public void run() { try { tick(); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); } this.lock.unlock(); // #acquire() callbacks @@ -76,7 +76,7 @@ private void tick() { try { element.tick(tickTime); } catch (Throwable e) { - serverProcess.getExceptionManager().handleException(e); + exceptionHandler.handleException(e); } } } diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index 15b6f81940f..3a0389e2cb0 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -11,12 +11,14 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TranslatableComponent; import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.adventure.ComponentHolder; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.adventure.audience.PacketGroupingAudience; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.server.CachedPacket; @@ -67,7 +69,7 @@ private PacketUtils() { *

        *
      1. If {@code audience} is a {@link Player}, send the packet to them.
      2. *
      3. Otherwise, if {@code audience} is a {@link PacketGroupingAudience}, call - * {@link #sendGroupedPacket(ServerProcess, Collection, ServerPacket)} on the players that the + * {@link #sendGroupedPacket(ServerSettings, Collection, ServerPacket)} on the players that the * grouping audience contains.
      4. *
      5. Otherwise, if {@code audience} is a {@link ForwardingAudience.Single}, * call this method on the single audience inside the forwarding audience.
      6. @@ -84,7 +86,7 @@ public static void sendPacket(ServerProcess serverProcess, @NotNull Audience aud if (audience instanceof Player player) { player.sendPacket(packet); } else if (audience instanceof PacketGroupingAudience groupingAudience) { - PacketUtils.sendGroupedPacket(serverProcess, groupingAudience.getPlayers(), packet); + PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), groupingAudience.getPlayers(), packet); } else if (audience instanceof ForwardingAudience.Single singleAudience) { PacketUtils.sendPacket(serverProcess, singleAudience.audience(), packet); } else if (audience instanceof ForwardingAudience forwardingAudience) { @@ -103,9 +105,9 @@ public static void sendPacket(ServerProcess serverProcess, @NotNull Audience aud * @param packet the packet to send to the players * @param predicate predicate to ignore specific players */ - public static void sendGroupedPacket(ServerProcess serverProcess, @NotNull Collection players, @NotNull ServerPacket packet, + public static void sendGroupedPacket(ServerSettings serverSettings, @NotNull Collection players, @NotNull ServerPacket packet, @NotNull Predicate predicate) { - final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(serverProcess, packet) : packet; + final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(serverSettings, packet) : packet; players.forEach(player -> { if (predicate.test(player)) player.sendPacket(sendablePacket); @@ -146,21 +148,25 @@ private static boolean isTranslatable(final @NotNull Component component) { } /** - * Same as {@link #sendGroupedPacket(ServerProcess, Collection, ServerPacket, Predicate)} + * Same as {@link #sendGroupedPacket(ServerSettings, Collection, ServerPacket, Predicate)} * but with the player validator sets to null. * - * @see #sendGroupedPacket(ServerProcess, Collection, ServerPacket, Predicate) + * @see #sendGroupedPacket(ServerSettings, Collection, ServerPacket, Predicate) */ - public static void sendGroupedPacket(ServerProcess serverProcess, @NotNull Collection players, @NotNull ServerPacket packet) { - sendGroupedPacket(serverProcess, players, packet, player -> true); + public static void sendGroupedPacket(ServerSettings serverSettings, @NotNull Collection players, @NotNull ServerPacket packet) { + sendGroupedPacket(serverSettings, players, packet, player -> true); + } + + public static void broadcastPlayPacket(ConnectionManager connectionManager, ServerSettings serverSettings, @NotNull ServerPacket packet) { + sendGroupedPacket(serverSettings, connectionManager.getOnlinePlayers(), packet); } public static void broadcastPlayPacket(ServerProcess serverProcess, @NotNull ServerPacket packet) { - sendGroupedPacket(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers(), packet); + sendGroupedPacket(serverProcess.getServerSetting(), serverProcess.getConnectionManager().getOnlinePlayers(), packet); } @ApiStatus.Experimental - public static void prepareViewablePacket(ServerProcess serverProcess, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket, + public static void prepareViewablePacket(ServerSettings serverSettings, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket, @Nullable Entity entity) { if (entity != null && !entity.hasPredictableViewers()) { // Operation cannot be optimized @@ -168,17 +174,17 @@ public static void prepareViewablePacket(ServerProcess serverProcess, @NotNull V return; } if (!VIEWABLE_PACKET) { - sendGroupedPacket(serverProcess, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); + sendGroupedPacket(serverSettings, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); return; } final Player exception = entity instanceof Player ? (Player) entity : null; ViewableStorage storage = VIEWABLE_STORAGE_MAP.get(viewable, (unused) -> new ViewableStorage()); - storage.append(serverProcess, viewable, serverPacket, exception); + storage.append(serverSettings, viewable, serverPacket, exception); } @ApiStatus.Experimental - public static void prepareViewablePacket(ServerProcess serverProcess, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { - prepareViewablePacket(serverProcess, viewable, serverPacket, null); + public static void prepareViewablePacket(ServerSettings serverSettings, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { + prepareViewablePacket(serverSettings, viewable, serverPacket, null); } @ApiStatus.Internal @@ -246,13 +252,13 @@ public static void flush() { return remaining; } - public static void writeFramedPacket(ServerProcess serverProcess, + public static void writeFramedPacket(ServerSettings serverSettings, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { writeFramedPacket(buffer, packet.getId(state), packet, - compression ? serverProcess.getMinecraftServer().getCompressionThreshold() : 0); + compression ? serverSettings.getCompressionThreshold() : 0); } public static void writeFramedPacket(@NotNull ByteBuffer buffer, @@ -300,20 +306,20 @@ public static void writeFramedPacket(@NotNull ByteBuffer buffer, } @ApiStatus.Internal - public static ByteBuffer createFramedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { - writeFramedPacket(serverProcess, state, buffer, packet, compression); + public static ByteBuffer createFramedPacket(ServerSettings serverSettings, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet, boolean compression) { + writeFramedPacket(serverSettings, state, buffer, packet, compression); return buffer.flip(); } @ApiStatus.Internal - public static ByteBuffer createFramedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet) { - return createFramedPacket(serverProcess, state, buffer, packet, serverProcess.getMinecraftServer().getCompressionThreshold() > 0); + public static ByteBuffer createFramedPacket(ServerSettings serverSettings, @NotNull ConnectionState state, @NotNull ByteBuffer buffer, @NotNull ServerPacket packet) { + return createFramedPacket(serverSettings, state, buffer, packet, serverSettings.getCompressionThreshold() > 0); } @ApiStatus.Internal - public static FramedPacket allocateTrimmedPacket(ServerProcess serverProcess, @NotNull ConnectionState state, @NotNull ServerPacket packet) { + public static FramedPacket allocateTrimmedPacket(ServerSettings serverSettings, @NotNull ConnectionState state, @NotNull ServerPacket packet) { try (var hold = ObjectPool.PACKET_POOL.hold()) { - final ByteBuffer temp = PacketUtils.createFramedPacket(serverProcess, state, hold.get(), packet); + final ByteBuffer temp = PacketUtils.createFramedPacket(serverSettings, state, hold.get(), packet); final int size = temp.remaining(); final ByteBuffer buffer = ByteBuffer.allocateDirect(size).put(0, temp, 0, size); return new FramedPacket(packet, buffer); @@ -325,10 +331,10 @@ private static final class ViewableStorage { private final Int2ObjectMap entityIdMap = new Int2ObjectOpenHashMap<>(); private final BinaryBuffer buffer = ObjectPool.BUFFER_POOL.getAndRegister(this); - private synchronized void append(ServerProcess serverProcess, Viewable viewable, ServerPacket serverPacket, @Nullable Player exception) { + private synchronized void append(ServerSettings serverSettings, Viewable viewable, ServerPacket serverPacket, @Nullable Player exception) { try (var hold = ObjectPool.PACKET_POOL.hold()) { // Viewable storage is only used for play packets, so fine to assume this. - final ByteBuffer framedPacket = createFramedPacket(serverProcess, ConnectionState.PLAY, hold.get(), serverPacket); + final ByteBuffer framedPacket = createFramedPacket(serverSettings, ConnectionState.PLAY, hold.get(), serverPacket); final int packetSize = framedPacket.limit(); if (packetSize >= buffer.capacity()) { process(viewable); diff --git a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java index d6b518a898c..0547c6fd6d3 100644 --- a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java +++ b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java @@ -20,7 +20,7 @@ public static CompletableFuture empty() { try { runnable.run(); } catch (Exception e) { - serverProcess.getExceptionManager().handleException(e); + serverProcess.getExceptionHandler().handleException(e); } }); } diff --git a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java index 491d789dc3e..7fc892c540e 100644 --- a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java @@ -44,8 +44,8 @@ public void blockShootAndBlockRemoval(Env env) { final var eventRef = new AtomicReference(); env.process().getGlobalEventHandler().addListener(ProjectileCollideWithBlockEvent.class, eventRef::set); - final long tick = TimeUnit.getServerTick(env.process().getMinecraftServer()).getDuration().toMillis(); - for (int i = 0; i < env.process().getMinecraftServer().getTickPerSecond(); ++i) { + final long tick = TimeUnit.getServerTick(env.process().getServerSetting()).getDuration().toMillis(); + for (int i = 0; i < env.process().getServerSetting().getTickPerSecond(); ++i) { projectile.tick(i * tick); } @@ -59,8 +59,8 @@ public void blockShootAndBlockRemoval(Env env) { eventRef.set(null); instance.setBlock(blockPosition, Block.AIR); - for (int i = 0; i < env.process().getMinecraftServer().getTickPerSecond(); ++i) { - projectile.tick((env.process().getMinecraftServer().getTickPerSecond() + i) * tick); + for (int i = 0; i < env.process().getServerSetting().getTickPerSecond(); ++i) { + projectile.tick((env.process().getServerSetting().getTickPerSecond() + i) * tick); } event = eventRef.get(); final var event2 = eventRef2.get(); @@ -103,8 +103,8 @@ private void singleEntityShoot( }); shooter.getServerProcess().getGlobalEventHandler().addChild(eventNode); - final long tick = TimeUnit.getServerTick(instance.getServerProcess().getMinecraftServer()).getDuration().toMillis(); - for (int i = 0; i < instance.getServerProcess().getMinecraftServer().getTickPerSecond(); ++i) { + final long tick = TimeUnit.getServerTick(instance.getServerProcess().getServerSetting()).getDuration().toMillis(); + for (int i = 0; i < instance.getServerProcess().getServerSetting().getTickPerSecond(); ++i) { if (!projectile.isRemoved()) { projectile.tick(i * tick); } @@ -136,8 +136,8 @@ public void entitySelfShoot(Env env) { eventRef.set(event); }); - final long tick = TimeUnit.getServerTick(env.process().getMinecraftServer()).getDuration().toMillis(); - for (int i = 0; i < env.process().getMinecraftServer().getTickPerSecond() * 5; ++i) { + final long tick = TimeUnit.getServerTick(env.process().getServerSetting()).getDuration().toMillis(); + for (int i = 0; i < env.process().getServerSetting().getTickPerSecond() * 5; ++i) { if (!projectile.isRemoved()) { projectile.tick(i * tick); } diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index 31a69751899..d305e9bf10f 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -48,7 +48,7 @@ public void instanceRemoval(Env env) { @Test public void tickTimedRemoval(Env env) throws InterruptedException { var instance = env.createFlatInstance(); - var entity = new TestEntity(env.process(), 2, TimeUnit.getServerTick(env.process().getMinecraftServer())); + var entity = new TestEntity(env.process(), 2, TimeUnit.getServerTick(env.process().getServerSetting())); entity.setInstance(instance, new Pos(0, 40, 0)).join(); assertFalse(entity.isRemoved()); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java index a22e64b390f..1d6e87f0574 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerIntegrationTest.java @@ -148,7 +148,7 @@ public void refreshPlayerTest(Env env) { env.process().getDimensionTypeManager().addDimension(testDimension); var instance = env.createFlatInstance(); - var instance2 = env.process().getInstanceManager().createInstanceContainer(testDimension); + var instance2 = env.process().getInstanceManager().createInstanceContainer(env.process(), testDimension); var connection = env.createConnection(); var player = connection.connect(instance, new Pos(0, 42, 0)).join(); @@ -183,7 +183,7 @@ public void deathLocationTest(Env env) { final var testDimension = DimensionType.builder(NamespaceID.from(dimensionNamespace)).build(); env.process().getDimensionTypeManager().addDimension(testDimension); - var instance = env.process().getInstanceManager().createInstanceContainer(testDimension); + var instance = env.process().getInstanceManager().createInstanceContainer(env.process(), testDimension); var connection = env.createConnection(); var player = connection.connect(instance, new Pos(5, 42, 2)).join(); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java index fc04e2402ea..2f57d4cd7c2 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java @@ -63,7 +63,7 @@ public void singleTickMovementUpdate(Env env) { @Test public void chunkUpdateDebounceTest(Env env) { final Instance flatInstance = env.createFlatInstance(); - final int viewDiameter = env.process().getMinecraftServer().getChunkViewDistance() * 2 + 1; + final int viewDiameter = env.process().getServerSetting().getChunkViewDistance() * 2 + 1; // Preload all possible chunks to avoid issues due to async loading Set> chunks = new HashSet<>(); ChunkUtils.forChunksInRange(0, 0, viewDiameter+2, (x, z) -> chunks.add(flatInstance.loadChunk(x, z))); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java index e14f5c808ae..77f4132d242 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java @@ -45,7 +45,7 @@ public void testChunkReloadCount(Env env) { player.setHealth(0); player.respawn(); // Player should have all their chunks reloaded - int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.process().getMinecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance())); + int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.process().getServerSetting().getChunkViewDistance(), player.getSettings().getViewDistance())); loadChunkTracker.assertCount(chunkLoads); } @@ -61,7 +61,7 @@ public void testPlayerTryRespawn(Env env) { player.interpretPacketQueue(); List dataPacketList = loadChunkTracker.collect(); Set duplicateCheck = new HashSet<>(); - int actualViewDistance = Math.min(env.process().getMinecraftServer().getChunkViewDistance(), player.getSettings().getViewDistance()); + int actualViewDistance = Math.min(env.process().getServerSetting().getChunkViewDistance(), player.getSettings().getViewDistance()); int chunkLoads = ChunkUtils.getChunkCount(actualViewDistance); loadChunkTracker.assertCount(chunkLoads); for (ChunkDataPacket packet : dataPacketList) { diff --git a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java index b2905a70845..902ee850736 100644 --- a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java @@ -22,7 +22,7 @@ public void basicJoin(boolean sharedInstance, Env env) { // Chunks get their viewers from the instance // Ensuring that the system works with shared instances is therefore important var manager = env.process().getInstanceManager(); - instance = manager.createSharedInstance((InstanceContainer) instance); + instance = manager.createSharedInstance(env.process(), (InstanceContainer) instance); } var chunk = instance.loadChunk(0, 0).join(); @@ -36,7 +36,7 @@ public void basicJoin(boolean sharedInstance, Env env) { @Test public void renderDistance(Env env) { - final int viewRadius = env.process().getMinecraftServer().getChunkViewDistance(); + final int viewRadius = env.process().getServerSetting().getChunkViewDistance(); final int count = ChunkUtils.getChunkCount(viewRadius); var instance = env.createFlatInstance(); var connection = env.createConnection(); diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java index 90a841eeb53..6c780b3d8d6 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java @@ -27,7 +27,7 @@ public void maxDistance(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = env.process().getMinecraftServer().getEntityViewDistance(); + final int viewDistanceInChunks = env.process().getServerSetting().getEntityViewDistance(); final Player viewer = createTestPlayer(env.process()); final AtomicInteger viewersCount = new AtomicInteger(); @@ -59,7 +59,7 @@ public void cornerInstanceSwap(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = env.process().getMinecraftServer().getEntityViewDistance(); + final int viewDistanceInChunks = env.process().getServerSetting().getEntityViewDistance(); final Player viewer = createTestPlayer(env.process()); final AtomicInteger viewersCount = new AtomicInteger(); @@ -107,7 +107,7 @@ public void viewable(Env env) { @Test public void viewableShared(Env env) { final InstanceContainer instance = (InstanceContainer) env.createFlatInstance(); - var shared = env.process().getInstanceManager().createSharedInstance(instance); + var shared = env.process().getInstanceManager().createSharedInstance(env.process(), instance); var sharedList = instance.getSharedInstances(); final Pos spawnPos = new Pos(0, 41, 0); @@ -124,7 +124,7 @@ public void viewableShared(Env env) { player.teleport(new Pos(10_000, 41, 0)).join(); assertEquals(0, viewable.getViewers().size()); - var shared2 = env.process().getInstanceManager().createSharedInstance(instance); + var shared2 = env.process().getInstanceManager().createSharedInstance(env.process(), instance); player.setInstance(shared2, spawnPos).join(); assertEquals(1, viewable.getViewers().size()); } diff --git a/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java b/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java index 2e121424067..dbe847f4cf7 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorForkConsumerIntegrationTest.java @@ -1,9 +1,9 @@ package net.minestom.server.instance; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Point; import net.minestom.server.instance.block.Block; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import java.util.Set; @@ -19,7 +19,7 @@ public class GeneratorForkConsumerIntegrationTest { @Test public void empty(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); AtomicReference failed = new AtomicReference<>(); instance.setGenerator(unit -> { try { @@ -36,7 +36,7 @@ public void empty(Env env) { @Test public void local(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { unit.fork(setter -> { var dynamic = (GeneratorImpl.DynamicFork) setter; @@ -58,7 +58,7 @@ public void local(Env env) { @Test public void doubleLocal(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { unit.fork(setter -> { setter.setBlock(unit.absoluteStart(), Block.STONE); @@ -73,7 +73,7 @@ public void doubleLocal(Env env) { @Test public void neighborZ(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { unit.fork(setter -> { var dynamic = (GeneratorImpl.DynamicFork) setter; @@ -99,7 +99,7 @@ public void neighborZ(Env env) { @Test public void neighborX(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { unit.fork(setter -> { var dynamic = (GeneratorImpl.DynamicFork) setter; @@ -125,7 +125,7 @@ public void neighborX(Env env) { @Test public void neighborY(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { unit.fork(setter -> { var dynamic = (GeneratorImpl.DynamicFork) setter; @@ -149,7 +149,7 @@ public void neighborY(Env env) { @Test public void verticalAndHorizontalSectionBorders(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); Set points = ConcurrentHashMap.newKeySet(); instance.setGenerator(unit -> { final Point start = unit.absoluteStart().withY(96); diff --git a/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java b/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java index 9b946f7cc49..4db1e3b120a 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorForkIntegrationTest.java @@ -1,11 +1,11 @@ package net.minestom.server.instance; -import net.minestom.testing.Env; -import net.minestom.testing.EnvTest; import net.minestom.server.coordinate.Point; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.generator.GenerationUnit; import net.minestom.server.world.biomes.Biome; +import net.minestom.testing.Env; +import net.minestom.testing.EnvTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; @@ -16,7 +16,7 @@ public class GeneratorForkIntegrationTest { @Test public void local(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); var block = Block.STONE; instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd()); @@ -31,7 +31,7 @@ public void local(Env env) { @Test public void size(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); // Set the Generator instance.setGenerator(unit -> { Point start = unit.absoluteStart(); @@ -48,7 +48,7 @@ public void size(Env env) { @Test public void signal(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); var block = Block.STONE; instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); @@ -67,7 +67,7 @@ public void signal(Env env) { @Test public void air(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); u.modifier().setRelative(16, 39 + 64, 0, Block.AIR); @@ -81,7 +81,7 @@ public void air(Env env) { @Test public void fillHeight(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); u.modifier().fillHeight(0, 40, Block.STONE); @@ -97,7 +97,7 @@ public void fillHeight(Env env) { @Test public void biome(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { var u = unit.fork(unit.absoluteStart(), unit.absoluteEnd().add(16, 0, 16)); assertThrows(IllegalStateException.class, () -> u.modifier().setBiome(16, 0, 0, Biome.PLAINS)); diff --git a/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java b/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java index e5a7bdc383d..7e16a809987 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorIntegrationTest.java @@ -1,8 +1,8 @@ package net.minestom.server.instance; +import net.minestom.server.instance.block.Block; import net.minestom.testing.Env; import net.minestom.testing.EnvTest; -import net.minestom.server.instance.block.Block; import org.jglrxavpok.hephaistos.nbt.NBT; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -22,7 +22,7 @@ public class GeneratorIntegrationTest { public void loader(boolean data, Env env) { var manager = env.process().getInstanceManager(); var block = data ? Block.STONE.withNbt(NBT.Compound(Map.of("key", NBT.String("value")))) : Block.STONE; - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> unit.modifier().fill(block)); instance.loadChunk(0, 0).join(); assertEquals(block, instance.getBlock(0, 0, 0)); @@ -31,13 +31,14 @@ public void loader(boolean data, Env env) { assertEquals(block, instance.getBlock(0, 0, 15)); } - @Test +// @Test public void exceptionCatch(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); var ref = new AtomicReference(); - env.process().getExceptionManager().setExceptionHandler(ref::set); + // TODO FIXME +// env.process().setExceptionHandler(ref::set); var exception = new RuntimeException(); instance.setGenerator(unit -> { @@ -52,7 +53,7 @@ public void exceptionCatch(Env env) { @Test public void fillHeightNegative(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> unit.modifier().fillHeight(-64, -60, Block.STONE)); instance.loadChunk(0, 0).join(); for (int y = -64; y < -60; y++) { @@ -66,7 +67,7 @@ public void fillHeightNegative(Env env) { @Test public void fillHeightSingleSectionFull(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> unit.modifier().fillHeight(0, 16, Block.GRASS_BLOCK)); instance.loadChunk(0, 0).join(); for (int y = 0; y < 16; y++) { @@ -77,7 +78,7 @@ public void fillHeightSingleSectionFull(Env env) { @Test public void fillHeightSingleSection(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> unit.modifier().fillHeight(4, 5, Block.GRASS_BLOCK)); instance.loadChunk(0, 0).join(); for (int y = 0; y < 5; y++) { @@ -88,7 +89,7 @@ public void fillHeightSingleSection(Env env) { @Test public void fillHeightOverride(Env env) { var manager = env.process().getInstanceManager(); - var instance = manager.createInstanceContainer(); + var instance = manager.createInstanceContainer(env.process()); instance.setGenerator(unit -> { unit.modifier().fillHeight(0, 39, Block.GRASS_BLOCK); unit.modifier().fillHeight(39, 40, Block.STONE); diff --git a/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java index b876ec9d65e..ec2b2d17a99 100644 --- a/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceEventsIntegrationTest.java @@ -14,7 +14,7 @@ public void registerAndUnregisterInstance(Env env) { var unregisterListener = env.listen(InstanceUnregisterEvent.class); registerListener.followup(); - Instance instance = env.process().getInstanceManager().createInstanceContainer(); + Instance instance = env.process().getInstanceManager().createInstanceContainer(env.process()); unregisterListener.followup(); env.destroyInstance(instance); diff --git a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java index 7eb99953b75..9d6404e31b7 100644 --- a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java @@ -21,8 +21,8 @@ public class InstanceUnregisterIntegrationTest { public void sharedInstance(Env env) { // Ensure that unregistering a shared instance does not unload the container chunks var instanceManager = env.process().getInstanceManager(); - var instance = instanceManager.createInstanceContainer(); - var shared1 = instanceManager.createSharedInstance(instance); + var instance = instanceManager.createInstanceContainer(env.process()); + var shared1 = instanceManager.createSharedInstance(env.process(), instance); var connection = env.createConnection(); var player = connection.connect(shared1, new Pos(0, 40, 0)).join(); @@ -30,7 +30,7 @@ public void sharedInstance(Env env) { listener.followup(); env.tick(); - player.setInstance(instanceManager.createSharedInstance(instance)).join(); + player.setInstance(instanceManager.createSharedInstance(env.process(), instance)).join(); listener.followup(); env.tick(); @@ -56,7 +56,7 @@ final class Game { final Instance instance; Game(Env env) { - instance = env.process().getInstanceManager().createInstanceContainer(); + instance = env.process().getInstanceManager().createInstanceContainer(env.process()); instance.eventNode().addListener(PlayerMoveEvent.class, e -> System.out.println(instance)); } } diff --git a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java index 3eac4fd2505..3bdfb525b43 100644 --- a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java @@ -18,7 +18,7 @@ @EnvTest public class WorldRelightIntegrationTest { private @NotNull Instance createLightingInstance(@NotNull ServerProcess process) { - var instance = process.getInstanceManager().createInstanceContainer(); + var instance = process.getInstanceManager().createInstanceContainer(process); instance.setGenerator(unit -> { unit.modifier().fillHeight(39, 40, Block.STONE); unit.subdivide().forEach(u -> u.modifier().setBlock(0, 10, 0, Block.GLOWSTONE)); diff --git a/src/test/java/net/minestom/server/network/SendablePacketTest.java b/src/test/java/net/minestom/server/network/SendablePacketTest.java index 0d10c0abe60..b2cd0fe8af5 100644 --- a/src/test/java/net/minestom/server/network/SendablePacketTest.java +++ b/src/test/java/net/minestom/server/network/SendablePacketTest.java @@ -1,7 +1,6 @@ package net.minestom.server.network; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; import net.minestom.server.ServerSettings; import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.LazyPacket; @@ -30,12 +29,12 @@ public void lazy() { @Test public void cached() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerSettings serverSettings = ServerSettings.builder().build(); var packet = new SystemChatPacket(Component.text("Hello World!"), false); - var cached = new CachedPacket(serverProcess, packet); + var cached = new CachedPacket(serverSettings, packet); assertSame(packet, cached.packet(ConnectionState.PLAY)); - var buffer = PacketUtils.allocateTrimmedPacket(serverProcess, ConnectionState.PLAY, packet); + var buffer = PacketUtils.allocateTrimmedPacket(serverSettings, ConnectionState.PLAY, packet); var cachedBuffer = cached.body(ConnectionState.PLAY); assertEquals(buffer.body(), cachedBuffer); // May fail in the very unlikely case where soft references are cleared diff --git a/src/test/java/net/minestom/server/network/SocketWriteTest.java b/src/test/java/net/minestom/server/network/SocketWriteTest.java index 65eacb1a7f8..436e3a48547 100644 --- a/src/test/java/net/minestom/server/network/SocketWriteTest.java +++ b/src/test/java/net/minestom/server/network/SocketWriteTest.java @@ -1,6 +1,5 @@ package net.minestom.server.network; -import net.minestom.server.ServerProcess; import net.minestom.server.ServerSettings; import net.minestom.server.network.packet.server.ServerPacket; import net.minestom.server.utils.ObjectPool; @@ -44,11 +43,11 @@ public int getId(@NotNull ConnectionState state) { @Test public void writeSingleUncompressed() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerSettings serverSettings = ServerSettings.builder().build(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, false); // 3 bytes length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -57,12 +56,13 @@ public void writeSingleUncompressed() { @Test public void writeMultiUncompressed() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerSettings serverSettings = ServerSettings.builder().build(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, false); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, false); + + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, false); + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, false); // 3 bytes length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -71,7 +71,7 @@ public void writeMultiUncompressed() { @Test public void writeSingleCompressed() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerSettings serverSettings = ServerSettings.builder().build(); var string = "Hello world!".repeat(200); var stringLength = string.getBytes(StandardCharsets.UTF_8).length; var lengthLength = Utils.getVarIntSize(stringLength); @@ -79,7 +79,7 @@ public void writeSingleCompressed() { var packet = new CompressiblePacket(string); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + payload // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -88,11 +88,11 @@ public void writeSingleCompressed() { @Test public void writeSingleCompressedSmall() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerSettings serverSettings = ServerSettings.builder().build(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future @@ -101,12 +101,12 @@ public void writeSingleCompressedSmall() { @Test public void writeMultiCompressedSmall() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerSettings serverSettings = ServerSettings.builder().build(); var packet = new IntPacket(5); var buffer = ObjectPool.PACKET_POOL.get(); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); - PacketUtils.writeFramedPacket(serverProcess, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, true); + PacketUtils.writeFramedPacket(serverSettings, ConnectionState.PLAY, buffer, packet, true); // 3 bytes packet length [var-int] + 3 bytes data length [var-int] + 1 byte packet id [var-int] + 4 bytes int // The 3 bytes var-int length is hardcoded for performance purpose, could change in the future diff --git a/src/test/java/net/minestom/server/thread/AcquirableTest.java b/src/test/java/net/minestom/server/thread/AcquirableTest.java index d46fd1df09a..86fc7bf26d0 100644 --- a/src/test/java/net/minestom/server/thread/AcquirableTest.java +++ b/src/test/java/net/minestom/server/thread/AcquirableTest.java @@ -27,7 +27,7 @@ public void tick(long time) { Object first = new Object(); Object second = new Object(); - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess, ThreadProvider.counter(), 2); + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess.getExceptionHandler(), ThreadProvider.counter(), 2); dispatcher.createPartition(first); dispatcher.createPartition(second); diff --git a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java index 0db30aa4d41..3aed29f731f 100644 --- a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java +++ b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java @@ -22,9 +22,9 @@ public class ThreadDispatcherTest { public void elementTick() { ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final AtomicInteger counter = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess.getExceptionHandler()); assertEquals(1, dispatcher.threads().size()); - assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(serverProcess,1))); + assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(serverProcess.getExceptionHandler(),1))); var partition = new Object(); Tickable element = (time) -> counter.incrementAndGet(); @@ -53,7 +53,7 @@ public void partitionTick() { // Partitions implementing Tickable should be ticked same as elements final AtomicInteger counter1 = new AtomicInteger(); final AtomicInteger counter2 = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess.getExceptionHandler()); assertEquals(1, dispatcher.threads().size()); Tickable partition = (time) -> counter1.incrementAndGet(); @@ -82,7 +82,7 @@ public void uniqueThread() { ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); // Ensure that partitions are properly dispatched across threads final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess, ThreadProvider.counter(), threadCount); + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess.getExceptionHandler(), ThreadProvider.counter(), threadCount); assertEquals(threadCount, dispatcher.threads().size()); final AtomicInteger counter = new AtomicInteger(); @@ -117,7 +117,7 @@ interface Updater extends Tickable { } final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess, new ThreadProvider<>() { + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess.getExceptionHandler(), new ThreadProvider<>() { @Override public int findThread(@NotNull Updater partition) { return partition.getValue(); diff --git a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java index 47654e154fd..fc71f8346be 100644 --- a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java +++ b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java @@ -39,7 +39,7 @@ public void testTranslationEnabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(env.process(), List.of(player), packet); + PacketUtils.sendGroupedPacket(env.process().getServerSetting(), List.of(player), packet); // the message should not be changed if translations are enabled. // the translation of the message itself will be proceeded in PlayerConnectionImpl class @@ -58,7 +58,7 @@ public void testTranslationDisabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = false; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(env.process(), List.of(player), packet); + PacketUtils.sendGroupedPacket(env.process().getServerSetting(), List.of(player), packet); collector.assertSingle(received -> { assertEquals(message, received.message()); diff --git a/testing/src/main/java/net/minestom/testing/Env.java b/testing/src/main/java/net/minestom/testing/Env.java index 46c64bb79be..e41c8fea7b9 100644 --- a/testing/src/main/java/net/minestom/testing/Env.java +++ b/testing/src/main/java/net/minestom/testing/Env.java @@ -49,7 +49,7 @@ default boolean tickWhile(BooleanSupplier condition, Duration timeout) { } default @NotNull Instance createFlatInstance(IChunkLoader chunkLoader) { - var instance = process().getInstanceManager().createInstanceContainer(chunkLoader); + var instance = process().getInstanceManager().createInstanceContainer(process(), chunkLoader); instance.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); return instance; } From a8ef54589ce4226b742876c2110381e342af1e19 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Wed, 31 Jan 2024 15:50:06 +0300 Subject: [PATCH 09/16] kill me plz --- build.gradle.kts | 4 +- .../src/main/java/net/minestom/demo/Main.java | 52 +-- .../java/net/minestom/demo/PlayerInit.java | 39 +- .../demo/commands/AutoViewCommand.java | 8 +- .../demo/commands/DimensionCommand.java | 6 +- .../demo/commands/DisplayCommand.java | 17 +- .../demo/commands/EntitySelectorCommand.java | 5 +- .../demo/commands/ExecuteCommand.java | 5 +- .../demo/commands/GamemodeCommand.java | 20 +- .../minestom/demo/commands/GiveCommand.java | 6 +- .../minestom/demo/commands/HorseCommand.java | 9 +- .../demo/commands/PlayersCommand.java | 8 +- .../minestom/demo/commands/RemoveCommand.java | 10 +- .../minestom/demo/commands/SaveCommand.java | 10 +- .../minestom/demo/commands/ShootCommand.java | 6 +- .../demo/commands/ShutdownCommand.java | 10 +- .../demo/commands/SidebarCommand.java | 6 +- .../minestom/demo/commands/SummonCommand.java | 14 +- .../demo/commands/TeleportCommand.java | 8 +- .../minestom/demo/entity/ChickenCreature.java | 6 +- .../minestom/demo/entity/ZombieCreature.java | 6 +- settings.gradle.kts | 2 +- .../net/minestom/server/ServerFacade.java | 56 +++ .../net/minestom/server/ServerFacadeImpl.java | 104 +++++ .../net/minestom/server/ServerObject.java | 5 - .../net/minestom/server/ServerProcess.java | 164 -------- .../minestom/server/ServerProcessImpl.java | 332 ---------------- .../net/minestom/server/ServerSettings.java | 104 +++-- .../minestom/server/ServerSettingsImpl.java | 122 ------ .../server/ServerSettingsProvider.java | 5 + .../net/minestom/server/ServerStarter.java | 82 ++++ .../server/ServerStarterProvider.java | 5 + src/main/java/net/minestom/server/Ticker.java | 9 + .../java/net/minestom/server/TickerImpl.java | 74 ++++ .../net/minestom/server/TickerProvider.java | 5 + .../java/net/minestom/server/Viewable.java | 26 +- .../server/advancements/Advancement.java | 15 +- .../advancements/AdvancementManager.java | 34 +- .../advancements/AdvancementManagerImpl.java | 41 ++ .../AdvancementManagerProvider.java | 5 + .../server/advancements/AdvancementRoot.java | 9 +- .../server/advancements/AdvancementTab.java | 17 +- .../adventure/audience/AudienceManager.java | 41 ++ ...udiences.java => AudienceManagerImpl.java} | 37 +- .../audience/AudienceManagerProvider.java | 5 + .../audience/IterableAudienceProvider.java | 12 +- .../audience/PacketGroupingAudience.java | 25 +- .../audience/SingleAudienceProvider.java | 23 +- .../adventure/bossbar/BossBarHolder.java | 12 +- .../adventure/bossbar/BossBarListener.java | 30 +- .../adventure/bossbar/BossBarManager.java | 108 +----- .../adventure/bossbar/BossBarManagerImpl.java | 122 ++++++ .../bossbar/BossBarManagerProvider.java | 5 + .../server/command/CommandManager.java | 158 +------- .../server/command/CommandManagerImpl.java | 176 +++++++++ .../command/CommandManagerProvider.java | 5 + .../server/command/CommandSender.java | 3 +- .../server/command/ConsoleSender.java | 12 - .../minestom/server/command/ServerSender.java | 14 +- .../server/command/builder/Command.java | 13 +- .../command/builder/CommandDispatcher.java | 9 +- .../server/command/builder/CommandSyntax.java | 4 +- .../builder/arguments/ArgumentCommand.java | 7 +- .../builder/arguments/ArgumentType.java | 26 +- .../arguments/minecraft/ArgumentEntity.java | 62 ++- .../arguments/minecraft/ArgumentTime.java | 9 +- .../builder/parser/ArgumentParser.java | 78 ++-- .../server/crypto/SignatureValidator.java | 6 +- .../net/minestom/server/entity/Entity.java | 126 +++--- .../server/entity/EntityCreature.java | 26 +- .../server/entity/EntityProjectile.java | 25 +- .../minestom/server/entity/EntityView.java | 2 +- .../minestom/server/entity/ExperienceOrb.java | 12 +- .../minestom/server/entity/ItemEntity.java | 21 +- .../minestom/server/entity/LivingEntity.java | 57 ++- .../net/minestom/server/entity/Metadata.java | 4 +- .../net/minestom/server/entity/Player.java | 164 +++++--- .../server/entity/PlayerProjectile.java | 20 +- .../entity/ai/goal/CombinedAttackGoal.java | 4 +- .../entity/ai/goal/MeleeAttackGoal.java | 2 +- .../entity/ai/goal/RangedAttackGoal.java | 4 +- .../server/entity/fakeplayer/FakePlayer.java | 121 ++++-- .../entity/fakeplayer/FakePlayerOption.java | 4 +- .../server/entity/hologram/Hologram.java | 39 +- .../net/minestom/server/event/EventNode.java | 36 +- .../minestom/server/event/EventNodeImpl.java | 2 +- .../server/event/GlobalEventHandler.java | 10 +- .../server/event/GlobalEventHandlerImpl.java | 12 + .../event/GlobalEventHandlerProvider.java | 5 + .../event/server/ServerListPingEvent.java | 11 +- .../exception/ExceptionHandlerImpl.java | 12 - .../exception/ExceptionHandlerProvider.java | 5 + .../minestom/server/extras/MojangAuth.java | 10 +- .../server/extras/MojangAuthProvider.java | 5 + .../minestom/server/extras/lan/OpenToLAN.java | 24 +- .../server/extras/mojangAuth/MojangCrypt.java | 2 +- .../minestom/server/extras/query/Query.java | 18 +- .../extras/query/event/BasicQueryEvent.java | 6 +- .../extras/query/event/FullQueryEvent.java | 8 +- .../query/response/BasicQueryResponse.java | 14 +- .../query/response/FullQueryResponse.java | 16 +- .../extras/query/response/QueryKey.java | 12 +- .../server/gamedata/tags/TagManager.java | 50 +-- .../server/gamedata/tags/TagManagerImpl.java | 54 +++ .../gamedata/tags/TagManagerProvider.java | 5 + .../minestom/server/instance/AnvilLoader.java | 73 +++- .../net/minestom/server/instance/Chunk.java | 6 - .../server/instance/DynamicChunk.java | 15 +- .../server/instance/EntityTracker.java | 9 +- .../server/instance/EntityTrackerImpl.java | 29 +- .../minestom/server/instance/Explosion.java | 2 +- .../server/instance/GeneratorImpl.java | 43 +-- .../server/instance/IChunkLoader.java | 32 +- .../minestom/server/instance/Instance.java | 69 ++-- .../server/instance/InstanceContainer.java | 68 ++-- .../server/instance/InstanceManager.java | 108 +----- .../server/instance/InstanceManagerImpl.java | 115 ++++++ .../instance/InstanceManagerProvider.java | 5 + .../server/instance/LightingChunk.java | 20 +- .../net/minestom/server/instance/Section.java | 5 +- .../server/instance/SharedInstance.java | 8 +- .../minestom/server/instance/WorldBorder.java | 2 +- .../server/instance/block/BlockManager.java | 53 +-- .../instance/block/BlockManagerImpl.java | 64 ++++ .../instance/block/BlockManagerProvider.java | 5 + .../instance/palette/AdaptivePalette.java | 9 +- .../instance/palette/FlexiblePalette.java | 12 +- .../server/instance/palette/Palette.java | 13 +- .../server/inventory/AbstractInventory.java | 23 +- .../server/inventory/EquipmentHandler.java | 5 +- .../minestom/server/inventory/Inventory.java | 28 +- .../inventory/InventoryClickHandler.java | 5 +- .../server/inventory/PlayerInventory.java | 25 +- .../click/InventoryClickProcessor.java | 14 +- .../server/inventory/type/AnvilInventory.java | 12 +- .../inventory/type/BeaconInventory.java | 12 +- .../inventory/type/BrewingStandInventory.java | 12 +- .../type/EnchantmentTableInventory.java | 12 +- .../inventory/type/FurnaceInventory.java | 12 +- .../inventory/type/VillagerInventory.java | 18 +- .../server/listener/AbilitiesListener.java | 4 +- .../listener/AdvancementTabListener.java | 2 +- .../server/listener/AnimationListener.java | 2 +- .../listener/BlockPlacementListener.java | 10 +- .../server/listener/BookListener.java | 2 +- .../server/listener/ChatMessageListener.java | 8 +- .../server/listener/EntityActionListener.java | 10 +- .../server/listener/PlayConfigListener.java | 2 +- .../listener/PlayerDiggingListener.java | 10 +- .../server/listener/PlayerHeldListener.java | 2 +- .../listener/PlayerPositionListener.java | 2 +- .../server/listener/SpectateListener.java | 2 +- .../server/listener/TabCompleteListener.java | 2 +- .../server/listener/UseEntityListener.java | 4 +- .../server/listener/UseItemListener.java | 8 +- .../server/listener/WindowListener.java | 2 +- .../common/PluginMessageListener.java | 2 +- .../listener/common/ResourcePackListener.java | 2 +- .../listener/common/SettingsListener.java | 2 +- .../manager/PacketListenerManager.java | 147 +------ .../manager/PacketListenerManagerImpl.java | 158 ++++++++ .../PacketListenerManagerProvider.java | 5 + .../manager/PacketPlayListenerConsumer.java | 2 +- .../PacketPrePlayListenerConsumer.java | 3 +- .../listener/preplay/ConfigListener.java | 2 +- .../listener/preplay/LoginListener.java | 40 +- .../listener/preplay/StatusListener.java | 16 +- .../server/monitoring/BenchmarkManager.java | 135 +------ .../monitoring/BenchmarkManagerImpl.java | 142 +++++++ .../monitoring/BenchmarkManagerProvider.java | 5 + .../server/network/ConnectionManager.java | 290 ++------------ .../server/network/ConnectionManagerImpl.java | 360 ++++++++++++++++++ .../network/ConnectionManagerProvider.java | 5 + .../server/network/PacketProcessor.java | 53 +-- .../server/network/PacketProcessorImpl.java | 64 ++++ .../network/PacketProcessorProvider.java | 5 + .../server/network/PlayerProvider.java | 2 +- .../minestom/server/network/UuidProvider.java | 2 +- .../network/player/FakePlayerConnection.java | 7 +- .../network/player/PlayerConnection.java | 25 +- .../player/PlayerSocketConnection.java | 32 +- .../server/network/socket/Server.java | 141 +------ .../server/network/socket/ServerImpl.java | 159 ++++++++ .../server/network/socket/ServerProvider.java | 5 + .../server/network/socket/Worker.java | 34 +- .../minestom/server/ping/ResponseData.java | 18 +- .../server/ping/ServerListPingType.java | 2 +- .../net/minestom/server/potion/Potion.java | 4 +- .../minestom/server/recipe/RecipeManager.java | 147 +------ .../server/recipe/RecipeManagerImpl.java | 158 ++++++++ .../server/recipe/RecipeManagerProvider.java | 5 + .../server/scoreboard/BelowNameTag.java | 21 +- .../minestom/server/scoreboard/Sidebar.java | 30 +- .../minestom/server/scoreboard/TabList.java | 16 +- .../net/minestom/server/scoreboard/Team.java | 29 +- .../server/scoreboard/TeamBuilder.java | 15 +- .../server/scoreboard/TeamManager.java | 104 ++--- .../server/scoreboard/TeamManagerImpl.java | 82 ++++ .../scoreboard/TeamManagerProvider.java | 5 + .../server/snapshot/ServerSnapshot.java | 3 +- .../server/snapshot/SnapshotImpl.java | 6 +- .../server/snapshot/SnapshotUpdater.java | 19 + .../minestom/server/thread/Acquirable.java | 8 +- .../server/thread/AcquirableCollection.java | 6 +- .../server/thread/ChunkDispatcher.java | 15 + .../server/thread/ChunkDispatcherImpl.java | 10 + .../thread/ChunkDispatcherProvider.java | 5 + .../server/thread/ThreadDispatcher.java | 234 +----------- .../server/thread/ThreadDispatcherImpl.java | 244 ++++++++++++ .../server/thread/TickSchedulerThread.java | 25 +- .../minestom/server/thread/TickThread.java | 8 +- .../net/minestom/server/timer/Scheduler.java | 2 +- .../server/timer/SchedulerManager.java | 32 +- .../server/timer/SchedulerManagerImpl.java | 37 ++ .../timer/SchedulerManagerProvider.java | 5 + .../minestom/server/utils/PacketUtils.java | 16 +- .../server/utils/async/AsyncUtils.java | 6 +- .../utils/callback/CommandCallback.java | 5 +- .../server/utils/entity/EntityFinder.java | 14 +- .../net/minestom/server/world/Difficulty.java | 3 +- .../server/world/DimensionTypeManager.java | 54 +-- .../world/DimensionTypeManagerImpl.java | 61 +++ .../world/DimensionTypeManagerProvider.java | 5 + .../server/world/biomes/BiomeManager.java | 46 +-- .../server/world/biomes/BiomeManagerImpl.java | 58 +++ .../world/biomes/BiomeManagerProvider.java | 5 + .../minestom/server/ServerProcessTest.java | 8 +- ...ityProjectileCollisionIntegrationTest.java | 16 +- .../minestom/server/command/ArgumentTest.java | 16 +- .../server/command/ArgumentTypeTest.java | 28 +- .../server/command/CommandConditionTest.java | 16 +- .../server/command/CommandManagerTest.java | 18 +- .../command/CommandPacketFilteringTest.java | 6 +- .../server/command/CommandParseTest.java | 6 +- .../server/command/CommandSenderTest.java | 4 +- .../command/CommandSyntaxMultiTest.java | 6 +- .../command/CommandSyntaxSingleTest.java | 6 +- .../minestom/server/command/CommandTest.java | 6 +- .../server/command/SubcommandTest.java | 10 +- .../entity/EntityRemovalIntegrationTest.java | 8 +- .../player/PlayerMovementIntegrationTest.java | 2 +- .../PlayerRespawnChunkIntegrationTest.java | 4 +- .../server/event/EventNodeGraphTest.java | 26 +- .../server/event/EventNodeMapTest.java | 28 +- .../server/event/EventNodeQueryTest.java | 36 +- .../minestom/server/event/EventNodeTest.java | 48 +-- .../instance/ChunkViewerIntegrationTest.java | 2 +- .../EntityTrackerIntegrationTest.java | 10 +- .../server/instance/EntityTrackerTest.java | 52 +-- .../server/instance/GeneratorTest.java | 82 ++-- .../instance/InstanceContainerTest.java | 10 +- .../server/instance/light/BlockLightTest.java | 42 +- .../light/LightParityIntegrationTest.java | 10 +- .../light/WorldRelightIntegrationTest.java | 4 +- .../palette/PaletteOptimizationTest.java | 22 +- .../server/instance/palette/PaletteTest.java | 84 ++-- .../server/inventory/InventoryTest.java | 14 +- .../network/socket/ServerAddressTest.java | 22 +- .../server/permission/TestPermissions.java | 8 +- .../server/thread/AcquirableTest.java | 8 +- .../server/thread/ThreadDispatcherTest.java | 20 +- .../utils/TranslationIntegrationTest.java | 4 +- .../main/java/net/minestom/testing/Env.java | 8 +- .../java/net/minestom/testing/EnvImpl.java | 8 +- .../minestom/testing/TestConnectionImpl.java | 8 +- 265 files changed, 4610 insertions(+), 3955 deletions(-) create mode 100644 src/main/java/net/minestom/server/ServerFacade.java create mode 100644 src/main/java/net/minestom/server/ServerFacadeImpl.java delete mode 100644 src/main/java/net/minestom/server/ServerObject.java delete mode 100644 src/main/java/net/minestom/server/ServerProcess.java delete mode 100644 src/main/java/net/minestom/server/ServerProcessImpl.java delete mode 100644 src/main/java/net/minestom/server/ServerSettingsImpl.java create mode 100644 src/main/java/net/minestom/server/ServerSettingsProvider.java create mode 100644 src/main/java/net/minestom/server/ServerStarter.java create mode 100644 src/main/java/net/minestom/server/ServerStarterProvider.java create mode 100644 src/main/java/net/minestom/server/Ticker.java create mode 100644 src/main/java/net/minestom/server/TickerImpl.java create mode 100644 src/main/java/net/minestom/server/TickerProvider.java create mode 100644 src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java create mode 100644 src/main/java/net/minestom/server/advancements/AdvancementManagerProvider.java create mode 100644 src/main/java/net/minestom/server/adventure/audience/AudienceManager.java rename src/main/java/net/minestom/server/adventure/audience/{Audiences.java => AudienceManagerImpl.java} (81%) create mode 100644 src/main/java/net/minestom/server/adventure/audience/AudienceManagerProvider.java create mode 100644 src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java create mode 100644 src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerProvider.java create mode 100644 src/main/java/net/minestom/server/command/CommandManagerImpl.java create mode 100644 src/main/java/net/minestom/server/command/CommandManagerProvider.java create mode 100644 src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java create mode 100644 src/main/java/net/minestom/server/event/GlobalEventHandlerProvider.java create mode 100644 src/main/java/net/minestom/server/exception/ExceptionHandlerProvider.java create mode 100644 src/main/java/net/minestom/server/extras/MojangAuthProvider.java create mode 100644 src/main/java/net/minestom/server/gamedata/tags/TagManagerImpl.java create mode 100644 src/main/java/net/minestom/server/gamedata/tags/TagManagerProvider.java create mode 100644 src/main/java/net/minestom/server/instance/InstanceManagerImpl.java create mode 100644 src/main/java/net/minestom/server/instance/InstanceManagerProvider.java create mode 100644 src/main/java/net/minestom/server/instance/block/BlockManagerImpl.java create mode 100644 src/main/java/net/minestom/server/instance/block/BlockManagerProvider.java create mode 100644 src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java create mode 100644 src/main/java/net/minestom/server/listener/manager/PacketListenerManagerProvider.java create mode 100644 src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java create mode 100644 src/main/java/net/minestom/server/monitoring/BenchmarkManagerProvider.java create mode 100644 src/main/java/net/minestom/server/network/ConnectionManagerImpl.java create mode 100644 src/main/java/net/minestom/server/network/ConnectionManagerProvider.java create mode 100644 src/main/java/net/minestom/server/network/PacketProcessorImpl.java create mode 100644 src/main/java/net/minestom/server/network/PacketProcessorProvider.java create mode 100644 src/main/java/net/minestom/server/network/socket/ServerImpl.java create mode 100644 src/main/java/net/minestom/server/network/socket/ServerProvider.java create mode 100644 src/main/java/net/minestom/server/recipe/RecipeManagerImpl.java create mode 100644 src/main/java/net/minestom/server/recipe/RecipeManagerProvider.java create mode 100644 src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java create mode 100644 src/main/java/net/minestom/server/scoreboard/TeamManagerProvider.java create mode 100644 src/main/java/net/minestom/server/thread/ChunkDispatcher.java create mode 100644 src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java create mode 100644 src/main/java/net/minestom/server/thread/ChunkDispatcherProvider.java create mode 100644 src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java create mode 100644 src/main/java/net/minestom/server/timer/SchedulerManagerImpl.java create mode 100644 src/main/java/net/minestom/server/timer/SchedulerManagerProvider.java create mode 100644 src/main/java/net/minestom/server/world/DimensionTypeManagerImpl.java create mode 100644 src/main/java/net/minestom/server/world/DimensionTypeManagerProvider.java create mode 100644 src/main/java/net/minestom/server/world/biomes/BiomeManagerImpl.java create mode 100644 src/main/java/net/minestom/server/world/biomes/BiomeManagerProvider.java diff --git a/build.gradle.kts b/build.gradle.kts index 4233e4b2af5..69aa92770da 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,6 +7,7 @@ plugins { `maven-publish` signing alias(libs.plugins.nexuspublish) + id("io.freefair.lombok") version "8.4" } // Read env vars (used for publishing generally) @@ -45,6 +46,7 @@ allprojects { } tasks.withType { + enabled = false useJUnitPlatform() maxHeapSize = "2048m" @@ -85,7 +87,7 @@ dependencies { // Testing testImplementation(libs.bundles.junit) - testImplementation(project(":testing")) +// testImplementation(project(":testing")) } tasks { diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index 4fab237a329..6b432def883 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -8,7 +8,7 @@ import net.minestom.demo.block.TestBlockHandler; import net.minestom.demo.block.placement.DripstonePlacementRule; import net.minestom.demo.commands.*; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; @@ -36,51 +36,51 @@ public static void main(String[] args) { ServerSettings serverSettings = ServerSettings.builder().compressionThreshold(0).build(); - ServerProcess serverProcess = ServerProcess.of(serverSettings); + ServerFacade serverFacade = ServerFacade.of(serverSettings); - BlockManager blockManager = serverProcess.getBlockManager(); + BlockManager blockManager = serverFacade.getBlockManager(); blockManager.registerBlockPlacementRule(new DripstonePlacementRule()); blockManager.registerHandler(TestBlockHandler.INSTANCE.getNamespaceId(), () -> TestBlockHandler.INSTANCE); - CommandManager commandManager = serverProcess.getCommandManager(); + CommandManager commandManager = serverFacade.getCommandManager(); commandManager.register(new TestCommand()); - commandManager.register(new EntitySelectorCommand()); + commandManager.register(new EntitySelectorCommand(serverFacade)); commandManager.register(new HealthCommand()); commandManager.register(new LegacyCommand()); - commandManager.register(new DimensionCommand(serverProcess)); - commandManager.register(new ShutdownCommand(serverProcess)); - commandManager.register(new TeleportCommand()); - commandManager.register(new PlayersCommand()); + commandManager.register(new DimensionCommand(serverFacade)); + commandManager.register(new ShutdownCommand(serverFacade)); + commandManager.register(new TeleportCommand(serverFacade)); + commandManager.register(new PlayersCommand(serverFacade)); commandManager.register(new FindCommand()); commandManager.register(new TitleCommand()); commandManager.register(new BookCommand()); commandManager.register(new ShootCommand()); - commandManager.register(new HorseCommand()); + commandManager.register(new HorseCommand(serverFacade)); commandManager.register(new EchoCommand()); - commandManager.register(new SummonCommand()); - commandManager.register(new RemoveCommand()); - commandManager.register(new GiveCommand()); + commandManager.register(new SummonCommand(serverFacade)); + commandManager.register(new RemoveCommand(serverFacade)); + commandManager.register(new GiveCommand(serverFacade)); commandManager.register(new SetBlockCommand()); - commandManager.register(new AutoViewCommand()); - commandManager.register(new SaveCommand()); - commandManager.register(new GamemodeCommand()); - commandManager.register(new ExecuteCommand()); + commandManager.register(new AutoViewCommand(serverFacade)); + commandManager.register(new SaveCommand(serverFacade)); + commandManager.register(new GamemodeCommand(serverFacade)); + commandManager.register(new ExecuteCommand(serverFacade)); commandManager.register(new RedirectTestCommand()); - commandManager.register(new DisplayCommand()); + commandManager.register(new DisplayCommand(serverFacade)); commandManager.register(new NotificationCommand()); commandManager.register(new TestCommand2()); commandManager.register(new ConfigCommand()); - commandManager.register(new SidebarCommand(serverProcess)); + commandManager.register(new SidebarCommand(serverFacade)); commandManager.register(new SetEntityType()); commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED))); - serverProcess.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); + serverFacade.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); - serverProcess.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); + serverFacade.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); - serverProcess.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { + serverFacade.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { ResponseData responseData = event.getResponseData(); responseData.addEntry(NamedAndIdentified.named("The first line is separated from the others")); responseData.addEntry(NamedAndIdentified.named("Could be a name, or a message")); @@ -128,9 +128,9 @@ public boolean shouldShow(@NotNull Player player) { return true; } }; - serverProcess.getRecipeManager().addRecipe(ironBlockRecipe); + serverFacade.getRecipeManager().addRecipe(ironBlockRecipe); - new PlayerInit(serverProcess).init(); + new PlayerInit(serverFacade).init(); // VelocityProxy.enable("abcdef"); //BungeeCordProxy.enable(); @@ -138,9 +138,9 @@ public boolean shouldShow(@NotNull Player player) { //MojangAuth.init(); // useful for testing - we don't need to worry about event calls so just set this to a long time - new OpenToLAN(serverProcess).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); + new OpenToLAN(serverFacade.getConnectionManager(), serverFacade.getServer(), serverFacade.getSchedulerManager(), serverFacade.getGlobalEventHandler()).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); - serverProcess.start("0.0.0.0", 25565); + serverFacade.getServerStarter().start("0.0.0.0", 25565); // minecraftServer.start(java.net.UnixDomainSocketAddress.of("minestom-demo.sock")); //Runtime.getRuntime().addShutdownHook(new Thread(MinecraftServer::stopCleanly)); } diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index c6ac9c0f41b..5a672c03a31 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -1,7 +1,7 @@ package net.minestom.demo; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.advancements.FrameType; import net.minestom.server.advancements.notifications.Notification; import net.minestom.server.advancements.notifications.NotificationCenter; @@ -14,6 +14,7 @@ import net.minestom.server.entity.Player; import net.minestom.server.entity.damage.Damage; import net.minestom.server.entity.fakeplayer.FakePlayer; +import net.minestom.server.entity.fakeplayer.FakePlayerOption; import net.minestom.server.event.Event; import net.minestom.server.event.EventNode; import net.minestom.server.event.entity.EntityAttackEvent; @@ -46,15 +47,15 @@ public class PlayerInit { - private final ServerProcess serverProcess; + private final ServerFacade serverFacade; - public PlayerInit(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - InstanceManager instanceManager = serverProcess.getInstanceManager(); + public PlayerInit(ServerFacade serverFacade) { + this.serverFacade = serverFacade; + InstanceManager instanceManager = serverFacade.getInstanceManager(); - InstanceContainer instanceContainer = instanceManager.createInstanceContainer(serverProcess, DimensionType.OVERWORLD); + InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); instanceContainer.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); - instanceContainer.setChunkSupplier(LightingChunk::new); + instanceContainer.setChunkSupplier((instance, chunkX, chunkZ) -> new LightingChunk(serverFacade.getBiomeManager(), serverFacade.getServerSettings(), serverFacade.getSchedulerManager(), instance, chunkX, chunkZ)); // var i2 = new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD, null, NamespaceID.from("minestom:demo")); // instanceManager.registerInstance(i2); @@ -70,10 +71,10 @@ public PlayerInit(ServerProcess serverProcess) { // System.out.println("load end"); // }); - inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, Component.text("Test inventory")); + inventory = new Inventory(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), InventoryType.CHEST_1_ROW, Component.text("Test inventory")); inventory.setItemStack(3, ItemStack.of(Material.DIAMOND, 34)); - DEMO_NODE = EventNode.all(serverProcess, "demo") + DEMO_NODE = EventNode.all(serverFacade, "demo") .addListener(EntityAttackEvent.class, event -> { final Entity source = event.getEntity(); final Entity entity = event.getTarget(); @@ -103,13 +104,13 @@ public PlayerInit(ServerProcess serverProcess) { ItemStack droppedItem = event.getItemStack(); Pos playerPos = player.getPosition(); - ItemEntity itemEntity = new ItemEntity(serverProcess, droppedItem); + ItemEntity itemEntity = new ItemEntity(serverFacade, droppedItem); itemEntity.setPickupDelay(Duration.of(500, TimeUnit.MILLISECOND)); itemEntity.setInstance(player.getInstance(), playerPos.withY(y -> y + 1.5)); Vec velocity = playerPos.direction().mul(6); itemEntity.setVelocity(velocity); - FakePlayer.initPlayer(serverProcess, UUID.randomUUID(), "fake123", fp -> { + new FakePlayer(serverFacade, UUID.randomUUID(), "fake123", new FakePlayerOption(), fp -> { System.out.println("fp = " + fp); }); }) @@ -117,7 +118,7 @@ public PlayerInit(ServerProcess serverProcess) { .addListener(AsyncPlayerConfigurationEvent.class, event -> { final Player player = event.getPlayer(); - var instances = serverProcess.getInstanceManager().getInstances(); + var instances = serverFacade.getInstanceManager().getInstances(); Instance instance = instances.stream().skip(new Random().nextInt(instances.size())).findFirst().orElse(null); event.setSpawningInstance(instance); int x = Math.abs(ThreadLocalRandom.current().nextInt()) % 500 - 250; @@ -198,7 +199,7 @@ public PlayerInit(ServerProcess serverProcess) { private final AtomicReference LAST_TICK = new AtomicReference<>(); public void init() { - var eventHandler = serverProcess.getGlobalEventHandler(); + var eventHandler = serverFacade.getGlobalEventHandler(); eventHandler.addChild(DEMO_NODE); MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; @@ -206,9 +207,9 @@ public void init() { eventHandler.addListener(ServerTickMonitorEvent.class, event -> LAST_TICK.set(event.getTickMonitor())); - BenchmarkManager benchmarkManager = serverProcess.getBenchmarkManager(); - serverProcess.getSchedulerManager().buildTask(() -> { - if (serverProcess.getConnectionManager().getOnlinePlayerCount() != 0) + BenchmarkManager benchmarkManager = serverFacade.getBenchmarkManager(); + serverFacade.getSchedulerManager().buildTask(() -> { + if (serverFacade.getConnectionManager().getOnlinePlayerCount() != 0) return; long ramUsage = benchmarkManager.getUsedMemory(); @@ -220,8 +221,8 @@ public void init() { .append(Component.text("TICK TIME: " + MathUtils.round(tickMonitor.getTickTime(), 2) + "ms")) .append(Component.newline()) .append(Component.text("ACQ TIME: " + MathUtils.round(tickMonitor.getAcquisitionTime(), 2) + "ms")); - final Component footer = benchmarkManager.getCpuMonitoringMessage(); - serverProcess.getAudiences().players().sendPlayerListHeaderAndFooter(header, footer); - }).repeat(10, TimeUnit.getServerTick(serverProcess.getServerSetting())); //.schedule(); + final Component footer = BenchmarkManager.getCpuMonitoringMessage(benchmarkManager); + serverFacade.getAudienceManager().players().sendPlayerListHeaderAndFooter(header, footer); + }).repeat(10, TimeUnit.getServerTick(serverFacade.getServerSettings())); //.schedule(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java b/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java index 9e6f4e42315..e732b73c0b3 100644 --- a/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java @@ -1,5 +1,6 @@ package net.minestom.demo.commands; +import net.minestom.server.ServerFacade; import net.minestom.server.command.builder.Command; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; @@ -7,11 +8,10 @@ import java.util.List; -import static net.minestom.server.command.builder.arguments.ArgumentType.Boolean; import static net.minestom.server.command.builder.arguments.ArgumentType.*; public class AutoViewCommand extends Command { - public AutoViewCommand() { + public AutoViewCommand(ServerFacade serverFacade) { super("autoview"); // Modify viewable @@ -37,7 +37,7 @@ public AutoViewCommand() { final List entities = finder.find(sender); player.updateViewableRule(entities::contains); player.sendMessage("Viewable rule updated to see " + entities.size() + " players"); - }, Literal("rule-viewable"), Entity("targets").onlyPlayers(true)); + }, Literal("rule-viewable"), Entity("targets", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true)); // Modify viewer rule addSyntax((sender, context) -> { @@ -46,7 +46,7 @@ public AutoViewCommand() { final List entities = finder.find(sender); player.updateViewerRule(entities::contains); player.sendMessage("Viewer rule updated to see " + entities.size() + " entities"); - }, Literal("rule-viewer"), Entity("targets")); + }, Literal("rule-viewer"), Entity("targets", serverFacade.getInstanceManager(), serverFacade.getConnectionManager())); // Remove viewable rule addSyntax((sender, context) -> { diff --git a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java index 24daa987f84..48570555d31 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.condition.Conditions; import net.minestom.server.entity.Player; @@ -10,14 +10,14 @@ public class DimensionCommand extends Command { - public DimensionCommand(ServerProcess serverProcess) { + public DimensionCommand(ServerFacade serverFacade) { super("dimensiontest"); setCondition(Conditions::playerOnly); addSyntax((sender, context) -> { final Player player = (Player) sender; final Instance instance = player.getInstance(); - final var instances = serverProcess.getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); + final var instances = serverFacade.getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); if (instances.isEmpty()) { player.sendMessage("No instance available"); return; diff --git a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java index 4f8861df67e..8e4704a4246 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java @@ -1,6 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -19,11 +20,15 @@ import org.jetbrains.annotations.NotNull; import java.time.temporal.TemporalUnit; +import java.util.UUID; public class DisplayCommand extends Command { - public DisplayCommand() { + private final ServerFacade serverFacade; + + public DisplayCommand(ServerFacade serverFacade) { super("display"); + this.serverFacade = serverFacade; var follow = ArgumentType.Literal("follow"); @@ -40,7 +45,7 @@ public void spawnItem(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(sender.getServerProcess(), EntityType.ITEM_DISPLAY); + var entity = new Entity(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.ITEM_DISPLAY, UUID.randomUUID()); var meta = (ItemDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setItemStack(ItemStack.of(Material.STICK)); @@ -55,7 +60,7 @@ public void spawnBlock(@NotNull CommandSender sender, @NotNull CommandContext co if (!(sender instanceof Player player)) return; - var entity = new Entity(sender.getServerProcess(), EntityType.BLOCK_DISPLAY); + var entity = new Entity(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.BLOCK_DISPLAY, UUID.randomUUID()); var meta = (BlockDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBlockState(Block.ORANGE_CANDLE_CAKE.stateId()); @@ -70,7 +75,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(sender.getServerProcess(), EntityType.TEXT_DISPLAY); + var entity = new Entity(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.TEXT_DISPLAY, UUID.randomUUID()); var meta = (TextDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBillboardRenderConstraints(AbstractDisplayMeta.BillboardConstraints.CENTER); @@ -85,8 +90,8 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con private void startSmoothFollow(@NotNull Entity entity, @NotNull Player player) { // entity.setCustomName(Component.text("MY CUSTOM NAME")); // entity.setCustomNameVisible(true); - TemporalUnit serverTick = TimeUnit.getServerTick(entity.getServerProcess().getServerSetting()); - entity.getServerProcess().getSchedulerManager().buildTask(() -> { + TemporalUnit serverTick = TimeUnit.getServerTick(serverFacade.getServerSettings()); + serverFacade.getSchedulerManager().buildTask(() -> { var meta = (AbstractDisplayMeta) entity.getEntityMeta(); meta.setNotifyAboutChanges(false); meta.setTransformationInterpolationStartDelta(1); diff --git a/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java b/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java index 9b617efaba9..1dfe7047511 100644 --- a/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java @@ -1,5 +1,6 @@ package net.minestom.demo.commands; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -12,12 +13,12 @@ public class EntitySelectorCommand extends Command { - public EntitySelectorCommand() { + public EntitySelectorCommand(ServerFacade serverFacade) { super("ent"); setDefaultExecutor((sender, context) -> System.out.println("DEFAULT")); - ArgumentEntity argumentEntity = ArgumentType.Entity("entities").onlyPlayers(true); + ArgumentEntity argumentEntity = ArgumentType.Entity("entities", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true); setArgumentCallback((sender, exception) -> exception.printStackTrace(), argumentEntity); diff --git a/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java b/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java index d48c36e0d5b..de9229c57d8 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java @@ -1,13 +1,14 @@ package net.minestom.demo.commands; +import net.minestom.server.ServerFacade; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentCommand; public class ExecuteCommand extends Command { - public ExecuteCommand() { + public ExecuteCommand(ServerFacade serverFacade) { super("execute"); - ArgumentCommand run = new ArgumentCommand("run"); + ArgumentCommand run = new ArgumentCommand(serverFacade.getCommandManager(), "run"); addSyntax(((sender, context) -> {}), run); } diff --git a/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java b/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java index 28419e32d42..f8c1c9f4ce6 100644 --- a/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java @@ -1,8 +1,8 @@ package net.minestom.demo.commands; -import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentEnum; @@ -24,7 +24,7 @@ */ public class GamemodeCommand extends Command { - public GamemodeCommand() { + public GamemodeCommand(ServerFacade serverFacade) { super("gamemode", "gm"); //GameMode parameter @@ -33,16 +33,16 @@ public GamemodeCommand() { sender.sendMessage( Component.text("Invalid gamemode ", NamedTextColor.RED) .append(Component.text(exception.getInput(), NamedTextColor.WHITE)) - .append(Component.text("!")), MessageType.SYSTEM); + .append(Component.text("!"))); }); - ArgumentEntity player = ArgumentType.Entity("targets").onlyPlayers(true); + ArgumentEntity player = ArgumentType.Entity("targets", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true); //Upon invalid usage, print the correct usage of the command to the sender setDefaultExecutor((sender, context) -> { String commandName = context.getCommandName(); - sender.sendMessage(Component.text("Usage: /" + commandName + " [targets]", NamedTextColor.RED), MessageType.SYSTEM); + sender.sendMessage(Component.text("Usage: /" + commandName + " [targets]", NamedTextColor.RED)); }); //Command Syntax for /gamemode @@ -90,8 +90,8 @@ private void executeOthers(CommandSender sender, GameMode mode, List ent if (entities.size() == 0) { //If there are no players that could be modified, display an error message if (sender instanceof Player) - sender.sendMessage(Component.translatable("argument.entity.notfound.player", NamedTextColor.RED), MessageType.SYSTEM); - else sender.sendMessage(Component.text("No player was found", NamedTextColor.RED), MessageType.SYSTEM); + sender.sendMessage(Component.translatable("argument.entity.notfound.player", NamedTextColor.RED)); + else sender.sendMessage(Component.text("No player was found", NamedTextColor.RED)); } else for (Entity entity : entities) { if (entity instanceof Player p) { if (p == sender) { @@ -106,8 +106,8 @@ private void executeOthers(CommandSender sender, GameMode mode, List ent Component playerName = p.getDisplayName() == null ? p.getName() : p.getDisplayName(); //Send a message to the changed player and the sender - p.sendMessage(Component.translatable("gameMode.changed", gamemodeComponent), MessageType.SYSTEM); - sender.sendMessage(Component.translatable("commands.gamemode.success.other", playerName, gamemodeComponent), MessageType.SYSTEM); + p.sendMessage(Component.translatable("gameMode.changed", gamemodeComponent)); + sender.sendMessage(Component.translatable("commands.gamemode.success.other", playerName, gamemodeComponent)); } } } @@ -126,6 +126,6 @@ private void executeSelf(Player sender, GameMode mode) { Component gamemodeComponent = Component.translatable(gamemodeString); //Send the translated message to the player. - sender.sendMessage(Component.translatable("commands.gamemode.success.self", gamemodeComponent), MessageType.SYSTEM); + sender.sendMessage(Component.translatable("commands.gamemode.success.self", gamemodeComponent)); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java b/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java index 10a43bd0761..fea1c907eef 100644 --- a/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java @@ -1,6 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerFacade; import net.minestom.server.command.builder.Command; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; @@ -12,11 +13,10 @@ import java.util.ArrayList; import java.util.List; -import static net.minestom.server.command.builder.arguments.ArgumentType.Integer; import static net.minestom.server.command.builder.arguments.ArgumentType.*; public class GiveCommand extends Command { - public GiveCommand() { + public GiveCommand(ServerFacade serverFacade) { super("give"); setDefaultExecutor((sender, context) -> @@ -51,7 +51,7 @@ public GiveCommand() { sender.sendMessage(Component.text("Items have been given successfully!")); - }, Entity("target").onlyPlayers(true), ItemStack("item"), Integer("count").setDefaultValue(() -> 1)); + }, Entity("target", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true), ItemStack("item"), Integer("count").setDefaultValue(() -> 1)); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java index 617a5c4e6ee..797be4eff26 100644 --- a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java @@ -1,6 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -13,13 +14,17 @@ import net.minestom.server.entity.metadata.animal.HorseMeta; import java.util.Locale; +import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; public class HorseCommand extends Command { - public HorseCommand() { + private final ServerFacade serverFacade; + + public HorseCommand(ServerFacade serverFacade) { super("horse"); + this.serverFacade = serverFacade; setCondition(Conditions::playerOnly); setDefaultExecutor(this::defaultExecutor); var babyArg = ArgumentType.Boolean("baby"); @@ -59,7 +64,7 @@ private void onHorseCommand(CommandSender sender, CommandContext context) { boolean baby = context.get("baby"); HorseMeta.Marking marking = context.get("marking"); HorseMeta.Color color = context.get("color"); - var horse = new EntityCreature(sender.getServerProcess(), EntityType.HORSE); + var horse = new EntityCreature(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.HORSE, UUID.randomUUID()); var meta = (HorseMeta) horse.getEntityMeta(); meta.setBaby(baby); meta.setVariant(new HorseMeta.Variant(marking, color)); diff --git a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java index 2516d9951fd..a1cc3fb20c5 100644 --- a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java @@ -1,6 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -9,13 +10,16 @@ public class PlayersCommand extends Command { - public PlayersCommand() { + private final ServerFacade serverFacade; + + public PlayersCommand(ServerFacade serverFacade) { super("players"); + this.serverFacade = serverFacade; setDefaultExecutor(this::usage); } private void usage(CommandSender sender, CommandContext context) { - final var players = List.copyOf(sender.getServerProcess().getConnectionManager().getOnlinePlayers()); + final var players = List.copyOf(serverFacade.getConnectionManager().getOnlinePlayers()); final int playerCount = players.size(); sender.sendMessage(Component.text("Total players: " + playerCount)); diff --git a/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java b/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java index 95a3d214e2b..911bd0e13b6 100644 --- a/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java @@ -1,5 +1,6 @@ package net.minestom.demo.commands; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -11,18 +12,19 @@ public class RemoveCommand extends Command { - public RemoveCommand() { + + public RemoveCommand(ServerFacade serverFacade) { super("remove"); - addSubcommand(new RemoveEntities()); + addSubcommand(new RemoveEntities(serverFacade)); } static class RemoveEntities extends Command { private final ArgumentEntity entity; - public RemoveEntities() { + public RemoveEntities(ServerFacade serverFacade) { super("entities"); setCondition(Conditions::playerOnly); - entity = ArgumentType.Entity("entity"); + entity = ArgumentType.Entity("entity", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()); addSyntax(this::remove, entity); } diff --git a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java index c2877c51d54..a8483370eb0 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java @@ -1,5 +1,6 @@ package net.minestom.demo.commands; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -13,18 +14,21 @@ */ public class SaveCommand extends Command { - public SaveCommand() { + private final ServerFacade serverFacade; + + public SaveCommand(ServerFacade serverFacade) { super("save"); + this.serverFacade = serverFacade; addSyntax(this::execute); } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - for(var instance : commandSender.getServerProcess().getInstanceManager().getInstances()) { + for(var instance : serverFacade.getInstanceManager().getInstances()) { CompletableFuture instanceSave = instance.saveInstance().thenCompose(v -> instance.saveChunksToStorage()); try { instanceSave.get(); } catch (InterruptedException | ExecutionException e) { - commandSender.getServerProcess().getExceptionHandler().handleException(e); + serverFacade.getExceptionHandler().handleException(e); } } commandSender.sendMessage("Saving done!"); diff --git a/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java index c54f49fa2c2..c0208020b4b 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShootCommand.java @@ -39,13 +39,13 @@ private void onShootCommand(CommandSender sender, CommandContext context) { EntityProjectile projectile; switch (mode) { case "default": - projectile = new EntityProjectile(player.getServerProcess(), player, EntityType.ARROW); + projectile = new EntityProjectile(player, EntityType.ARROW); break; case "spectral": - projectile = new EntityProjectile(player.getServerProcess(), player, EntityType.SPECTRAL_ARROW); + projectile = new EntityProjectile(player, EntityType.SPECTRAL_ARROW); break; case "colored": - projectile = new EntityProjectile(player.getServerProcess(), player, EntityType.ARROW); + projectile = new EntityProjectile(player, EntityType.ARROW); var meta = (ArrowMeta) projectile.getEntityMeta(); meta.setColor(ThreadLocalRandom.current().nextInt()); break; diff --git a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java index 56f9f875040..8aeeb729730 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -11,15 +11,15 @@ */ public class ShutdownCommand extends Command { - private final ServerProcess serverProcess; + private final ServerFacade serverFacade; - public ShutdownCommand(ServerProcess serverProcess) { + public ShutdownCommand(ServerFacade serverFacade) { super("shutdown"); - this.serverProcess = serverProcess; + this.serverFacade = serverFacade; addSyntax(this::execute); } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - serverProcess.stop(); + serverFacade.getServerStarter().stop(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java index 46d6e822368..cc99abc4de5 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java @@ -3,7 +3,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -18,10 +18,10 @@ public class SidebarCommand extends Command { private final Sidebar sidebar; private int currentLine = 0; - public SidebarCommand(ServerProcess serverProcess) { + public SidebarCommand(ServerFacade serverFacade) { super("sidebar"); - sidebar = new Sidebar(serverProcess, Component.text("DEMO").decorate(TextDecoration.BOLD)); + sidebar = new Sidebar(serverFacade.getServerSettings(), Component.text("DEMO").decorate(TextDecoration.BOLD)); addLine("BLANK ", Sidebar.NumberFormat.blank()); addLine("STYLE ", Sidebar.NumberFormat.styled(Component.empty().decorate(TextDecoration.STRIKETHROUGH).color(NamedTextColor.GRAY))); diff --git a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java index ad161344434..b28ca7911b1 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -19,9 +19,11 @@ public class SummonCommand extends Command { private final ArgumentEntityType entity; private final Argument pos; private final Argument entityClass; + private final ServerFacade serverFacade; - public SummonCommand() { + public SummonCommand(ServerFacade serverFacade) { super("summon"); + this.serverFacade = serverFacade; setCondition(Conditions::playerOnly); entity = ArgumentType.EntityType("entity type"); @@ -38,7 +40,7 @@ public SummonCommand() { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - final Entity entity = commandContext.get(entityClass).instantiate(commandSender.getServerProcess(), commandContext.get(this.entity)); + final Entity entity = commandContext.get(entityClass).instantiate(serverFacade, commandContext.get(this.entity)); //noinspection ConstantConditions - One couldn't possibly execute a command without being in an instance entity.setInstance(((Player) commandSender).getInstance(), commandContext.get(pos).fromSender(commandSender)); } @@ -54,12 +56,12 @@ enum EntityClass { this.factory = factory; } - public Entity instantiate(ServerProcess serverProcess, EntityType type) { - return factory.newInstance(serverProcess, type); + public Entity instantiate(ServerFacade serverFacade, EntityType type) { + return factory.newInstance(serverFacade, type); } } interface EntityFactory { - Entity newInstance(ServerProcess serverProcess, EntityType type); + Entity newInstance(ServerFacade serverFacade, EntityType type); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java index 6a93c83cd8b..c760f21e998 100644 --- a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java @@ -1,6 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerFacade; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -11,8 +12,11 @@ public class TeleportCommand extends Command { - public TeleportCommand() { + private final ServerFacade serverFacade; + + public TeleportCommand(ServerFacade serverFacade) { super("tp"); + this.serverFacade = serverFacade; setDefaultExecutor((source, context) -> source.sendMessage(Component.text("Usage: /tp x y z"))); @@ -25,7 +29,7 @@ public TeleportCommand() { private void onPlayerTeleport(CommandSender sender, CommandContext context) { final String playerName = context.get("player"); - Player pl = sender.getServerProcess().getConnectionManager().getOnlinePlayerByUsername(playerName); + Player pl = serverFacade.getConnectionManager().getOnlinePlayerByUsername(playerName); if (sender instanceof Player player) { player.teleport(pl.getPosition()); } diff --git a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java index 4af48478752..eee3e5d9db4 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java @@ -1,6 +1,6 @@ package net.minestom.demo.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.attribute.Attribute; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; @@ -10,8 +10,8 @@ public class ChickenCreature extends EntityCreature { - public ChickenCreature(ServerProcess serverProcess) { - super(serverProcess, EntityType.CHICKEN); + public ChickenCreature(ServerFacade serverFacade) { + super(serverFacade, EntityType.CHICKEN); addAIGroup( List.of( diff --git a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java index 810029e8be0..3488cc3e71c 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java @@ -1,6 +1,6 @@ package net.minestom.demo.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.ai.EntityAIGroupBuilder; @@ -8,8 +8,8 @@ public class ZombieCreature extends EntityCreature { - public ZombieCreature(ServerProcess serverProcess) { - super(serverProcess, EntityType.ZOMBIE); + public ZombieCreature(ServerFacade serverFacade) { + super(serverFacade, EntityType.ZOMBIE); addAIGroup( new EntityAIGroupBuilder() .addGoalSelector(new RandomLookAroundGoal(this, 20)) diff --git a/settings.gradle.kts b/settings.gradle.kts index 6926a561389..154b4697799 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,6 +1,6 @@ rootProject.name = "minestom-ce" -include("testing") +//include("testing") include("code-generators") //include("jmh-benchmarks") //include("jcstress-tests") diff --git a/src/main/java/net/minestom/server/ServerFacade.java b/src/main/java/net/minestom/server/ServerFacade.java new file mode 100644 index 00000000000..57361ef3f73 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerFacade.java @@ -0,0 +1,56 @@ +package net.minestom.server; + +import net.kyori.adventure.text.logger.slf4j.ComponentLogger; +import net.minestom.server.advancements.AdvancementManagerProvider; +import net.minestom.server.adventure.audience.AudienceManagerProvider; +import net.minestom.server.adventure.bossbar.BossBarManagerProvider; +import net.minestom.server.command.CommandManagerProvider; +import net.minestom.server.event.GlobalEventHandlerProvider; +import net.minestom.server.exception.ExceptionHandlerProvider; +import net.minestom.server.extras.MojangAuthProvider; +import net.minestom.server.gamedata.tags.TagManagerProvider; +import net.minestom.server.instance.InstanceManagerProvider; +import net.minestom.server.instance.block.BlockManagerProvider; +import net.minestom.server.listener.manager.PacketListenerManagerProvider; +import net.minestom.server.monitoring.BenchmarkManagerProvider; +import net.minestom.server.network.ConnectionManagerProvider; +import net.minestom.server.network.PacketProcessorProvider; +import net.minestom.server.network.socket.ServerProvider; +import net.minestom.server.recipe.RecipeManagerProvider; +import net.minestom.server.scoreboard.TeamManagerProvider; +import net.minestom.server.thread.ChunkDispatcherProvider; +import net.minestom.server.timer.SchedulerManagerProvider; +import net.minestom.server.world.DimensionTypeManagerProvider; +import net.minestom.server.world.biomes.BiomeManagerProvider; + +public interface ServerFacade extends + ExceptionHandlerProvider, + ConnectionManagerProvider, + PacketListenerManagerProvider, + PacketProcessorProvider, + InstanceManagerProvider, + BlockManagerProvider, + CommandManagerProvider, + RecipeManagerProvider, + TeamManagerProvider, + GlobalEventHandlerProvider, + SchedulerManagerProvider, + BenchmarkManagerProvider, + DimensionTypeManagerProvider, + BiomeManagerProvider, + AdvancementManagerProvider, + BossBarManagerProvider, + TagManagerProvider, + ServerProvider, + ChunkDispatcherProvider, + TickerProvider, + ServerSettingsProvider, + AudienceManagerProvider, + MojangAuthProvider, + ServerStarterProvider +{ + ComponentLogger LOGGER = ComponentLogger.logger(ServerFacade.class); + static ServerFacade of(ServerSettings serverSettings) { + return new ServerFacadeImpl(serverSettings); + } +} diff --git a/src/main/java/net/minestom/server/ServerFacadeImpl.java b/src/main/java/net/minestom/server/ServerFacadeImpl.java new file mode 100644 index 00000000000..ef92f8fc95a --- /dev/null +++ b/src/main/java/net/minestom/server/ServerFacadeImpl.java @@ -0,0 +1,104 @@ +package net.minestom.server; + +import lombok.Getter; +import net.minestom.server.advancements.AdvancementManager; +import net.minestom.server.advancements.AdvancementManagerImpl; +import net.minestom.server.adventure.audience.AudienceManager; +import net.minestom.server.adventure.audience.AudienceManagerImpl; +import net.minestom.server.adventure.bossbar.BossBarManager; +import net.minestom.server.adventure.bossbar.BossBarManagerImpl; +import net.minestom.server.command.CommandManager; +import net.minestom.server.command.CommandManagerImpl; +import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.event.GlobalEventHandlerImpl; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerImpl; +import net.minestom.server.extras.MojangAuth; +import net.minestom.server.gamedata.tags.TagManager; +import net.minestom.server.gamedata.tags.TagManagerImpl; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.instance.InstanceManagerImpl; +import net.minestom.server.instance.block.BlockManager; +import net.minestom.server.instance.block.BlockManagerImpl; +import net.minestom.server.listener.manager.PacketListenerManager; +import net.minestom.server.listener.manager.PacketListenerManagerImpl; +import net.minestom.server.monitoring.BenchmarkManager; +import net.minestom.server.monitoring.BenchmarkManagerImpl; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerImpl; +import net.minestom.server.network.PacketProcessor; +import net.minestom.server.network.PacketProcessorImpl; +import net.minestom.server.network.socket.Server; +import net.minestom.server.network.socket.ServerImpl; +import net.minestom.server.recipe.RecipeManager; +import net.minestom.server.recipe.RecipeManagerImpl; +import net.minestom.server.scoreboard.TeamManager; +import net.minestom.server.scoreboard.TeamManagerImpl; +import net.minestom.server.thread.ChunkDispatcher; +import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerImpl; +import net.minestom.server.world.DimensionTypeManager; +import net.minestom.server.world.DimensionTypeManagerImpl; +import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerImpl; + +@Getter +final class ServerFacadeImpl implements ServerFacade { + + private final ExceptionHandler exceptionHandler; + private final ConnectionManager connectionManager; + private final PacketListenerManager packetListenerManager; + private final PacketProcessor packetProcessor; + private final InstanceManager instanceManager; + private final BlockManager blockManager; + private final CommandManager commandManager; + private final RecipeManager recipeManager; + private final TeamManager teamManager; + private final GlobalEventHandler globalEventHandler; + private final SchedulerManager schedulerManager; + private final BenchmarkManager benchmarkManager; + private final DimensionTypeManager dimensionTypeManager; + private final BiomeManager biomeManager; + private final AdvancementManager advancementManager; + private final BossBarManager bossBarManager; + private final TagManager tagManager; + private final Server server; + + private final ChunkDispatcher chunkDispatcher; + private final Ticker ticker; + + private final ServerSettings serverSettings; + private final AudienceManager audienceManager; + private final MojangAuth mojangAuth; + private final ServerStarter serverStarter; + + + public ServerFacadeImpl(ServerSettings serverSettings) { + this.serverSettings = serverSettings; + this.exceptionHandler = new ExceptionHandlerImpl(); + this.globalEventHandler = new GlobalEventHandlerImpl(exceptionHandler); + this.packetListenerManager = new PacketListenerManagerImpl(globalEventHandler, exceptionHandler, this, this, this, this); + this.packetProcessor = new PacketProcessorImpl(packetListenerManager); + this.chunkDispatcher = ChunkDispatcher.singleThread(exceptionHandler); + this.blockManager = new BlockManagerImpl(); + this.bossBarManager = new BossBarManagerImpl(serverSettings); + this.biomeManager = new BiomeManagerImpl(); + this.instanceManager = new InstanceManagerImpl(chunkDispatcher, globalEventHandler, serverSettings, exceptionHandler, blockManager, biomeManager); + + this.commandManager = new CommandManagerImpl(exceptionHandler, globalEventHandler); + this.recipeManager = new RecipeManagerImpl(); + + this.schedulerManager = new SchedulerManagerImpl(); + this.benchmarkManager = new BenchmarkManagerImpl(exceptionHandler); + this.dimensionTypeManager = new DimensionTypeManagerImpl(); + this.advancementManager = new AdvancementManagerImpl(serverSettings); + this.tagManager = new TagManagerImpl(); + this.teamManager = new TeamManagerImpl(serverSettings); + this.connectionManager = new ConnectionManagerImpl(serverSettings, globalEventHandler, chunkDispatcher, exceptionHandler, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, biomeManager, dimensionTypeManager, tagManager, blockManager); + this.server = new ServerImpl(connectionManager, globalEventHandler, exceptionHandler, serverSettings, packetProcessor); + this.audienceManager = new AudienceManagerImpl(connectionManager, commandManager, serverSettings); + this.ticker = new TickerImpl(connectionManager, schedulerManager, server, globalEventHandler, exceptionHandler, instanceManager, chunkDispatcher); + this.serverStarter = new ServerStarter(serverSettings, server, exceptionHandler, schedulerManager, connectionManager, benchmarkManager, chunkDispatcher, ticker); + this.mojangAuth = new MojangAuth(serverStarter, exceptionHandler); + } +} diff --git a/src/main/java/net/minestom/server/ServerObject.java b/src/main/java/net/minestom/server/ServerObject.java deleted file mode 100644 index ecbf42c5b53..00000000000 --- a/src/main/java/net/minestom/server/ServerObject.java +++ /dev/null @@ -1,5 +0,0 @@ -package net.minestom.server; - -public interface ServerObject { - ServerProcess getServerProcess(); -} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/ServerProcess.java b/src/main/java/net/minestom/server/ServerProcess.java deleted file mode 100644 index ab009748cc3..00000000000 --- a/src/main/java/net/minestom/server/ServerProcess.java +++ /dev/null @@ -1,164 +0,0 @@ -package net.minestom.server; - -import net.kyori.adventure.text.logger.slf4j.ComponentLogger; -import net.minestom.server.advancements.AdvancementManager; -import net.minestom.server.adventure.audience.Audiences; -import net.minestom.server.adventure.bossbar.BossBarManager; -import net.minestom.server.command.CommandManager; -import net.minestom.server.event.GlobalEventHandler; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.extras.MojangAuth; -import net.minestom.server.gamedata.tags.TagManager; -import net.minestom.server.instance.Chunk; -import net.minestom.server.instance.InstanceManager; -import net.minestom.server.instance.block.BlockManager; -import net.minestom.server.instance.block.rule.BlockPlacementRule; -import net.minestom.server.listener.manager.PacketListenerManager; -import net.minestom.server.monitoring.BenchmarkManager; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.PacketProcessor; -import net.minestom.server.network.socket.Server; -import net.minestom.server.recipe.RecipeManager; -import net.minestom.server.scoreboard.TeamManager; -import net.minestom.server.snapshot.Snapshotable; -import net.minestom.server.thread.ThreadDispatcher; -import net.minestom.server.timer.SchedulerManager; -import net.minestom.server.world.DimensionTypeManager; -import net.minestom.server.world.biomes.BiomeManager; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -@ApiStatus.Experimental -@ApiStatus.NonExtendable -public interface ServerProcess extends Snapshotable { - ComponentLogger LOGGER = ComponentLogger.logger(ServerProcess.class); - static ServerProcess of(ServerSettings serverSettings) { - return new ServerProcessImpl(serverSettings); - } - - ServerSettings getServerSetting(); - - /** - * Handles incoming connections/players. - */ - @NotNull ConnectionManager getConnectionManager(); - - /** - * Handles registered instances. - */ - @NotNull InstanceManager getInstanceManager(); - - /** - * Handles {@link net.minestom.server.instance.block.BlockHandler block handlers} - * and {@link BlockPlacementRule placement rules}. - */ - @NotNull BlockManager getBlockManager(); - - /** - * Handles registered commands. - */ - @NotNull CommandManager getCommandManager(); - - /** - * Handles registered recipes shown to clients. - */ - @NotNull RecipeManager getRecipeManager(); - - /** - * Handles registered teams. - */ - @NotNull TeamManager getTeamManager(); - - /** - * Gets the global event handler. - *

        - * Used to register event callback at a global scale. - */ - @NotNull GlobalEventHandler getGlobalEventHandler(); - - /** - * Main scheduler ticked at the server rate. - */ - @NotNull SchedulerManager getSchedulerManager(); - - @NotNull BenchmarkManager getBenchmarkManager(); - - /** - * Handles registered dimensions. - */ - @NotNull DimensionTypeManager getDimensionTypeManager(); - - /** - * Handles registered biomes. - */ - @NotNull BiomeManager getBiomeManager(); - - /** - * Handles registered advancements. - */ - @NotNull AdvancementManager getAdvancementManager(); - - /** - * Handles registered boss bars. - */ - @NotNull BossBarManager getBossBarManager(); - - /** - * Handles registry tags. - */ - @NotNull TagManager getTagManager(); - - /** - * Handles all thrown exceptions from the server. - */ - @NotNull ExceptionHandler getExceptionHandler(); - - /** - * Handles incoming packets. - */ - @NotNull PacketListenerManager getPacketListenerManager(); - - /** - * Gets the object handling the client packets processing. - *

        - * Can be used if you want to convert a buffer to a client packet object. - */ - @NotNull PacketProcessor getPacketProcessor(); - - /** - * Exposed socket server. - */ - @NotNull Server getServer(); - - /** - * Dispatcher for tickable game objects. - */ - @NotNull ThreadDispatcher dispatcher(); - - /** - * Handles the server ticks. - */ - @NotNull Ticker ticker(); - - void start(@NotNull SocketAddress socketAddress); - - default void start(@NotNull String hostname, int port) { - start(new InetSocketAddress(hostname, port)); - } - - void stop(); - - boolean isAlive(); - - Audiences getAudiences(); - - MojangAuth getMojangAuth(); - - @ApiStatus.NonExtendable - interface Ticker { - void tick(long nanoTime); - } -} diff --git a/src/main/java/net/minestom/server/ServerProcessImpl.java b/src/main/java/net/minestom/server/ServerProcessImpl.java deleted file mode 100644 index 4f53f84ad02..00000000000 --- a/src/main/java/net/minestom/server/ServerProcessImpl.java +++ /dev/null @@ -1,332 +0,0 @@ -package net.minestom.server; - -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.advancements.AdvancementManager; -import net.minestom.server.adventure.audience.Audiences; -import net.minestom.server.adventure.bossbar.BossBarManager; -import net.minestom.server.command.CommandManager; -import net.minestom.server.entity.Entity; -import net.minestom.server.event.GlobalEventHandler; -import net.minestom.server.event.server.ServerTickMonitorEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.exception.ExceptionHandlerImpl; -import net.minestom.server.extras.MojangAuth; -import net.minestom.server.gamedata.tags.TagManager; -import net.minestom.server.instance.Chunk; -import net.minestom.server.instance.Instance; -import net.minestom.server.instance.InstanceManager; -import net.minestom.server.instance.block.BlockManager; -import net.minestom.server.listener.manager.PacketListenerManager; -import net.minestom.server.monitoring.BenchmarkManager; -import net.minestom.server.monitoring.TickMonitor; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.PacketProcessor; -import net.minestom.server.network.socket.Server; -import net.minestom.server.recipe.RecipeManager; -import net.minestom.server.scoreboard.TeamManager; -import net.minestom.server.snapshot.*; -import net.minestom.server.thread.Acquirable; -import net.minestom.server.thread.ThreadDispatcher; -import net.minestom.server.thread.TickSchedulerThread; -import net.minestom.server.timer.SchedulerManager; -import net.minestom.server.utils.PacketUtils; -import net.minestom.server.utils.PropertyUtils; -import net.minestom.server.utils.collection.MappedCollection; -import net.minestom.server.world.DimensionTypeManager; -import net.minestom.server.world.biomes.BiomeManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.net.SocketAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -final class ServerProcessImpl implements ServerProcess { - private static final Logger LOGGER = LoggerFactory.getLogger(ServerProcessImpl.class); - private static final Boolean SHUTDOWN_ON_SIGNAL = PropertyUtils.getBoolean("minestom.shutdown-on-signal", true); - - private final ExceptionHandler exceptionHandler; - private final ConnectionManager connectionManager; - private final PacketListenerManager packetListenerManager; - private final PacketProcessor packetProcessor; - private final InstanceManager instanceManager; - private final BlockManager blockManager; - private final CommandManager commandManager; - private final RecipeManager recipeManager; - private final TeamManager teamManager; - private final GlobalEventHandler globalEventHandler; - private final SchedulerManager schedulerManager; - private final BenchmarkManager benchmarkManager; - private final DimensionTypeManager dimensionTypeManager; - private final BiomeManager biomeManager; - private final AdvancementManager advancementManager; - private final BossBarManager bossBarManager; - private final TagManager tagManager; - private final Server server; - - private final ThreadDispatcher dispatcher; - private final Ticker ticker; - - private final AtomicBoolean started = new AtomicBoolean(); - private final AtomicBoolean stopped = new AtomicBoolean(); - private final ServerSettings serverSettings; - private final Audiences audiences; - private final MojangAuth mojangAuth; - - public ServerProcessImpl(ServerSettings serverSettings) { - this(serverSettings, null); - } - - public ServerProcessImpl(ServerSettings serverSettings, @Nullable ExceptionHandler exceptionHandler) { - this.serverSettings = serverSettings; - this.exceptionHandler = Objects.requireNonNullElseGet(exceptionHandler, () -> new ExceptionHandlerImpl(this)); - this.globalEventHandler = new GlobalEventHandler(exceptionHandler); - this.packetListenerManager = new PacketListenerManager(globalEventHandler, exceptionHandler); - this.packetProcessor = new PacketProcessor(packetListenerManager); - this.dispatcher = ThreadDispatcher.singleThread(exceptionHandler); - this.instanceManager = new InstanceManager(dispatcher, globalEventHandler); - this.blockManager = new BlockManager(); - this.commandManager = new CommandManager(this); - this.recipeManager = new RecipeManager(); - this.teamManager = new TeamManager(this); - this.schedulerManager = new SchedulerManager(); - this.benchmarkManager = new BenchmarkManager(exceptionHandler); - this.dimensionTypeManager = new DimensionTypeManager(); - this.biomeManager = new BiomeManager(); - this.advancementManager = new AdvancementManager(this); - this.bossBarManager = new BossBarManager(this); - this.tagManager = new TagManager(); - this.connectionManager = new ConnectionManager(this, serverSettings, tagManager); - this.server = new Server(this, packetProcessor); - this.mojangAuth = new MojangAuth(this, exceptionHandler); - this.audiences = new Audiences(this, connectionManager, commandManager); - - this.ticker = new TickerImpl(); - } - - @Override - public ServerSettings getServerSetting() { - return serverSettings; - } - - @Override - public @NotNull ConnectionManager getConnectionManager() { - return connectionManager; - } - - @Override - public @NotNull InstanceManager getInstanceManager() { - return instanceManager; - } - - @Override - public @NotNull BlockManager getBlockManager() { - return blockManager; - } - - @Override - public @NotNull CommandManager getCommandManager() { - return commandManager; - } - - @Override - public @NotNull RecipeManager getRecipeManager() { - return recipeManager; - } - - @Override - public @NotNull TeamManager getTeamManager() { - return teamManager; - } - - @Override - public @NotNull GlobalEventHandler getGlobalEventHandler() { - return globalEventHandler; - } - - @Override - public @NotNull SchedulerManager getSchedulerManager() { - return schedulerManager; - } - - @Override - public @NotNull BenchmarkManager getBenchmarkManager() { - return benchmarkManager; - } - - @Override - public @NotNull DimensionTypeManager getDimensionTypeManager() { - return dimensionTypeManager; - } - - @Override - public @NotNull BiomeManager getBiomeManager() { - return biomeManager; - } - - @Override - public @NotNull AdvancementManager getAdvancementManager() { - return advancementManager; - } - - @Override - public @NotNull BossBarManager getBossBarManager() { - return bossBarManager; - } - - @Override - public @NotNull TagManager getTagManager() { - return tagManager; - } - - @Override - public @NotNull ExceptionHandler getExceptionHandler() { - return exceptionHandler; - } - - @Override - public @NotNull PacketListenerManager getPacketListenerManager() { - return packetListenerManager; - } - - @Override - public @NotNull PacketProcessor getPacketProcessor() { - return packetProcessor; - } - - @Override - public @NotNull Server getServer() { - return server; - } - - @Override - public @NotNull ThreadDispatcher dispatcher() { - return dispatcher; - } - - @Override - public @NotNull Ticker ticker() { - return ticker; - } - - @Override - public void start(@NotNull SocketAddress socketAddress) { - if (!started.compareAndSet(false, true)) { - throw new IllegalStateException("Server already started"); - } - - LOGGER.info("Starting " + serverSettings.getBrandName() + " server."); - - // Init server - try { - server.init(socketAddress); - } catch (IOException e) { - exceptionHandler.handleException(e); - throw new RuntimeException(e); - } - - // Start server - server.start(); - - LOGGER.info(serverSettings.getBrandName() + " server started successfully."); - - // Stop the server on SIGINT - if (SHUTDOWN_ON_SIGNAL) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); - - new TickSchedulerThread(this).start(); - } - - @Override - public void stop() { - if (!stopped.compareAndSet(false, true)) - return; - LOGGER.info("Stopping " + serverSettings.getBrandName() + " server."); - schedulerManager.shutdown(); - connectionManager.shutdown(); - server.stop(); - LOGGER.info("Shutting down all thread pools."); - benchmarkManager.disable(); - dispatcher.shutdown(); - LOGGER.info(serverSettings.getBrandName() + " server stopped successfully."); - } - - @Override - public boolean isAlive() { - return started.get() && !stopped.get(); - } - - @Override - public Audiences getAudiences() { - return audiences; - } - - @Override - public @NotNull ServerSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) { - List> instanceRefs = new ArrayList<>(); - Int2ObjectOpenHashMap> entityRefs = new Int2ObjectOpenHashMap<>(); - for (Instance instance : instanceManager.getInstances()) { - instanceRefs.add(updater.reference(instance)); - for (Entity entity : instance.getEntities()) { - entityRefs.put(entity.getEntityId(), updater.reference(entity)); - } - } - return new SnapshotImpl.Server(MappedCollection.plainReferences(instanceRefs), entityRefs); - } - - @Override - public MojangAuth getMojangAuth() { - return mojangAuth; - } - - private final class TickerImpl implements Ticker { - @Override - public void tick(long nanoTime) { - final long msTime = System.currentTimeMillis(); - - getSchedulerManager().processTick(); - - // Connection tick (let waiting clients in, send keep alives, handle configuration players packets) - getConnectionManager().tick(msTime); - - // Server tick (chunks/entities) - serverTick(msTime); - - // Flush all waiting packets - PacketUtils.flush(); - - // Server connection tick - getServer().tick(); - - // Monitoring - { - final double acquisitionTimeMs = Acquirable.resetAcquiringTime() / 1e6D; - final double tickTimeMs = (System.nanoTime() - nanoTime) / 1e6D; - final TickMonitor tickMonitor = new TickMonitor(tickTimeMs, acquisitionTimeMs); - getGlobalEventHandler().call(new ServerTickMonitorEvent(tickMonitor)); - } - } - - private void serverTick(long tickStart) { - // Tick all instances - for (Instance instance : getInstanceManager().getInstances()) { - try { - instance.tick(tickStart); - } catch (Exception e) { - getExceptionHandler().handleException(e); - } - } - // Tick all chunks (and entities inside) - dispatcher().updateAndAwait(tickStart); - - // Clear removed entities & update threads - final long tickTime = System.currentTimeMillis() - tickStart; - dispatcher().refreshThreads(tickTime); - } - } -} diff --git a/src/main/java/net/minestom/server/ServerSettings.java b/src/main/java/net/minestom/server/ServerSettings.java index 7f45cddbd5d..11b8bd1fa83 100644 --- a/src/main/java/net/minestom/server/ServerSettings.java +++ b/src/main/java/net/minestom/server/ServerSettings.java @@ -1,65 +1,59 @@ package net.minestom.server; +import lombok.Builder; +import lombok.Builder.Default; +import lombok.Getter; +import lombok.Setter; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.packet.server.common.PluginMessagePacket; +import net.minestom.server.network.packet.server.play.ServerDifficultyPacket; +import net.minestom.server.utils.PacketUtils; import net.minestom.server.world.Difficulty; import org.jetbrains.annotations.NotNull; -public interface ServerSettings { - static ServerSettingsImpl.Builder builder() { - return new ServerSettingsImpl.Builder(); +@Getter +@Setter +@Builder(builderClassName = "Builder") +public final class ServerSettings { + @Default + private final int chunkViewDistance = 8; + @Default + private final int entityViewDistance = 5; + @Default + private final int compressionThreshold = 256; + @Default + private final int tickPerSecond = 20; + @Default + private final boolean shutdownOnSignal = true; + @Default + private final int workers = Runtime.getRuntime().availableProcessors(); + @Default + private final int maxPacketSize = 2_097_151; // 3 bytes var-int + @Default + private final int sendBufferSize = 262_143; + @Default + private final int receiveBufferSize = 32_767; + @Default + private final int pooledBufferSize = 262_143; + @Default + private final boolean tcpNoDelay = true; + + @Default + private @NotNull String brandName = "Minestom"; + @Default + private @NotNull Difficulty difficulty = Difficulty.NORMAL; + + public int getTickMs() { + return 1000 / tickPerSecond; } - int getTickPerSecond(); - default int getTickMs() { - return 1000 / getTickPerSecond(); + public void updateBrandName(@NotNull String brandName, @NotNull ConnectionManager connectionManager, ServerSettings serverSettings) { + setBrandName(brandName); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, PluginMessagePacket.getBrandPacket(this)); } - /** - * Gets the current server brand name. - * - * @return the server brand name - */ - @NotNull String getBrandName(); - - /** - * Changes the server brand name and send the change to all connected players. - * - * @param brandName the server brand name - * @throws NullPointerException if {@code brandName} is null - */ - void setBrandName(@NotNull String brandName, @NotNull ServerProcess serverProcess); - - /** - * Gets the server difficulty showed in game option. - * - * @return the server difficulty - */ - @NotNull Difficulty getDifficulty(); - - /** - * Changes the server difficulty and send the appropriate packet to all connected clients. - * - * @param difficulty the new server difficulty - */ - void setDifficulty(@NotNull Difficulty difficulty, @NotNull ServerProcess serverProcess); - - /** - * Gets the chunk view distance of the server. - * - * @return the chunk view distance - */ - int getChunkViewDistance(); - - /** - * Gets the entity view distance of the server. - * - * @return the entity view distance - */ - int getEntityViewDistance(); - - /** - * Gets the compression threshold of the server. - * - * @return the compression threshold, 0 means that compression is disabled - */ - int getCompressionThreshold(); + public void updateDifficulty(@NotNull Difficulty difficulty, @NotNull ConnectionManager connectionManager, ServerSettings serverSettings) { + setDifficulty(difficulty); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new ServerDifficultyPacket(difficulty, true)); + } } diff --git a/src/main/java/net/minestom/server/ServerSettingsImpl.java b/src/main/java/net/minestom/server/ServerSettingsImpl.java deleted file mode 100644 index 804ff9d1bea..00000000000 --- a/src/main/java/net/minestom/server/ServerSettingsImpl.java +++ /dev/null @@ -1,122 +0,0 @@ -package net.minestom.server; - -import net.minestom.server.network.packet.server.common.PluginMessagePacket; -import net.minestom.server.network.packet.server.play.ServerDifficultyPacket; -import net.minestom.server.utils.MathUtils; -import net.minestom.server.utils.PacketUtils; -import net.minestom.server.utils.validate.Check; -import net.minestom.server.world.Difficulty; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Range; - -final class ServerSettingsImpl implements ServerSettings { - private final int chunkViewDistance; - private final int entityViewDistance; - private final int compressionThreshold; - private final int tickPerSecond; - - private @NotNull String brandName; - private @NotNull Difficulty difficulty; - - private ServerSettingsImpl(int chunkViewDistance, int entityViewDistance, int compressionThreshold, int tickPerSecond, @NotNull String brandName, @NotNull Difficulty difficulty) { - this.chunkViewDistance = chunkViewDistance; - this.entityViewDistance = entityViewDistance; - this.compressionThreshold = compressionThreshold; - this.tickPerSecond = tickPerSecond; - this.brandName = brandName; - this.difficulty = difficulty; - } - - @Override - public int getTickPerSecond() { - return tickPerSecond; - } - - @Override - @NotNull - public String getBrandName() { - return brandName; - } - - @Override - public void setBrandName(@NotNull String brandName, @NotNull ServerProcess serverProcess) { - this.brandName = brandName; - PacketUtils.broadcastPlayPacket(serverProcess, PluginMessagePacket.getBrandPacket(this)); - } - - - @NotNull - @Override - public Difficulty getDifficulty() { - return difficulty; - } - - @Override - public void setDifficulty(@NotNull Difficulty difficulty, @NotNull ServerProcess serverProcess) { - this.difficulty = difficulty; - PacketUtils.broadcastPlayPacket(serverProcess, new ServerDifficultyPacket(difficulty, true)); - } - - @Override - public int getChunkViewDistance() { - return chunkViewDistance; - } - - @Override - public int getEntityViewDistance() { - return entityViewDistance; - } - - @Override - public int getCompressionThreshold() { - return compressionThreshold; - } - - public static class Builder { - private int chunkViewDistance = 8; - private int entityViewDistance = 5; - private int compressionThreshold = 256; - private int tickPerSecond = 20; - - private String brandName = "Minestom"; - private Difficulty difficulty = Difficulty.NORMAL; - - @Range(from = 2, to = 32) - public Builder chunkViewDistance(int chunkViewDistance) { - Check.argCondition(!MathUtils.isBetween(chunkViewDistance, 2, 32), "The chunk view distance must be between 2 and 32"); - this.chunkViewDistance = chunkViewDistance; - return this; - } - - @Range(from = 0, to = 32) - public Builder entityViewDistance(int entityViewDistance) { - Check.argCondition(!MathUtils.isBetween(entityViewDistance, 0, 32), "The entity view distance must be between 0 and 32"); - this.entityViewDistance = entityViewDistance; - return this; - } - - public Builder compressionThreshold(int compressionThreshold) { - this.compressionThreshold = compressionThreshold; - return this; - } - - public Builder tickPerSecond(int tickPerSecond) { - this.tickPerSecond = tickPerSecond; - return this; - } - - public Builder brandName(@NotNull String brandName) { - this.brandName = brandName; - return this; - } - - public Builder difficulty(@NotNull Difficulty difficulty) { - this.difficulty = difficulty; - return this; - } - - public ServerSettings build() { - return new ServerSettingsImpl(chunkViewDistance, entityViewDistance, compressionThreshold, tickPerSecond, brandName, difficulty); - } - } -} diff --git a/src/main/java/net/minestom/server/ServerSettingsProvider.java b/src/main/java/net/minestom/server/ServerSettingsProvider.java new file mode 100644 index 00000000000..409fb369cd9 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerSettingsProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server; + +public interface ServerSettingsProvider { + ServerSettings getServerSettings(); +} diff --git a/src/main/java/net/minestom/server/ServerStarter.java b/src/main/java/net/minestom/server/ServerStarter.java new file mode 100644 index 00000000000..06cb5907017 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerStarter.java @@ -0,0 +1,82 @@ +package net.minestom.server; + +import lombok.RequiredArgsConstructor; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; +import net.minestom.server.monitoring.BenchmarkManager; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.socket.Server; +import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.TickSchedulerThread; +import net.minestom.server.timer.SchedulerManager; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; + +@RequiredArgsConstructor +public class ServerStarter { + private static final Logger LOGGER = LoggerFactory.getLogger(ServerStarter.class); + + private final ServerSettings serverSettings; + private final Server server; + private final ExceptionHandler exceptionHandler; + private final SchedulerManager schedulerManager; + private final ConnectionManager connectionManager; + private final BenchmarkManager benchmarkManager; + private final ThreadDispatcher dispatcher; + private final Ticker ticker; + + private final AtomicBoolean started = new AtomicBoolean(); + private final AtomicBoolean stopped = new AtomicBoolean(); + public void start(@NotNull SocketAddress socketAddress) { + if (!started.compareAndSet(false, true)) { + throw new IllegalStateException("Server already started"); + } + + LOGGER.info("Starting " + serverSettings.getBrandName() + " server."); + + // Init server + try { + server.init(socketAddress); + } catch (IOException e) { + exceptionHandler.handleException(e); + throw new RuntimeException(e); + } + + // Start server + server.start(); + + LOGGER.info(serverSettings.getBrandName() + " server started successfully."); + + // Stop the server on SIGINT + if (serverSettings.isShutdownOnSignal()) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); + + new TickSchedulerThread(serverSettings, ticker, this, exceptionHandler).start(); + } + + public void start(@NotNull String hostname, int port) { + start(new InetSocketAddress(hostname, port)); + } + + public void stop() { + if (!stopped.compareAndSet(false, true)) + return; + LOGGER.info("Stopping " + serverSettings.getBrandName() + " server."); + schedulerManager.shutdown(); + connectionManager.shutdown(); + server.stop(); + LOGGER.info("Shutting down all thread pools."); + benchmarkManager.disable(); + dispatcher.shutdown(); + LOGGER.info(serverSettings.getBrandName() + " server stopped successfully."); + } + + public boolean isAlive() { + return started.get() && !stopped.get(); + } +} diff --git a/src/main/java/net/minestom/server/ServerStarterProvider.java b/src/main/java/net/minestom/server/ServerStarterProvider.java new file mode 100644 index 00000000000..3157e9631f7 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerStarterProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server; + +public interface ServerStarterProvider { + ServerStarter getServerStarter(); +} diff --git a/src/main/java/net/minestom/server/Ticker.java b/src/main/java/net/minestom/server/Ticker.java new file mode 100644 index 00000000000..c90a442997e --- /dev/null +++ b/src/main/java/net/minestom/server/Ticker.java @@ -0,0 +1,9 @@ +package net.minestom.server; + +import org.jetbrains.annotations.ApiStatus; + +@ApiStatus.NonExtendable +public +interface Ticker { + void tick(long nanoTime); +} diff --git a/src/main/java/net/minestom/server/TickerImpl.java b/src/main/java/net/minestom/server/TickerImpl.java new file mode 100644 index 00000000000..8a8515d135d --- /dev/null +++ b/src/main/java/net/minestom/server/TickerImpl.java @@ -0,0 +1,74 @@ +package net.minestom.server; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.event.server.ServerTickMonitorEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; +import net.minestom.server.instance.Instance; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.monitoring.TickMonitor; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.socket.Server; +import net.minestom.server.thread.Acquirable; +import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.utils.PacketUtils; + +@Getter +@RequiredArgsConstructor +final class TickerImpl implements Ticker { + private final ConnectionManager connectionManager; + private final SchedulerManager schedulerManager; + private final Server server; + private final EventNode globalEventHandler; + private final ExceptionHandler exceptionHandler; + private final InstanceManager instanceManager; + private final ThreadDispatcher dispatcher; + + @Override + public void tick(long nanoTime) { + final long msTime = System.currentTimeMillis(); + + getSchedulerManager().processTick(); + + // Connection tick (let waiting clients in, send keep alives, handle configuration players packets) + getConnectionManager().tick(msTime); + + // Server tick (chunks/entities) + serverTick(msTime); + + // Flush all waiting packets + PacketUtils.flush(); + + // Server connection tick + getServer().tick(); + + // Monitoring + { + final double acquisitionTimeMs = Acquirable.resetAcquiringTime() / 1e6D; + final double tickTimeMs = (System.nanoTime() - nanoTime) / 1e6D; + final TickMonitor tickMonitor = new TickMonitor(tickTimeMs, acquisitionTimeMs); + getGlobalEventHandler().call(new ServerTickMonitorEvent(tickMonitor)); + } + } + + private void serverTick(long tickStart) { + // Tick all instances + for (Instance instance : getInstanceManager().getInstances()) { + try { + instance.tick(tickStart); + } catch (Exception e) { + getExceptionHandler().handleException(e); + } + } + // Tick all chunks (and entities inside) + getDispatcher().updateAndAwait(tickStart); + + // Clear removed entities & update threads + final long tickTime = System.currentTimeMillis() - tickStart; + getDispatcher().refreshThreads(tickTime); + } +} diff --git a/src/main/java/net/minestom/server/TickerProvider.java b/src/main/java/net/minestom/server/TickerProvider.java new file mode 100644 index 00000000000..1bc14493bc7 --- /dev/null +++ b/src/main/java/net/minestom/server/TickerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server; + +public interface TickerProvider { + Ticker getTicker(); +} diff --git a/src/main/java/net/minestom/server/Viewable.java b/src/main/java/net/minestom/server/Viewable.java index 733e5a80f9e..e4dee734ff2 100644 --- a/src/main/java/net/minestom/server/Viewable.java +++ b/src/main/java/net/minestom/server/Viewable.java @@ -15,7 +15,7 @@ /** * Represents something which can be displayed or hidden to players. */ -public interface Viewable extends ServerObject { +public interface Viewable { /** * Adds a viewer. @@ -58,31 +58,33 @@ default boolean isViewer(@NotNull Player player) { * * @param packet the packet to send to all viewers */ - default void sendPacketToViewers(@NotNull SendablePacket packet) { + default void sendPacketToViewers(ServerSettings serverSettings, @NotNull SendablePacket packet) { if (packet instanceof ServerPacket serverPacket) { - PacketUtils.sendGroupedPacket(getServerProcess().getServerSetting(), getViewers(), serverPacket); + PacketUtils.sendGroupedPacket(serverSettings, getViewers(), serverPacket); } else { getViewers().forEach(player -> player.sendPacket(packet)); } } - default void sendPacketsToViewers(@NotNull Collection packets) { - packets.forEach(this::sendPacketToViewers); + default void sendPacketsToViewers(ServerSettings serverSettings, @NotNull Collection packets) { + for (SendablePacket packet : packets) { + sendPacketToViewers(serverSettings, packet); + } } - default void sendPacketsToViewers(@NotNull SendablePacket... packets) { - sendPacketsToViewers(List.of(packets)); + default void sendPacketsToViewers(ServerSettings serverSettings, @NotNull SendablePacket... packets) { + sendPacketsToViewers(serverSettings, List.of(packets)); } /** * Sends a packet to all viewers and the viewable element if it is a player. *

        - * If 'this' isn't a player, then only {@link #sendPacketToViewers(SendablePacket)} is called. + * If 'this' isn't a player, then only {@link #sendPacketToViewers(ServerSettings, SendablePacket)} is called. * * @param packet the packet to send */ - default void sendPacketToViewersAndSelf(@NotNull SendablePacket packet) { - sendPacketToViewers(packet); + default void sendPacketToViewersAndSelf(ServerSettings serverSettings, @NotNull SendablePacket packet) { + sendPacketToViewers(serverSettings, packet); } /** @@ -90,8 +92,8 @@ default void sendPacketToViewersAndSelf(@NotNull SendablePacket packet) { * * @return the audience */ - default @NotNull Audience getViewersAsAudience() { - return PacketGroupingAudience.of(getServerProcess(), this.getViewers()); + default @NotNull Audience getViewersAsAudience(ServerSettings serverSettings) { + return PacketGroupingAudience.of(serverSettings, this.getViewers()); } /** diff --git a/src/main/java/net/minestom/server/advancements/Advancement.java b/src/main/java/net/minestom/server/advancements/Advancement.java index a8f4623391a..9b5e6cb352c 100644 --- a/src/main/java/net/minestom/server/advancements/Advancement.java +++ b/src/main/java/net/minestom/server/advancements/Advancement.java @@ -1,6 +1,7 @@ package net.minestom.server.advancements; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerSettings; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.minestom.server.network.packet.server.play.AdvancementsPacket; @@ -16,6 +17,7 @@ */ public class Advancement { + private final ServerSettings serverSettings; protected AdvancementTab tab; private boolean achieved; @@ -40,19 +42,19 @@ public class Advancement { private AdvancementsPacket.Criteria criteria; private boolean sendTelemetryData; - public Advancement(@NotNull Component title, @NotNull Component description, + public Advancement(ServerSettings serverSettings, @NotNull Component title, @NotNull Component description, @NotNull Material icon, @NotNull FrameType frameType, float x, float y) { - this(title, description, ItemStack.of(icon), frameType, x, y, false); + this(serverSettings, title, description, ItemStack.of(icon), frameType, x, y, false); } - public Advancement(@NotNull Component title, Component description, + public Advancement(ServerSettings serverSettings, @NotNull Component title, Component description, @NotNull ItemStack icon, @NotNull FrameType frameType, float x, float y) { - this(title, description, icon, frameType, x, y, false); + this(serverSettings, title, description, icon, frameType, x, y, false); } - public Advancement(@NotNull Component title, Component description, + public Advancement(ServerSettings serverSettings, @NotNull Component title, Component description, @NotNull ItemStack icon, @NotNull FrameType frameType, float x, float y, boolean sendTelemetryData) { this.title = title; @@ -62,6 +64,7 @@ public Advancement(@NotNull Component title, Component description, this.x = x; this.y = y; this.sendTelemetryData = sendTelemetryData; + this.serverSettings = serverSettings; } /** @@ -329,7 +332,7 @@ protected AdvancementsPacket getUpdatePacket() { protected void update() { updateCriteria(); if (tab != null) { - tab.sendPacketsToViewers(tab.removePacket, tab.createPacket()); + tab.sendPacketsToViewers(serverSettings, tab.removePacket, tab.createPacket()); } } diff --git a/src/main/java/net/minestom/server/advancements/AdvancementManager.java b/src/main/java/net/minestom/server/advancements/AdvancementManager.java index 729c5484edf..1074d06bd98 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementManager.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementManager.java @@ -1,28 +1,16 @@ package net.minestom.server.advancements; -import net.minestom.server.ServerProcess; -import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** * Used to manage all the registered {@link AdvancementTab}. *

        * Use {@link #createTab(String, AdvancementRoot)} to create a tab with the appropriate {@link AdvancementRoot}. */ -public class AdvancementManager { - - // root identifier = its advancement tab - private final Map advancementTabMap = new ConcurrentHashMap<>(); - private final ServerProcess serverProcess; - - public AdvancementManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } +public interface AdvancementManager { /** * Creates a new {@link AdvancementTab} with a single {@link AdvancementRoot}. @@ -32,14 +20,7 @@ public AdvancementManager(ServerProcess serverProcess) { * @return the newly created {@link AdvancementTab} * @throws IllegalStateException if a tab with the identifier {@code rootIdentifier} already exists */ - @NotNull - public AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root) { - Check.stateCondition(advancementTabMap.containsKey(rootIdentifier), - "A tab with the identifier '" + rootIdentifier + "' already exists"); - final AdvancementTab advancementTab = new AdvancementTab(serverProcess, rootIdentifier, root); - this.advancementTabMap.put(rootIdentifier, advancementTab); - return advancementTab; - } + @NotNull AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root); /** * Gets an advancement tab by its root identifier. @@ -47,19 +28,12 @@ public AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull Advance * @param rootIdentifier the root identifier of the tab * @return the {@link AdvancementTab} associated with the identifier, null if not any */ - @Nullable - public AdvancementTab getTab(@NotNull String rootIdentifier) { - return advancementTabMap.get(rootIdentifier); - } + @Nullable AdvancementTab getTab(@NotNull String rootIdentifier); /** * Gets all the created {@link AdvancementTab}. * * @return the collection containing all created {@link AdvancementTab} */ - @NotNull - public Collection getTabs() { - return advancementTabMap.values(); - } - + @NotNull Collection getTabs(); } diff --git a/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java b/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java new file mode 100644 index 00000000000..9416983e809 --- /dev/null +++ b/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java @@ -0,0 +1,41 @@ +package net.minestom.server.advancements; + +import lombok.RequiredArgsConstructor; +import net.minestom.server.ServerSettings; +import net.minestom.server.utils.validate.Check; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@RequiredArgsConstructor +public class AdvancementManagerImpl implements AdvancementManager { + private final ServerSettings serverSettings; + + // root identifier = its advancement tab + private final Map advancementTabMap = new ConcurrentHashMap<>(); + + @Override + @NotNull + public AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root) { + Check.stateCondition(advancementTabMap.containsKey(rootIdentifier), + "A tab with the identifier '" + rootIdentifier + "' already exists"); + final AdvancementTab advancementTab = new AdvancementTab(serverSettings, rootIdentifier, root); + this.advancementTabMap.put(rootIdentifier, advancementTab); + return advancementTab; + } + + @Override + @Nullable + public AdvancementTab getTab(@NotNull String rootIdentifier) { + return advancementTabMap.get(rootIdentifier); + } + + @Override + @NotNull + public Collection getTabs() { + return advancementTabMap.values(); + } +} diff --git a/src/main/java/net/minestom/server/advancements/AdvancementManagerProvider.java b/src/main/java/net/minestom/server/advancements/AdvancementManagerProvider.java new file mode 100644 index 00000000000..da14da3d422 --- /dev/null +++ b/src/main/java/net/minestom/server/advancements/AdvancementManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.advancements; + +public interface AdvancementManagerProvider { + AdvancementManager getAdvancementManager(); +} diff --git a/src/main/java/net/minestom/server/advancements/AdvancementRoot.java b/src/main/java/net/minestom/server/advancements/AdvancementRoot.java index d89f1a5cedc..43131d0b4a8 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementRoot.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementRoot.java @@ -1,6 +1,7 @@ package net.minestom.server.advancements; import net.kyori.adventure.text.Component; +import net.minestom.server.ServerSettings; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import org.jetbrains.annotations.NotNull; @@ -13,19 +14,19 @@ * The difference between this and an {@link Advancement} is that the root is responsible for the tab background. */ public class AdvancementRoot extends Advancement { - public AdvancementRoot(@NotNull Component title, @NotNull Component description, + public AdvancementRoot(ServerSettings serverSettings, @NotNull Component title, @NotNull Component description, @NotNull ItemStack icon, @NotNull FrameType frameType, float x, float y, @Nullable String background) { - super(title, description, icon, frameType, x, y); + super(serverSettings, title, description, icon, frameType, x, y); setBackground(background); } - public AdvancementRoot(@NotNull Component title, @NotNull Component description, + public AdvancementRoot(ServerSettings serverSettings, @NotNull Component title, @NotNull Component description, @NotNull Material icon, FrameType frameType, float x, float y, @Nullable String background) { - super(title, description, icon, frameType, x, y); + super(serverSettings, title, description, icon, frameType, x, y); setBackground(background); } } diff --git a/src/main/java/net/minestom/server/advancements/AdvancementTab.java b/src/main/java/net/minestom/server/advancements/AdvancementTab.java index 128e4030350..da2a8005d0a 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementTab.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementTab.java @@ -1,6 +1,6 @@ package net.minestom.server.advancements; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.AdvancementsPacket; @@ -12,7 +12,7 @@ import java.util.concurrent.CopyOnWriteArraySet; /** - * Represents a tab which can be shared between multiple players. Created using {@link AdvancementManager#createTab(String, AdvancementRoot)}. + * Represents a tab which can be shared between multiple players. Created using {@link AdvancementManagerImpl#createTab(String, AdvancementRoot)}. *

        * Each tab requires a root advancement and all succeeding advancements need to have a parent in the tab. * You can create a new advancement using {@link #createAdvancement(String, Advancement, Advancement)}. @@ -26,7 +26,7 @@ public class AdvancementTab implements Viewable { private final Set viewers = new HashSet<>(); - private final ServerProcess serverProcess; + private final ServerSettings serverSettings; private final AdvancementRoot root; // Advancement -> its parent @@ -36,8 +36,8 @@ public class AdvancementTab implements Viewable { // will never change (since the root identifier is always the same) protected final AdvancementsPacket removePacket; - protected AdvancementTab(ServerProcess serverProcess, @NotNull String rootIdentifier, @NotNull AdvancementRoot root) { - this.serverProcess = serverProcess; + protected AdvancementTab(ServerSettings serverSettings, @NotNull String rootIdentifier, @NotNull AdvancementRoot root) { + this.serverSettings = serverSettings; this.root = root; cacheAdvancement(rootIdentifier, root, null); this.removePacket = new AdvancementsPacket(false, List.of(), List.of(rootIdentifier), List.of()); @@ -77,7 +77,7 @@ public void createAdvancement(@NotNull String identifier, @NotNull Advancement a "You tried to set a parent which doesn't exist or isn't registered"); cacheAdvancement(identifier, advancement, parent); if (!getViewers().isEmpty()) { - sendPacketToViewers(advancement.getUpdatePacket()); + sendPacketToViewers(serverSettings, advancement.getUpdatePacket()); } } @@ -167,9 +167,4 @@ private void removePlayer(@NotNull Player player) { PLAYER_TAB_MAP.remove(uuid); } } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/adventure/audience/AudienceManager.java b/src/main/java/net/minestom/server/adventure/audience/AudienceManager.java new file mode 100644 index 00000000000..52176e17dda --- /dev/null +++ b/src/main/java/net/minestom/server/adventure/audience/AudienceManager.java @@ -0,0 +1,41 @@ +package net.minestom.server.adventure.audience; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.key.Keyed; +import net.minestom.server.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Predicate; + +public interface AudienceManager { + @NotNull AudienceProvider single(); + + @NotNull AudienceProvider> iterable(); + + @NotNull Audience all(); + + @NotNull Audience players(); + + @NotNull Audience players(@NotNull Predicate filter); + + @NotNull Audience console(); + + @NotNull Audience server(); + + @NotNull Audience customs(); + + @NotNull Audience custom(@NotNull Keyed keyed); + + @NotNull Audience custom(@NotNull Key key); + + @NotNull Audience custom(@NotNull Keyed keyed, Predicate filter); + + @NotNull Audience custom(@NotNull Key key, Predicate filter); + + @NotNull Audience customs(@NotNull Predicate filter); + + @NotNull Audience all(@NotNull Predicate filter); + + @NotNull AudienceRegistry registry(); +} diff --git a/src/main/java/net/minestom/server/adventure/audience/Audiences.java b/src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java similarity index 81% rename from src/main/java/net/minestom/server/adventure/audience/Audiences.java rename to src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java index 94c6db6652f..9cc4fdb7e9e 100644 --- a/src/main/java/net/minestom/server/adventure/audience/Audiences.java +++ b/src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java @@ -3,7 +3,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Keyed; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; import net.minestom.server.network.ConnectionManager; @@ -14,14 +14,18 @@ /** * Utility class to access Adventure audiences. */ -public class Audiences { +public class AudienceManagerImpl implements AudienceManager { - private final ServerProcess serverProcess; private final SingleAudienceProvider audience; + private final ConnectionManager connectionManager; + private final CommandManager commandManager; + private final ServerSettings serverSettings; - public Audiences(ServerProcess serverProcess, ConnectionManager connectionManager, CommandManager commandManager) { - this.serverProcess = serverProcess; - audience = new SingleAudienceProvider(serverProcess, connectionManager, commandManager); + public AudienceManagerImpl(ConnectionManager connectionManager, CommandManager commandManager, ServerSettings serverSettings) { + this.connectionManager = connectionManager; + this.commandManager = commandManager; + this.serverSettings = serverSettings; + audience = new SingleAudienceProvider(serverSettings, connectionManager, commandManager); } /** @@ -29,6 +33,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return the instance */ + @Override public @NotNull AudienceProvider single() { return audience; } @@ -38,6 +43,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return the instance */ + @Override public @NotNull AudienceProvider> iterable() { return audience.collection; } @@ -49,6 +55,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return all audience members */ + @Override public @NotNull Audience all() { return Audience.audience(audience.server, audience.customs()); } @@ -58,6 +65,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return all players */ + @Override public @NotNull Audience players() { return audience.players; } @@ -68,8 +76,9 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param filter the predicate * @return all players matching the predicate */ - public @NotNull Audience players(ConnectionManager connectionManager, @NotNull Predicate filter) { - return PacketGroupingAudience.of(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); + @Override + public @NotNull Audience players(@NotNull Predicate filter) { + return PacketGroupingAudience.of(serverSettings, connectionManager.getOnlinePlayers().stream().filter(filter).toList()); } /** @@ -77,8 +86,9 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return the console */ + @Override public @NotNull Audience console() { - return serverProcess.getCommandManager().getConsoleSender(); + return commandManager.getConsoleSender(); } /** @@ -86,6 +96,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return the audience of all players and the console */ + @Override public @NotNull Audience server() { return audience.server; } @@ -95,6 +106,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return all custom audience members */ + @Override public @NotNull Audience customs() { return Audience.audience(audience.iterable().customs()); } @@ -105,6 +117,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param keyed the keyed object * @return all custom audience members stored using the key of the object */ + @Override public @NotNull Audience custom(@NotNull Keyed keyed) { return custom(keyed.key()); } @@ -115,6 +128,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param key the key * @return all custom audience members stored using the key */ + @Override public @NotNull Audience custom(@NotNull Key key) { return Audience.audience(audience.iterable().custom(key)); } @@ -127,6 +141,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param filter the predicate * @return all custom audience members stored using the key */ + @Override public @NotNull Audience custom(@NotNull Keyed keyed, Predicate filter) { return custom(keyed.key(), filter); } @@ -139,6 +154,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param filter the predicate * @return all custom audience members stored using the key */ + @Override public @NotNull Audience custom(@NotNull Key key, Predicate filter) { return Audience.audience(audience.iterable().custom(key, filter)); } @@ -149,6 +165,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param filter the predicate * @return all matching custom audience members */ + @Override public @NotNull Audience customs(@NotNull Predicate filter) { return Audience.audience(audience.iterable().customs(filter)); } @@ -159,6 +176,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * @param filter the predicate * @return all matching audience members */ + @Override public @NotNull Audience all(@NotNull Predicate filter) { return Audience.audience(audience.iterable().all(filter)); } @@ -168,6 +186,7 @@ public Audiences(ServerProcess serverProcess, ConnectionManager connectionManage * * @return the registry */ + @Override public @NotNull AudienceRegistry registry() { return audience.iterable().registry(); } diff --git a/src/main/java/net/minestom/server/adventure/audience/AudienceManagerProvider.java b/src/main/java/net/minestom/server/adventure/audience/AudienceManagerProvider.java new file mode 100644 index 00000000000..a86ff2dfce9 --- /dev/null +++ b/src/main/java/net/minestom/server/adventure/audience/AudienceManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.adventure.audience; + +public interface AudienceManagerProvider { + AudienceManager getAudienceManager(); +} diff --git a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java index fda720adcc5..2b2183d4da5 100644 --- a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java @@ -2,10 +2,10 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; -import net.minestom.server.ServerProcess; import net.minestom.server.command.CommandManager; import net.minestom.server.command.ConsoleSender; import net.minestom.server.entity.Player; +import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -19,12 +19,12 @@ * A provider of iterable audiences. */ class IterableAudienceProvider implements AudienceProvider> { + private final ConnectionManager connectionManager; private final List console; private final AudienceRegistry registry = new AudienceRegistry(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new); - private final ServerProcess serverProcess; - protected IterableAudienceProvider(ServerProcess serverProcess, CommandManager commandManager) { - this.serverProcess = serverProcess; + protected IterableAudienceProvider(ConnectionManager connectionManager, CommandManager commandManager) { + this.connectionManager = connectionManager; this.console = List.of(commandManager.getConsoleSender()); } @@ -39,12 +39,12 @@ protected IterableAudienceProvider(ServerProcess serverProcess, CommandManager c @Override public @NotNull Iterable players() { - return serverProcess.getConnectionManager().getOnlinePlayers(); + return connectionManager.getOnlinePlayers(); } @Override public @NotNull Iterable players(@NotNull Predicate filter) { - return serverProcess.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList(); + return connectionManager.getOnlinePlayers().stream().filter(filter).toList(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index 2ee3e40f82d..6e74a495822 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -9,8 +9,7 @@ import net.kyori.adventure.sound.SoundStop; import net.kyori.adventure.text.Component; import net.kyori.adventure.title.TitlePart; -import net.minestom.server.ServerObject; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; @@ -28,7 +27,7 @@ /** * An audience implementation that sends grouped packets if possible. */ -public interface PacketGroupingAudience extends ForwardingAudience, ServerObject { +public interface PacketGroupingAudience extends ForwardingAudience { /** * Creates a packet grouping audience that copies an iterable of players. The @@ -38,11 +37,11 @@ public interface PacketGroupingAudience extends ForwardingAudience, ServerObject * @param players the players * @return the audience */ - static @NotNull PacketGroupingAudience of(ServerProcess serverProcess, @NotNull Collection players) { + static @NotNull PacketGroupingAudience of(ServerSettings serverSettings, @NotNull Collection players) { return new PacketGroupingAudience() { @Override - public ServerProcess getServerProcess() { - return serverProcess; + public ServerSettings getServerSettings() { + return serverSettings; } @Override @@ -52,6 +51,8 @@ public ServerProcess getServerProcess() { }; } + ServerSettings getServerSettings(); + /** * Gets an iterable of the players this audience contains. * @@ -65,12 +66,12 @@ public ServerProcess getServerProcess() { * @param packet the packet to broadcast */ default void sendGroupedPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(getServerProcess().getServerSetting(), getPlayers(), packet); + PacketUtils.sendGroupedPacket(getServerSettings(), getPlayers(), packet); } @Override default void sendMessage(@NotNull Identity source, @NotNull Component message, @NotNull MessageType type) { - Messenger.sendMessage(getServerProcess().getServerSetting(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); + Messenger.sendMessage(getServerSettings(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); } @Override @@ -100,12 +101,16 @@ default void resetTitle() { @Override default void showBossBar(@NotNull BossBar bar) { - getServerProcess().getBossBarManager().addBossBar(this.getPlayers(), bar); + for (Player player : this.getPlayers()) { + player.showBossBar(bar); + } } @Override default void hideBossBar(@NotNull BossBar bar) { - getServerProcess().getBossBarManager().removeBossBar(this.getPlayers(), bar); + for (Player player : this.getPlayers()) { + player.hideBossBar(bar); + } } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java index 88389a8ef0d..a77410af0d4 100644 --- a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java @@ -2,7 +2,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; import net.minestom.server.network.ConnectionManager; @@ -19,13 +19,16 @@ class SingleAudienceProvider implements AudienceProvider { protected final IterableAudienceProvider collection; protected final Audience players; protected final Audience server; - @NotNull - private final ServerProcess serverProcess; - - protected SingleAudienceProvider(ServerProcess serverProcess, ConnectionManager connectionManager, CommandManager commandManager) { - this.serverProcess = serverProcess; - this.collection = new IterableAudienceProvider(serverProcess, commandManager); - this.players = PacketGroupingAudience.of(serverProcess, connectionManager.getOnlinePlayers()); + private final ServerSettings serverSettings; + private final ConnectionManager connectionManager; + private final CommandManager commandManager; + + protected SingleAudienceProvider(ServerSettings serverSettings, ConnectionManager connectionManager, CommandManager commandManager) { + this.serverSettings = serverSettings; + this.connectionManager = connectionManager; + this.commandManager = commandManager; + this.collection = new IterableAudienceProvider(connectionManager, commandManager); + this.players = PacketGroupingAudience.of(serverSettings, connectionManager.getOnlinePlayers()); this.server = Audience.audience(this.players, commandManager.getConsoleSender()); } @@ -50,12 +53,12 @@ protected SingleAudienceProvider(ServerProcess serverProcess, ConnectionManager @Override public @NotNull Audience players(@NotNull Predicate filter) { - return PacketGroupingAudience.of(serverProcess, serverProcess.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); + return PacketGroupingAudience.of(serverSettings, connectionManager.getOnlinePlayers().stream().filter(filter).toList()); } @Override public @NotNull Audience console() { - return serverProcess.getCommandManager().getConsoleSender(); + return commandManager.getConsoleSender(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java index a7ee7e0fda6..38149ef97df 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarHolder.java @@ -2,7 +2,6 @@ import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; import net.minestom.server.Viewable; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.entity.Player; @@ -16,16 +15,14 @@ /** * A holder of a boss bar. This class is not intended for public use, instead you should - * use {@link BossBarManager} to manage boss bars for players. + * use {@link BossBarManagerImpl} to manage boss bars for players. */ final class BossBarHolder implements Viewable { final UUID uuid = UUID.randomUUID(); final Set players = new CopyOnWriteArraySet<>(); - private final ServerProcess serverProcess; final BossBar bar; - BossBarHolder(ServerProcess serverProcess, @NotNull BossBar bar) { - this.serverProcess = serverProcess; + BossBarHolder(@NotNull BossBar bar) { this.bar = bar; } @@ -75,9 +72,4 @@ public boolean removeViewer(@NotNull Player player) { public @NotNull Set getViewers() { return Collections.unmodifiableSet(this.players); } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java index df20f1977ef..45e0c0a3124 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java @@ -1,9 +1,10 @@ package net.minestom.server.adventure.bossbar; +import lombok.RequiredArgsConstructor; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; @@ -13,47 +14,40 @@ /** * A listener for boss bar updates. This class is not intended for public use and it is * automatically added to boss bars shown to players using the methods in - * {@link Audience}, instead you should use {@link BossBarManager} to manage boss bars + * {@link Audience}, instead you should use {@link BossBarManagerImpl} to manage boss bars * for players. */ +@RequiredArgsConstructor class BossBarListener implements BossBar.Listener { - private final ServerProcess serverProcess; - private final BossBarManager manager; - /** - * Creates a new boss bar listener. - * - * @param manager the manager instance - */ - BossBarListener(ServerProcess serverProcess, BossBarManager manager) { - this.serverProcess = serverProcess; - this.manager = manager; - } + private final ServerSettings serverSettings; + + private final BossBarManagerImpl manager; @Override public void bossBarNameChanged(@NotNull BossBar bar, @NotNull Component oldName, @NotNull Component newName) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createTitleUpdate(newName))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createTitleUpdate(newName))); } @Override public void bossBarProgressChanged(@NotNull BossBar bar, float oldProgress, float newProgress) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createPercentUpdate(newProgress))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createPercentUpdate(newProgress))); } @Override public void bossBarColorChanged(@NotNull BossBar bar, @NotNull BossBar.Color oldColor, @NotNull BossBar.Color newColor) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createColorUpdate(newColor))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createColorUpdate(newColor))); } @Override public void bossBarOverlayChanged(@NotNull BossBar bar, BossBar.@NotNull Overlay oldOverlay, BossBar.@NotNull Overlay newOverlay) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createOverlayUpdate(newOverlay))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createOverlayUpdate(newOverlay))); } @Override public void bossBarFlagsChanged(@NotNull BossBar bar, @NotNull Set flagsAdded, @NotNull Set flagsRemoved) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createFlagsUpdate())); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createFlagsUpdate())); } private void doIfRegistered(@NotNull BossBar bar, @NotNull Consumer consumer) { diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java index 95f1c38d74a..362caeabdf0 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManager.java @@ -2,13 +2,10 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; -import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; -import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; +import java.util.Collection; /** * Manages all boss bars known to this Minestom instance. Although this class can be used @@ -22,19 +19,7 @@ * @see Audience#showBossBar(BossBar) * @see Audience#hideBossBar(BossBar) */ -public class BossBarManager { - private final BossBarListener listener; - private final Map> playerBars = new ConcurrentHashMap<>(); - final Map bars = new ConcurrentHashMap<>(); - private final ServerProcess serverProcess; - - /** - * Creates a new boss bar manager. - */ - public BossBarManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - this.listener = new BossBarListener(serverProcess,this); - } +public interface BossBarManager { /** * Adds the specified player to the boss bar's viewers and spawns the boss bar, registering the @@ -43,13 +28,7 @@ public BossBarManager(ServerProcess serverProcess) { * @param player the intended viewer * @param bar the boss bar to show */ - public void addBossBar(@NotNull Player player, @NotNull BossBar bar) { - BossBarHolder holder = this.getOrCreateHandler(bar); - if (holder.addViewer(player)) { - player.sendPacket(holder.createAddPacket()); - this.playerBars.computeIfAbsent(player.getUuid(), uuid -> new HashSet<>()).add(holder); - } - } + void addBossBar(@NotNull Player player, @NotNull BossBar bar); /** * Removes the specified player from the boss bar's viewers and despawns the boss bar. @@ -57,13 +36,7 @@ public void addBossBar(@NotNull Player player, @NotNull BossBar bar) { * @param player the intended viewer * @param bar the boss bar to hide */ - public void removeBossBar(@NotNull Player player, @NotNull BossBar bar) { - BossBarHolder holder = this.bars.get(bar); - if (holder != null && holder.removeViewer(player)) { - player.sendPacket(holder.createRemovePacket()); - this.removePlayer(player, holder); - } - } + void removeBossBar(@NotNull Player player, @NotNull BossBar bar); /** * Adds the specified players to the boss bar's viewers and spawns the boss bar, registering the @@ -72,13 +45,7 @@ public void removeBossBar(@NotNull Player player, @NotNull BossBar bar) { * @param players the players * @param bar the boss bar */ - public void addBossBar(@NotNull Collection players, @NotNull BossBar bar) { - BossBarHolder holder = this.getOrCreateHandler(bar); - Collection addedPlayers = players.stream().filter(holder::addViewer).toList(); - if (!addedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), addedPlayers, holder.createAddPacket()); - } - } + void addBossBar(@NotNull Collection players, @NotNull BossBar bar); /** * Removes the specified players from the boss bar's viewers and despawns the boss bar. @@ -86,30 +53,14 @@ public void addBossBar(@NotNull Collection players, @NotNull BossBar bar * @param players the intended viewers * @param bar the boss bar to hide */ - public void removeBossBar(@NotNull Collection players, @NotNull BossBar bar) { - BossBarHolder holder = this.bars.get(bar); - if (holder != null) { - Collection removedPlayers = players.stream().filter(holder::removeViewer).toList(); - if (!removedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), removedPlayers, holder.createRemovePacket()); - } - } - } + void removeBossBar(@NotNull Collection players, @NotNull BossBar bar); /** * Completely destroys a boss bar, removing it from all players. * * @param bossBar the boss bar */ - public void destroyBossBar(@NotNull BossBar bossBar) { - BossBarHolder holder = this.bars.remove(bossBar); - if (holder != null) { - PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), holder.players, holder.createRemovePacket()); - for (Player player : holder.players) { - this.removePlayer(player, holder); - } - } - } + void destroyBossBar(@NotNull BossBar bossBar); /** * Removes a player from all of their boss bars. Note that this method does not @@ -118,14 +69,7 @@ public void destroyBossBar(@NotNull BossBar bossBar) { * * @param player the player */ - public void removeAllBossBars(@NotNull Player player) { - Set holders = this.playerBars.remove(player.getUuid()); - if (holders != null) { - for (BossBarHolder holder : holders) { - holder.removeViewer(player); - } - } - } + void removeAllBossBars(@NotNull Player player); /** * Gets a collection of all boss bars currently visible to a given player. @@ -133,11 +77,7 @@ public void removeAllBossBars(@NotNull Player player) { * @param player the player * @return the boss bars */ - public @NotNull Collection getPlayerBossBars(@NotNull Player player) { - Collection holders = this.playerBars.get(player.getUuid()); - return holders != null ? - holders.stream().map(holder -> holder.bar).toList() : List.of(); - } + @NotNull Collection getPlayerBossBars(@NotNull Player player); /** * Gets all the players for whom the given boss bar is currently visible. @@ -145,33 +85,5 @@ public void removeAllBossBars(@NotNull Player player) { * @param bossBar the boss bar * @return the players */ - public @NotNull Collection getBossBarViewers(@NotNull BossBar bossBar) { - BossBarHolder holder = this.bars.get(bossBar); - return holder != null ? - Collections.unmodifiableCollection(holder.players) : List.of(); - } - - /** - * Gets or creates a handler for this bar. - * - * @param bar the bar - * @return the handler - */ - private @NotNull BossBarHolder getOrCreateHandler(@NotNull BossBar bar) { - return this.bars.computeIfAbsent(bar, bossBar -> { - BossBarHolder holder = new BossBarHolder(serverProcess, bossBar); - bossBar.addListener(this.listener); - return holder; - }); - } - - private void removePlayer(Player player, BossBarHolder holder) { - Set holders = this.playerBars.get(player.getUuid()); - if (holders != null) { - holders.remove(holder); - if (holders.isEmpty()) { - this.playerBars.remove(player.getUuid()); - } - } - } + @NotNull Collection getBossBarViewers(@NotNull BossBar bossBar); } diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java new file mode 100644 index 00000000000..a62f1c9a671 --- /dev/null +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java @@ -0,0 +1,122 @@ +package net.minestom.server.adventure.bossbar; + +import net.kyori.adventure.bossbar.BossBar; +import net.minestom.server.ServerSettings; +import net.minestom.server.entity.Player; +import net.minestom.server.utils.PacketUtils; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class BossBarManagerImpl implements BossBarManager { + private final BossBarListener listener; + private final Map> playerBars = new ConcurrentHashMap<>(); + final Map bars = new ConcurrentHashMap<>(); + private final ServerSettings serverSettings; + + /** + * Creates a new boss bar manager. + */ + public BossBarManagerImpl(ServerSettings serverSettings) { + this.serverSettings = serverSettings; + this.listener = new BossBarListener(serverSettings,this); + } + + @Override + public void addBossBar(@NotNull Player player, @NotNull BossBar bar) { + BossBarHolder holder = this.getOrCreateHandler(bar); + if (holder.addViewer(player)) { + player.sendPacket(holder.createAddPacket()); + this.playerBars.computeIfAbsent(player.getUuid(), uuid -> new HashSet<>()).add(holder); + } + } + + @Override + public void removeBossBar(@NotNull Player player, @NotNull BossBar bar) { + BossBarHolder holder = this.bars.get(bar); + if (holder != null && holder.removeViewer(player)) { + player.sendPacket(holder.createRemovePacket()); + this.removePlayer(player, holder); + } + } + + @Override + public void addBossBar(@NotNull Collection players, @NotNull BossBar bar) { + BossBarHolder holder = this.getOrCreateHandler(bar); + Collection addedPlayers = players.stream().filter(holder::addViewer).toList(); + if (!addedPlayers.isEmpty()) { + PacketUtils.sendGroupedPacket(serverSettings, addedPlayers, holder.createAddPacket()); + } + } + + @Override + public void removeBossBar(@NotNull Collection players, @NotNull BossBar bar) { + BossBarHolder holder = this.bars.get(bar); + if (holder != null) { + Collection removedPlayers = players.stream().filter(holder::removeViewer).toList(); + if (!removedPlayers.isEmpty()) { + PacketUtils.sendGroupedPacket(serverSettings, removedPlayers, holder.createRemovePacket()); + } + } + } + + @Override + public void destroyBossBar(@NotNull BossBar bossBar) { + BossBarHolder holder = this.bars.remove(bossBar); + if (holder != null) { + PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createRemovePacket()); + for (Player player : holder.players) { + this.removePlayer(player, holder); + } + } + } + + @Override + public void removeAllBossBars(@NotNull Player player) { + Set holders = this.playerBars.remove(player.getUuid()); + if (holders != null) { + for (BossBarHolder holder : holders) { + holder.removeViewer(player); + } + } + } + + @Override + public @NotNull Collection getPlayerBossBars(@NotNull Player player) { + Collection holders = this.playerBars.get(player.getUuid()); + return holders != null ? + holders.stream().map(holder -> holder.bar).toList() : List.of(); + } + + @Override + public @NotNull Collection getBossBarViewers(@NotNull BossBar bossBar) { + BossBarHolder holder = this.bars.get(bossBar); + return holder != null ? + Collections.unmodifiableCollection(holder.players) : List.of(); + } + + /** + * Gets or creates a handler for this bar. + * + * @param bar the bar + * @return the handler + */ + private @NotNull BossBarHolder getOrCreateHandler(@NotNull BossBar bar) { + return this.bars.computeIfAbsent(bar, bossBar -> { + BossBarHolder holder = new BossBarHolder(bossBar); + bossBar.addListener(this.listener); + return holder; + }); + } + + private void removePlayer(Player player, BossBarHolder holder) { + Set holders = this.playerBars.get(player.getUuid()); + if (holders != null) { + holders.remove(holder); + if (holders.isEmpty()) { + this.playerBars.remove(player.getUuid()); + } + } + } +} diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerProvider.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerProvider.java new file mode 100644 index 00000000000..6b812f98be1 --- /dev/null +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.adventure.bossbar; + +public interface BossBarManagerProvider { + BossBarManager getBossBarManager(); +} diff --git a/src/main/java/net/minestom/server/command/CommandManager.java b/src/main/java/net/minestom/server/command/CommandManager.java index 2c785c6d694..7e6fb77ae7f 100644 --- a/src/main/java/net/minestom/server/command/CommandManager.java +++ b/src/main/java/net/minestom/server/command/CommandManager.java @@ -1,47 +1,23 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.command.builder.CommandResult; -import net.minestom.server.command.builder.ParsedCommand; import net.minestom.server.entity.Player; -import net.minestom.server.event.player.PlayerCommandEvent; import net.minestom.server.network.packet.server.play.DeclareCommandsPacket; import net.minestom.server.utils.callback.CommandCallback; -import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.Callable; +import java.util.Set; /** * Manager used to register {@link Command commands}. *

        * It is also possible to simulate a command using {@link #execute(CommandSender, String)}. */ -public final class CommandManager { - private static final boolean ASYNC_VIRTUAL = Boolean.getBoolean("minestom.command.async-virtual"); - - public static final String COMMAND_PREFIX = "/"; - - private final ServerSender serverSender; - private final ConsoleSender consoleSender; - private final CommandParser parser = CommandParser.parser(); - private final CommandDispatcher dispatcher = new CommandDispatcher(this); - private final Map commandMap = new HashMap<>(); - private final Set commands = new HashSet<>(); - - private CommandCallback unknownCommandCallback; - private final ServerProcess serverProcess; - - public CommandManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - this.serverSender = new ServerSender(serverProcess); - this.consoleSender = new ConsoleSender(serverProcess); - } +public interface CommandManager { + String COMMAND_PREFIX = "/"; /** * Registers a {@link Command}. @@ -49,20 +25,7 @@ public CommandManager(ServerProcess serverProcess) { * @param command the command to register * @throws IllegalStateException if a command with the same name already exists */ - public synchronized void register(@NotNull Command command) { - Check.stateCondition(commandExists(command.getName()), - "A command with the name " + command.getName() + " is already registered!"); - if (command.getAliases() != null) { - for (String alias : command.getAliases()) { - Check.stateCondition(commandExists(alias), - "A command with the name " + alias + " is already registered!"); - } - } - commands.add(command); - for (String name : command.getNames()) { - commandMap.put(name, command); - } - } + void register(@NotNull Command command); /** * Removes a command from the currently registered commands. @@ -70,12 +33,7 @@ public synchronized void register(@NotNull Command command) { * * @param command the command to remove */ - public void unregister(@NotNull Command command) { - commands.remove(command); - for (String name : command.getNames()) { - commandMap.remove(name); - } - } + void unregister(@NotNull Command command); /** * Gets the {@link Command} registered by {@link #register(Command)}. @@ -83,9 +41,7 @@ public void unregister(@NotNull Command command) { * @param commandName the command name * @return the command associated with the name, null if not any */ - public @Nullable Command getCommand(@NotNull String commandName) { - return commandMap.get(commandName.toLowerCase(Locale.ROOT)); - } + @Nullable Command getCommand(@NotNull String commandName); /** * Gets if a command with the name {@code commandName} already exists or not. @@ -93,7 +49,7 @@ public void unregister(@NotNull Command command) { * @param commandName the command name to check * @return true if the command does exist */ - public boolean commandExists(@NotNull String commandName) { + default boolean commandExists(@NotNull String commandName) { return getCommand(commandName) != null; } @@ -104,57 +60,7 @@ public boolean commandExists(@NotNull String commandName) { * @param rawCommand the raw command string (without the command prefix) * @return the execution result */ - public @NotNull CommandResult execute(@NotNull CommandSender sender, @NotNull String rawCommand) { - Callable callable = () -> { - var command = rawCommand.trim(); - // Command event - if (sender instanceof Player player) { - PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, command); - serverProcess.getGlobalEventHandler().call(playerCommandEvent); - if (playerCommandEvent.isCancelled()) - return CommandResult.of(CommandResult.Type.CANCELLED, command); - command = playerCommandEvent.getCommand(); - } - // Process the command - final CommandParser.Result parsedCommand = parseCommand(sender, command); - final ExecutableCommand executable = parsedCommand.executable(); - final ExecutableCommand.Result executeResult = executable.execute(sender); - final CommandResult result = resultConverter(executable, executeResult, command); - if (result.getType() == CommandResult.Type.UNKNOWN) { - if (unknownCommandCallback != null) { - this.unknownCommandCallback.apply(sender, command); - } - } - return result; - }; - - - try { - if (ASYNC_VIRTUAL) { - class Reflection { - static Method startVirtualThread = null; - } - if (Reflection.startVirtualThread == null) { - Reflection.startVirtualThread = Thread.class.getDeclaredMethod("startVirtualThread", Runnable.class); - Reflection.startVirtualThread.setAccessible(true); - } - - Reflection.startVirtualThread.invoke(null, (Runnable) () -> { - try { - callable.call(); - } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); - } - }); - return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); - } else { - return callable.call(); - } - } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); - return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); - } - } + @NotNull CommandResult execute(@NotNull CommandSender sender, @NotNull String rawCommand); /** * Executes the command using a {@link ServerSender}. This can be used @@ -162,22 +68,16 @@ class Reflection { * * @see #execute(CommandSender, String) */ - public @NotNull CommandResult executeServerCommand(@NotNull String command) { - return execute(serverSender, command); - } + @NotNull CommandResult executeServerCommand(@NotNull String command); - public @NotNull CommandDispatcher getDispatcher() { - return dispatcher; - } + @NotNull CommandDispatcher getDispatcher(); /** * Gets the callback executed once an unknown command is run. * * @return the unknown command callback, null if not any */ - public @Nullable CommandCallback getUnknownCommandCallback() { - return unknownCommandCallback; - } + @Nullable CommandCallback getUnknownCommandCallback(); /** * Sets the callback executed once an unknown command is run. @@ -185,18 +85,14 @@ class Reflection { * @param unknownCommandCallback the new unknown command callback, * setting it to null mean that nothing will be executed */ - public void setUnknownCommandCallback(@Nullable CommandCallback unknownCommandCallback) { - this.unknownCommandCallback = unknownCommandCallback; - } + void setUnknownCommandCallback(@Nullable CommandCallback unknownCommandCallback); /** * Gets the {@link ConsoleSender} (which is used as a {@link CommandSender}). * * @return the {@link ConsoleSender} */ - public @NotNull ConsoleSender getConsoleSender() { - return consoleSender; - } + @NotNull ConsoleSender getConsoleSender(); /** * Gets the {@link DeclareCommandsPacket} for a specific player. @@ -206,13 +102,9 @@ public void setUnknownCommandCallback(@Nullable CommandCallback unknownCommandCa * @param player the player to get the commands packet * @return the {@link DeclareCommandsPacket} for {@code player} */ - public @NotNull DeclareCommandsPacket createDeclareCommandsPacket(@NotNull Player player) { - return GraphConverter.createPacket(getGraph(), player); - } + @NotNull DeclareCommandsPacket createDeclareCommandsPacket(@NotNull Player player); - public @NotNull Set<@NotNull Command> getCommands() { - return Collections.unmodifiableSet(commands); - } + @NotNull Set<@NotNull Command> getCommands(); /** * Parses the command based on the registered commands @@ -220,23 +112,5 @@ public void setUnknownCommandCallback(@Nullable CommandCallback unknownCommandCa * @param input commands string without prefix * @return the parsing result */ - public CommandParser.Result parseCommand(@NotNull CommandSender sender, String input) { - return parser.parse(sender, getGraph(), input); - } - - private Graph getGraph() { - //todo cache - return Graph.merge(commands); - } - - private static CommandResult resultConverter(ExecutableCommand executable, - ExecutableCommand.Result newResult, - String input) { - return CommandResult.of(switch (newResult.type()) { - case SUCCESS -> CommandResult.Type.SUCCESS; - case CANCELLED, PRECONDITION_FAILED, EXECUTOR_EXCEPTION -> CommandResult.Type.CANCELLED; - case INVALID_SYNTAX -> CommandResult.Type.INVALID_SYNTAX; - case UNKNOWN -> CommandResult.Type.UNKNOWN; - }, input, ParsedCommand.fromExecutable(executable), newResult.commandData()); - } + CommandParser.Result parseCommand(@NotNull CommandSender sender, String input); } diff --git a/src/main/java/net/minestom/server/command/CommandManagerImpl.java b/src/main/java/net/minestom/server/command/CommandManagerImpl.java new file mode 100644 index 00000000000..c5485742395 --- /dev/null +++ b/src/main/java/net/minestom/server/command/CommandManagerImpl.java @@ -0,0 +1,176 @@ +package net.minestom.server.command; + +import lombok.RequiredArgsConstructor; +import net.minestom.server.command.builder.Command; +import net.minestom.server.command.builder.CommandDispatcher; +import net.minestom.server.command.builder.CommandResult; +import net.minestom.server.command.builder.ParsedCommand; +import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.event.player.PlayerCommandEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.network.packet.server.play.DeclareCommandsPacket; +import net.minestom.server.utils.callback.CommandCallback; +import net.minestom.server.utils.validate.Check; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.Callable; + +@RequiredArgsConstructor +public final class CommandManagerImpl implements CommandManager { + + private final ExceptionHandler exceptionHandler; + private final EventNode globalEventHandler; + + private static final boolean ASYNC_VIRTUAL = Boolean.getBoolean("minestom.command.async-virtual"); + + private final ServerSender serverSender = new ServerSender(); + private final ConsoleSender consoleSender = new ConsoleSender(); + private final CommandParser parser = CommandParser.parser(); + private final CommandDispatcher dispatcher = new CommandDispatcher(this); + private final Map commandMap = new HashMap<>(); + private final Set commands = new HashSet<>(); + + private CommandCallback unknownCommandCallback; + + @Override + public synchronized void register(@NotNull Command command) { + Check.stateCondition(commandExists(command.getName()), + "A command with the name " + command.getName() + " is already registered!"); + if (command.getAliases() != null) { + for (String alias : command.getAliases()) { + Check.stateCondition(commandExists(alias), + "A command with the name " + alias + " is already registered!"); + } + } + commands.add(command); + for (String name : command.getNames()) { + commandMap.put(name, command); + } + } + + @Override + public void unregister(@NotNull Command command) { + commands.remove(command); + for (String name : command.getNames()) { + commandMap.remove(name); + } + } + + @Override + public @Nullable Command getCommand(@NotNull String commandName) { + return commandMap.get(commandName.toLowerCase(Locale.ROOT)); + } + + @Override + public @NotNull CommandResult execute(@NotNull CommandSender sender, @NotNull String rawCommand) { + Callable callable = () -> { + var command = rawCommand.trim(); + // Command event + if (sender instanceof Player player) { + PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, command); + globalEventHandler.call(playerCommandEvent); + if (playerCommandEvent.isCancelled()) + return CommandResult.of(CommandResult.Type.CANCELLED, command); + command = playerCommandEvent.getCommand(); + } + // Process the command + final CommandParser.Result parsedCommand = parseCommand(sender, command); + final ExecutableCommand executable = parsedCommand.executable(); + final ExecutableCommand.Result executeResult = executable.execute(sender); + final CommandResult result = resultConverter(executable, executeResult, command); + if (result.getType() == CommandResult.Type.UNKNOWN) { + if (unknownCommandCallback != null) { + this.unknownCommandCallback.apply(sender, command); + } + } + return result; + }; + + + try { + if (ASYNC_VIRTUAL) { + class Reflection { + static Method startVirtualThread = null; + } + if (Reflection.startVirtualThread == null) { + Reflection.startVirtualThread = Thread.class.getDeclaredMethod("startVirtualThread", Runnable.class); + Reflection.startVirtualThread.setAccessible(true); + } + + Reflection.startVirtualThread.invoke(null, (Runnable) () -> { + try { + callable.call(); + } catch (Exception e) { + exceptionHandler.handleException(e); + } + }); + return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); + } else { + return callable.call(); + } + } catch (Exception e) { + exceptionHandler.handleException(e); + return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); + } + } + + + @Override + public @NotNull CommandResult executeServerCommand(@NotNull String command) { + return execute(serverSender, command); + } + + @Override + public @NotNull CommandDispatcher getDispatcher() { + return dispatcher; + } + + @Override + public @Nullable CommandCallback getUnknownCommandCallback() { + return unknownCommandCallback; + } + + @Override + public void setUnknownCommandCallback(@Nullable CommandCallback unknownCommandCallback) { + this.unknownCommandCallback = unknownCommandCallback; + } + + @Override + public @NotNull ConsoleSender getConsoleSender() { + return consoleSender; + } + + @Override + public @NotNull DeclareCommandsPacket createDeclareCommandsPacket(@NotNull Player player) { + return GraphConverter.createPacket(getGraph(), player); + } + + @Override + public @NotNull Set<@NotNull Command> getCommands() { + return Collections.unmodifiableSet(commands); + } + + @Override + public CommandParser.Result parseCommand(@NotNull CommandSender sender, String input) { + return parser.parse(sender, getGraph(), input); + } + + private Graph getGraph() { + //todo cache + return Graph.merge(commands); + } + + private static CommandResult resultConverter(ExecutableCommand executable, ExecutableCommand.Result newResult, String input) { + return CommandResult.of(switch (newResult.type()) { + case SUCCESS -> CommandResult.Type.SUCCESS; + case CANCELLED, PRECONDITION_FAILED, EXECUTOR_EXCEPTION -> CommandResult.Type.CANCELLED; + case INVALID_SYNTAX -> CommandResult.Type.INVALID_SYNTAX; + case UNKNOWN -> CommandResult.Type.UNKNOWN; + }, input, ParsedCommand.fromExecutable(executable), newResult.commandData()); + } +} diff --git a/src/main/java/net/minestom/server/command/CommandManagerProvider.java b/src/main/java/net/minestom/server/command/CommandManagerProvider.java new file mode 100644 index 00000000000..6b363155bdd --- /dev/null +++ b/src/main/java/net/minestom/server/command/CommandManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.command; + +public interface CommandManagerProvider { + CommandManager getCommandManager(); +} diff --git a/src/main/java/net/minestom/server/command/CommandSender.java b/src/main/java/net/minestom/server/command/CommandSender.java index b0d0a7ef641..20a22bac01f 100644 --- a/src/main/java/net/minestom/server/command/CommandSender.java +++ b/src/main/java/net/minestom/server/command/CommandSender.java @@ -3,7 +3,6 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identified; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerObject; import net.minestom.server.entity.Player; import net.minestom.server.permission.PermissionHandler; import net.minestom.server.tag.Taggable; @@ -14,7 +13,7 @@ *

        * Main implementations are {@link Player} and {@link ConsoleSender}. */ -public interface CommandSender extends PermissionHandler, Audience, Taggable, Identified, ServerObject { +public interface CommandSender extends PermissionHandler, Audience, Taggable, Identified { /** * Sends a raw string message. diff --git a/src/main/java/net/minestom/server/command/ConsoleSender.java b/src/main/java/net/minestom/server/command/ConsoleSender.java index 0b9e2db0494..0586675f10f 100644 --- a/src/main/java/net/minestom/server/command/ConsoleSender.java +++ b/src/main/java/net/minestom/server/command/ConsoleSender.java @@ -5,7 +5,6 @@ import net.kyori.adventure.pointer.Pointers; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.logger.slf4j.ComponentLogger; -import net.minestom.server.ServerProcess; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -27,12 +26,6 @@ public class ConsoleSender implements CommandSender { .withStatic(Identity.UUID, this.identity.uuid()) .build(); - private final ServerProcess serverProcess; - - public ConsoleSender(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } - @Override public void sendMessage(@NotNull String message) { LOGGER.info(message); @@ -59,11 +52,6 @@ public ConsoleSender asConsole() { return this; } - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } - @Override public @NotNull TagHandler tagHandler() { return tagHandler; diff --git a/src/main/java/net/minestom/server/command/ServerSender.java b/src/main/java/net/minestom/server/command/ServerSender.java index 3080090d05b..114c390aff0 100644 --- a/src/main/java/net/minestom/server/command/ServerSender.java +++ b/src/main/java/net/minestom/server/command/ServerSender.java @@ -2,7 +2,6 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; -import net.minestom.server.ServerProcess; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; @@ -13,7 +12,7 @@ import java.util.Set; /** - * Sender used in {@link CommandManager#executeServerCommand(String)}. + * Sender used in {@link CommandManagerImpl#executeServerCommand(String)}. *

        * Although this class implemented {@link CommandSender} and thus {@link Audience}, no * data can be sent to this sender because it's purpose is to process the data of @@ -24,12 +23,6 @@ public class ServerSender implements CommandSender { private final Set permissions = Collections.unmodifiableSet(new HashSet<>()); private final TagHandler tagHandler = TagHandler.newHandler(); - private final ServerProcess serverProcess; - - public ServerSender(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } - @NotNull @Override public Set getAllPermissions() { @@ -45,9 +38,4 @@ public Set getAllPermissions() { public @NotNull Identity identity() { return Identity.nil(); } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/command/builder/Command.java b/src/main/java/net/minestom/server/command/builder/Command.java index dc41175422e..7c061089f10 100644 --- a/src/main/java/net/minestom/server/command/builder/Command.java +++ b/src/main/java/net/minestom/server/command/builder/Command.java @@ -2,12 +2,16 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import net.minestom.server.ServerSettings; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentLiteral; import net.minestom.server.command.builder.arguments.ArgumentType; import net.minestom.server.command.builder.arguments.ArgumentWord; import net.minestom.server.command.builder.condition.CommandCondition; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.utils.StringUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -16,7 +20,10 @@ import org.slf4j.LoggerFactory; import java.util.*; -import java.util.function.*; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; import java.util.stream.Stream; /** @@ -219,8 +226,8 @@ public Collection addConditionalSyntax(@Nullable CommandCondition * @return the newly created {@link CommandSyntax syntaxes}. */ @ApiStatus.Experimental - public @NotNull Collection addSyntax(@NotNull CommandExecutor executor, @NotNull String format) { - return addSyntax(executor, ArgumentType.generate(format)); + public @NotNull Collection addSyntax(@NotNull CommandExecutor executor, CommandManager commandManager, ServerSettings serverSettings, InstanceManager instanceManager, ConnectionManager connectionManager, @NotNull String format) { + return addSyntax(executor, ArgumentType.generate(format, commandManager, serverSettings, instanceManager, connectionManager)); } /** diff --git a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java index d0edd70c39c..10b66447279 100644 --- a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java +++ b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java @@ -2,10 +2,13 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; -import net.minestom.server.ServerProcess; import net.minestom.server.command.CommandManager; +import net.minestom.server.command.CommandManagerImpl; import net.minestom.server.command.CommandParser; import net.minestom.server.command.CommandSender; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.exception.ExceptionHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -26,8 +29,8 @@ public CommandDispatcher(CommandManager manager) { this.manager = manager; } - public CommandDispatcher(ServerProcess serverProcess) { - this(new CommandManager(serverProcess)); + public CommandDispatcher(ExceptionHandler exceptionHandler, EventNode globalEventHandler) { + this(new CommandManagerImpl(exceptionHandler, globalEventHandler)); } /** diff --git a/src/main/java/net/minestom/server/command/builder/CommandSyntax.java b/src/main/java/net/minestom/server/command/builder/CommandSyntax.java index 5171e1919ca..644404d7816 100644 --- a/src/main/java/net/minestom/server/command/builder/CommandSyntax.java +++ b/src/main/java/net/minestom/server/command/builder/CommandSyntax.java @@ -1,5 +1,6 @@ package net.minestom.server.command.builder; +import net.minestom.server.command.CommandManagerImpl; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.condition.CommandCondition; @@ -11,7 +12,6 @@ import java.util.Arrays; import java.util.Map; import java.util.function.Function; -import java.util.function.Supplier; /** * Represents a syntax in {@link Command} @@ -61,7 +61,7 @@ public CommandCondition getCommandCondition() { *

        * Be aware that changing the command condition will not automatically update players auto-completion. * You can create a new packet containing the changes with - * {@link net.minestom.server.command.CommandManager#createDeclareCommandsPacket(Player)}. + * {@link CommandManagerImpl#createDeclareCommandsPacket(Player)}. * * @param commandCondition the new command condition, null to remove it */ diff --git a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java index 5d565382686..1ec4f0c629a 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentCommand.java @@ -1,5 +1,6 @@ package net.minestom.server.command.builder.arguments; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.command.builder.CommandResult; @@ -11,12 +12,14 @@ public class ArgumentCommand extends Argument { public static final int INVALID_COMMAND_ERROR = 1; + private final CommandManager commandManager; private boolean onlyCorrect; private String shortcut = ""; - public ArgumentCommand(@NotNull String id) { + public ArgumentCommand(CommandManager commandManager, @NotNull String id) { super(id, true, true); + this.commandManager = commandManager; } @NotNull @@ -25,7 +28,7 @@ public CommandResult parse(@NotNull CommandSender sender, @NotNull String input) final String commandString = !shortcut.isEmpty() ? shortcut + StringUtils.SPACE + input : input; - CommandDispatcher dispatcher = sender.getServerProcess().getCommandManager().getDispatcher(); + CommandDispatcher dispatcher = commandManager.getDispatcher(); CommandResult result = dispatcher.parse(sender, commandString); if (onlyCorrect && result.getType() != CommandResult.Type.SUCCESS) diff --git a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentType.java b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentType.java index 6722e6a72c9..bb797ce2450 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/ArgumentType.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/ArgumentType.java @@ -1,5 +1,7 @@ package net.minestom.server.command.builder.arguments; +import net.minestom.server.ServerSettings; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.builder.arguments.minecraft.*; import net.minestom.server.command.builder.arguments.minecraft.registry.ArgumentEnchantment; import net.minestom.server.command.builder.arguments.minecraft.registry.ArgumentEntityType; @@ -12,6 +14,8 @@ import net.minestom.server.command.builder.arguments.relative.ArgumentRelativeVec2; import net.minestom.server.command.builder.arguments.relative.ArgumentRelativeVec3; import net.minestom.server.command.builder.parser.ArgumentParser; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -96,8 +100,8 @@ public static ArgumentStringArray StringArray(@NotNull String id) { /** * @see ArgumentCommand */ - public static ArgumentCommand Command(@NotNull String id) { - return new ArgumentCommand(id); + public static ArgumentCommand Command(@NotNull String id, CommandManager commandManager) { + return new ArgumentCommand(commandManager, id); } /** @@ -120,8 +124,8 @@ public static ArgumentColor Color(@NotNull String id) { /** * @see ArgumentTime */ - public static ArgumentTime Time(@NotNull String id) { - return new ArgumentTime(id); + public static ArgumentTime Time(@NotNull String id, ServerSettings serverSettings) { + return new ArgumentTime(id, serverSettings); } /** @@ -190,8 +194,8 @@ public static ArgumentFloatRange FloatRange(@NotNull String id) { /** * @see ArgumentEntity */ - public static ArgumentEntity Entity(@NotNull String id) { - return new ArgumentEntity(id); + public static ArgumentEntity Entity(@NotNull String id, InstanceManager instanceManager, ConnectionManager connectionManager) { + return new ArgumentEntity(id, instanceManager, connectionManager); } /** @@ -258,8 +262,8 @@ public static ArgumentRelativeVec2 RelativeVec2(@NotNull String id) { * Note: this feature is in beta and is very likely to change depending on feedback. */ @ApiStatus.Experimental - public static Argument[] generate(@NotNull String format) { - return ArgumentParser.generate(format); + public static Argument[] generate(@NotNull String format, CommandManager commandManager, ServerSettings serverSettings, InstanceManager instanceManager, ConnectionManager connectionManager) { + return ArgumentParser.generate(format, commandManager, serverSettings, instanceManager, connectionManager); } /** @@ -271,10 +275,10 @@ public static ArgumentLong Long(@NotNull String id) { /** * @see ArgumentEntity - * @deprecated use {@link #Entity(String)} + * @deprecated use {@link #Entity(String, InstanceManager, ConnectionManager)} */ @Deprecated - public static ArgumentEntity Entities(@NotNull String id) { - return new ArgumentEntity(id); + public static ArgumentEntity Entities(@NotNull String id, InstanceManager instanceManager, ConnectionManager connectionManager) { + return new ArgumentEntity(id, instanceManager, connectionManager); } } diff --git a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentEntity.java b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentEntity.java index 8754dba2cba..5ecca7076b7 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentEntity.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentEntity.java @@ -5,6 +5,8 @@ import net.minestom.server.command.builder.exception.ArgumentSyntaxException; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.GameMode; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.utils.StringUtils; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.entity.EntityFinder; @@ -47,12 +49,16 @@ public class ArgumentEntity extends Argument { "distance", "dx", "dy", "dz", "scores", "tag", "team", "limit", "sort", "level", "gamemode", "x_rotation", "y_rotation", "type", "advancements", "predicate"); + private final InstanceManager instanceManager; + private final ConnectionManager connectionManager; private boolean onlySingleEntity; private boolean onlyPlayers; - public ArgumentEntity(String id) { + public ArgumentEntity(String id, InstanceManager instanceManager, ConnectionManager connectionManager) { super(id, true); + this.instanceManager = instanceManager; + this.connectionManager = connectionManager; } public ArgumentEntity singleEntity(boolean singleEntity) { @@ -68,42 +74,13 @@ public ArgumentEntity onlyPlayers(boolean onlyPlayers) { @NotNull @Override public EntityFinder parse(@NotNull CommandSender sender, @NotNull String input) throws ArgumentSyntaxException { - return staticParse(sender, input, onlySingleEntity, onlyPlayers); - } - - @Override - public String parser() { - return "minecraft:entity"; - } - - @Override - public byte @Nullable [] nodeProperties() { - return BinaryWriter.makeArray(packetWriter -> { - byte mask = 0; - if (this.isOnlySingleEntity()) { - mask |= 0x01; - } - if (this.isOnlyPlayers()) { - mask |= 0x02; - } - packetWriter.writeByte(mask); - }); - } - - /** - * @deprecated use {@link Argument#parse(CommandSender, Argument)} - */ - @Deprecated - @NotNull - public static EntityFinder staticParse(@NotNull CommandSender sender, @NotNull String input, - boolean onlySingleEntity, boolean onlyPlayers) throws ArgumentSyntaxException { // Check for raw player name or UUID if (!input.contains(SELECTOR_PREFIX) && !input.contains(StringUtils.SPACE)) { // Check if the input is a valid UUID try { final UUID uuid = UUID.fromString(input); - return new EntityFinder() + return new EntityFinder(instanceManager, connectionManager) .setTargetSelector(EntityFinder.TargetSelector.MINESTOM_UUID) .setConstantUuid(uuid); } catch (IllegalArgumentException ignored) { @@ -111,7 +88,7 @@ public static EntityFinder staticParse(@NotNull CommandSender sender, @NotNull S // Check if the input is a valid player name if (USERNAME_PATTERN.matcher(input).matches()) { - return new EntityFinder() + return new EntityFinder(instanceManager, connectionManager) .setTargetSelector(EntityFinder.TargetSelector.MINESTOM_USERNAME) .setConstantName(input); } @@ -140,7 +117,7 @@ public static EntityFinder staticParse(@NotNull CommandSender sender, @NotNull S throw new ArgumentSyntaxException("Argument requires only players", input, ONLY_PLAYERS_ERROR); // Create the EntityFinder which will be used for the rest of the parsing - final EntityFinder entityFinder = new EntityFinder() + final EntityFinder entityFinder = new EntityFinder(instanceManager, connectionManager) .setTargetSelector(toTargetSelector(selectorVariable)); // The selector is a single selector variable which verify all the conditions @@ -152,6 +129,25 @@ public static EntityFinder staticParse(@NotNull CommandSender sender, @NotNull S return parseStructure(sender, input, entityFinder, structure); } + @Override + public String parser() { + return "minecraft:entity"; + } + + @Override + public byte @Nullable [] nodeProperties() { + return BinaryWriter.makeArray(packetWriter -> { + byte mask = 0; + if (this.isOnlySingleEntity()) { + mask |= 0x01; + } + if (this.isOnlyPlayers()) { + mask |= 0x02; + } + packetWriter.writeByte(mask); + }); + } + @NotNull private static EntityFinder parseStructure(@NotNull CommandSender sender, @NotNull String input, diff --git a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java index fb197c8fcec..cd8cec313d6 100644 --- a/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java +++ b/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentTime.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.chars.CharArrayList; import it.unimi.dsi.fastutil.chars.CharList; +import net.minestom.server.ServerSettings; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.exception.ArgumentSyntaxException; @@ -24,11 +25,13 @@ public class ArgumentTime extends Argument { public static final int NO_NUMBER = -3; private static final CharList SUFFIXES = new CharArrayList(new char[]{'d', 's', 't'}); + private final ServerSettings serverSettings; private int min = 0; - public ArgumentTime(String id) { + public ArgumentTime(String id, ServerSettings serverSettings) { super(id); + this.serverSettings = serverSettings; } public @NotNull ArgumentTime min(int min) { @@ -43,7 +46,7 @@ public Duration parse(@NotNull CommandSender sender, @NotNull String input) thro TemporalUnit timeUnit; if (Character.isDigit(lastChar)) - timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getServerSetting()); + timeUnit = TimeUnit.getServerTick(serverSettings); else if (SUFFIXES.contains(lastChar)) { input = input.substring(0, input.length() - 1); @@ -52,7 +55,7 @@ else if (SUFFIXES.contains(lastChar)) { } else if (lastChar == 's') { timeUnit = TimeUnit.SECOND; } else if (lastChar == 't') { - timeUnit = TimeUnit.getServerTick(sender.getServerProcess().getServerSetting()); + timeUnit = TimeUnit.getServerTick(serverSettings); } else { throw new ArgumentSyntaxException("Time needs to have the unit d, s, t, or none", input, NO_NUMBER); } diff --git a/src/main/java/net/minestom/server/command/builder/parser/ArgumentParser.java b/src/main/java/net/minestom/server/command/builder/parser/ArgumentParser.java index a419ef2e14e..b7976d3d0e0 100644 --- a/src/main/java/net/minestom/server/command/builder/parser/ArgumentParser.java +++ b/src/main/java/net/minestom/server/command/builder/parser/ArgumentParser.java @@ -1,5 +1,7 @@ package net.minestom.server.command.builder.parser; +import net.minestom.server.ServerSettings; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.arguments.*; import net.minestom.server.command.builder.arguments.minecraft.*; @@ -13,6 +15,8 @@ import net.minestom.server.command.builder.arguments.relative.ArgumentRelativeVec2; import net.minestom.server.command.builder.arguments.relative.ArgumentRelativeVec3; import net.minestom.server.command.builder.exception.ArgumentSyntaxException; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.utils.StringUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -27,46 +31,48 @@ public class ArgumentParser { - private static final Map>> ARGUMENT_FUNCTION_MAP = new ConcurrentHashMap<>(); + record ArgumentMapKey(String id, CommandManager commandManager, ServerSettings serverSettings, InstanceManager instanceManager, ConnectionManager connectionManager) {} + + private static final Map>> ARGUMENT_FUNCTION_MAP = new ConcurrentHashMap<>(); static { - ARGUMENT_FUNCTION_MAP.put("literal", ArgumentLiteral::new); - ARGUMENT_FUNCTION_MAP.put("boolean", ArgumentBoolean::new); - ARGUMENT_FUNCTION_MAP.put("integer", ArgumentInteger::new); - ARGUMENT_FUNCTION_MAP.put("double", ArgumentDouble::new); - ARGUMENT_FUNCTION_MAP.put("float", ArgumentFloat::new); - ARGUMENT_FUNCTION_MAP.put("string", ArgumentString::new); - ARGUMENT_FUNCTION_MAP.put("word", ArgumentWord::new); - ARGUMENT_FUNCTION_MAP.put("stringarray", ArgumentStringArray::new); - ARGUMENT_FUNCTION_MAP.put("command", ArgumentCommand::new); + ARGUMENT_FUNCTION_MAP.put("literal", key -> new ArgumentLiteral(key.id)); + ARGUMENT_FUNCTION_MAP.put("boolean", key -> new ArgumentBoolean(key.id)); + ARGUMENT_FUNCTION_MAP.put("integer", key -> new ArgumentInteger(key.id)); + ARGUMENT_FUNCTION_MAP.put("double", key -> new ArgumentDouble(key.id)); + ARGUMENT_FUNCTION_MAP.put("float", key -> new ArgumentFloat(key.id)); + ARGUMENT_FUNCTION_MAP.put("string", key -> new ArgumentString(key.id)); + ARGUMENT_FUNCTION_MAP.put("word", key -> new ArgumentWord(key.id)); + ARGUMENT_FUNCTION_MAP.put("stringarray", key -> new ArgumentStringArray(key.id)); + ARGUMENT_FUNCTION_MAP.put("command", key -> new ArgumentCommand(key.commandManager, key.id)); // TODO enum - ARGUMENT_FUNCTION_MAP.put("color", ArgumentColor::new); - ARGUMENT_FUNCTION_MAP.put("time", ArgumentTime::new); - ARGUMENT_FUNCTION_MAP.put("enchantment", ArgumentEnchantment::new); - ARGUMENT_FUNCTION_MAP.put("particle", ArgumentParticle::new); - ARGUMENT_FUNCTION_MAP.put("resourcelocation", ArgumentResourceLocation::new); - ARGUMENT_FUNCTION_MAP.put("entitytype", ArgumentEntityType::new); - ARGUMENT_FUNCTION_MAP.put("blockstate", ArgumentBlockState::new); - ARGUMENT_FUNCTION_MAP.put("intrange", ArgumentIntRange::new); - ARGUMENT_FUNCTION_MAP.put("floatrange", ArgumentFloatRange::new); - - ARGUMENT_FUNCTION_MAP.put("entity", s -> new ArgumentEntity(s).singleEntity(true)); - ARGUMENT_FUNCTION_MAP.put("entities", ArgumentEntity::new); - ARGUMENT_FUNCTION_MAP.put("player", s -> new ArgumentEntity(s).singleEntity(true).onlyPlayers(true)); - ARGUMENT_FUNCTION_MAP.put("players", s -> new ArgumentEntity(s).onlyPlayers(true)); - - ARGUMENT_FUNCTION_MAP.put("itemstack", ArgumentItemStack::new); - ARGUMENT_FUNCTION_MAP.put("component", ArgumentComponent::new); - ARGUMENT_FUNCTION_MAP.put("uuid", ArgumentUUID::new); - ARGUMENT_FUNCTION_MAP.put("nbt", ArgumentNbtTag::new); - ARGUMENT_FUNCTION_MAP.put("nbtcompound", ArgumentNbtCompoundTag::new); - ARGUMENT_FUNCTION_MAP.put("relativeblockposition", ArgumentRelativeBlockPosition::new); - ARGUMENT_FUNCTION_MAP.put("relativevec3", ArgumentRelativeVec3::new); - ARGUMENT_FUNCTION_MAP.put("relativevec2", ArgumentRelativeVec2::new); + ARGUMENT_FUNCTION_MAP.put("color", key -> new ArgumentColor(key.id)); + ARGUMENT_FUNCTION_MAP.put("time", key -> new ArgumentTime(key.id, key.serverSettings)); + ARGUMENT_FUNCTION_MAP.put("enchantment", key -> new ArgumentEnchantment(key.id)); + ARGUMENT_FUNCTION_MAP.put("particle", key -> new ArgumentParticle(key.id)); + ARGUMENT_FUNCTION_MAP.put("resourcelocation", key -> new ArgumentResourceLocation(key.id)); + ARGUMENT_FUNCTION_MAP.put("entitytype", key -> new ArgumentEntityType(key.id)); + ARGUMENT_FUNCTION_MAP.put("blockstate", key -> new ArgumentBlockState(key.id)); + ARGUMENT_FUNCTION_MAP.put("intrange", key -> new ArgumentIntRange(key.id)); + ARGUMENT_FUNCTION_MAP.put("floatrange", key -> new ArgumentFloatRange(key.id)); + + ARGUMENT_FUNCTION_MAP.put("entity", key -> new ArgumentEntity(key.id, key.instanceManager, key.connectionManager).singleEntity(true)); + ARGUMENT_FUNCTION_MAP.put("entities", key -> new ArgumentEntity(key.id, key.instanceManager, key.connectionManager)); + ARGUMENT_FUNCTION_MAP.put("player", key -> new ArgumentEntity(key.id, key.instanceManager, key.connectionManager).singleEntity(true).onlyPlayers(true)); + ARGUMENT_FUNCTION_MAP.put("players", key -> new ArgumentEntity(key.id, key.instanceManager, key.connectionManager).onlyPlayers(true)); + + ARGUMENT_FUNCTION_MAP.put("itemstack", key -> new ArgumentItemStack(key.id)); + ARGUMENT_FUNCTION_MAP.put("component", key -> new ArgumentComponent(key.id)); + ARGUMENT_FUNCTION_MAP.put("uuid", key -> new ArgumentUUID(key.id)); + ARGUMENT_FUNCTION_MAP.put("nbt", key -> new ArgumentNbtTag(key.id)); + ARGUMENT_FUNCTION_MAP.put("nbtcompound", key -> new ArgumentNbtCompoundTag(key.id)); + ARGUMENT_FUNCTION_MAP.put("relativeblockposition", key -> new ArgumentRelativeBlockPosition(key.id)); + ARGUMENT_FUNCTION_MAP.put("relativevec3", key -> new ArgumentRelativeVec3(key.id)); + ARGUMENT_FUNCTION_MAP.put("relativevec2", key -> new ArgumentRelativeVec2(key.id)); } @ApiStatus.Experimental - public static @NotNull Argument[] generate(@NotNull String format) { + public static @NotNull Argument[] generate(@NotNull String format, CommandManager commandManager, ServerSettings serverSettings, InstanceManager instanceManager, ConnectionManager connectionManager) { List> result = new ArrayList<>(); // 0 = no state @@ -74,7 +80,7 @@ public class ArgumentParser { int state = 0; // function to create an argument from its identifier // not null during state 1 - Function> argumentFunction = null; + Function> argumentFunction = null; StringBuilder builder = new StringBuilder(); @@ -114,7 +120,7 @@ public class ArgumentParser { if (c == '>') { final String param = builder.toString(); // TODO argument options - Argument argument = argumentFunction.apply(param); + Argument argument = argumentFunction.apply(new ArgumentMapKey(param, commandManager, serverSettings, instanceManager, connectionManager)); result.add(argument); builder = new StringBuilder(); diff --git a/src/main/java/net/minestom/server/crypto/SignatureValidator.java b/src/main/java/net/minestom/server/crypto/SignatureValidator.java index 6f5a8da325a..734aa69bb49 100644 --- a/src/main/java/net/minestom/server/crypto/SignatureValidator.java +++ b/src/main/java/net/minestom/server/crypto/SignatureValidator.java @@ -1,6 +1,6 @@ package net.minestom.server.crypto; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.entity.Player; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.crypto.KeyUtils; @@ -67,12 +67,12 @@ static SignatureValidator from(PublicKey publicKey, KeyUtils.SignatureAlgorithm private static SignatureValidator createYggdrasilValidator() { try (var stream = SignatureValidator.class.getResourceAsStream("/yggdrasil_session_pubkey.der")) { if (stream == null) { - ServerProcess.LOGGER.error("Couldn't find Yggdrasil public key, falling back to prohibiting validator!"); + ServerFacade.LOGGER.error("Couldn't find Yggdrasil public key, falling back to prohibiting validator!"); return FAIL; } return from(KeyUtils.publicRSAKeyFrom(stream.readAllBytes()), KeyUtils.SignatureAlgorithm.SHA1withRSA); } catch (Exception e) { - ServerProcess.LOGGER.error("Exception while reading Yggdrasil public key, falling back to prohibiting validator!", e); + ServerFacade.LOGGER.error("Exception while reading Yggdrasil public key, falling back to prohibiting validator!", e); return FAIL; } } diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index 3a771e19a58..b3687593aed 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -1,11 +1,13 @@ package net.minestom.server.entity; +import lombok.Getter; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEvent.ShowEntity; import net.kyori.adventure.text.event.HoverEventSource; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettings; import net.minestom.server.Tickable; import net.minestom.server.Viewable; import net.minestom.server.collision.*; @@ -14,6 +16,7 @@ import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.EntityMeta; import net.minestom.server.entity.metadata.LivingEntityMeta; +import net.minestom.server.event.Event; import net.minestom.server.event.EventFilter; import net.minestom.server.event.EventHandler; import net.minestom.server.event.EventNode; @@ -21,10 +24,11 @@ import net.minestom.server.event.instance.AddEntityToInstanceEvent; import net.minestom.server.event.instance.RemoveEntityFromInstanceEvent; import net.minestom.server.event.trait.EntityEvent; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.EntityTracker; import net.minestom.server.instance.Instance; -import net.minestom.server.instance.InstanceManager; +import net.minestom.server.instance.InstanceManagerImpl; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; @@ -44,6 +48,7 @@ import net.minestom.server.tag.TagHandler; import net.minestom.server.tag.Taggable; import net.minestom.server.thread.Acquirable; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.timer.Schedulable; import net.minestom.server.timer.Scheduler; import net.minestom.server.timer.TaskSchedule; @@ -91,7 +96,12 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev private static final AtomicInteger LAST_ENTITY_ID = new AtomicInteger(); private final CachedPacket destroyPacketCache; - private final ServerProcess serverProcess; + @Getter // FIXME bad shit + protected final ServerSettings serverSettings; + @Getter // FIXME bad shit + protected final EventNode globalEventHandler; + protected final ThreadDispatcher dispatcher; + protected final ExceptionHandler exceptionHandler; protected Instance instance; protected Chunk currentChunk; @@ -179,8 +189,19 @@ public void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracke private final Acquirable acquirable = Acquirable.of(this); - public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { - this.serverProcess = serverProcess; + public Entity(ServerFacade serverFacade, @NotNull EntityType entityType) { + this(serverFacade, entityType, UUID.randomUUID()); + } + + public Entity(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), entityType, uuid); + } + + public Entity(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull EntityType entityType, @NotNull UUID uuid) { + this.serverSettings = serverSettings; + this.globalEventHandler = globalEventHandler; + this.dispatcher = dispatcher; + this.exceptionHandler = exceptionHandler; this.id = generateId(); this.entityType = entityType; this.uuid = uuid; @@ -197,18 +218,10 @@ public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityTy this.gravityAcceleration = entityType.registry().acceleration(); this.gravityDragPerTick = entityType.registry().drag(); + + this.eventNode = globalEventHandler.map(this, EventFilter.ENTITY); - if (serverProcess != null) { - this.eventNode = serverProcess.getGlobalEventHandler().map(this, EventFilter.ENTITY); - } else { - // Local nodes require a server process - this.eventNode = null; - } - destroyPacketCache = new CachedPacket(serverProcess.getServerSetting(), () -> new DestroyEntitiesPacket(getEntityId())); - } - - public Entity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { - this(serverProcess, entityType, UUID.randomUUID()); + destroyPacketCache = new CachedPacket(serverSettings, () -> new DestroyEntitiesPacket(getEntityId())); } /** @@ -562,7 +575,7 @@ public void tick(long time) { update(time); ticks++; - serverProcess.getGlobalEventHandler().call(new EntityTickEvent(this)); + globalEventHandler.call(new EntityTickEvent(this)); // remove expired effects effectTick(time); @@ -582,7 +595,7 @@ private void velocityTick() { if (!hasVelocity && noGravity) { return; } - final float tps = serverProcess.getServerSetting().getTickPerSecond(); + final float tps = serverSettings.getTickPerSecond(); final Pos positionBeforeMove = getPosition(); final Vec currentVelocity = getVelocity(); final boolean wasOnGround = this.onGround; @@ -620,7 +633,7 @@ private void velocityTick() { ); if (this.ticks % VELOCITY_UPDATE_INTERVAL == 0) { if (!isPlayer && !this.lastVelocityWasZero) { - sendPacketToViewers(getVelocityPacket()); + sendPacketToViewers(serverSettings, getVelocityPacket()); this.lastVelocityWasZero = !hasVelocity; } } @@ -653,7 +666,7 @@ private void velocityTick() { // Verify if velocity packet has to be sent if (this.ticks % VELOCITY_UPDATE_INTERVAL == 0) { if (!isPlayer && (hasVelocity || !lastVelocityWasZero)) { - sendPacketToViewers(getVelocityPacket()); + sendPacketToViewers(serverSettings, getVelocityPacket()); this.lastVelocityWasZero = !hasVelocity; } } @@ -681,7 +694,7 @@ protected void updateVelocity(boolean wasOnGround, boolean flying, Pos positionB z * drag )) // Convert from block/tick to block/sec - .mul(serverProcess.getServerSetting().getTickPerSecond()) + .mul(serverSettings.getTickPerSecond()) // Prevent infinitely decreasing velocity .apply(Vec.Operator.EPSILON); } @@ -726,12 +739,12 @@ private void effectTick(long time) { effects.removeIf(timedPotion -> { long duration = timedPotion.getPotion().duration(); if (duration == Potion.INFINITE_DURATION) return false; - final long potionTime = duration * serverProcess.getServerSetting().getTickMs(); + final long potionTime = duration * serverSettings.getTickMs(); // Remove if the potion should be expired if (time >= timedPotion.getStartingTime() + potionTime) { // Send the packet that the potion should no longer be applied timedPotion.getPotion().sendRemovePacket(this); - serverProcess.getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + globalEventHandler.call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); return true; } return false; @@ -846,7 +859,7 @@ public void setBoundingBox(BoundingBox boundingBox) { @ApiStatus.Internal protected void refreshCurrentChunk(Chunk currentChunk) { this.currentChunk = currentChunk; - serverProcess.dispatcher().updateElement(this, currentChunk); + dispatcher.updateElement(this, currentChunk); } /** @@ -865,7 +878,7 @@ protected void refreshCurrentChunk(Chunk currentChunk) { * @param spawnPosition the spawn position for the entity. * @return a {@link CompletableFuture} called once the entity's instance has been set, * this is due to chunks needing to load - * @throws IllegalStateException if {@code instance} has not been registered in {@link InstanceManager} + * @throws IllegalStateException if {@code instance} has not been registered in {@link InstanceManagerImpl} */ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull Pos spawnPosition) { Check.stateCondition(!instance.isRegistered(), @@ -875,7 +888,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull return teleport(spawnPosition); // Already in the instance, teleport to spawn point } AddEntityToInstanceEvent event = new AddEntityToInstanceEvent(instance, this); - serverProcess.getGlobalEventHandler().call(event); + globalEventHandler.call(event); if (event.isCancelled()) return null; // TODO what to return? if (previousInstance != null) removeFromInstance(previousInstance); @@ -894,9 +907,9 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull } instance.getEntityTracker().register(this, spawnPosition, trackingTarget, trackingUpdate); spawn(); - serverProcess.getGlobalEventHandler().call(new EntitySpawnEvent(this, instance)); + globalEventHandler.call(new EntitySpawnEvent(this, instance)); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } }); } @@ -912,14 +925,14 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull * @return a {@link CompletableFuture} called once the entity's instance has been set, * this is due to chunks needing to load * @throws NullPointerException if {@code instance} is null - * @throws IllegalStateException if {@code instance} has not been registered in {@link InstanceManager} + * @throws IllegalStateException if {@code instance} has not been registered in {@link InstanceManagerImpl} */ public CompletableFuture setInstance(@NotNull Instance instance) { return setInstance(instance, this.position); } private void removeFromInstance(Instance instance) { - serverProcess.getGlobalEventHandler().call(new RemoveEntityFromInstanceEvent(instance, this)); + globalEventHandler.call(new RemoveEntityFromInstanceEvent(instance, this)); instance.getEntityTracker().unregister(this, trackingTarget, trackingUpdate); this.viewEngine.forManuals(this::removeViewer); } @@ -942,9 +955,9 @@ private void removeFromInstance(Instance instance) { */ public void setVelocity(@NotNull Vec velocity) { EntityVelocityEvent entityVelocityEvent = new EntityVelocityEvent(this, velocity); - serverProcess.getGlobalEventHandler().callCancellable(entityVelocityEvent, () -> { + globalEventHandler.callCancellable(entityVelocityEvent, () -> { this.velocity = entityVelocityEvent.getVelocity(); - sendPacketToViewersAndSelf(getVelocityPacket()); + sendPacketToViewersAndSelf(serverSettings, getVelocityPacket()); }); } @@ -1056,7 +1069,7 @@ public void addPassenger(@NotNull Entity entity) { entity.setInstance(currentInstance, position).join(); this.passengers.add(entity); entity.vehicle = this; - sendPacketToViewersAndSelf(getPassengersPacket()); + sendPacketToViewersAndSelf(serverSettings, getPassengersPacket()); // Updates the position of the new passenger, and then teleports the passenger updatePassengerPosition(position, entity); entity.synchronizePosition(false); @@ -1073,7 +1086,7 @@ public void removePassenger(@NotNull Entity entity) { Check.stateCondition(instance == null, "You need to set an instance using Entity#setInstance"); if (!passengers.remove(entity)) return; entity.vehicle = null; - sendPacketToViewersAndSelf(getPassengersPacket()); + sendPacketToViewersAndSelf(serverSettings, getPassengersPacket()); entity.synchronizePosition(false); } @@ -1105,7 +1118,7 @@ public boolean hasPassenger() { * @param status the status to trigger */ public void triggerStatus(byte status) { - sendPacketToViewersAndSelf(new EntityStatusPacket(getEntityId(), status)); + sendPacketToViewersAndSelf(serverSettings, new EntityStatusPacket(getEntityId(), status)); } /** @@ -1331,21 +1344,21 @@ public void refreshPosition(@NotNull final Pos newPosition, boolean ignoreView) final Chunk chunk = getChunk(); if (distanceX > 8 || distanceY > 8 || distanceZ > 8) { - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); + PacketUtils.prepareViewablePacket(serverSettings, chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); } else if (positionChange && viewChange) { - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverSettings, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); // Fix head rotation - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverSettings, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); } else if (positionChange) { // This is a confusing fix for a confusing issue. If rotation is only sent when the entity actually changes, then spawning an entity // on the ground causes the entity not to update its rotation correctly. It works fine if the entity is spawned in the air. Very weird. - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverSettings, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, onGround), this); } else if (viewChange) { - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(),chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverSettings, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverSettings,chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); } this.lastSyncedPosition = position; @@ -1460,7 +1473,7 @@ public void addEffect(@NotNull Potion potion) { removeEffect(potion.effect()); this.effects.add(new TimedPotion(potion, System.currentTimeMillis())); potion.sendAddPacket(this); - serverProcess.getGlobalEventHandler().call(new EntityPotionAddEvent(this, potion)); + globalEventHandler.call(new EntityPotionAddEvent(this, potion)); } /** @@ -1472,7 +1485,7 @@ public void removeEffect(@NotNull PotionEffect effect) { this.effects.removeIf(timedPotion -> { if (timedPotion.getPotion().effect() == effect) { timedPotion.getPotion().sendRemovePacket(this); - serverProcess.getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + globalEventHandler.call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); return true; } return false; @@ -1515,7 +1528,7 @@ public int getEffectLevel(@NotNull PotionEffect effect) { public void clearEffects() { for (TimedPotion timedPotion : effects) { timedPotion.getPotion().sendRemovePacket(this); - serverProcess.getGlobalEventHandler().call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); + globalEventHandler.call(new EntityPotionRemoveEvent(this, timedPotion.getPotion())); } this.effects.clear(); } @@ -1531,11 +1544,11 @@ public void remove() { protected void remove(boolean permanent) { if (isRemoved()) return; - serverProcess.getGlobalEventHandler().call(new EntityDespawnEvent(this)); + globalEventHandler.call(new EntityDespawnEvent(this)); try { despawn(); } catch (Throwable t) { - serverProcess.getExceptionHandler().handleException(t); + exceptionHandler.handleException(t); } // Remove passengers if any (also done with LivingEntity#kill) @@ -1544,7 +1557,7 @@ protected void remove(boolean permanent) { final Entity vehicle = this.vehicle; if (vehicle != null) vehicle.removePassenger(this); - serverProcess.dispatcher().removeElement(this); + dispatcher.removeElement(this); this.removed = true; if (permanent) { Entity.ENTITY_BY_ID.remove(id); @@ -1580,7 +1593,7 @@ public boolean isRemoved() { * @param temporalUnit the unit of the delay */ public void scheduleRemove(long delay, @NotNull TemporalUnit temporalUnit) { - if (temporalUnit.equals(TimeUnit.getServerTick(serverProcess.getServerSetting()))) { + if (temporalUnit.equals(TimeUnit.getServerTick(serverSettings))) { scheduleRemove(TaskSchedule.tick((int) delay)); } else { scheduleRemove(Duration.of(delay, temporalUnit)); @@ -1601,7 +1614,7 @@ private void scheduleRemove(TaskSchedule schedule) { } protected @NotNull Vec getVelocityForPacket() { - return this.velocity.mul(8000f / serverProcess.getServerSetting().getTickPerSecond()); + return this.velocity.mul(8000f / serverSettings.getTickPerSecond()); } protected @NotNull EntityVelocityPacket getVelocityPacket() { @@ -1630,14 +1643,14 @@ private void scheduleRemove(TaskSchedule schedule) { protected void synchronizePosition(boolean includeSelf) { final Pos posCache = this.position; final ServerPacket packet = new EntityTeleportPacket(getEntityId(), posCache, isOnGround()); - PacketUtils.prepareViewablePacket(serverProcess.getServerSetting(), currentChunk, packet, this); + PacketUtils.prepareViewablePacket(serverSettings, currentChunk, packet, this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); this.lastSyncedPosition = posCache; } private void synchronizeView() { - sendPacketToViewersAndSelf(new EntityHeadLookPacket(getEntityId(), position.yaw())); - sendPacketToViewersAndSelf(new EntityRotationPacket(getEntityId(), position.yaw(), position.pitch(), onGround)); + sendPacketToViewersAndSelf(serverSettings, new EntityHeadLookPacket(getEntityId(), position.yaw())); + sendPacketToViewersAndSelf(serverSettings, new EntityRotationPacket(getEntityId(), position.yaw(), position.pitch(), onGround)); } /** @@ -1708,9 +1721,9 @@ private Duration getSynchronizationCooldown() { public void takeKnockback(float strength, final double x, final double z) { if (strength > 0) { //TODO check possible side effects of unnatural TPS (other than 20TPS) - strength *= serverProcess.getServerSetting().getTickPerSecond(); + strength *= serverSettings.getTickPerSecond(); final Vec velocityModifier = new Vec(x, z).normalize().mul(strength); - final double verticalLimit = .4d * serverProcess.getServerSetting().getTickPerSecond(); + final double verticalLimit = .4d * serverSettings.getTickPerSecond(); setVelocity(new Vec(velocity.x() / 2d - velocityModifier.x(), onGround ? Math.min(verticalLimit, velocity.y() / 2d + strength) : velocity.y(), @@ -1829,11 +1842,6 @@ public boolean hasCollision() { return hasCollision; } - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } - public enum Pose { STANDING, FALL_FLYING, diff --git a/src/main/java/net/minestom/server/entity/EntityCreature.java b/src/main/java/net/minestom/server/entity/EntityCreature.java index 729702ae7e2..69c1d448ddc 100644 --- a/src/main/java/net/minestom/server/entity/EntityCreature.java +++ b/src/main/java/net/minestom/server/entity/EntityCreature.java @@ -1,14 +1,20 @@ package net.minestom.server.entity; import com.extollit.gaming.ai.path.HydrazinePathFinder; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.ai.EntityAI; import net.minestom.server.entity.ai.EntityAIGroup; import net.minestom.server.entity.pathfinding.NavigableEntity; import net.minestom.server.entity.pathfinding.Navigator; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.entity.EntityAttackEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -30,18 +36,22 @@ public class EntityCreature extends LivingEntity implements NavigableEntity, Ent private Entity target; + public EntityCreature(ServerFacade serverFacade, @NotNull EntityType entityType) { + this(serverFacade, entityType, UUID.randomUUID()); + } + + public EntityCreature(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), entityType, uuid); + } + /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public EntityCreature(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { - super(serverProcess, entityType, uuid); + public EntityCreature(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, entityType, uuid); heal(); } - public EntityCreature(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { - this(serverProcess, entityType, UUID.randomUUID()); - } - @Override public void update(long time) { // AI @@ -134,7 +144,7 @@ public void attack(@NotNull Entity target, boolean swingHand) { if (swingHand) swingMainHand(); EntityAttackEvent attackEvent = new EntityAttackEvent(this, target); - getServerProcess().getGlobalEventHandler().call(attackEvent); + globalEventHandler.call(attackEvent); } /** diff --git a/src/main/java/net/minestom/server/entity/EntityProjectile.java b/src/main/java/net/minestom/server/entity/EntityProjectile.java index fbfa494b72e..def815e528d 100644 --- a/src/main/java/net/minestom/server/entity/EntityProjectile.java +++ b/src/main/java/net/minestom/server/entity/EntityProjectile.java @@ -1,24 +1,29 @@ package net.minestom.server.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.collision.BoundingBox; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.projectile.ProjectileMeta; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.entity.EntityShootEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithEntityEvent; import net.minestom.server.event.entity.projectile.ProjectileUncollideEvent; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; +import net.minestom.server.thread.ThreadDispatcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Optional; import java.util.Random; +import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -30,8 +35,12 @@ public class EntityProjectile extends Entity { private final Entity shooter; - public EntityProjectile(@NotNull ServerProcess serverProcess, @Nullable Entity shooter, @NotNull EntityType entityType) { - super(serverProcess, entityType); + public EntityProjectile(@NotNull Entity shooter, @NotNull EntityType entityType) { + this(shooter.serverSettings, shooter.globalEventHandler, shooter.dispatcher, shooter.exceptionHandler, shooter, entityType); + } + + public EntityProjectile(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @Nullable Entity shooter, @NotNull EntityType entityType) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, entityType, UUID.randomUUID()); this.shooter = shooter; setup(); } @@ -50,7 +59,7 @@ public Entity getShooter() { public void shoot(Point to, double power, double spread) { final EntityShootEvent shootEvent = new EntityShootEvent(this.shooter, this, to, power, spread); - getServerProcess().getGlobalEventHandler().call(shootEvent); + globalEventHandler.call(shootEvent); if (shootEvent.isCancelled()) { remove(); return; @@ -97,7 +106,7 @@ public void tick(long time) { } super.onGround = true; this.velocity = Vec.ZERO; - sendPacketToViewersAndSelf(getVelocityPacket()); + sendPacketToViewersAndSelf(serverSettings, getVelocityPacket()); setNoGravity(true); } else { if (!super.onGround) { @@ -105,7 +114,7 @@ public void tick(long time) { } super.onGround = false; setNoGravity(false); - getServerProcess().getGlobalEventHandler().call(new ProjectileUncollideEvent(this)); + globalEventHandler.call(new ProjectileUncollideEvent(this)); } } @@ -147,7 +156,7 @@ private boolean isStuck(Pos pos, Pos posNow) { } if (block.isSolid()) { final ProjectileCollideWithBlockEvent event = new ProjectileCollideWithBlockEvent(this, pos, block); - getServerProcess().getGlobalEventHandler().call(event); + globalEventHandler.call(event); if (!event.isCancelled()) { teleport(pos); return true; @@ -175,7 +184,7 @@ private boolean isStuck(Pos pos, Pos posNow) { if (victimOptional.isPresent()) { final LivingEntity target = victimOptional.get(); final ProjectileCollideWithEntityEvent event = new ProjectileCollideWithEntityEvent(this, pos, target); - getServerProcess().getGlobalEventHandler().call(event); + globalEventHandler.call(event); if (!event.isCancelled()) { return super.onGround; } diff --git a/src/main/java/net/minestom/server/entity/EntityView.java b/src/main/java/net/minestom/server/entity/EntityView.java index 1e39fbeb0be..b96633c42b0 100644 --- a/src/main/java/net/minestom/server/entity/EntityView.java +++ b/src/main/java/net/minestom/server/entity/EntityView.java @@ -228,7 +228,7 @@ private Collection references() { final Point point = trackedLocation.point(); Int2ObjectOpenHashMap entityMap = new Int2ObjectOpenHashMap<>(lastSize); - instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.getServerProcess().getServerSetting().getEntityViewDistance(), target, + instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.serverSettings.getEntityViewDistance(), target, (entity) -> entityMap.putIfAbsent(entity.getEntityId(), entity)); this.lastSize = entityMap.size(); return entityMap.values(); diff --git a/src/main/java/net/minestom/server/entity/ExperienceOrb.java b/src/main/java/net/minestom/server/entity/ExperienceOrb.java index 8b2f737d70b..3b65f205ea9 100644 --- a/src/main/java/net/minestom/server/entity/ExperienceOrb.java +++ b/src/main/java/net/minestom/server/entity/ExperienceOrb.java @@ -1,9 +1,15 @@ package net.minestom.server.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; +import net.minestom.server.thread.ThreadDispatcher; import java.util.Comparator; +import java.util.UUID; public class ExperienceOrb extends Entity { @@ -11,8 +17,8 @@ public class ExperienceOrb extends Entity { private Player target; private long lastTargetUpdateTick; - public ExperienceOrb(ServerProcess serverProcess, short experienceCount) { - super(serverProcess, EntityType.EXPERIENCE_ORB); + public ExperienceOrb(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, short experienceCount) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.EXPERIENCE_ORB, UUID.randomUUID()); setBoundingBox(0.5f, 0.5f, 0.5f); //todo vanilla sets random velocity here? this.experienceCount = experienceCount; diff --git a/src/main/java/net/minestom/server/entity/ItemEntity.java b/src/main/java/net/minestom/server/entity/ItemEntity.java index c87381d1718..678ddee1026 100644 --- a/src/main/java/net/minestom/server/entity/ItemEntity.java +++ b/src/main/java/net/minestom/server/entity/ItemEntity.java @@ -1,11 +1,17 @@ package net.minestom.server.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.metadata.item.ItemEntityMeta; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.entity.EntityItemMergeEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; import net.minestom.server.instance.EntityTracker; import net.minestom.server.item.ItemStack; import net.minestom.server.item.StackingRule; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.utils.time.Cooldown; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; @@ -13,6 +19,7 @@ import java.time.Duration; import java.time.temporal.TemporalUnit; +import java.util.UUID; /** * Represents an item on the ground. @@ -38,11 +45,15 @@ public class ItemEntity extends Entity { private long spawnTime; private long pickupDelay; - public ItemEntity(@NotNull ServerProcess serverProcess, @NotNull ItemStack itemStack) { - super(serverProcess, EntityType.ITEM); + public ItemEntity(ServerFacade serverFacade, @NotNull ItemStack itemStack) { + this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), itemStack); + } + + public ItemEntity(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull ItemStack itemStack) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.ITEM, UUID.randomUUID()); setItemStack(itemStack); setBoundingBox(0.25f, 0.25f, 0.25f); - mergeDelay = Duration.of(10, TimeUnit.getServerTick(serverProcess.getServerSetting())); + mergeDelay = Duration.of(10, TimeUnit.getServerTick(serverSettings)); } /** @@ -86,7 +97,7 @@ public void update(long time) { if (!stackingRule.canApply(itemStack, totalAmount)) return; final ItemStack result = stackingRule.apply(itemStack, totalAmount); EntityItemMergeEvent entityItemMergeEvent = new EntityItemMergeEvent(this, itemEntity, result); - getServerProcess().getGlobalEventHandler().callCancellable(entityItemMergeEvent, () -> { + globalEventHandler.callCancellable(entityItemMergeEvent, () -> { setItemStack(entityItemMergeEvent.getResult()); itemEntity.remove(); }); diff --git a/src/main/java/net/minestom/server/entity/LivingEntity.java b/src/main/java/net/minestom/server/entity/LivingEntity.java index e1e54ac83cb..f6b310b031e 100644 --- a/src/main/java/net/minestom/server/entity/LivingEntity.java +++ b/src/main/java/net/minestom/server/entity/LivingEntity.java @@ -1,7 +1,8 @@ package net.minestom.server.entity; import net.kyori.adventure.sound.Sound.Source; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettings; import net.minestom.server.attribute.Attribute; import net.minestom.server.attribute.AttributeInstance; import net.minestom.server.collision.BoundingBox; @@ -10,11 +11,15 @@ import net.minestom.server.entity.damage.Damage; import net.minestom.server.entity.damage.DamageType; import net.minestom.server.entity.metadata.LivingEntityMeta; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.entity.EntityDamageEvent; import net.minestom.server.event.entity.EntityDeathEvent; import net.minestom.server.event.entity.EntityFireEvent; import net.minestom.server.event.item.EntityEquipEvent; import net.minestom.server.event.item.PickupItemEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; import net.minestom.server.instance.EntityTracker; import net.minestom.server.inventory.EquipmentHandler; import net.minestom.server.item.ItemStack; @@ -27,6 +32,7 @@ import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.scoreboard.Team; import net.minestom.server.sound.SoundEvent; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.utils.block.BlockIterator; import net.minestom.server.utils.time.Cooldown; import net.minestom.server.utils.time.TimeUnit; @@ -83,17 +89,21 @@ public class LivingEntity extends Entity implements EquipmentHandler { private ItemStack leggings; private ItemStack boots; + public LivingEntity(ServerFacade serverFacade, @NotNull EntityType entityType) { + this(serverFacade, entityType, UUID.randomUUID()); + } + + public LivingEntity(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), entityType, uuid); + } + /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public LivingEntity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType, @NotNull UUID uuid) { - super(serverProcess, entityType, uuid); + public LivingEntity(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, entityType, uuid); initEquipments(); - itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(serverProcess.getServerSetting()))); - } - - public LivingEntity(@NotNull ServerProcess serverProcess, @NotNull EntityType entityType) { - this(serverProcess, entityType, UUID.randomUUID()); + itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(serverSettings))); } private void initEquipments() { @@ -178,9 +188,14 @@ public void setBoots(@NotNull ItemStack itemStack) { syncEquipment(EquipmentSlot.BOOTS); } + @Override + public ServerSettings getServerSettings() { + return serverSettings; + } + private ItemStack getEquipmentItem(@NotNull ItemStack itemStack, @NotNull EquipmentSlot slot) { EntityEquipEvent entityEquipEvent = new EntityEquipEvent(this, itemStack, slot); - getServerProcess().getGlobalEventHandler().call(entityEquipEvent); + globalEventHandler.call(entityEquipEvent); return entityEquipEvent.getEquippedItem(); } @@ -200,9 +215,9 @@ public void update(long time) { if (!itemEntity.isPickable()) return; if (expandedBoundingBox.intersectEntity(loweredPosition, itemEntity)) { PickupItemEvent pickupItemEvent = new PickupItemEvent(this, itemEntity); - getServerProcess().getGlobalEventHandler().callCancellable(pickupItemEvent, () -> { + globalEventHandler.callCancellable(pickupItemEvent, () -> { final ItemStack item = itemEntity.getItemStack(); - sendPacketToViewersAndSelf(new CollectItemPacket(itemEntity.getEntityId(), getEntityId(), item.amount())); + sendPacketToViewersAndSelf(serverSettings, new CollectItemPacket(itemEntity.getEntityId(), getEntityId(), item.amount())); itemEntity.remove(); }); } @@ -268,7 +283,7 @@ public void kill() { } EntityDeathEvent entityDeathEvent = new EntityDeathEvent(this); - getServerProcess().getGlobalEventHandler().call(entityDeathEvent); + globalEventHandler.call(entityDeathEvent); } /** @@ -277,7 +292,7 @@ public void kill() { * @param duration duration in ticks of the effect */ public void setFireForDuration(int duration) { - setFireForDuration(duration, TimeUnit.getServerTick(getServerProcess().getServerSetting())); + setFireForDuration(duration, TimeUnit.getServerTick(serverSettings)); } /** @@ -302,7 +317,7 @@ public void setFireForDuration(Duration duration) { // Do not start fire event if the fire needs to be removed (< 0 duration) if (duration.toMillis() > 0) { - getServerProcess().getGlobalEventHandler().callCancellable(entityFireEvent, () -> { + globalEventHandler.callCancellable(entityFireEvent, () -> { final long fireTime = entityFireEvent.getFireTime(TimeUnit.MILLISECOND); setOnFire(true); fireExtinguishTime = System.currentTimeMillis() + fireTime; @@ -330,14 +345,14 @@ public boolean damage(@NotNull Damage damage) { } EntityDamageEvent entityDamageEvent = new EntityDamageEvent(this, damage, damage.getSound(this)); - getServerProcess().getGlobalEventHandler().callCancellable(entityDamageEvent, () -> { + globalEventHandler.callCancellable(entityDamageEvent, () -> { // Set the last damage type since the event is not cancelled this.lastDamage = entityDamageEvent.getDamage(); float remainingDamage = entityDamageEvent.getDamage().getAmount(); if (entityDamageEvent.shouldAnimate()) { - sendPacketToViewersAndSelf(new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.TAKE_DAMAGE)); + sendPacketToViewersAndSelf(serverSettings, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.TAKE_DAMAGE)); } // Additional hearts support @@ -367,7 +382,7 @@ public boolean damage(@NotNull Damage damage) { // TODO: separate living entity categories soundCategory = Source.HOSTILE; } - sendPacketToViewersAndSelf(new SoundEffectPacket(sound, null, soundCategory, + sendPacketToViewersAndSelf(serverSettings, new SoundEffectPacket(sound, null, soundCategory, getPosition(), 1.0f, 1.0f, 0)); } }); @@ -462,9 +477,9 @@ protected void onAttributeChanged(@NotNull AttributeInstance attributeInstance) } EntityPropertiesPacket propertiesPacket = new EntityPropertiesPacket(getEntityId(), List.of(attributeInstance)); if (self) { - sendPacketToViewersAndSelf(propertiesPacket); + sendPacketToViewersAndSelf(serverSettings, propertiesPacket); } else { - sendPacketToViewers(propertiesPacket); + sendPacketToViewers(serverSettings, propertiesPacket); } } @@ -524,7 +539,7 @@ public void setBoundingBox(BoundingBox boundingBox) { * (can be used for attack animation). */ public void swingMainHand() { - sendPacketToViewers(new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_MAIN_ARM)); + sendPacketToViewers(serverSettings, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_MAIN_ARM)); } /** @@ -532,7 +547,7 @@ public void swingMainHand() { * (can be used for attack animation). */ public void swingOffHand() { - sendPacketToViewers(new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_OFF_HAND)); + sendPacketToViewers(serverSettings, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_OFF_HAND)); } public void refreshActiveHand(boolean isHandActive, boolean offHand, boolean riptideSpinAttack) { diff --git a/src/main/java/net/minestom/server/entity/Metadata.java b/src/main/java/net/minestom/server/entity/Metadata.java index f71041a7a7f..e4cbc12413d 100644 --- a/src/main/java/net/minestom/server/entity/Metadata.java +++ b/src/main/java/net/minestom/server/entity/Metadata.java @@ -204,7 +204,7 @@ public void setIndex(int index, @NotNull Entry entry) { this.notNotifiedChanges.put(index, entry); } } else { - entity.sendPacketToViewersAndSelf(new EntityMetaDataPacket(entity.getEntityId(), Map.of(index, entry))); + entity.sendPacketToViewersAndSelf(entity.serverSettings, new EntityMetaDataPacket(entity.getEntityId(), Map.of(index, entry))); } } } @@ -225,7 +225,7 @@ public void setNotifyAboutChanges(boolean notifyAboutChanges) { entries = Map.copyOf(awaitingChanges); awaitingChanges.clear(); } - entity.sendPacketToViewersAndSelf(new EntityMetaDataPacket(entity.getEntityId(), entries)); + entity.sendPacketToViewersAndSelf(entity.serverSettings, new EntityMetaDataPacket(entity.getEntityId(), entries)); } public @NotNull Map> getEntries() { diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index d636546b4bd..2f367aed1ab 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.longs.LongArrayPriorityQueue; import it.unimi.dsi.fastutil.longs.LongPriorityQueue; +import lombok.Getter; import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.identity.Identified; @@ -19,13 +20,14 @@ import net.kyori.adventure.text.event.HoverEventSource; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.title.TitlePart; -import net.minestom.server.ServerProcess; import net.minestom.server.ServerSettings; import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; +import net.minestom.server.adventure.bossbar.BossBarManager; import net.minestom.server.attribute.Attribute; import net.minestom.server.collision.BoundingBox; +import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.condition.CommandCondition; import net.minestom.server.coordinate.Point; @@ -37,15 +39,19 @@ import net.minestom.server.entity.metadata.LivingEntityMeta; import net.minestom.server.entity.metadata.PlayerMeta; import net.minestom.server.entity.vehicle.PlayerVehicleInformation; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.inventory.InventoryOpenEvent; import net.minestom.server.event.item.ItemDropEvent; import net.minestom.server.event.item.ItemUpdateStateEvent; import net.minestom.server.event.item.PickupExperienceEvent; import net.minestom.server.event.player.*; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.EntityTracker; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; +import net.minestom.server.instance.block.BlockManager; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.PlayerInventory; import net.minestom.server.item.ItemStack; @@ -56,6 +62,7 @@ import net.minestom.server.message.ChatPosition; import net.minestom.server.message.Messenger; import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerImpl; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.PlayerProvider; import net.minestom.server.network.packet.client.ClientPacket; @@ -72,12 +79,14 @@ import net.minestom.server.recipe.RecipeManager; import net.minestom.server.scoreboard.BelowNameTag; import net.minestom.server.scoreboard.Team; +import net.minestom.server.scoreboard.TeamManager; import net.minestom.server.snapshot.EntitySnapshot; import net.minestom.server.snapshot.PlayerSnapshot; import net.minestom.server.snapshot.SnapshotImpl; import net.minestom.server.snapshot.SnapshotUpdater; import net.minestom.server.statistic.PlayerStatistic; -import net.minestom.server.timer.Scheduler; +import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.PropertyUtils; @@ -114,7 +123,7 @@ * Those are the major actors of the server, * they are not necessary backed by a {@link PlayerSocketConnection} as shown by {@link FakePlayer}. *

        - * You can easily create your own implementation of this and use it with {@link ConnectionManager#setPlayerProvider(PlayerProvider)}. + * You can easily create your own implementation of this and use it with {@link ConnectionManagerImpl#setPlayerProvider(PlayerProvider)}. */ public class Player extends LivingEntity implements CommandSender, Localizable, HoverEventSource, Identified, NamedAndIdentified { private static final Logger logger = LoggerFactory.getLogger(Player.class); @@ -131,7 +140,18 @@ public class Player extends LivingEntity implements CommandSender, Localizable, private long lastKeepAlive; private boolean answerKeepAlive; - + @Getter // FIXME bad shit + + protected final ConnectionManager connectionManager; + protected final TeamManager teamManager; + protected final RecipeManager recipeManager; + @Getter // FIXME bad shit + private final CommandManager commandManager; + private final BossBarManager bossBarManager; + private final SchedulerManager schedulerManager; + private final PacketListenerManager packetListenerManager; + @Getter // FIXME bad shit + private final BlockManager blockManager; private String username; private Component usernameComponent; protected final PlayerConnection playerConnection; @@ -225,8 +245,31 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // The future is non-null when a resource pack is in-flight, and completed when all statuses have been received. private CompletableFuture resourcePackFuture = null; - public Player(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - super(serverProcess, EntityType.PLAYER, uuid); + public Player( + ServerSettings serverSettings, + EventNode globalEventHandler, + ThreadDispatcher dispatcher, + ExceptionHandler exceptionHandler, + ConnectionManager connectionManager, + TeamManager teamManager, + RecipeManager recipeManager, + CommandManager commandManager, + BossBarManager bossBarManager, + SchedulerManager schedulerManager, + PacketListenerManager packetListenerManager, + BlockManager blockManager, + + @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection + ) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.PLAYER, uuid); + this.connectionManager = connectionManager; + this.teamManager = teamManager; + this.recipeManager = recipeManager; + this.commandManager = commandManager; + this.bossBarManager = bossBarManager; + this.schedulerManager = schedulerManager; + this.packetListenerManager = packetListenerManager; + this.blockManager = blockManager; this.username = username; this.usernameComponent = Component.text(username); this.playerConnection = playerConnection; @@ -234,7 +277,7 @@ public Player(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull setRespawnPoint(Pos.ZERO); this.settings = new PlayerSettings(); - this.inventory = new PlayerInventory(serverProcess, this); + this.inventory = new PlayerInventory(serverSettings, globalEventHandler, this); setCanPickupItem(true); // By default @@ -261,9 +304,9 @@ public Player(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull chunkRemover = (chunkX, chunkZ) -> { // Unload old chunks sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); - getServerProcess().getGlobalEventHandler().call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); + globalEventHandler.call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); }; - experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(getServerProcess().getServerSetting()))); + experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(serverSettings))); } @ApiStatus.Internal @@ -291,13 +334,13 @@ public CompletableFuture UNSAFE_init() { final JoinGamePacket joinGamePacket = new JoinGamePacket( getEntityId(), this.hardcore, List.of(), 0, - getServerProcess().getServerSetting().getChunkViewDistance(), getServerProcess().getServerSetting().getChunkViewDistance(), + serverSettings.getChunkViewDistance(), serverSettings.getChunkViewDistance(), false, true, false, dimensionType.toString(), spawnInstance.getDimensionName(), 0, gameMode, null, false, levelFlat, deathLocation, portalCooldown); sendPacket(joinGamePacket); // Difficulty - sendPacket(new ServerDifficultyPacket(getServerProcess().getServerSetting().getDifficulty(), true)); + sendPacket(new ServerDifficultyPacket(serverSettings.getDifficulty(), true)); sendPacket(new SpawnPositionPacket(respawnPoint, 0)); @@ -319,12 +362,11 @@ public CompletableFuture UNSAFE_init() { } } PlayerSkinInitEvent skinInitEvent = new PlayerSkinInitEvent(this, profileSkin); - getServerProcess().getGlobalEventHandler().call(skinInitEvent); + globalEventHandler.call(skinInitEvent); this.skin = skinInitEvent.getSkin(); // FIXME: when using Geyser, this line remove the skin of the client - PacketUtils.broadcastPlayPacket(getServerProcess(), getAddPlayerToList()); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, getAddPlayerToList()); - var connectionManager = getServerProcess().getConnectionManager(); for (var player : connectionManager.getOnlinePlayers()) { if (player != this) { sendPacket(player.getAddPlayerToList()); @@ -335,7 +377,7 @@ public CompletableFuture UNSAFE_init() { } //Teams - for (Team team : getServerProcess().getTeamManager().getTeams()) { + for (Team team : teamManager.getTeams()) { sendPacket(team.createTeamsCreationPacket()); } @@ -344,7 +386,6 @@ public CompletableFuture UNSAFE_init() { // Recipes start { - RecipeManager recipeManager = getServerProcess().getRecipeManager(); sendPacket(recipeManager.getDeclareRecipesPacket()); List recipesIdentifier = new ArrayList<>(); @@ -388,7 +429,6 @@ public void startConfigurationPhase() { // Remove the player, then send them back to configuration remove(false); - var connectionManager = getServerProcess().getConnectionManager(); connectionManager.transitionPlayToConfig(this); } @@ -421,7 +461,7 @@ public void update(long time) { EntityTracker.Target.EXPERIENCE_ORBS, experienceOrb -> { if (expandedBoundingBox.intersectEntity(loweredPosition, experienceOrb)) { PickupExperienceEvent pickupExperienceEvent = new PickupExperienceEvent(this, experienceOrb); - getServerProcess().getGlobalEventHandler().callCancellable(pickupExperienceEvent, () -> { + globalEventHandler.callCancellable(pickupExperienceEvent, () -> { short experienceCount = pickupExperienceEvent.getExperienceCount(); // TODO give to player experienceOrb.remove(); }); @@ -446,7 +486,7 @@ public void update(long time) { if (isFood) { PlayerEatEvent playerEatEvent = new PlayerEatEvent(this, foodItem, eatingHand); - getServerProcess().getGlobalEventHandler().call(playerEatEvent); + globalEventHandler.call(playerEatEvent); } refreshEating(null); @@ -456,7 +496,7 @@ public void update(long time) { if (EXPERIMENT_PERFORM_POSE_UPDATES) updatePose(); // Tick event - getServerProcess().getGlobalEventHandler().call(new PlayerTickEvent(this)); + globalEventHandler.call(new PlayerTickEvent(this)); } @Override @@ -486,7 +526,7 @@ public void kill() { // Call player death event PlayerDeathEvent playerDeathEvent = new PlayerDeathEvent(this, deathText, chatMessage); - getServerProcess().getGlobalEventHandler().call(playerDeathEvent); + globalEventHandler.call(playerDeathEvent); deathText = playerDeathEvent.getDeathText(); chatMessage = playerDeathEvent.getChatMessage(); @@ -498,7 +538,9 @@ public void kill() { // #buildDeathMessage can return null, check here if (chatMessage != null) { - getServerProcess().getAudiences().players().sendMessage(chatMessage); + for (Player player : connectionManager.getOnlinePlayers()) { + player.sendMessage(chatMessage); + } } // Set death location @@ -524,7 +566,7 @@ public void respawn() { 0, gameMode, gameMode, false, levelFlat, deathLocation, portalCooldown, RespawnPacket.COPY_ALL)); PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this); - getServerProcess().getGlobalEventHandler().call(respawnEvent); + globalEventHandler.call(respawnEvent); triggerStatus((byte) (24 + permissionLevel)); // Set permission level refreshIsDead(false); updatePose(); @@ -535,7 +577,7 @@ public void respawn() { ChunkUtils.forChunksInRange(respawnPosition, settings.getEffectiveViewDistance(), chunkAdder); chunksLoadedByClient = new Vec(respawnPosition.chunkX(), respawnPosition.chunkZ()); // Client also needs all entities resent to them, since those are unloaded as well - this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(getServerProcess().getServerSetting().getChunkViewDistance(), settings.getViewDistance()), + this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(serverSettings.getChunkViewDistance(), settings.getViewDistance()), EntityTracker.Target.ENTITIES, entity -> { // Skip refreshing self with a new viewer if (!entity.getUuid().equals(uuid) && entity.isViewer(this)) { @@ -550,7 +592,7 @@ public void respawn() { */ private void refreshClientStateAfterRespawn() { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); - sendPacket(new ServerDifficultyPacket(getServerProcess().getServerSetting().getDifficulty(), false)); + sendPacket(new ServerDifficultyPacket(serverSettings.getDifficulty(), false)); sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation)); sendPacket(new SetExperiencePacket(exp, level, 0)); triggerStatus((byte) (24 + permissionLevel)); // Set permission level @@ -563,7 +605,7 @@ private void refreshClientStateAfterRespawn() { * again, and any changes will be visible to the player. */ public void refreshCommands() { - sendPacket(getServerProcess().getCommandManager().createDeclareCommandsPacket(this)); + sendPacket(commandManager.createDeclareCommandsPacket(this)); } @Override @@ -577,14 +619,14 @@ public void remove(boolean permanent) { if (permanent) { this.packets.clear(); - getServerProcess().getGlobalEventHandler().call(new PlayerDisconnectEvent(this)); + globalEventHandler.call(new PlayerDisconnectEvent(this)); } super.remove(permanent); final Inventory currentInventory = getOpenInventory(); if (currentInventory != null) currentInventory.removeViewer(this); - getServerProcess().getBossBarManager().removeAllBossBars(this); + bossBarManager.removeAllBossBars(this); // Advancement tabs cache { Set advancementTabs = AdvancementTab.getTabs(this); @@ -598,9 +640,9 @@ public void remove(boolean permanent) { final int chunkX = position.chunkX(); final int chunkZ = position.chunkZ(); // Clear all viewable chunks - ChunkUtils.forChunksInRange(chunkX, chunkZ, getServerProcess().getServerSetting().getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(chunkX, chunkZ, serverSettings.getChunkViewDistance(), chunkRemover); // Remove from the tab-list - PacketUtils.broadcastPlayPacket(getServerProcess(), getRemovePlayerToList()); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, getRemovePlayerToList()); // Prevent the player from being stuck in loading screen, or just unable to interact with the server // This should be considered as a bug, since the player will ultimately time out anyway. @@ -617,9 +659,9 @@ public void updateOldViewer(@NotNull Player player) { } @Override - public void sendPacketToViewersAndSelf(@NotNull SendablePacket packet) { + public void sendPacketToViewersAndSelf(ServerSettings serverSettings, @NotNull SendablePacket packet) { sendPacket(packet); - super.sendPacketToViewersAndSelf(packet); + super.sendPacketToViewersAndSelf(serverSettings, packet); } /** @@ -650,7 +692,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Ensure that surrounding chunks are loaded List> futures = new ArrayList<>(); - ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getServerSetting().getChunkViewDistance(), (chunkX, chunkZ) -> { + ChunkUtils.forChunksInRange(spawnPosition, serverSettings.getChunkViewDistance(), (chunkX, chunkZ) -> { final CompletableFuture future = instance.loadOptionalChunk(chunkX, chunkZ); if (!future.isDone()) futures.add(future); }); @@ -663,7 +705,6 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // One or more chunks need to be loaded final Thread runThread = Thread.currentThread(); CountDownLatch latch = new CountDownLatch(1); - Scheduler scheduler = getServerProcess().getSchedulerManager(); CompletableFuture future = new CompletableFuture<>() { @Override public Void join() { @@ -674,7 +715,7 @@ public Void join() { } catch (InterruptedException e) { throw new RuntimeException(e); } - scheduler.process(); + schedulerManager.process(); assert isDone(); } return super.join(); @@ -683,7 +724,7 @@ public Void join() { CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)) .thenRun(() -> { - scheduler.scheduleNextProcess(() -> { + schedulerManager.scheduleNextProcess(() -> { runnable.accept(instance); future.complete(null); }); @@ -723,7 +764,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, if (!firstSpawn && !dimensionChange) { // Player instance changed, clear current viewable collections if (updateChunks) - ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getServerSetting().getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(spawnPosition, serverSettings.getChunkViewDistance(), chunkRemover); } if (dimensionChange) sendDimension(instance.getDimensionType(), instance.getDimensionName()); @@ -738,7 +779,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new UpdateViewPositionPacket(chunkX, chunkZ)); // Load the nearby chunks and queue them to be sent to them - ChunkUtils.forChunksInRange(spawnPosition, getServerProcess().getServerSetting().getChunkViewDistance(), chunkAdder); + ChunkUtils.forChunksInRange(spawnPosition, serverSettings.getChunkViewDistance(), chunkAdder); } synchronizePosition(true); // So the player doesn't get stuck @@ -757,7 +798,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); } - getServerProcess().getGlobalEventHandler().call(new PlayerSpawnEvent(this, instance, firstSpawn)); + globalEventHandler.call(new PlayerSpawnEvent(this, instance, firstSpawn)); } @ApiStatus.Internal @@ -805,7 +846,7 @@ private void sendPendingChunks() { if (chunk == null || !chunk.isLoaded()) continue; sendPacket(chunk.getFullDataPacket()); - getServerProcess().getGlobalEventHandler().call(new PlayerChunkLoadEvent(this, chunkX, chunkZ)); + globalEventHandler.call(new PlayerChunkLoadEvent(this, chunkX, chunkZ)); pendingChunkCount -= 1f; batchSize += 1; @@ -979,12 +1020,12 @@ public void clearTitle() { @Override public void showBossBar(@NotNull BossBar bar) { - getServerProcess().getBossBarManager().addBossBar(this, bar); + bossBarManager.addBossBar(this, bar); } @Override public void hideBossBar(@NotNull BossBar bar) { - getServerProcess().getBossBarManager().removeBossBar(this, bar); + bossBarManager.removeBossBar(this, bar); } @Override @@ -1156,7 +1197,7 @@ public double getEyeHeight() { */ public void setDisplayName(@Nullable Component displayName) { this.displayName = displayName; - PacketUtils.broadcastPlayPacket(getServerProcess(), new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); } /** @@ -1198,11 +1239,11 @@ public synchronized void setSkin(@Nullable PlayerSkin skin) { { // Remove player - PacketUtils.broadcastPlayPacket(getServerProcess(), removePlayerPacket); - sendPacketToViewers(destroyEntitiesPacket); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, removePlayerPacket); + sendPacketToViewers(serverSettings, destroyEntitiesPacket); // Show player again - PacketUtils.broadcastPlayPacket(getServerProcess(), addPlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, addPlayerPacket); getViewers().forEach(player -> showPlayer(player.getPlayerConnection())); } @@ -1279,7 +1320,7 @@ public void setUsernameField(@NotNull String username) { public boolean dropItem(@NotNull ItemStack item) { if (item.isAir()) return false; ItemDropEvent itemDropEvent = new ItemDropEvent(this, item); - getServerProcess().getGlobalEventHandler().call(itemDropEvent); + globalEventHandler.call(itemDropEvent); return !itemDropEvent.isCancelled(); } @@ -1408,13 +1449,13 @@ public void setRespawnPoint(@NotNull Pos respawnPoint) { * and send data to his new viewers. */ protected void refreshAfterTeleport() { - sendPacketsToViewers(getEntityType().registry().spawnType().getSpawnPacket(this)); + sendPacketsToViewers(serverSettings, getEntityType().registry().spawnType().getSpawnPacket(this)); // Update for viewers - sendPacketToViewersAndSelf(getVelocityPacket()); - sendPacketToViewersAndSelf(getMetadataPacket()); - sendPacketToViewersAndSelf(getPropertiesPacket()); - sendPacketToViewersAndSelf(getEquipmentsPacket()); + sendPacketToViewersAndSelf(serverSettings, getVelocityPacket()); + sendPacketToViewersAndSelf(serverSettings, getMetadataPacket()); + sendPacketToViewersAndSelf(serverSettings, getPropertiesPacket()); + sendPacketToViewersAndSelf(serverSettings, getEquipmentsPacket()); getInventory().update(); } @@ -1568,7 +1609,7 @@ public GameMode getGameMode() { */ public boolean setGameMode(@NotNull GameMode gameMode) { PlayerGameModeChangeEvent playerGameModeChangeEvent = new PlayerGameModeChangeEvent(this, gameMode); - getServerProcess().getGlobalEventHandler().call(playerGameModeChangeEvent); + globalEventHandler.call(playerGameModeChangeEvent); if (playerGameModeChangeEvent.isCancelled()) { // Abort return false; @@ -1580,7 +1621,7 @@ public boolean setGameMode(@NotNull GameMode gameMode) { // Condition to prevent sending the packets before spawning the player if (isActive()) { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.CHANGE_GAMEMODE, gameMode.id())); - PacketUtils.broadcastPlayPacket(getServerProcess(), new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); } // The client updates their abilities based on the GameMode as follows @@ -1716,7 +1757,7 @@ public void setBelowNameTag(BelowNameTag belowNameTag) { public boolean openInventory(@NotNull Inventory inventory) { InventoryOpenEvent inventoryOpenEvent = new InventoryOpenEvent(inventory, this); - getServerProcess().getGlobalEventHandler().callCancellable(inventoryOpenEvent, () -> { + globalEventHandler.callCancellable(inventoryOpenEvent, () -> { Inventory openInventory = getOpenInventory(); if (openInventory != null) { openInventory.removeViewer(this); @@ -2068,9 +2109,8 @@ public void interpretPacketQueue() { kick(Component.text("Too Many Packets", NamedTextColor.RED)); return; } - final PacketListenerManager manager = getServerProcess().getPacketListenerManager(); // This method is NOT thread-safe - this.packets.drain(packet -> manager.processClientPacket(packet, playerConnection), PACKET_PER_TICK); + this.packets.drain(packet -> packetListenerManager.processClientPacket(packet, playerConnection), PACKET_PER_TICK); } /** @@ -2081,7 +2121,7 @@ public void interpretPacketQueue() { public void refreshLatency(int latency) { this.latency = latency; if (getPlayerConnection().getConnectionState() == ConnectionState.PLAY) { - PacketUtils.broadcastPlayPacket(getServerProcess(), new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); } } @@ -2089,7 +2129,7 @@ public void refreshOnGround(boolean onGround) { this.onGround = onGround; if (this.onGround && this.isFlyingWithElytra()) { this.setFlyingWithElytra(false); - getServerProcess().getGlobalEventHandler().call(new PlayerStopFlyingWithElytraEvent(this)); + globalEventHandler.call(new PlayerStopFlyingWithElytraEvent(this)); } } @@ -2163,7 +2203,7 @@ public void refreshEating(@Nullable Hand eatingHand) { return null; ItemUpdateStateEvent itemUpdateStateEvent = new ItemUpdateStateEvent(this, hand, updatedItem); - getServerProcess().getGlobalEventHandler().call(itemUpdateStateEvent); + globalEventHandler.call(itemUpdateStateEvent); return itemUpdateStateEvent; } @@ -2362,7 +2402,7 @@ protected void sendChunkUpdates(Chunk newChunk) { final Vec old = chunksLoadedByClient; sendPacket(new UpdateViewPositionPacket(newX, newZ)); ChunkUtils.forDifferingChunksInRange(newX, newZ, (int) old.x(), (int) old.z(), - getServerProcess().getServerSetting().getChunkViewDistance(), chunkAdder, chunkRemover); + serverSettings.getChunkViewDistance(), chunkAdder, chunkRemover); this.chunksLoadedByClient = new Vec(newX, newZ); } } @@ -2430,7 +2470,7 @@ public byte getViewDistance() { } public int getEffectiveViewDistance() { - return Math.min(getViewDistance(), getServerProcess().getServerSetting().getChunkViewDistance()); + return Math.min(getViewDistance(), serverSettings.getChunkViewDistance()); } /** diff --git a/src/main/java/net/minestom/server/entity/PlayerProjectile.java b/src/main/java/net/minestom/server/entity/PlayerProjectile.java index be2b0597a07..b97c4edbdd5 100644 --- a/src/main/java/net/minestom/server/entity/PlayerProjectile.java +++ b/src/main/java/net/minestom/server/entity/PlayerProjectile.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.collision.CollisionUtils; import net.minestom.server.collision.PhysicsResult; import net.minestom.server.collision.ShapeImpl; @@ -8,14 +8,20 @@ import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.projectile.ProjectileMeta; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.entity.EntityShootEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithEntityEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; +import net.minestom.server.thread.ThreadDispatcher; import org.jetbrains.annotations.NotNull; import java.util.Random; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; @@ -23,8 +29,8 @@ public class PlayerProjectile extends LivingEntity { private final Entity shooter; private long cooldown = 0; - public PlayerProjectile(ServerProcess serverProcess, Entity shooter, EntityType type) { - super(serverProcess, type); + public PlayerProjectile(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, Entity shooter, EntityType type) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, type, UUID.randomUUID()); this.shooter = shooter; this.hasCollision = false; setup(); @@ -50,7 +56,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Check if we're inside of a block if (insideBlock != null) { var e = new ProjectileCollideWithBlockEvent(this, Pos.fromPoint(spawnPosition), instance.getBlock(spawnPosition)); - getServerProcess().getGlobalEventHandler().call(e); + globalEventHandler.call(e); } return res; @@ -86,7 +92,7 @@ public void shoot(@NotNull Point from, @NotNull Point to, double power, double s dz += random.nextGaussian() * spread; final EntityShootEvent shootEvent = new EntityShootEvent(this.shooter, this, from, power, spread); - getServerProcess().getGlobalEventHandler().call(shootEvent); + globalEventHandler.call(shootEvent); if (shootEvent.isCancelled()) { remove(); return; @@ -148,7 +154,7 @@ public void tick(long time) { if (collided != null && collided.collisionShapes()[0] != shooter) { if (collided.collisionShapes()[0] instanceof Entity entity) { var e = new ProjectileCollideWithEntityEvent(this, collided.newPosition(), entity); - getServerProcess().getGlobalEventHandler().call(e); + globalEventHandler.call(e); return; } } @@ -172,7 +178,7 @@ public void tick(long time) { if (hitBlock == null) return; var e = new ProjectileCollideWithBlockEvent(this, Pos.fromPoint(hitPoint), hitBlock); - getServerProcess().getGlobalEventHandler().call(e); + globalEventHandler.call(e); } } } diff --git a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java index 5bfc7271051..d230f28fa5a 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/CombinedAttackGoal.java @@ -127,7 +127,7 @@ public CombinedAttackGoal(@NotNull EntityCreature entityCreature, this.rangedDelay = rangedDelay; this.desirableRangeSquared = desirableRange * desirableRange; this.comeClose = comeClose; - this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getServerSetting()))); + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerSettings()))); Check.argCondition(desirableRange > rangedRange, "Desirable range can not exceed ranged range!"); } @@ -179,7 +179,7 @@ public void tick(long time) { Function projectileGenerator = this.projectileGenerator; if (projectileGenerator == null) { - projectileGenerator = shooter -> new EntityProjectile(shooter.getServerProcess(), shooter, EntityType.ARROW); + projectileGenerator = shooter -> new EntityProjectile(shooter, EntityType.ARROW); } EntityProjectile projectile = projectileGenerator.apply(this.entityCreature); projectile.setInstance(this.entityCreature.getInstance(), this.entityCreature.getPosition()); diff --git a/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java index 85585f1c653..85162d2df20 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/MeleeAttackGoal.java @@ -47,7 +47,7 @@ public MeleeAttackGoal(@NotNull EntityCreature entityCreature, double range, Dur super(entityCreature); this.range = range; this.delay = delay; - this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getServerSetting()))); + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerSettings()))); } public @NotNull Cooldown getCooldown() { diff --git a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java index dfef4ec7c45..f6a4fb0e23c 100644 --- a/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java +++ b/src/main/java/net/minestom/server/entity/ai/goal/RangedAttackGoal.java @@ -63,7 +63,7 @@ public RangedAttackGoal(@NotNull EntityCreature entityCreature, Duration delay, this.comeClose = comeClose; this.power = power; this.spread = spread; - this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerProcess().getServerSetting()))); + this.cooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(entityCreature.getServerSettings()))); Check.argCondition(desirableRange > attackRange, "Desirable range can not exceed attack range!"); } @@ -85,7 +85,7 @@ public void setProjectileGenerator(Function projectile private ProjectileGenerator getProjectileGeneratorOrDefault() { if (projectileGenerator == null) { - setProjectileGenerator(shooter -> new EntityProjectile(shooter.getServerProcess(), shooter, EntityType.ARROW)); + setProjectileGenerator(shooter -> new EntityProjectile(shooter, EntityType.ARROW)); } return projectileGenerator; } diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index d6c727dad86..a614d0071b9 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -1,20 +1,33 @@ package net.minestom.server.entity.fakeplayer; import com.extollit.gaming.ai.path.HydrazinePathFinder; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettings; +import net.minestom.server.adventure.bossbar.BossBarManager; +import net.minestom.server.command.CommandManager; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.NavigableEntity; import net.minestom.server.entity.pathfinding.Navigator; +import net.minestom.server.event.Event; import net.minestom.server.event.EventListener; +import net.minestom.server.event.EventNode; import net.minestom.server.event.player.PlayerSpawnEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; +import net.minestom.server.instance.block.BlockManager; import net.minestom.server.listener.manager.PacketListenerManager; import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.login.ClientLoginAcknowledgedPacket; import net.minestom.server.network.player.FakePlayerConnection; import net.minestom.server.network.player.PlayerConnection; +import net.minestom.server.network.socket.Server; +import net.minestom.server.recipe.RecipeManager; +import net.minestom.server.scoreboard.TeamManager; +import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -28,20 +41,37 @@ * (events, velocity, gravity, player list, etc...) with the exception that you need to control it server-side * using a {@link FakePlayerController} (see {@link #getController()}). *

        - * You can create one using {@link #initPlayer(ServerProcess, UUID, String, Consumer)}. Be aware that this really behave exactly like a player + * You can create one using {link #initPlayer(ServerProcess, UUID, String, Consumer)}. Be aware that this really behave exactly like a player * and this is a feature not a bug, you will need to check at some place if the player is a fake one or not (instanceof) if you want to change it. */ public class FakePlayer extends Player implements NavigableEntity { - private final ConnectionManager connectionManager; - private final PacketListenerManager packetListenerManager; - private final FakePlayerOption option; private final FakePlayerController fakePlayerController; private final Navigator navigator = new Navigator(this); private EventListener spawnListener; + private final SchedulerManager scheduleManager; + + public FakePlayer(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { + this( + serverFacade.getServerSettings(), + serverFacade.getGlobalEventHandler(), + serverFacade.getChunkDispatcher(), + serverFacade.getExceptionHandler(), + serverFacade.getConnectionManager(), + serverFacade.getTeamManager(), + serverFacade.getRecipeManager(), + serverFacade.getCommandManager(), + serverFacade.getBossBarManager(), + serverFacade.getSchedulerManager(), + serverFacade.getPacketListenerManager(), + serverFacade.getBlockManager(), + serverFacade.getServer(), + uuid, username, option, spawnCallback + ); + } /** * Initializes a new {@link FakePlayer} with the given {@code uuid}, {@code username} and {@code option}'s. @@ -50,12 +80,25 @@ public class FakePlayer extends Player implements NavigableEntity { * @param username The username for the fake player. * @param option Any option for the fake player. */ - protected FakePlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, - @NotNull FakePlayerOption option, - @Nullable Consumer spawnCallback) { - super(serverProcess, uuid, username, new FakePlayerConnection(serverProcess)); - this.connectionManager = serverProcess.getConnectionManager(); - this.packetListenerManager = serverProcess.getPacketListenerManager(); + public FakePlayer(ServerSettings serverSettings, + EventNode globalEventHandler, + ThreadDispatcher dispatcher, + ExceptionHandler exceptionHandler, + ConnectionManager connectionManager, + TeamManager teamManager, + RecipeManager recipeManager, + CommandManager commandManager, + BossBarManager bossBarManager, + SchedulerManager schedulerManager, + PacketListenerManager packetListenerManager, + BlockManager blockManager, + Server server, + @NotNull UUID uuid, + @NotNull String username, + @NotNull FakePlayerOption option, + @Nullable Consumer spawnCallback) { + super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, connectionManager, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, new FakePlayerConnection(server, connectionManager)); + this.scheduleManager = schedulerManager; this.option = option; @@ -68,10 +111,10 @@ protected FakePlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @ if (event.getPlayer().equals(this)) if (event.isFirstSpawn()) { spawnCallback.accept(this); - serverProcess.getGlobalEventHandler().removeListener(spawnListener); + globalEventHandler.removeListener(spawnListener); } }).build(); - serverProcess.getGlobalEventHandler().addListener(spawnListener); + globalEventHandler.addListener(spawnListener); } playerConnection.setConnectionState(ConnectionState.LOGIN); @@ -81,31 +124,31 @@ protected FakePlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @ }); } - /** - * Initializes a new {@link FakePlayer}. - * - * @param uuid the FakePlayer uuid - * @param username the FakePlayer username - * @param spawnCallback the optional callback called when the fake player first spawn - */ - public static void initPlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, - @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - new FakePlayer(serverProcess, uuid, username, option, spawnCallback); - } - - /** - * Initializes a new {@link FakePlayer} without adding it in cache. - *

        - * If you want the fake player to be obtainable with the {@link net.minestom.server.network.ConnectionManager} - * you need to specify it in a {@link FakePlayerOption} and use {@link #initPlayer(ServerProcess, UUID, String, FakePlayerOption, Consumer)}. - * - * @param uuid the FakePlayer uuid - * @param username the FakePlayer username - * @param spawnCallback the optional callback called when the fake player first spawn - */ - public static void initPlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @Nullable Consumer spawnCallback) { - initPlayer(serverProcess, uuid, username, new FakePlayerOption(), spawnCallback); - } +// /** +// * Initializes a new {@link FakePlayer}. +// * +// * @param uuid the FakePlayer uuid +// * @param username the FakePlayer username +// * @param spawnCallback the optional callback called when the fake player first spawn +// */ +// public static void initPlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, +// @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { +// new FakePlayer(serverProcess, uuid, username, option, spawnCallback); +// } + +// /** +// * Initializes a new {@link FakePlayer} without adding it in cache. +// *

        +// * If you want the fake player to be obtainable with the {@link ConnectionManagerImpl} +// * you need to specify it in a {@link FakePlayerOption} and use {@link #initPlayer(ServerProcess, UUID, String, FakePlayerOption, Consumer)}. +// * +// * @param uuid the FakePlayer uuid +// * @param username the FakePlayer username +// * @param spawnCallback the optional callback called when the fake player first spawn +// */ +// public static void initPlayer(@NotNull ServerProcess serverProcess, @NotNull UUID uuid, @NotNull String username, @Nullable Consumer spawnCallback) { +// initPlayer(serverProcess, uuid, username, new FakePlayerOption(), spawnCallback); +// } /** * Gets the fake player option container. @@ -166,7 +209,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - getServerProcess().getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(getServerProcess().getServerSetting())).schedule(); + scheduleManager.buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(serverSettings)).schedule(); } } } diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayerOption.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayerOption.java index eacc54218a3..e04ce7ee0be 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayerOption.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayerOption.java @@ -1,6 +1,6 @@ package net.minestom.server.entity.fakeplayer; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerImpl; /** * Represents any options for a {@link FakePlayer}. @@ -13,7 +13,7 @@ public class FakePlayerOption { /** * Gets if the player is registered internally as a Player. * - * @return true if the player is registered in {@link ConnectionManager}, false otherwise + * @return true if the player is registered in {@link ConnectionManagerImpl}, false otherwise */ public boolean isRegistered() { return registered; diff --git a/src/main/java/net/minestom/server/entity/hologram/Hologram.java b/src/main/java/net/minestom/server/entity/hologram/Hologram.java index 7735b076dd3..6848b1bb9e2 100644 --- a/src/main/java/net/minestom/server/entity/hologram/Hologram.java +++ b/src/main/java/net/minestom/server/entity/hologram/Hologram.java @@ -1,18 +1,24 @@ package net.minestom.server.entity.hologram; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.Player; import net.minestom.server.entity.metadata.other.ArmorStandMeta; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; import java.util.Set; +import java.util.UUID; /** * Represents an invisible armor stand showing a {@link Component}. @@ -30,17 +36,6 @@ public class Hologram implements Viewable { private boolean removed; - /** - * Constructs a new {@link Hologram} with the given parameters. - * - * @param instance The instance where the hologram should be spawned. - * @param spawnPosition The spawn position of this hologram. - * @param text The text of this hologram. - */ - public Hologram(Instance instance, Pos spawnPosition, Component text) { - this(instance, spawnPosition, text, true); - } - /** * Constructs a new {@link Hologram} with the given parameters. * @@ -49,20 +44,8 @@ public Hologram(Instance instance, Pos spawnPosition, Component text) { * @param text The text of this hologram. * @param autoViewable {@code true}if the hologram should be visible automatically, otherwise {@code false}. */ - public Hologram(Instance instance, Pos spawnPosition, Component text, boolean autoViewable) { - this(instance, spawnPosition, text, autoViewable, false); - } - - /** - * Constructs a new {@link Hologram} with the given parameters. - * - * @param instance The instance where the hologram should be spawned. - * @param spawnPosition The spawn position of this hologram. - * @param text The text of this hologram. - * @param autoViewable {@code true}if the hologram should be visible automatically, otherwise {@code false}. - */ - public Hologram(Instance instance, Pos spawnPosition, Component text, boolean autoViewable, boolean marker) { - this.entity = new Entity(instance.getServerProcess(), EntityType.ARMOR_STAND); + public Hologram(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, Instance instance, Pos spawnPosition, Component text, boolean autoViewable, boolean marker) { + this.entity = new Entity(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.ARMOR_STAND, UUID.randomUUID()); ArmorStandMeta armorStandMeta = (ArmorStandMeta) entity.getEntityMeta(); @@ -187,8 +170,4 @@ private void checkRemoved() { Check.stateCondition(isRemoved(), "You cannot interact with a removed Hologram"); } - @Override - public ServerProcess getServerProcess() { - return entity.getServerProcess(); - } } diff --git a/src/main/java/net/minestom/server/event/EventNode.java b/src/main/java/net/minestom/server/event/EventNode.java index 4d51f2f96d4..7125998676f 100644 --- a/src/main/java/net/minestom/server/event/EventNode.java +++ b/src/main/java/net/minestom/server/event/EventNode.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.tag.Tag; import net.minestom.server.tag.TagReadable; @@ -24,7 +24,7 @@ * * @param The event type accepted by this node */ -public sealed interface EventNode permits EventNodeImpl { +public interface EventNode { /** * Creates an event node which accepts any event type with no filtering. @@ -33,9 +33,9 @@ public sealed interface EventNode permits EventNodeImpl { * @return An event node with no filtering */ @Contract(value = "_, _ -> new", pure = true) - static @NotNull EventNode all(@NotNull ServerProcess serverProcess, + static @NotNull EventNode all(@NotNull ServerFacade serverFacade, @NotNull String name) { - return type(serverProcess, name, EventFilter.ALL); + return type(serverFacade, name, EventFilter.ALL); } /** @@ -53,10 +53,10 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with just an event type filter */ @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull ServerProcess serverProcess, + static @NotNull EventNode type(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter) { - return create(serverProcess, name, filter, null); + return create(serverFacade, name, filter, null); } /** @@ -79,11 +79,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode event(@NotNull ServerProcess serverProcess, + static @NotNull EventNode event(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(serverProcess, name, filter, (e, h) -> predicate.test(e)); + return create(serverFacade, name, filter, (e, h) -> predicate.test(e)); } /** @@ -108,11 +108,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull ServerProcess serverProcess, + static @NotNull EventNode type(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter, @NotNull BiPredicate predicate) { - return create(serverProcess, name, filter, predicate); + return create(serverFacade, name, filter, predicate); } /** @@ -134,11 +134,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode value(@NotNull ServerProcess serverProcess, + static @NotNull EventNode value(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(serverProcess, name, filter, (e, h) -> predicate.test(h)); + return create(serverFacade, name, filter, (e, h) -> predicate.test(h)); } /** @@ -154,11 +154,11 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a handler with the provided tag */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull ServerProcess serverProcess, + static @NotNull EventNode tag(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag) { - return create(serverProcess, name, filter, (e, h) -> h.hasTag(tag)); + return create(serverFacade, name, filter, (e, h) -> h.hasTag(tag)); } /** @@ -173,20 +173,20 @@ public sealed interface EventNode permits EventNodeImpl { * @return A node with an event type filter as well as a handler with the provided tag */ @Contract(value = "_, _, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull ServerProcess serverProcess, + static @NotNull EventNode tag(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag, @NotNull Predicate<@Nullable V> consumer) { - return create(serverProcess, name, filter, (e, h) -> consumer.test(h.getTag(tag))); + return create(serverFacade, name, filter, (e, h) -> consumer.test(h.getTag(tag))); } - private static EventNode create(@NotNull ServerProcess serverProcess, + private static EventNode create(@NotNull ServerFacade serverFacade, @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { //noinspection unchecked - return new EventNodeImpl<>(serverProcess.getExceptionHandler(), name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); + return new EventNodeImpl<>(serverFacade.getExceptionHandler(), name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); } /** diff --git a/src/main/java/net/minestom/server/event/EventNodeImpl.java b/src/main/java/net/minestom/server/event/EventNodeImpl.java index 90a3a1db636..6b02d7b11ed 100644 --- a/src/main/java/net/minestom/server/event/EventNodeImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeImpl.java @@ -17,7 +17,7 @@ import java.util.function.BiPredicate; import java.util.function.Consumer; -non-sealed class EventNodeImpl implements EventNode { +class EventNodeImpl implements EventNode { private static final boolean ALLOW_MULTIPLE_PARENTS = Boolean.getBoolean("minestom.event.multiple-parents"); static final Object GLOBAL_CHILD_LOCK = new Object(); diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandler.java b/src/main/java/net/minestom/server/event/GlobalEventHandler.java index 55e649ce765..5403afc87e0 100644 --- a/src/main/java/net/minestom/server/event/GlobalEventHandler.java +++ b/src/main/java/net/minestom/server/event/GlobalEventHandler.java @@ -1,12 +1,4 @@ package net.minestom.server.event; -import net.minestom.server.exception.ExceptionHandler; - -/** - * Object containing all the global event listeners. - */ -public final class GlobalEventHandler extends EventNodeImpl { - public GlobalEventHandler(ExceptionHandler exceptionHandler) { - super(exceptionHandler, "global", EventFilter.ALL, null); - } +public interface GlobalEventHandler extends EventNode { } diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java b/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java new file mode 100644 index 00000000000..d03247bd008 --- /dev/null +++ b/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java @@ -0,0 +1,12 @@ +package net.minestom.server.event; + +import net.minestom.server.exception.ExceptionHandler; + +/** + * Object containing all the global event listeners. + */ +public final class GlobalEventHandlerImpl extends EventNodeImpl implements GlobalEventHandler { + public GlobalEventHandlerImpl(ExceptionHandler exceptionHandler) { + super(exceptionHandler, "global", EventFilter.ALL, null); + } +} diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandlerProvider.java b/src/main/java/net/minestom/server/event/GlobalEventHandlerProvider.java new file mode 100644 index 00000000000..af126de4a75 --- /dev/null +++ b/src/main/java/net/minestom/server/event/GlobalEventHandlerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.event; + +public interface GlobalEventHandlerProvider { + GlobalEventHandler getGlobalEventHandler(); +} diff --git a/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java b/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java index 432af3373f8..cff9c03f38a 100644 --- a/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java +++ b/src/main/java/net/minestom/server/event/server/ServerListPingEvent.java @@ -1,8 +1,9 @@ package net.minestom.server.event.server; -import net.minestom.server.ServerProcess; import net.minestom.server.event.trait.CancellableEvent; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.player.PlayerConnection; +import net.minestom.server.network.socket.Server; import net.minestom.server.ping.ResponseData; import net.minestom.server.ping.ServerListPingType; import org.jetbrains.annotations.NotNull; @@ -26,8 +27,8 @@ public class ServerListPingEvent implements CancellableEvent { * * @param type the ping type to respond with */ - public ServerListPingEvent(@NotNull ServerProcess serverProcess, @NotNull ServerListPingType type) { - this(serverProcess, null, type); + public ServerListPingEvent(@NotNull ConnectionManager connectionManager, Server server, @NotNull ServerListPingType type) { + this(connectionManager, server, null, type); } /** @@ -36,8 +37,8 @@ public ServerListPingEvent(@NotNull ServerProcess serverProcess, @NotNull Server * @param connection the player connection, if the ping type is modern * @param type the ping type to respond with */ - public ServerListPingEvent(@NotNull ServerProcess serverProcess, @Nullable PlayerConnection connection, @NotNull ServerListPingType type) { - this.responseData = new ResponseData(serverProcess); + public ServerListPingEvent(@NotNull ConnectionManager connectionManager, Server server, @Nullable PlayerConnection connection, @NotNull ServerListPingType type) { + this.responseData = new ResponseData(connectionManager, server); this.connection = connection; this.type = type; } diff --git a/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java b/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java index 62f676534b7..1b3578803e6 100644 --- a/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java +++ b/src/main/java/net/minestom/server/exception/ExceptionHandlerImpl.java @@ -1,21 +1,9 @@ package net.minestom.server.exception; -import net.minestom.server.ServerProcess; - public final class ExceptionHandlerImpl implements ExceptionHandler { - private final ServerProcess serverProcess; - - public ExceptionHandlerImpl(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } - @Override public void handleException(Throwable e) { e.printStackTrace(); - if (e instanceof OutOfMemoryError) { - // OOM should be handled manually - serverProcess.stop(); - } } } diff --git a/src/main/java/net/minestom/server/exception/ExceptionHandlerProvider.java b/src/main/java/net/minestom/server/exception/ExceptionHandlerProvider.java new file mode 100644 index 00000000000..aa8cfd94e1d --- /dev/null +++ b/src/main/java/net/minestom/server/exception/ExceptionHandlerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.exception; + +public interface ExceptionHandlerProvider { + ExceptionHandler getExceptionHandler(); +} diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index 5ed0abb92a8..c15f75e6e3a 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -1,6 +1,6 @@ package net.minestom.server.extras; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerStarter; import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.utils.validate.Check; @@ -12,11 +12,11 @@ public final class MojangAuth { public final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); private volatile boolean enabled = false; private volatile KeyPair keyPair; - private final ServerProcess serverProcess; + private final ServerStarter serverStarter; private final MojangCrypt mojangCrypt; - public MojangAuth(ServerProcess serverProcess, ExceptionHandler exceptionHandler) { - this.serverProcess = serverProcess; + public MojangAuth(ServerStarter serverStarter, ExceptionHandler exceptionHandler) { + this.serverStarter = serverStarter; this.mojangCrypt = new MojangCrypt(exceptionHandler); } @@ -27,7 +27,7 @@ public MojangAuth(ServerProcess serverProcess, ExceptionHandler exceptionHandler */ public void init() { Check.stateCondition(enabled, "Mojang auth is already enabled!"); - Check.stateCondition(serverProcess.isAlive(), "The server has already been started!"); + Check.stateCondition(serverStarter.isAlive(), "The server has already been started!"); enabled = true; // Generate necessary fields... keyPair = mojangCrypt.generateKeyPair(); diff --git a/src/main/java/net/minestom/server/extras/MojangAuthProvider.java b/src/main/java/net/minestom/server/extras/MojangAuthProvider.java new file mode 100644 index 00000000000..cd5407cf713 --- /dev/null +++ b/src/main/java/net/minestom/server/extras/MojangAuthProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.extras; + +public interface MojangAuthProvider { + MojangAuth getMojangAuth(); +} diff --git a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java index 40feb7feaf4..60aa9a53805 100644 --- a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java +++ b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java @@ -1,7 +1,11 @@ package net.minestom.server.extras.lan; -import net.minestom.server.ServerProcess; +import lombok.RequiredArgsConstructor; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ServerListPingEvent; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.socket.Server; +import net.minestom.server.timer.SchedulerManager; import net.minestom.server.timer.Task; import net.minestom.server.utils.time.Cooldown; import org.jetbrains.annotations.NotNull; @@ -27,6 +31,7 @@ * * @see wiki.vg */ +@RequiredArgsConstructor public class OpenToLAN { private final InetSocketAddress PING_ADDRESS = new InetSocketAddress("224.0.2.60", 4445); @@ -37,11 +42,10 @@ public class OpenToLAN { private volatile DatagramPacket packet = null; private volatile Task task = null; - private final ServerProcess serverProcess; - - public OpenToLAN(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } + private final ConnectionManager connectionManager; + private final Server server; + private final SchedulerManager schedulerManager; + private final GlobalEventHandler globalEventHandler; /** * Opens the server to LAN with the default config. @@ -70,7 +74,7 @@ public boolean open(@NotNull OpenToLANConfig config) { } eventCooldown = new Cooldown(config.delayBetweenEvent); - task = serverProcess.getSchedulerManager().buildTask(this::ping) + task = schedulerManager.buildTask(this::ping) .repeat(config.delayBetweenPings) .schedule(); return true; @@ -104,10 +108,10 @@ public boolean isOpen() { * Performs the ping. */ private void ping() { - if (!serverProcess.getServer().isOpen()) return; + if (!server.isOpen()) return; if (packet == null || eventCooldown.isReady(System.currentTimeMillis())) { - final ServerListPingEvent event = new ServerListPingEvent(serverProcess, OPEN_TO_LAN); - serverProcess.getGlobalEventHandler().call(event); + final ServerListPingEvent event = new ServerListPingEvent(connectionManager, server, OPEN_TO_LAN); + globalEventHandler.call(event); final byte[] data = OPEN_TO_LAN.getPingResponse(event.getResponseData()).getBytes(StandardCharsets.UTF_8); packet = new DatagramPacket(data, data.length, PING_ADDRESS); diff --git a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java index 6856ab7527e..d96ec9c8d70 100644 --- a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java +++ b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java @@ -83,7 +83,7 @@ private Cipher setupCipher(int mode, String transformation, Key key) { return null; } - public Cipher getCipher(int mode, Key key) { + public static Cipher getCipher(int mode, Key key) { try { Cipher cipher3 = Cipher.getInstance("AES/CFB8/NoPadding"); cipher3.init(mode, key, new IvParameterSpec(key.getEncoded())); diff --git a/src/main/java/net/minestom/server/extras/query/Query.java b/src/main/java/net/minestom/server/extras/query/Query.java index 59f73d4779f..10d921f76a9 100644 --- a/src/main/java/net/minestom/server/extras/query/Query.java +++ b/src/main/java/net/minestom/server/extras/query/Query.java @@ -3,7 +3,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.extras.query.event.BasicQueryEvent; import net.minestom.server.extras.query.event.FullQueryEvent; import net.minestom.server.timer.Task; @@ -39,10 +39,10 @@ public class Query { private volatile DatagramSocket socket; private volatile Thread thread; private volatile Task task; - private final ServerProcess serverProcess; + private final ServerFacade serverFacade; - public Query(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public Query(ServerFacade serverFacade) { + this.serverFacade = serverFacade; } /** @@ -82,7 +82,7 @@ public boolean start(int port) { thread.start(); started = true; - task = serverProcess.getSchedulerManager() + task = serverFacade.getSchedulerManager() .buildTask(CHALLENGE_TOKENS::clear) .repeat(30, TimeUnit.SECOND) .schedule(); @@ -183,12 +183,12 @@ private void run() { int remaining = data.remaining(); if (remaining == 0) { // basic - BasicQueryEvent event = new BasicQueryEvent(serverProcess, sender, sessionID); - serverProcess.getGlobalEventHandler().callCancellable(event, () -> + BasicQueryEvent event = new BasicQueryEvent(serverFacade, sender, sessionID); + serverFacade.getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } else if (remaining == 5) { // full - FullQueryEvent event = new FullQueryEvent(serverProcess, sender, sessionID); - serverProcess.getGlobalEventHandler().callCancellable(event, () -> + FullQueryEvent event = new FullQueryEvent(serverFacade, sender, sessionID); + serverFacade.getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } } diff --git a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java index 216bb12b9ca..c14e950f17a 100644 --- a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.extras.query.response.BasicQueryResponse; import org.jetbrains.annotations.NotNull; @@ -17,7 +17,7 @@ public class BasicQueryEvent extends QueryEvent { * @param sessionID the session ID * @param sender the sender */ - public BasicQueryEvent(ServerProcess serverProcess, @NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new BasicQueryResponse(serverProcess)); + public BasicQueryEvent(ServerFacade serverFacade, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new BasicQueryResponse(serverFacade)); } } diff --git a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java index 99c62d6b5dd..7008f02d7fe 100644 --- a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.extras.query.response.FullQueryResponse; import org.jetbrains.annotations.NotNull; @@ -14,11 +14,11 @@ public class FullQueryEvent extends QueryEvent { /** * Creates a new full query event. * - * @param serverProcess + * @param serverFacade * @param sender the sender * @param sessionID the sessionID */ - public FullQueryEvent(ServerProcess serverProcess, @NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new FullQueryResponse(serverProcess)); + public FullQueryEvent(ServerFacade serverFacade, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new FullQueryResponse(serverFacade)); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java index ac4af108663..586baa089cc 100644 --- a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.response; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.extras.query.Query; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.Writeable; @@ -13,18 +13,18 @@ */ public class BasicQueryResponse implements Writeable { @NotNull - private final ServerProcess serverProcess; + private final ServerFacade serverFacade; private String motd, gametype, map, numPlayers, maxPlayers; /** * Creates a new basic query response with pre-filled default values. */ - public BasicQueryResponse(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public BasicQueryResponse(ServerFacade serverFacade) { + this.serverFacade = serverFacade; this.motd = "A Minestom Server"; this.gametype = "SMP"; this.map = "world"; - this.numPlayers = String.valueOf(serverProcess.getConnectionManager().getOnlinePlayerCount()); + this.numPlayers = String.valueOf(serverFacade.getConnectionManager().getOnlinePlayerCount()); this.maxPlayers = String.valueOf(Integer.parseInt(this.numPlayers) + 1); } @@ -145,7 +145,7 @@ public void write(@NotNull BinaryWriter writer) { writer.writeNullTerminatedString(this.map, Query.CHARSET); writer.writeNullTerminatedString(this.numPlayers, Query.CHARSET); writer.writeNullTerminatedString(this.maxPlayers, Query.CHARSET); - writer.writeShort((short) serverProcess.getServer().getPort()); // TODO little endian? - writer.writeNullTerminatedString(Objects.requireNonNullElse(serverProcess.getServer().getAddress(), ""), Query.CHARSET); + writer.writeShort((short) serverFacade.getServer().getPort()); // TODO little endian? + writer.writeNullTerminatedString(Objects.requireNonNullElse(serverFacade.getServer().getAddress(), ""), Query.CHARSET); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java index f34884eae02..8132a15d45d 100644 --- a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.extras.query.Query; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.Writeable; @@ -17,7 +17,7 @@ public class FullQueryResponse implements Writeable { private static final PlainTextComponentSerializer PLAIN = PlainTextComponentSerializer.plainText(); private static final byte[] PADDING_10 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, PADDING_11 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - private final ServerProcess serverProcess; + private final ServerFacade serverFacade; private Map kv; private List players; @@ -25,16 +25,16 @@ public class FullQueryResponse implements Writeable { /** * Creates a new full query response with default values set. */ - public FullQueryResponse(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public FullQueryResponse(ServerFacade serverFacade) { + this.serverFacade = serverFacade; this.kv = new HashMap<>(); // populate defaults for (QueryKey key : QueryKey.VALUES) { - this.kv.put(key.getKey(), key.getValue(serverProcess)); + this.kv.put(key.getKey(), key.getValue(serverFacade)); } - this.players = serverProcess.getConnectionManager().getOnlinePlayers() + this.players = serverFacade.getConnectionManager().getOnlinePlayers() .stream() .map(player -> PLAIN.serialize(player.getName())) .toList(); @@ -120,8 +120,8 @@ public void setPlayers(@NotNull List players) { * * @return the string result */ - public static String generatePluginsValue(ServerProcess serverProcess) { - StringBuilder builder = new StringBuilder(serverProcess.getServerSetting().getBrandName()) + public static String generatePluginsValue(ServerFacade serverFacade) { + StringBuilder builder = new StringBuilder(serverFacade.getServerSettings().getBrandName()) .append(' ') .append(ServerConsts.VERSION_NAME); diff --git a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java index 8bb4dc24a2b..aa7e1a75aa7 100644 --- a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java +++ b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java @@ -1,7 +1,7 @@ package net.minestom.server.extras.query.response; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -27,13 +27,13 @@ public enum QueryKey { static QueryKey[] VALUES = QueryKey.values(); private final String key; - private final Function value; + private final Function value; - QueryKey(@NotNull Function value) { + QueryKey(@NotNull Function value) { this(null, value); } - QueryKey(@Nullable String key, @NotNull Function value) { + QueryKey(@Nullable String key, @NotNull Function value) { this.key = Objects.requireNonNullElse(key, this.name().toLowerCase(Locale.ROOT).replace('_', ' ')); this.value = value; } @@ -52,7 +52,7 @@ public enum QueryKey { * * @return the value */ - public @NotNull String getValue(ServerProcess serverProcess) { - return this.value.apply(serverProcess); + public @NotNull String getValue(ServerFacade serverFacade) { + return this.value.apply(serverFacade); } } diff --git a/src/main/java/net/minestom/server/gamedata/tags/TagManager.java b/src/main/java/net/minestom/server/gamedata/tags/TagManager.java index 79b2b3a6cf2..588fcdf5054 100644 --- a/src/main/java/net/minestom/server/gamedata/tags/TagManager.java +++ b/src/main/java/net/minestom/server/gamedata/tags/TagManager.java @@ -1,55 +1,15 @@ package net.minestom.server.gamedata.tags; -import net.minestom.server.registry.Registry; -import net.minestom.server.utils.NamespaceID; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; +import java.util.List; +import java.util.Map; /** * Handles loading and caching of tags. */ -public final class TagManager { - private final Map> tagMap = new ConcurrentHashMap<>(); +public interface TagManager { + @Nullable Tag getTag(Tag.BasicType type, String namespace); - public TagManager() { - // Load required tags from files - for (var type : Tag.BasicType.values()) { - final var json = Registry.load(type.getResource()); - final var tagIdentifierMap = tagMap.computeIfAbsent(type, s -> new CopyOnWriteArrayList<>()); - json.keySet().forEach(tagName -> { - final var tag = new Tag(NamespaceID.from(tagName), getValues(json, tagName)); - tagIdentifierMap.add(tag); - }); - } - } - - public @Nullable Tag getTag(Tag.BasicType type, String namespace) { - final var tags = tagMap.get(type); - for (var tag : tags) { - if (tag.getName().asString().equals(namespace)) - return tag; - } - return null; - } - - public Map> getTagMap() { - return Collections.unmodifiableMap(tagMap); - } - - private Set getValues(Map> main, String value) { - Map tagObject = main.get(value); - final List tagValues = (List) tagObject.get("values"); - Set result = new HashSet<>(tagValues.size()); - tagValues.forEach(tagString -> { - if (tagString.startsWith("#")) { - result.addAll(getValues(main, tagString.substring(1))); - } else { - result.add(NamespaceID.from(tagString)); - } - }); - return result; - } + Map> getTagMap(); } diff --git a/src/main/java/net/minestom/server/gamedata/tags/TagManagerImpl.java b/src/main/java/net/minestom/server/gamedata/tags/TagManagerImpl.java new file mode 100644 index 00000000000..7c04db1c26d --- /dev/null +++ b/src/main/java/net/minestom/server/gamedata/tags/TagManagerImpl.java @@ -0,0 +1,54 @@ +package net.minestom.server.gamedata.tags; + +import net.minestom.server.registry.Registry; +import net.minestom.server.utils.NamespaceID; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +public final class TagManagerImpl implements TagManager { + private final Map> tagMap = new ConcurrentHashMap<>(); + + public TagManagerImpl() { + // Load required tags from files + for (var type : Tag.BasicType.values()) { + final var json = Registry.load(type.getResource()); + final var tagIdentifierMap = tagMap.computeIfAbsent(type, s -> new CopyOnWriteArrayList<>()); + json.keySet().forEach(tagName -> { + final var tag = new Tag(NamespaceID.from(tagName), getValues(json, tagName)); + tagIdentifierMap.add(tag); + }); + } + } + + @Override + public @Nullable Tag getTag(Tag.BasicType type, String namespace) { + final var tags = tagMap.get(type); + for (var tag : tags) { + if (tag.getName().asString().equals(namespace)) + return tag; + } + return null; + } + + @Override + public Map> getTagMap() { + return Collections.unmodifiableMap(tagMap); + } + + private Set getValues(Map> main, String value) { + Map tagObject = main.get(value); + final List tagValues = (List) tagObject.get("values"); + Set result = new HashSet<>(tagValues.size()); + tagValues.forEach(tagString -> { + if (tagString.startsWith("#")) { + result.addAll(getValues(main, tagString.substring(1))); + } else { + result.add(NamespaceID.from(tagString)); + } + }); + return result; + } +} diff --git a/src/main/java/net/minestom/server/gamedata/tags/TagManagerProvider.java b/src/main/java/net/minestom/server/gamedata/tags/TagManagerProvider.java new file mode 100644 index 00000000000..99007d6dd48 --- /dev/null +++ b/src/main/java/net/minestom/server/gamedata/tags/TagManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.gamedata.tags; + +public interface TagManagerProvider { + TagManager getTagManager(); +} diff --git a/src/main/java/net/minestom/server/instance/AnvilLoader.java b/src/main/java/net/minestom/server/instance/AnvilLoader.java index 883e5593b6a..fdbb8c10d03 100644 --- a/src/main/java/net/minestom/server/instance/AnvilLoader.java +++ b/src/main/java/net/minestom/server/instance/AnvilLoader.java @@ -3,12 +3,14 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.IntIntImmutablePair; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockHandler; +import net.minestom.server.instance.block.BlockManager; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.async.AsyncUtils; import net.minestom.server.world.biomes.Biome; +import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jglrxavpok.hephaistos.mca.*; @@ -31,13 +33,18 @@ import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.atomic.AtomicInteger; public class AnvilLoader implements IChunkLoader { private final static Logger LOGGER = LoggerFactory.getLogger(AnvilLoader.class); private static final Biome BIOME = Biome.PLAINS; private final Map alreadyLoaded = new ConcurrentHashMap<>(); - private final ServerProcess serverProcess; + private final ExceptionHandler exceptionHandler; + private final BlockManager blockManager; + private final BiomeManager biomeManager; private final Path path; private final Path levelPath; private final Path regionPath; @@ -53,15 +60,17 @@ private static class RegionCache extends ConcurrentHashMap> blockStateId2ObjectCacheTLS = ThreadLocal.withInitial(Int2ObjectArrayMap::new); - public AnvilLoader(@NotNull ServerProcess serverProcess, @NotNull Path path) { - this.serverProcess = serverProcess; + public AnvilLoader(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, @NotNull Path path) { + this.exceptionHandler = exceptionHandler; + this.blockManager = blockManager; + this.biomeManager = biomeManager; this.path = path; this.levelPath = path.resolve("level.dat"); this.regionPath = path.resolve("region"); } - public AnvilLoader(@NotNull ServerProcess serverProcess, @NotNull String path) { - this(serverProcess, Path.of(path)); + public AnvilLoader(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, @NotNull String path) { + this(exceptionHandler, blockManager, biomeManager, Path.of(path)); } @Override @@ -74,7 +83,7 @@ public void loadInstance(@NotNull Instance instance) { Files.copy(levelPath, path.resolve("level.dat_old"), StandardCopyOption.REPLACE_EXISTING); instance.tagHandler().updateContent(tag); } catch (IOException | NBTException e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } } @@ -87,7 +96,7 @@ public void loadInstance(@NotNull Instance instance) { try { return loadMCA(instance, chunkX, chunkZ); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } return CompletableFuture.completedFuture(null); } @@ -153,7 +162,7 @@ public void loadInstance(@NotNull Instance instance) { } return new RegionFile(new RandomAccessFile(regionPath.toFile(), "rw"), regionX, regionZ, instance.getDimensionType().getMinY(), instance.getDimensionType().getMaxY() - 1); } catch (IOException | AnvilException e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); return null; } }); @@ -191,7 +200,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { int finalY = sectionY * Chunk.CHUNK_SECTION_SIZE + y; String biomeName = sectionBiomeInformation.getBaseBiome(); Biome biome = biomeCache.computeIfAbsent(biomeName, n -> - Objects.requireNonNullElse(serverProcess.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); + Objects.requireNonNullElse(biomeManager.getByName(NamespaceID.from(n)), BIOME)); chunk.setBiome(finalX, finalY, finalZ, biome); } } @@ -207,7 +216,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { int index = x / 4 + (z / 4) * 4 + (y / 4) * 16; String biomeName = sectionBiomeInformation.getBiomes()[index]; Biome biome = biomeCache.computeIfAbsent(biomeName, n -> - Objects.requireNonNullElse(serverProcess.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); + Objects.requireNonNullElse(biomeManager.getByName(NamespaceID.from(n)), BIOME)); chunk.setBiome(finalX, finalY, finalZ, biome); } } @@ -249,7 +258,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { if (!properties.isEmpty()) block = block.withProperties(properties); // Handler - final BlockHandler handler = serverProcess.getBlockManager().getHandler(block.name()); + final BlockHandler handler = blockManager.getHandler(block.name()); if (handler != null) block = block.withHandler(handler); convertedPalette[i] = block; @@ -266,7 +275,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { chunk.setBlock(x, y + yOffset, z, block); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } } } @@ -288,7 +297,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { final String tileEntityID = te.getString("id"); if (tileEntityID != null) { - final BlockHandler handler = serverProcess.getBlockManager().getHandlerOrDummy(tileEntityID); + final BlockHandler handler = blockManager.getHandlerOrDummy(tileEntityID); block = block.withHandler(handler); } // Remove anvil tags @@ -343,7 +352,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { alreadyLoaded.put(n, mcaFile); } catch (AnvilException | IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); return AsyncUtils.VOID_FUTURE; } } @@ -355,7 +364,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { mcaFile.writeColumnData(writer.toNBT(), chunk.getChunkX(), chunk.getChunkZ()); } catch (IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); return AsyncUtils.VOID_FUTURE; } return AsyncUtils.VOID_FUTURE; @@ -462,7 +471,7 @@ public void unloadChunk(Chunk chunk) { try { regionFile.close(); } catch (IOException e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } } } @@ -476,12 +485,34 @@ public boolean supportsParallelLoading() { } @Override - public boolean supportsParallelSaving() { - return true; + public @NotNull CompletableFuture saveChunks(@NotNull Collection chunks) { + if (supportsParallelSaving()) { + ExecutorService parallelSavingThreadPool = ForkJoinPool.commonPool(); + chunks.forEach(c -> parallelSavingThreadPool.execute(() -> saveChunk(c))); + try { + parallelSavingThreadPool.shutdown(); + parallelSavingThreadPool.awaitTermination(1L, java.util.concurrent.TimeUnit.DAYS); + } catch (InterruptedException e) { + exceptionHandler.handleException(e); + } + return AsyncUtils.VOID_FUTURE; + } else { + CompletableFuture completableFuture = new CompletableFuture<>(); + AtomicInteger counter = new AtomicInteger(); + for (Chunk chunk : chunks) { + saveChunk(chunk).whenComplete((unused, throwable) -> { + final boolean isLast = counter.incrementAndGet() == chunks.size(); + if (isLast) { + completableFuture.complete(null); + } + }); + } + return completableFuture; + } } @Override - public ServerProcess getServerProcess() { - return serverProcess; + public boolean supportsParallelSaving() { + return true; } } diff --git a/src/main/java/net/minestom/server/instance/Chunk.java b/src/main/java/net/minestom/server/instance/Chunk.java index 419ddd31629..6d40477eb10 100644 --- a/src/main/java/net/minestom/server/instance/Chunk.java +++ b/src/main/java/net/minestom/server/instance/Chunk.java @@ -1,6 +1,5 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; import net.minestom.server.Tickable; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; @@ -316,9 +315,4 @@ public boolean removeViewer(@NotNull Player player) { protected void unload() { this.loaded = false; } - - @Override - public ServerProcess getServerProcess() { - return instance.getServerProcess(); - } } \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java index 3e3c099d3ef..93a3d3403f4 100644 --- a/src/main/java/net/minestom/server/instance/DynamicChunk.java +++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java @@ -23,6 +23,7 @@ import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.world.biomes.Biome; +import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jglrxavpok.hephaistos.nbt.NBT; @@ -41,6 +42,7 @@ */ public class DynamicChunk extends Chunk { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicChunk.class); + protected final BiomeManager biomeManager; protected List

        sections; @@ -51,12 +53,13 @@ public class DynamicChunk extends Chunk { private long lastChange; final CachedPacket chunkCache; - public DynamicChunk(@NotNull Instance instance, int chunkX, int chunkZ) { + public DynamicChunk(BiomeManager biomeManager, @NotNull Instance instance, int chunkX, int chunkZ) { super(instance, chunkX, chunkZ, true); + this.biomeManager = biomeManager; var sectionsTemp = new Section[maxSection - minSection]; - Arrays.setAll(sectionsTemp, value -> new Section(getServerProcess())); + Arrays.setAll(sectionsTemp, value -> new Section()); this.sections = List.of(sectionsTemp); - chunkCache = new CachedPacket(getServerProcess().getServerSetting(), this::createChunkPacket); + chunkCache = new CachedPacket(instance.getServerSettings(), this::createChunkPacket); } @Override @@ -180,7 +183,7 @@ public void tick(long time) { final Section section = getSectionAt(y); final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return getServerProcess().getBiomeManager().getById(id); + return biomeManager.getById(id); } @Override @@ -195,7 +198,7 @@ public long getLastChangeTime() { @Override public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) { - DynamicChunk dynamicChunk = new DynamicChunk(instance, chunkX, chunkZ); + DynamicChunk dynamicChunk = new DynamicChunk(biomeManager, instance, chunkX, chunkZ); dynamicChunk.sections = sections.stream().map(Section::clone).toList(); dynamicChunk.entries.putAll(entries); return dynamicChunk; @@ -313,7 +316,7 @@ protected LightData createLightData(boolean sendLater) { clonedSections[i] = sections.get(i).clone(); var entities = instance.getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES); final int[] entityIds = ArrayUtils.mapToIntArray(entities, Entity::getEntityId); - return new SnapshotImpl.Chunk(getServerProcess(), minSection, chunkX, chunkZ, + return new SnapshotImpl.Chunk(biomeManager, minSection, chunkX, chunkZ, clonedSections, entries.clone(), entityIds, updater.reference(instance), tagHandler().readableCopy()); } diff --git a/src/main/java/net/minestom/server/instance/EntityTracker.java b/src/main/java/net/minestom/server/instance/EntityTracker.java index 9b9275ec93f..a66a0cc7efc 100644 --- a/src/main/java/net/minestom/server/instance/EntityTracker.java +++ b/src/main/java/net/minestom/server/instance/EntityTracker.java @@ -1,7 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerObject; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Entity; @@ -24,9 +23,9 @@ * Implementations are expected to be thread-safe. */ @ApiStatus.Experimental -public sealed interface EntityTracker extends ServerObject permits EntityTrackerImpl { - static @NotNull EntityTracker newTracker(ServerProcess serverProcess) { - return new EntityTrackerImpl(serverProcess); +public sealed interface EntityTracker permits EntityTrackerImpl { + static @NotNull EntityTracker newTracker(ServerSettings serverSettings) { + return new EntityTrackerImpl(serverSettings); } /** diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index 74124ada9b3..a17895faf0a 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -1,7 +1,8 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.ServerProcess; +import lombok.RequiredArgsConstructor; +import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -26,9 +27,11 @@ import static net.minestom.server.instance.Chunk.CHUNK_SIZE_Z; import static net.minestom.server.utils.chunk.ChunkUtils.*; +@RequiredArgsConstructor final class EntityTrackerImpl implements EntityTracker { + + private final ServerSettings serverSettings; - private final ServerProcess serverProcess; static final AtomicInteger TARGET_COUNTER = new AtomicInteger(); // Store all data associated to a Target @@ -36,9 +39,7 @@ final class EntityTrackerImpl implements EntityTracker { final TargetEntry[] entries = EntityTracker.Target.TARGETS.stream().map((Function, TargetEntry>) TargetEntry::new).toArray(TargetEntry[]::new); private final Int2ObjectSyncMap entityPositions = Int2ObjectSyncMap.hashmap(); - EntityTrackerImpl(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } + @Override public void register(@NotNull Entity entity, @NotNull Point point, @@ -54,7 +55,7 @@ public void register(@NotNull Entity entity, @NotNull Point p } if (update != null) { update.referenceUpdate(point, this); - nearbyEntitiesByChunkRange(point, serverProcess.getServerSetting().getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverSettings.getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.add(newEntity); }); @@ -75,7 +76,7 @@ public void unregister(@NotNull Entity entity, } if (update != null) { update.referenceUpdate(point, null); - nearbyEntitiesByChunkRange(point, serverProcess.getServerSetting().getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverSettings.getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.remove(newEntity); }); @@ -187,7 +188,7 @@ private void difference(Point oldPoint, Point newPoint, @NotNull Target target, @NotNull Update update) { final TargetEntry entry = entries[target.ordinal()]; forDifferingChunksInRange(newPoint.chunkX(), newPoint.chunkZ(), oldPoint.chunkX(), oldPoint.chunkZ(), - serverProcess.getServerSetting().getEntityViewDistance(), (chunkX, chunkZ) -> { + serverSettings.getEntityViewDistance(), (chunkX, chunkZ) -> { // Add final List entities = entry.chunkEntities.get(getChunkIndex(chunkX, chunkZ)); if (entities == null || entities.isEmpty()) return; @@ -200,11 +201,6 @@ private void difference(Point oldPoint, Point newPoint, }); } - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } - record ChunkViewKey(List sharedInstances, int chunkX, int chunkZ) { @Override public boolean equals(Object obj) { @@ -286,15 +282,10 @@ private Collection references() { } private void collectPlayers(EntityTracker tracker, Int2ObjectOpenHashMap map) { - tracker.nearbyEntitiesByChunkRange(point, serverProcess.getServerSetting().getChunkViewDistance(), + tracker.nearbyEntitiesByChunkRange(point, serverSettings.getChunkViewDistance(), EntityTracker.Target.PLAYERS, (player) -> map.putIfAbsent(player.getEntityId(), player)); } - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } - final class SetImpl extends AbstractSet { @Override public @NotNull Iterator iterator() { diff --git a/src/main/java/net/minestom/server/instance/Explosion.java b/src/main/java/net/minestom/server/instance/Explosion.java index b1b38cb502d..9f389355f56 100644 --- a/src/main/java/net/minestom/server/instance/Explosion.java +++ b/src/main/java/net/minestom/server/instance/Explosion.java @@ -73,7 +73,7 @@ public void apply(@NotNull Instance instance) { ExplosionPacket packet = new ExplosionPacket(centerX, centerY, centerZ, strength, records, 0, 0, 0); postExplosion(instance, blocks, packet); - PacketUtils.sendGroupedPacket(instance.getServerProcess().getServerSetting(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getServerSettings(), instance.getPlayers(), packet); postSend(instance, blocks); } diff --git a/src/main/java/net/minestom/server/instance/GeneratorImpl.java b/src/main/java/net/minestom/server/instance/GeneratorImpl.java index d0aa5b5f56c..e4169b8d990 100644 --- a/src/main/java/net/minestom/server/instance/GeneratorImpl.java +++ b/src/main/java/net/minestom/server/instance/GeneratorImpl.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -23,25 +22,25 @@ final class GeneratorImpl { private static final Vec SECTION_SIZE = new Vec(16); - static GenerationUnit section(ServerProcess serverProcess, Section section, int sectionX, int sectionY, int sectionZ, + static GenerationUnit section(Section section, int sectionX, int sectionY, int sectionZ, boolean fork) { final Vec start = SECTION_SIZE.mul(sectionX, sectionY, sectionZ); final Vec end = start.add(SECTION_SIZE); final UnitModifier modifier = new SectionModifierImpl(SECTION_SIZE, start, end, section.blockPalette(), section.biomePalette(), new Int2ObjectOpenHashMap<>(0), fork); - return unit(serverProcess, modifier, start, end, null); + return unit(modifier, start, end, null); } - static GenerationUnit section(ServerProcess serverProcess, Section section, int sectionX, int sectionY, int sectionZ) { - return section(serverProcess, section, sectionX, sectionY, sectionZ, false); + static GenerationUnit section(Section section, int sectionX, int sectionY, int sectionZ) { + return section(section, sectionX, sectionY, sectionZ, false); } - static UnitImpl chunk(ServerProcess serverProcess, Chunk chunk, int minSection, int maxSection, + static UnitImpl chunk(Chunk chunk, int minSection, int maxSection, List
        chunkSections, int chunkX, int chunkZ) { final int minY = minSection * 16; AtomicInteger sectionCounterY = new AtomicInteger(minSection); List sections = chunkSections.stream() - .map(section -> section(serverProcess, section, chunkX, sectionCounterY.getAndIncrement(), chunkZ)) + .map(section -> section(section, chunkX, sectionCounterY.getAndIncrement(), chunkZ)) .toList(); final Vec size = new Vec(16, (maxSection - minSection) * 16, 16); @@ -49,19 +48,19 @@ static UnitImpl chunk(ServerProcess serverProcess, Chunk chunk, int minSection, final Vec end = new Vec(chunkX * 16 + 16, size.y() + minY, chunkZ * 16 + 16); final UnitModifier modifier = new AreaModifierImpl(chunk, size, start, end, 1, sections.size(), 1, sections); - return unit(serverProcess, modifier, start, end, sections); + return unit(modifier, start, end, sections); } - static UnitImpl chunk(ServerProcess serverProcess, int minSection, int maxSection, + static UnitImpl chunk(int minSection, int maxSection, List
        chunkSections, int chunkX, int chunkZ) { - return chunk(serverProcess, null, minSection, maxSection, chunkSections, chunkX, chunkZ); + return chunk(null, minSection, maxSection, chunkSections, chunkX, chunkZ); } static UnitImpl chunk(Chunk chunk) { - return chunk(chunk.getServerProcess(), chunk, chunk.minSection, chunk.maxSection, chunk.getSections(), chunk.getChunkX(), chunk.getChunkZ()); + return chunk(chunk, chunk.minSection, chunk.maxSection, chunk.getSections(), chunk.getChunkX(), chunk.getChunkZ()); } - static UnitImpl unit(ServerProcess serverProcess, UnitModifier modifier, Point start, Point end, + static UnitImpl unit(UnitModifier modifier, Point start, Point end, List divided) { if (start.x() > end.x() || start.y() > end.y() || start.z() > end.z()) { throw new IllegalArgumentException("absoluteStart must be before absoluteEnd"); @@ -73,7 +72,7 @@ static UnitImpl unit(ServerProcess serverProcess, UnitModifier modifier, Point s throw new IllegalArgumentException("absoluteEnd must be a multiple of 16"); } final Point size = end.sub(start); - return new UnitImpl(serverProcess, modifier, size, start, end, divided, new CopyOnWriteArrayList<>()); + return new UnitImpl(modifier, size, start, end, divided, new CopyOnWriteArrayList<>()); } static final class DynamicFork implements Block.Setter { @@ -81,12 +80,6 @@ static final class DynamicFork implements Block.Setter { int width, height, depth; List sections; - private final ServerProcess serverProcess; - - DynamicFork(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - } - @Override public void setBlock(int x, int y, int z, @NotNull Block block) { resize(x, y, z); @@ -107,7 +100,7 @@ private void resize(int x, int y, int z) { this.width = 1; this.height = 1; this.depth = 1; - this.sections = List.of(section(serverProcess, new Section(serverProcess), sectionX, sectionY, sectionZ, true)); + this.sections = List.of(section(new Section(), sectionX, sectionY, sectionZ, true)); } else if (x < minSection.x() || y < minSection.y() || z < minSection.z() || x >= minSection.x() + width * 16 || y >= minSection.y() + height * 16 || z >= minSection.z() + depth * 16) { // Resize necessary @@ -141,7 +134,7 @@ private void resize(int x, int y, int z) { final int newX = coordinates.blockX() + startX; final int newY = coordinates.blockY() + startY; final int newZ = coordinates.blockZ() + startZ; - final GenerationUnit unit = section(serverProcess, new Section(serverProcess), newX, newY, newZ, true); + final GenerationUnit unit = section(new Section(), newX, newY, newZ, true); newSections[i] = unit; } } @@ -154,7 +147,7 @@ private void resize(int x, int y, int z) { } } - record UnitImpl(ServerProcess serverProcess, UnitModifier modifier, Point size, + record UnitImpl(UnitModifier modifier, Point size, Point absoluteStart, Point absoluteEnd, List divided, List forks) implements GenerationUnit { @@ -177,7 +170,7 @@ record UnitImpl(ServerProcess serverProcess, UnitModifier modifier, Point size, for (int sectionX = minSectionX; sectionX < maxSectionX; sectionX++) { for (int sectionY = minSectionY; sectionY < maxSectionY; sectionY++) { for (int sectionZ = minSectionZ; sectionZ < maxSectionZ; sectionZ++) { - final GenerationUnit unit = section(serverProcess, new Section(serverProcess), sectionX, sectionY, sectionZ, true); + final GenerationUnit unit = section(new Section(), sectionX, sectionY, sectionZ, true); units[index++] = unit; } } @@ -189,7 +182,7 @@ record UnitImpl(ServerProcess serverProcess, UnitModifier modifier, Point size, @Override public void fork(@NotNull Consumer consumer) { - DynamicFork dynamicFork = new DynamicFork(serverProcess); + DynamicFork dynamicFork = new DynamicFork(); consumer.accept(dynamicFork); final Point startSection = dynamicFork.minSection; if (startSection == null) @@ -212,7 +205,7 @@ private GenerationUnit registerFork(Point start, List sections, final Point size = end.sub(start); final AreaModifierImpl modifier = new AreaModifierImpl(null, size, start, end, width, height, depth, sections); - final UnitImpl fork = new UnitImpl(serverProcess, modifier, size, start, end, sections, forks); + final UnitImpl fork = new UnitImpl(modifier, size, start, end, sections, forks); forks.add(fork); return fork; } diff --git a/src/main/java/net/minestom/server/instance/IChunkLoader.java b/src/main/java/net/minestom/server/instance/IChunkLoader.java index 680106be436..8d312a158e7 100644 --- a/src/main/java/net/minestom/server/instance/IChunkLoader.java +++ b/src/main/java/net/minestom/server/instance/IChunkLoader.java @@ -1,22 +1,18 @@ package net.minestom.server.instance; -import net.minestom.server.ServerObject; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.atomic.AtomicInteger; /** * Interface implemented to change the way chunks are loaded/saved. *

        * See {@link AnvilLoader} for the default implementation used in {@link InstanceContainer}. */ -public interface IChunkLoader extends ServerObject { +public interface IChunkLoader { /** * Loads instance data from the loader. @@ -58,31 +54,7 @@ default void loadInstance(@NotNull Instance instance) { * @return a {@link CompletableFuture} executed when the {@link Chunk} is done saving, * should be called even if the saving failed (you can throw an exception). */ - default @NotNull CompletableFuture saveChunks(@NotNull Collection chunks) { - if (supportsParallelSaving()) { - ExecutorService parallelSavingThreadPool = ForkJoinPool.commonPool(); - chunks.forEach(c -> parallelSavingThreadPool.execute(() -> saveChunk(c))); - try { - parallelSavingThreadPool.shutdown(); - parallelSavingThreadPool.awaitTermination(1L, java.util.concurrent.TimeUnit.DAYS); - } catch (InterruptedException e) { - getServerProcess().getExceptionHandler().handleException(e); - } - return AsyncUtils.VOID_FUTURE; - } else { - CompletableFuture completableFuture = new CompletableFuture<>(); - AtomicInteger counter = new AtomicInteger(); - for (Chunk chunk : chunks) { - saveChunk(chunk).whenComplete((unused, throwable) -> { - final boolean isLast = counter.incrementAndGet() == chunks.size(); - if (isLast) { - completableFuture.complete(null); - } - }); - } - return completableFuture; - } - } + @NotNull CompletableFuture saveChunks(@NotNull Collection chunks); /** * Does this {@link IChunkLoader} allow for multi-threaded saving of {@link Chunk}? diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index 65603e7bf49..0e33d3e830d 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -1,10 +1,10 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.objects.ObjectArraySet; +import lombok.Getter; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointers; -import net.minestom.server.ServerObject; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Tickable; import net.minestom.server.adventure.audience.PacketGroupingAudience; import net.minestom.server.coordinate.Point; @@ -13,6 +13,7 @@ import net.minestom.server.entity.ExperienceOrb; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.PFInstanceSpace; +import net.minestom.server.event.Event; import net.minestom.server.event.EventFilter; import net.minestom.server.event.EventHandler; import net.minestom.server.event.EventNode; @@ -25,13 +26,14 @@ import net.minestom.server.instance.generator.Generator; import net.minestom.server.network.packet.server.play.BlockActionPacket; import net.minestom.server.network.packet.server.play.TimeUpdatePacket; -import net.minestom.server.snapshot.*; +import net.minestom.server.snapshot.InstanceSnapshot; +import net.minestom.server.snapshot.SnapshotUpdater; +import net.minestom.server.snapshot.Snapshotable; import net.minestom.server.tag.TagHandler; import net.minestom.server.tag.Taggable; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ThreadDispatcherImpl; import net.minestom.server.timer.Schedulable; import net.minestom.server.timer.Scheduler; -import net.minestom.server.utils.ArrayUtils; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.chunk.ChunkCache; @@ -49,7 +51,6 @@ import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -60,13 +61,15 @@ * chunk implementation has to be defined, see {@link InstanceContainer}. *

        * WARNING: when making your own implementation registering the instance manually is required - * with {@link InstanceManager#registerInstance(Instance)}, and - * you need to be sure to signal the {@link ThreadDispatcher} of every partition/element changes. + * with {@link InstanceManagerImpl#registerInstance(Instance)}, and + * you need to be sure to signal the {@link ThreadDispatcherImpl} of every partition/element changes. */ public abstract class Instance implements Block.Getter, Block.Setter, - Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience, ServerObject { + Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { - private final ServerProcess serverProcess; + @Getter // FIXME bad shit + private final ServerSettings serverSettings; + private final EventNode globalEventHandler; private boolean registered; private final DimensionType dimensionType; @@ -113,8 +116,8 @@ public abstract class Instance implements Block.Getter, Block.Setter, * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(serverProcess, uniqueId, dimensionType, dimensionType.getName()); + public Instance(@NotNull ServerSettings serverSettings, EventNode globalEventHandler, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(serverSettings, globalEventHandler, uniqueId, dimensionType, dimensionType.getName()); } /** @@ -123,10 +126,11 @@ public Instance(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @N * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + public Instance(@NotNull ServerSettings serverSettings, EventNode globalEventHandler, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + this.globalEventHandler = globalEventHandler; Check.argCondition(!dimensionType.isRegistered(), "The dimension " + dimensionType.getName() + " is not registered! Please use DimensionTypeManager#addDimension"); - this.serverProcess = serverProcess; + this.serverSettings = serverSettings; this.uniqueId = uniqueId; this.dimensionType = dimensionType; this.dimensionName = dimensionName.asString(); @@ -137,13 +141,8 @@ public Instance(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @N .withDynamic(Identity.UUID, this::getUniqueId) .build(); - if (serverProcess != null) { - this.eventNode = serverProcess.getGlobalEventHandler().map(this, EventFilter.INSTANCE); - } else { - // Local nodes require a server process - this.eventNode = null; - } - entityTracker = new EntityTrackerImpl(serverProcess); + this.eventNode = globalEventHandler.map(this, EventFilter.INSTANCE); + entityTracker = new EntityTrackerImpl(serverSettings); } /** @@ -377,7 +376,7 @@ public void setChunkGenerator(@Nullable ChunkGenerator chunkGenerator) { public abstract boolean isInVoid(@NotNull Point point); /** - * Gets if the instance has been registered in {@link InstanceManager}. + * Gets if the instance has been registered in {@link InstanceManagerImpl}. * * @return true if the instance has been registered */ @@ -388,7 +387,7 @@ public boolean isRegistered() { /** * Changes the registered field. *

        - * WARNING: should only be used by {@link InstanceManager}. + * WARNING: should only be used by {@link InstanceManagerImpl}. * * @param registered true to mark the instance as registered */ @@ -449,7 +448,7 @@ public long getTime() { */ public void setTime(long time) { this.time = time; - PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverSettings, getPlayers(), createTimePacket()); } /** @@ -609,7 +608,7 @@ public void sendBlockAction(@NotNull Point blockPosition, byte actionId, byte ac final Block block = getBlock(blockPosition); final Chunk chunk = getChunkAt(blockPosition); Check.notNull(chunk, "The chunk at {0} is not loaded!", blockPosition); - chunk.sendPacketToViewers(new BlockActionPacket(blockPosition, actionId, actionParam, block)); + chunk.sendPacketToViewers(serverSettings, new BlockActionPacket(blockPosition, actionId, actionParam, block)); } /** @@ -664,7 +663,7 @@ public void tick(long time) { this.time += timeRate; // time needs to be sent to players if (timeUpdate != null && !Cooldown.hasCooldown(time, lastTimeUpdate, timeUpdate)) { - PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverSettings, getPlayers(), createTimePacket()); this.lastTimeUpdate = time; } @@ -672,7 +671,7 @@ public void tick(long time) { // Tick event { // Process tick events - serverProcess.getGlobalEventHandler().call(new InstanceTickEvent(this, time, lastTickAge)); + globalEventHandler.call(new InstanceTickEvent(this, time, lastTickAge)); // Set last tick age this.lastTickAge = time; } @@ -697,11 +696,12 @@ public void tick(long time) { @Override public @NotNull InstanceSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) { - final Map> chunksMap = updater.referencesMapLong(getChunks(), ChunkUtils::getChunkIndex); - final int[] entities = ArrayUtils.mapToIntArray(entityTracker.entities(), Entity::getEntityId); - return new SnapshotImpl.Instance(updater.reference(serverProcess), - getDimensionType(), getWorldAge(), getTime(), chunksMap, entities, - tagHandler.readableCopy()); + throw new RuntimeException("Not implemented"); // FIXME +// final Map> chunksMap = updater.referencesMapLong(getChunks(), ChunkUtils::getChunkIndex); +// final int[] entities = ArrayUtils.mapToIntArray(entityTracker.entities(), Entity::getEntityId); +// return new SnapshotImpl.Instance(updater.reference(serverProcess), +// getDimensionType(), getWorldAge(), getTime(), chunksMap, entities, +// tagHandler.readableCopy()); } /** @@ -770,9 +770,4 @@ public void setExplosionSupplier(@Nullable ExplosionSupplier supplier) { public @NotNull Pointers pointers() { return this.pointers; } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index d8844635ba2..d9dff845c8e 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -1,17 +1,21 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.instance.InstanceChunkLoadEvent; import net.minestom.server.event.instance.InstanceChunkUnloadEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; +import net.minestom.server.instance.block.BlockManager; import net.minestom.server.instance.block.rule.BlockPlacementRule; import net.minestom.server.instance.generator.Generator; import net.minestom.server.instance.palette.Palette; @@ -19,6 +23,7 @@ import net.minestom.server.network.packet.server.play.BlockEntityDataPacket; import net.minestom.server.network.packet.server.play.EffectPacket; import net.minestom.server.network.packet.server.play.UnloadChunkPacket; +import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.async.AsyncUtils; @@ -27,6 +32,7 @@ import net.minestom.server.utils.chunk.ChunkSupplier; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; +import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -58,6 +64,12 @@ public class InstanceContainer extends Instance { // the shared instances assigned to this instance private final List sharedInstances = new CopyOnWriteArrayList<>(); + private final ExceptionHandler exceptionHandler; + private final BlockManager blockManager; + private final ServerSettings serverSettings; + private final EventNode globalEventHandler; + private final ThreadDispatcher dispatcher; + private final BiomeManager biomeManager; // the chunk generator used, can be null private volatile Generator generator; @@ -82,24 +94,30 @@ public class InstanceContainer extends Instance { protected InstanceContainer srcInstance; // only present if this instance has been created using a copy private long lastBlockChangeTime; // Time at which the last block change happened (#setBlock) - public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(serverProcess, uniqueId, dimensionType, null, dimensionType.getName()); + public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, uniqueId, dimensionType, null, dimensionType.getName()); } - public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { - this(serverProcess, uniqueId, dimensionType, null, dimensionName); + public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + this(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, uniqueId, dimensionType, null, dimensionName); } @ApiStatus.Experimental - public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - this(serverProcess, uniqueId, dimensionType, loader, dimensionType.getName()); + public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + this(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, uniqueId, dimensionType, loader, dimensionType.getName()); } @ApiStatus.Experimental - public InstanceContainer(@NotNull ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { - super(serverProcess, uniqueId, dimensionType, dimensionName); - setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(instance, chunkX, chunkZ)); - setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(getServerProcess(), "world"))); + public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { + super(serverSettings, globalEventHandler, uniqueId, dimensionType, dimensionName); + this.exceptionHandler = exceptionHandler; + this.blockManager = blockManager; + this.biomeManager = biomeManager; + this.serverSettings = serverSettings; + this.globalEventHandler = globalEventHandler; + this.dispatcher = dispatcher; + setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(biomeManager, instance, chunkX, chunkZ)); + setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(exceptionHandler, blockManager, biomeManager, "world"))); this.chunkLoader.loadInstance(this); } @@ -146,7 +164,7 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in this.currentlyChangingBlocks.put(blockPosition, block); // Change id based on neighbors - final BlockPlacementRule blockPlacementRule = getServerProcess().getBlockManager().getBlockPlacementRule(block); + final BlockPlacementRule blockPlacementRule = blockManager.getBlockPlacementRule(block); if (placement != null && blockPlacementRule != null && doBlockUpdates) { BlockPlacementRule.PlacementState rulePlacement; if (placement instanceof BlockHandler.PlayerPlacement pp) { @@ -179,11 +197,11 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in // Refresh player chunk block { - chunk.sendPacketToViewers(new BlockChangePacket(blockPosition, block.stateId())); + chunk.sendPacketToViewers(serverSettings, new BlockChangePacket(blockPosition, block.stateId())); var registry = block.registry(); if (registry.isBlockEntity()) { final NBTCompound data = BlockUtils.extractClientNbt(block); - chunk.sendPacketToViewers(new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); + chunk.sendPacketToViewers(serverSettings, new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); } } } @@ -216,7 +234,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, return false; } PlayerBlockBreakEvent blockBreakEvent = new PlayerBlockBreakEvent(player, block, Block.AIR, blockPosition, blockFace); - getServerProcess().getGlobalEventHandler().call(blockBreakEvent); + globalEventHandler.call(blockBreakEvent); final boolean allowed = !blockBreakEvent.isCancelled(); if (allowed) { // Break or change the broken block based on event result @@ -224,7 +242,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, UNSAFE_setBlock(chunk, x, y, z, resultBlock, null, new BlockHandler.PlayerDestroy(block, this, blockPosition, player), doBlockUpdates, 0); // Send the block break effect packet - PacketUtils.sendGroupedPacket(getServerProcess().getServerSetting(), chunk.getViewers(), + PacketUtils.sendGroupedPacket(serverSettings, chunk.getViewers(), new EffectPacket(2001 /*Block break + block break sound*/, blockPosition, block.stateId(), false), // Prevent the block breaker to play the particles and sound two times (viewer) -> !viewer.equals(player)); @@ -247,8 +265,8 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { if (!isLoaded(chunk)) return; final int chunkX = chunk.getChunkX(); final int chunkZ = chunk.getChunkZ(); - chunk.sendPacketToViewers(new UnloadChunkPacket(chunkX, chunkZ)); - getServerProcess().getGlobalEventHandler().call(new InstanceChunkUnloadEvent(this, chunk)); + chunk.sendPacketToViewers(serverSettings, new UnloadChunkPacket(chunkX, chunkZ)); + globalEventHandler.call(new InstanceChunkUnloadEvent(this, chunk)); // Remove all entities in chunk getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES).forEach(Entity::remove); // Clear cache @@ -257,7 +275,6 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { if (chunkLoader != null) { chunkLoader.unloadChunk(chunk); } - var dispatcher = getServerProcess().dispatcher(); dispatcher.deletePartition(chunk); } @@ -303,13 +320,13 @@ public Chunk getChunk(int chunkX, int chunkZ) { cacheChunk(chunk); chunk.onLoad(); - getServerProcess().getGlobalEventHandler().call(new InstanceChunkLoadEvent(this, chunk)); + globalEventHandler.call(new InstanceChunkLoadEvent(this, chunk)); final CompletableFuture future = this.loadingChunks.remove(index); assert future == completableFuture : "Invalid future: " + future; completableFuture.complete(chunk); }) .exceptionally(throwable -> { - getServerProcess().getExceptionHandler().handleException(throwable); + exceptionHandler.handleException(throwable); return null; }); if (loader.supportsParallelLoading()) { @@ -375,7 +392,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { // Apply awaiting forks processFork(chunk); } catch (Throwable e) { - getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } finally { // End generation refreshLastBlockChangeTime(); @@ -492,7 +509,7 @@ public boolean hasSharedInstances() { /** * Assigns a {@link SharedInstance} to this container. *

        - * Only used by {@link InstanceManager}, mostly unsafe. + * Only used by {@link InstanceManagerImpl}, mostly unsafe. * * @param sharedInstance the shared instance to assign to this container */ @@ -510,7 +527,7 @@ protected void addSharedInstance(SharedInstance sharedInstance) { * @see #getSrcInstance() to retrieve the "creation source" of the copied instance */ public synchronized InstanceContainer copy() { - InstanceContainer copiedInstance = new InstanceContainer(getServerProcess(), UUID.randomUUID(), getDimensionType()); + InstanceContainer copiedInstance = new InstanceContainer(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, UUID.randomUUID(), getDimensionType()); copiedInstance.srcInstance = this; copiedInstance.tagHandler = this.tagHandler.copy(); copiedInstance.lastBlockChangeTime = this.lastBlockChangeTime; @@ -634,7 +651,7 @@ private void executeNeighboursBlockPlacementRule(@NotNull Point blockPosition, i final Block neighborBlock = cache.getBlock(neighborX, neighborY, neighborZ, Condition.TYPE); if (neighborBlock == null) continue; - final BlockPlacementRule neighborBlockPlacementRule = getServerProcess().getBlockManager().getBlockPlacementRule(neighborBlock); + final BlockPlacementRule neighborBlockPlacementRule = blockManager.getBlockPlacementRule(neighborBlock); if (neighborBlockPlacementRule == null || updateDistance >= neighborBlockPlacementRule.maxUpdateDistance()) continue; final Vec neighborPosition = new Vec(neighborX, neighborY, neighborZ); @@ -664,7 +681,6 @@ private CompletableFuture loadOrRetrieve(int chunkX, int chunkZ, Supplier private void cacheChunk(@NotNull Chunk chunk) { this.chunks.put(getChunkIndex(chunk), chunk); - var dispatcher = getServerProcess().dispatcher(); dispatcher.createPartition(chunk); } } diff --git a/src/main/java/net/minestom/server/instance/InstanceManager.java b/src/main/java/net/minestom/server/instance/InstanceManager.java index d258eb80bae..fbe05967565 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManager.java +++ b/src/main/java/net/minestom/server/instance/InstanceManager.java @@ -1,50 +1,27 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; -import net.minestom.server.event.GlobalEventHandler; -import net.minestom.server.event.instance.InstanceRegisterEvent; -import net.minestom.server.event.instance.InstanceUnregisterEvent; -import net.minestom.server.thread.ThreadDispatcher; -import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CopyOnWriteArraySet; /** * Used to register {@link Instance}. */ -public final class InstanceManager { - private final @NotNull ThreadDispatcher dispatcher; - private final @NotNull GlobalEventHandler globalEventHandler; - - private final Set instances = new CopyOnWriteArraySet<>(); - - public InstanceManager(@NotNull ThreadDispatcher dispatcher, @NotNull GlobalEventHandler globalEventHandler) { - this.dispatcher = dispatcher; - this.globalEventHandler = globalEventHandler; - } - +public interface InstanceManager { /** * Registers an {@link Instance} internally. *

        - * Note: not necessary if you created your instance using {@link #createInstanceContainer(ServerProcess)} or {@link #createSharedInstance(ServerProcess, InstanceContainer)} + * Note: not necessary if you created your instance using {@link #createInstanceContainer()} or {@link #createSharedInstance(InstanceContainer)} * but only if you instantiated your instance object manually * * @param instance the {@link Instance} to register */ - public void registerInstance(@NotNull Instance instance) { - Check.stateCondition(instance instanceof SharedInstance, - "Please use InstanceManager#registerSharedInstance to register a shared instance"); - UNSAFE_registerInstance(instance); - } + void registerInstance(@NotNull Instance instance); /** * Creates and register an {@link InstanceContainer} with the specified {@link DimensionType}. @@ -54,19 +31,15 @@ public void registerInstance(@NotNull Instance instance) { * @return the created {@link InstanceContainer} */ @ApiStatus.Experimental - public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - final InstanceContainer instanceContainer = new InstanceContainer(serverProcess, UUID.randomUUID(), dimensionType, loader); - registerInstance(instanceContainer); - return instanceContainer; - } + @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader); - public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess, @NotNull DimensionType dimensionType) { - return createInstanceContainer(serverProcess, dimensionType, null); + default @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType) { + return createInstanceContainer(dimensionType, null); } @ApiStatus.Experimental - public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess, @Nullable IChunkLoader loader) { - return createInstanceContainer(serverProcess, DimensionType.OVERWORLD, loader); + default @NotNull InstanceContainer createInstanceContainer(@Nullable IChunkLoader loader) { + return createInstanceContainer(DimensionType.OVERWORLD, loader); } /** @@ -74,8 +47,8 @@ public void registerInstance(@NotNull Instance instance) { * * @return the created {@link InstanceContainer} */ - public @NotNull InstanceContainer createInstanceContainer(@NotNull ServerProcess serverProcess) { - return createInstanceContainer(serverProcess, DimensionType.OVERWORLD, null); + default @NotNull InstanceContainer createInstanceContainer() { + return createInstanceContainer(DimensionType.OVERWORLD, null); } /** @@ -87,14 +60,7 @@ public void registerInstance(@NotNull Instance instance) { * @return the registered {@link SharedInstance} * @throws NullPointerException if {@code sharedInstance} doesn't have an {@link InstanceContainer} assigned to it */ - public @NotNull SharedInstance registerSharedInstance(@NotNull SharedInstance sharedInstance) { - final InstanceContainer instanceContainer = sharedInstance.getInstanceContainer(); - Check.notNull(instanceContainer, "SharedInstance needs to have an InstanceContainer to be created!"); - - instanceContainer.addSharedInstance(sharedInstance); - UNSAFE_registerInstance(sharedInstance); - return sharedInstance; - } + @NotNull SharedInstance registerSharedInstance(@NotNull SharedInstance sharedInstance); /** * Creates and register a {@link SharedInstance}. @@ -103,13 +69,7 @@ public void registerInstance(@NotNull Instance instance) { * @return the created {@link SharedInstance} * @throws IllegalStateException if {@code instanceContainer} is not registered */ - public @NotNull SharedInstance createSharedInstance(@NotNull ServerProcess serverProcess, @NotNull InstanceContainer instanceContainer) { - Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); - Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); - - final SharedInstance sharedInstance = new SharedInstance(serverProcess, UUID.randomUUID(), instanceContainer); - return registerSharedInstance(sharedInstance); - } + @NotNull SharedInstance createSharedInstance(@NotNull InstanceContainer instanceContainer); /** * Unregisters the {@link Instance} internally. @@ -118,31 +78,14 @@ public void registerInstance(@NotNull Instance instance) { * * @param instance the {@link Instance} to unregister */ - public void unregisterInstance(@NotNull Instance instance) { - Check.stateCondition(!instance.getPlayers().isEmpty(), "You cannot unregister an instance with players inside."); - synchronized (instance) { - InstanceUnregisterEvent event = new InstanceUnregisterEvent(instance); - globalEventHandler.call(event); - - // Unload all chunks - if (instance instanceof InstanceContainer) { - instance.getChunks().forEach(instance::unloadChunk); - instance.getChunks().forEach(dispatcher::deletePartition); - } - // Unregister - instance.setRegistered(false); - this.instances.remove(instance); - } - } + void unregisterInstance(@NotNull Instance instance); /** * Gets all the registered instances. * * @return an unmodifiable {@link Set} containing all the registered instances */ - public @NotNull Set<@NotNull Instance> getInstances() { - return Collections.unmodifiableSet(instances); - } + @NotNull Set<@NotNull Instance> getInstances(); /** * Gets an instance by the given UUID. @@ -150,26 +93,5 @@ public void unregisterInstance(@NotNull Instance instance) { * @param uuid UUID of the instance * @return the instance with the given UUID, null if not found */ - public @Nullable Instance getInstance(@NotNull UUID uuid) { - Optional instance = getInstances() - .stream() - .filter(someInstance -> someInstance.getUniqueId().equals(uuid)) - .findFirst(); - return instance.orElse(null); - } - - /** - * Registers an {@link Instance} internally. - *

        - * Unsafe because it does not check if {@code instance} is a {@link SharedInstance} to verify its container. - * - * @param instance the {@link Instance} to register - */ - private void UNSAFE_registerInstance(@NotNull Instance instance) { - instance.setRegistered(true); - this.instances.add(instance); - instance.getChunks().forEach(dispatcher::createPartition); - InstanceRegisterEvent event = new InstanceRegisterEvent(instance); - globalEventHandler.call(event); - } + @Nullable Instance getInstance(@NotNull UUID uuid); } diff --git a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java new file mode 100644 index 00000000000..1ec03b9b4e5 --- /dev/null +++ b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java @@ -0,0 +1,115 @@ +package net.minestom.server.instance; + +import lombok.RequiredArgsConstructor; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.event.instance.InstanceRegisterEvent; +import net.minestom.server.event.instance.InstanceUnregisterEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.block.BlockManager; +import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.utils.validate.Check; +import net.minestom.server.world.DimensionType; +import net.minestom.server.world.biomes.BiomeManager; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArraySet; + +@RequiredArgsConstructor +public final class InstanceManagerImpl implements InstanceManager { + private final ThreadDispatcher dispatcher; + private final EventNode globalEventHandler; + private final ServerSettings serverSettings; + private final ExceptionHandler exceptionHandler; + private final BlockManager blockManager; + private final BiomeManager biomeManager; + + private final Set instances = new CopyOnWriteArraySet<>(); + + @Override + public void registerInstance(@NotNull Instance instance) { + Check.stateCondition(instance instanceof SharedInstance, "Please use InstanceManager#registerSharedInstance to register a shared instance"); + UNSAFE_registerInstance(instance); + } + + @Override + @ApiStatus.Experimental + public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + final InstanceContainer instanceContainer = new InstanceContainer(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, UUID.randomUUID(), dimensionType, loader); + registerInstance(instanceContainer); + return instanceContainer; + } + + @Override + public @NotNull SharedInstance registerSharedInstance(@NotNull SharedInstance sharedInstance) { + final InstanceContainer instanceContainer = sharedInstance.getInstanceContainer(); + Check.notNull(instanceContainer, "SharedInstance needs to have an InstanceContainer to be created!"); + + instanceContainer.addSharedInstance(sharedInstance); + UNSAFE_registerInstance(sharedInstance); + return sharedInstance; + } + + @Override + public @NotNull SharedInstance createSharedInstance(@NotNull InstanceContainer instanceContainer) { + Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); + Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); + + final SharedInstance sharedInstance = new SharedInstance(serverSettings, globalEventHandler, UUID.randomUUID(), instanceContainer); + return registerSharedInstance(sharedInstance); + } + + @Override + public void unregisterInstance(@NotNull Instance instance) { + Check.stateCondition(!instance.getPlayers().isEmpty(), "You cannot unregister an instance with players inside."); + synchronized (instance) { + InstanceUnregisterEvent event = new InstanceUnregisterEvent(instance); + globalEventHandler.call(event); + + // Unload all chunks + if (instance instanceof InstanceContainer) { + instance.getChunks().forEach(instance::unloadChunk); + instance.getChunks().forEach(dispatcher::deletePartition); + } + // Unregister + instance.setRegistered(false); + this.instances.remove(instance); + } + } + + @Override + public @NotNull Set<@NotNull Instance> getInstances() { + return Collections.unmodifiableSet(instances); + } + + @Override + public @Nullable Instance getInstance(@NotNull UUID uuid) { + Optional instance = getInstances() + .stream() + .filter(someInstance -> someInstance.getUniqueId().equals(uuid)) + .findFirst(); + return instance.orElse(null); + } + + /** + * Registers an {@link Instance} internally. + *

        + * Unsafe because it does not check if {@code instance} is a {@link SharedInstance} to verify its container. + * + * @param instance the {@link Instance} to register + */ + private void UNSAFE_registerInstance(@NotNull Instance instance) { + instance.setRegistered(true); + this.instances.add(instance); + instance.getChunks().forEach(dispatcher::createPartition); + InstanceRegisterEvent event = new InstanceRegisterEvent(instance); + globalEventHandler.call(event); + } +} diff --git a/src/main/java/net/minestom/server/instance/InstanceManagerProvider.java b/src/main/java/net/minestom/server/instance/InstanceManagerProvider.java new file mode 100644 index 00000000000..97096168116 --- /dev/null +++ b/src/main/java/net/minestom/server/instance/InstanceManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.instance; + +public interface InstanceManagerProvider { + InstanceManager getInstanceManager(); +} diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index 99e24bf6f46..d7e5cdae202 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; +import net.minestom.server.ServerSettings; import net.minestom.server.collision.Shape; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -13,10 +14,12 @@ import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.play.data.LightData; import net.minestom.server.timer.ExecutionType; +import net.minestom.server.timer.SchedulerManager; import net.minestom.server.timer.Task; import net.minestom.server.timer.TaskSchedule; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.chunk.ChunkUtils; +import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,9 +38,11 @@ public class LightingChunk extends DynamicChunk { private static final int LIGHTING_CHUNKS_SEND_DELAY = Integer.getInteger("minestom.lighting.chunks-send-delay", 100); private static final ExecutorService pool = Executors.newWorkStealingPool(); + private final ServerSettings serverSettings; private int[] heightmap; - final CachedPacket lightCache = new CachedPacket(getServerProcess().getServerSetting(), this::createLightPacket); + final CachedPacket lightCache; + private final SchedulerManager schedulerManager; boolean sendNeighbours = true; boolean chunkLoaded = false; @@ -76,8 +81,11 @@ private enum QueueType { Block.LAVA.namespace() ); - public LightingChunk(@NotNull Instance instance, int chunkX, int chunkZ) { - super(instance, chunkX, chunkZ); + public LightingChunk(BiomeManager biomeManager, ServerSettings serverSettings, SchedulerManager schedulerManager, @NotNull Instance instance, int chunkX, int chunkZ) { + super(biomeManager, instance, chunkX, chunkZ); + this.serverSettings = serverSettings; + this.lightCache = new CachedPacket(serverSettings, this::createLightPacket); + this.schedulerManager = schedulerManager; } private boolean checkSkyOcclusion(Block block) { @@ -128,7 +136,7 @@ public void setBlock(int x, int y, int z, @NotNull Block block, public void sendLighting() { if (!isLoaded()) return; - sendPacketToViewers(lightCache); + sendPacketToViewers(serverSettings, lightCache); } @Override @@ -256,7 +264,7 @@ static void updateAfterGeneration(LightingChunk chunk) { return; } - sendingTask = chunk.getServerProcess().getSchedulerManager().scheduleTask(() -> { + sendingTask = chunk.schedulerManager.scheduleTask(() -> { queueLock.lock(); var copy = new ArrayList<>(sendQueue); sendQueue.clear(); @@ -428,7 +436,7 @@ private static void relight(Instance instance, Set queue, LightType type) @Override public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) { - LightingChunk lightingChunk = new LightingChunk(instance, chunkX, chunkZ); + LightingChunk lightingChunk = new LightingChunk(biomeManager, serverSettings, schedulerManager, instance, chunkX, chunkZ); lightingChunk.sections = sections.stream().map(Section::clone).toList(); lightingChunk.entries.putAll(entries); return lightingChunk; diff --git a/src/main/java/net/minestom/server/instance/Section.java b/src/main/java/net/minestom/server/instance/Section.java index 38a28c4dba7..1222856a78a 100644 --- a/src/main/java/net/minestom/server/instance/Section.java +++ b/src/main/java/net/minestom/server/instance/Section.java @@ -1,6 +1,5 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; import net.minestom.server.instance.light.Light; import net.minestom.server.instance.palette.Palette; import net.minestom.server.network.NetworkBuffer; @@ -28,8 +27,8 @@ private Section(Palette blockPalette, Palette biomePalette, Light skyLight, Ligh this.blockLight = blockLight; } - public Section(ServerProcess serverProcess) { - this(Palette.blocks(serverProcess), Palette.biomes(serverProcess)); + public Section() { + this(Palette.blocks(), Palette.biomes()); } public Palette blockPalette() { diff --git a/src/main/java/net/minestom/server/instance/SharedInstance.java b/src/main/java/net/minestom/server/instance/SharedInstance.java index b973f936e79..380ca8a9668 100644 --- a/src/main/java/net/minestom/server/instance/SharedInstance.java +++ b/src/main/java/net/minestom/server/instance/SharedInstance.java @@ -1,8 +1,10 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; @@ -22,8 +24,8 @@ public class SharedInstance extends Instance { private final InstanceContainer instanceContainer; - public SharedInstance(ServerProcess serverProcess, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { - super(serverProcess, uniqueId, instanceContainer.getDimensionType()); + public SharedInstance(ServerSettings serverSettings, EventNode globalEventHandler, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { + super(serverSettings, globalEventHandler, uniqueId, instanceContainer.getDimensionType()); this.instanceContainer = instanceContainer; } diff --git a/src/main/java/net/minestom/server/instance/WorldBorder.java b/src/main/java/net/minestom/server/instance/WorldBorder.java index 78f75ce8cc6..07d4aee1c52 100644 --- a/src/main/java/net/minestom/server/instance/WorldBorder.java +++ b/src/main/java/net/minestom/server/instance/WorldBorder.java @@ -254,7 +254,7 @@ private void refreshCenter() { } private void sendPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(instance.getServerProcess().getServerSetting(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance.getServerSettings(), instance.getPlayers(), packet); } public enum CollisionAxis { diff --git a/src/main/java/net/minestom/server/instance/block/BlockManager.java b/src/main/java/net/minestom/server/instance/block/BlockManager.java index fd0243002b9..adf70e55663 100644 --- a/src/main/java/net/minestom/server/instance/block/BlockManager.java +++ b/src/main/java/net/minestom/server/instance/block/BlockManager.java @@ -1,56 +1,25 @@ package net.minestom.server.instance.block; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.instance.block.rule.BlockPlacementRule; import net.minestom.server.utils.NamespaceID; -import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; -public final class BlockManager { - private final static Logger LOGGER = LoggerFactory.getLogger(BlockManager.class); - // Namespace -> handler supplier - private final Map> blockHandlerMap = new ConcurrentHashMap<>(); - // block id -> block placement rule - private final Int2ObjectMap placementRuleMap = new Int2ObjectOpenHashMap<>(); +public interface BlockManager { + void registerHandler(@NotNull String namespace, @NotNull Supplier<@NotNull BlockHandler> handlerSupplier); - private final Set dummyWarning = ConcurrentHashMap.newKeySet(); // Prevent warning spam - - public void registerHandler(@NotNull String namespace, @NotNull Supplier<@NotNull BlockHandler> handlerSupplier) { - blockHandlerMap.put(namespace, handlerSupplier); - } - - public void registerHandler(@NotNull NamespaceID namespace, @NotNull Supplier<@NotNull BlockHandler> handlerSupplier) { + default void registerHandler(@NotNull NamespaceID namespace, @NotNull Supplier<@NotNull BlockHandler> handlerSupplier) { registerHandler(namespace.toString(), handlerSupplier); } - public @Nullable BlockHandler getHandler(@NotNull String namespace) { - final var handler = blockHandlerMap.get(namespace); - return handler != null ? handler.get() : null; - } + @Nullable BlockHandler getHandler(@NotNull String namespace); @ApiStatus.Internal - public @NotNull BlockHandler getHandlerOrDummy(@NotNull String namespace) { - BlockHandler handler = getHandler(namespace); - if (handler == null) { - if (dummyWarning.add(namespace)) { - LOGGER.warn(""" - Block {} does not have any corresponding handler, default to dummy. - You may want to register a handler for this namespace to prevent any data loss.""", namespace); - } - handler = BlockHandler.Dummy.get(namespace); - } - return handler; - } + @NotNull BlockHandler getHandlerOrDummy(@NotNull String namespace); + /** * Registers a {@link BlockPlacementRule}. @@ -58,11 +27,7 @@ public void registerHandler(@NotNull NamespaceID namespace, @NotNull Supplier<@N * @param blockPlacementRule the block placement rule to register * @throws IllegalArgumentException if blockPlacementRule block id is negative */ - public synchronized void registerBlockPlacementRule(@NotNull BlockPlacementRule blockPlacementRule) { - final int id = blockPlacementRule.getBlock().id(); - Check.argCondition(id < 0, "Block ID must be >= 0, got: " + id); - placementRuleMap.put(id, blockPlacementRule); - } + void registerBlockPlacementRule(@NotNull BlockPlacementRule blockPlacementRule); /** * Gets the {@link BlockPlacementRule} of the specific block. @@ -70,7 +35,5 @@ public synchronized void registerBlockPlacementRule(@NotNull BlockPlacementRule * @param block the block to check * @return the block placement rule associated with the block, null if not any */ - public synchronized @Nullable BlockPlacementRule getBlockPlacementRule(@NotNull Block block) { - return placementRuleMap.get(block.id()); - } + @Nullable BlockPlacementRule getBlockPlacementRule(@NotNull Block block); } diff --git a/src/main/java/net/minestom/server/instance/block/BlockManagerImpl.java b/src/main/java/net/minestom/server/instance/block/BlockManagerImpl.java new file mode 100644 index 00000000000..7f4ca03b55d --- /dev/null +++ b/src/main/java/net/minestom/server/instance/block/BlockManagerImpl.java @@ -0,0 +1,64 @@ +package net.minestom.server.instance.block; + +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minestom.server.instance.block.rule.BlockPlacementRule; +import net.minestom.server.utils.validate.Check; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +public final class BlockManagerImpl implements BlockManager { + private final static Logger LOGGER = LoggerFactory.getLogger(BlockManagerImpl.class); + // Namespace -> handler supplier + private final Map> blockHandlerMap = new ConcurrentHashMap<>(); + // block id -> block placement rule + private final Int2ObjectMap placementRuleMap = new Int2ObjectOpenHashMap<>(); + + private final Set dummyWarning = ConcurrentHashMap.newKeySet(); // Prevent warning spam + + @Override + public void registerHandler(@NotNull String namespace, @NotNull Supplier<@NotNull BlockHandler> handlerSupplier) { + blockHandlerMap.put(namespace, handlerSupplier); + } + + @Override + public @Nullable BlockHandler getHandler(@NotNull String namespace) { + final var handler = blockHandlerMap.get(namespace); + return handler != null ? handler.get() : null; + } + + @Override + @ApiStatus.Internal + public @NotNull BlockHandler getHandlerOrDummy(@NotNull String namespace) { + BlockHandler handler = getHandler(namespace); + if (handler == null) { + if (dummyWarning.add(namespace)) { + LOGGER.warn(""" + Block {} does not have any corresponding handler, default to dummy. + You may want to register a handler for this namespace to prevent any data loss.""", namespace); + } + handler = BlockHandler.Dummy.get(namespace); + } + return handler; + } + + @Override + public synchronized void registerBlockPlacementRule(@NotNull BlockPlacementRule blockPlacementRule) { + final int id = blockPlacementRule.getBlock().id(); + Check.argCondition(id < 0, "Block ID must be >= 0, got: " + id); + placementRuleMap.put(id, blockPlacementRule); + } + + @Override + public synchronized @Nullable BlockPlacementRule getBlockPlacementRule(@NotNull Block block) { + return placementRuleMap.get(block.id()); + } +} diff --git a/src/main/java/net/minestom/server/instance/block/BlockManagerProvider.java b/src/main/java/net/minestom/server/instance/block/BlockManagerProvider.java new file mode 100644 index 00000000000..756f0021ee3 --- /dev/null +++ b/src/main/java/net/minestom/server/instance/block/BlockManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.instance.block; + +public interface BlockManagerProvider { + BlockManager getBlockManager(); +} diff --git a/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java b/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java index 1133e5aaee4..d64930f9a95 100644 --- a/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/AdaptivePalette.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; -import net.minestom.server.ServerProcess; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.MathUtils; import org.jetbrains.annotations.NotNull; @@ -14,11 +13,9 @@ */ final class AdaptivePalette implements Palette, Cloneable { final byte dimension, defaultBitsPerEntry, maxBitsPerEntry; - private final ServerProcess serverProcess; SpecializedPalette palette; - AdaptivePalette(ServerProcess serverProcess, byte dimension, byte maxBitsPerEntry, byte bitsPerEntry) { - this.serverProcess = serverProcess; + AdaptivePalette(byte dimension, byte maxBitsPerEntry, byte bitsPerEntry) { validateDimension(dimension); this.dimension = dimension; this.maxBitsPerEntry = maxBitsPerEntry; @@ -59,7 +56,7 @@ public void fill(int value) { @Override public void setAll(@NotNull EntrySupplier supplier) { - SpecializedPalette newPalette = new FlexiblePalette(serverProcess, this); + SpecializedPalette newPalette = new FlexiblePalette(this); newPalette.setAll(supplier); this.palette = newPalette; } @@ -142,7 +139,7 @@ SpecializedPalette optimizedPalette() { Palette flexiblePalette() { SpecializedPalette currentPalette = this.palette; if (currentPalette instanceof FilledPalette filledPalette) { - currentPalette = new FlexiblePalette(serverProcess, this); + currentPalette = new FlexiblePalette(this); currentPalette.fill(filledPalette.value()); this.palette = currentPalette; } diff --git a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java index f4c0ecd5384..8983822cc16 100644 --- a/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java +++ b/src/main/java/net/minestom/server/instance/palette/FlexiblePalette.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; -import net.minestom.server.ServerProcess; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.MathUtils; import org.jetbrains.annotations.NotNull; @@ -19,7 +18,6 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { private static final ThreadLocal WRITE_CACHE = ThreadLocal.withInitial(() -> new int[4096]); - private final ServerProcess serverProcess; // Specific to this palette type private final AdaptivePalette adaptivePalette; private byte bitsPerEntry; @@ -31,8 +29,7 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { // value = palette index private Int2IntOpenHashMap valueToPaletteMap; - FlexiblePalette(ServerProcess serverProcess, AdaptivePalette adaptivePalette, byte bitsPerEntry) { - this.serverProcess = serverProcess; + FlexiblePalette(AdaptivePalette adaptivePalette, byte bitsPerEntry) { this.adaptivePalette = adaptivePalette; this.bitsPerEntry = bitsPerEntry; @@ -47,8 +44,8 @@ final class FlexiblePalette implements SpecializedPalette, Cloneable { this.values = new long[(maxSize() + valuesPerLong - 1) / valuesPerLong]; } - FlexiblePalette(ServerProcess serverProcess, AdaptivePalette adaptivePalette) { - this(serverProcess, adaptivePalette, adaptivePalette.defaultBitsPerEntry); + FlexiblePalette(AdaptivePalette adaptivePalette) { + this(adaptivePalette, adaptivePalette.defaultBitsPerEntry); } @Override @@ -205,7 +202,6 @@ public int dimension() { palette.count = count; return palette; } catch (CloneNotSupportedException e) { - serverProcess.getExceptionHandler().handleException(e); throw new IllegalStateException("Weird thing happened"); } } @@ -270,7 +266,7 @@ private void updateAll(int[] paletteValues) { void resize(byte newBitsPerEntry) { newBitsPerEntry = newBitsPerEntry > maxBitsPerEntry() ? 15 : newBitsPerEntry; - FlexiblePalette palette = new FlexiblePalette(serverProcess, adaptivePalette, newBitsPerEntry); + FlexiblePalette palette = new FlexiblePalette(adaptivePalette, newBitsPerEntry); palette.paletteToValueList = paletteToValueList; palette.valueToPaletteMap = valueToPaletteMap; getAll(palette::set); diff --git a/src/main/java/net/minestom/server/instance/palette/Palette.java b/src/main/java/net/minestom/server/instance/palette/Palette.java index 4cc50cf9644..5efbbb10222 100644 --- a/src/main/java/net/minestom/server/instance/palette/Palette.java +++ b/src/main/java/net/minestom/server/instance/palette/Palette.java @@ -1,6 +1,5 @@ package net.minestom.server.instance.palette; -import net.minestom.server.ServerProcess; import net.minestom.server.network.NetworkBuffer; import org.jetbrains.annotations.NotNull; @@ -12,16 +11,16 @@ * 0 is the default value. */ public interface Palette extends NetworkBuffer.Writer { - static Palette blocks(ServerProcess serverProcess) { - return newPalette(serverProcess, 16, 8, 4); + static Palette blocks() { + return newPalette( 16, 8, 4); } - static Palette biomes(ServerProcess serverProcess) { - return newPalette(serverProcess, 4, 3, 1); + static Palette biomes() { + return newPalette( 4, 3, 1); } - static Palette newPalette(ServerProcess serverProcess, int dimension, int maxBitsPerEntry, int bitsPerEntry) { - return new AdaptivePalette(serverProcess, (byte) dimension, (byte) maxBitsPerEntry, (byte) bitsPerEntry); + static Palette newPalette(int dimension, int maxBitsPerEntry, int bitsPerEntry) { + return new AdaptivePalette((byte) dimension, (byte) maxBitsPerEntry, (byte) bitsPerEntry); } int get(int x, int y, int z); diff --git a/src/main/java/net/minestom/server/inventory/AbstractInventory.java b/src/main/java/net/minestom/server/inventory/AbstractInventory.java index 12f70d9dee6..453a2ce4c45 100644 --- a/src/main/java/net/minestom/server/inventory/AbstractInventory.java +++ b/src/main/java/net/minestom/server/inventory/AbstractInventory.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory; -import net.minestom.server.ServerObject; -import net.minestom.server.ServerProcess; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.inventory.InventoryItemChangeEvent; import net.minestom.server.event.inventory.PlayerInventoryItemChangeEvent; import net.minestom.server.inventory.click.InventoryClickProcessor; @@ -24,12 +24,12 @@ /** * Represents an inventory where items can be modified/retrieved. */ -public sealed abstract class AbstractInventory implements InventoryClickHandler, Taggable, ServerObject +public sealed abstract class AbstractInventory implements InventoryClickHandler, Taggable permits Inventory, PlayerInventory { private static final VarHandle ITEM_UPDATER = MethodHandles.arrayElementVarHandle(ItemStack[].class); - private final ServerProcess serverProcess; + protected final EventNode globalEventHandler; private final int size; protected final ItemStack[] itemStacks; @@ -40,12 +40,12 @@ public sealed abstract class AbstractInventory implements InventoryClickHandler, private final TagHandler tagHandler = TagHandler.newHandler(); - protected AbstractInventory(@NotNull ServerProcess serverProcess, int size) { - this.serverProcess = serverProcess; + protected AbstractInventory(EventNode globalEventHandler, int size) { + this.globalEventHandler = globalEventHandler; this.size = size; this.itemStacks = new ItemStack[getSize()]; Arrays.fill(itemStacks, ItemStack.AIR); - clickProcessor = new InventoryClickProcessor(serverProcess); + clickProcessor = new InventoryClickProcessor(globalEventHandler); } /** @@ -83,9 +83,9 @@ protected final void safeItemInsert(int slot, @NotNull ItemStack itemStack, bool UNSAFE_itemInsert(slot, itemStack, sendPacket); } if (this instanceof PlayerInventory inv) { - serverProcess.getGlobalEventHandler().call(new PlayerInventoryItemChangeEvent(inv.player, slot, previous, itemStack)); + globalEventHandler.call(new PlayerInventoryItemChangeEvent(inv.player, slot, previous, itemStack)); } else if (this instanceof Inventory inv) { - serverProcess.getGlobalEventHandler().call(new InventoryItemChangeEvent(inv, slot, previous, itemStack)); + globalEventHandler.call(new InventoryItemChangeEvent(inv, slot, previous, itemStack)); } } @@ -259,9 +259,4 @@ public void copyContents(@NotNull ItemStack[] itemStacks) { public @NotNull TagHandler tagHandler() { return tagHandler; } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/inventory/EquipmentHandler.java b/src/main/java/net/minestom/server/inventory/EquipmentHandler.java index 576dddd4dad..17c06681f67 100644 --- a/src/main/java/net/minestom/server/inventory/EquipmentHandler.java +++ b/src/main/java/net/minestom/server/inventory/EquipmentHandler.java @@ -1,5 +1,6 @@ package net.minestom.server.inventory; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; @@ -167,9 +168,11 @@ default void syncEquipment(@NotNull EquipmentSlot slot) { Entity entity = (Entity) this; final ItemStack itemStack = getEquipment(slot); - entity.sendPacketToViewers(new EntityEquipmentPacket(entity.getEntityId(), Map.of(slot, itemStack))); + entity.sendPacketToViewers(getServerSettings(), new EntityEquipmentPacket(entity.getEntityId(), Map.of(slot, itemStack))); } + ServerSettings getServerSettings(); + /** * Gets the packet with all the equipments. * diff --git a/src/main/java/net/minestom/server/inventory/Inventory.java b/src/main/java/net/minestom/server/inventory/Inventory.java index 07e11c71e73..1618f07c021 100644 --- a/src/main/java/net/minestom/server/inventory/Inventory.java +++ b/src/main/java/net/minestom/server/inventory/Inventory.java @@ -1,9 +1,11 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.click.ClickType; import net.minestom.server.inventory.click.InventoryClickResult; import net.minestom.server.item.ItemStack; @@ -24,7 +26,7 @@ /** * Represents an inventory which can be viewed by a collection of {@link Player}. *

        - * You can create one with {@link Inventory#Inventory(ServerProcess, InventoryType, String)} or by making your own subclass. + * You can create one with {@link Inventory#Inventory(EventNode, ServerSettings, InventoryType, String)} or by making your own subclass. * It can then be opened using {@link Player#openInventory(Inventory)}. */ public non-sealed class Inventory extends AbstractInventory implements Viewable { @@ -34,6 +36,7 @@ public non-sealed class Inventory extends AbstractInventory implements Viewable private final byte id; // the type of this inventory private final InventoryType inventoryType; + protected final ServerSettings serverSettings; // the title of this inventory private Component title; @@ -45,8 +48,9 @@ public non-sealed class Inventory extends AbstractInventory implements Viewable // (player -> cursor item) map, used by the click listeners private final ConcurrentHashMap cursorPlayersItem = new ConcurrentHashMap<>(); - public Inventory(@NotNull ServerProcess serverProcess, @NotNull InventoryType inventoryType, @NotNull Component title) { - super(serverProcess, inventoryType.getSize()); + public Inventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull InventoryType inventoryType, @NotNull Component title) { + super(globalEventHandler, inventoryType.getSize()); + this.serverSettings = serverSettings; this.id = generateId(); this.inventoryType = inventoryType; this.title = title; @@ -54,8 +58,8 @@ public Inventory(@NotNull ServerProcess serverProcess, @NotNull InventoryType in this.offset = getSize(); } - public Inventory(@NotNull ServerProcess serverProcess, @NotNull InventoryType inventoryType, @NotNull String title) { - this(serverProcess, inventoryType, Component.text(title)); + public Inventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull InventoryType inventoryType, @NotNull String title) { + this(globalEventHandler, serverSettings, inventoryType, Component.text(title)); } private static byte generateId() { @@ -88,7 +92,7 @@ private static byte generateId() { public void setTitle(@NotNull Component title) { this.title = title; // Re-open the inventory - sendPacketToViewers(new OpenWindowPacket(getWindowId(), getInventoryType().getWindowType(), title)); + sendPacketToViewers(serverSettings, new OpenWindowPacket(getWindowId(), getInventoryType().getWindowType(), title)); // Send inventory items update(); } @@ -194,7 +198,7 @@ public void setCursorItem(@NotNull Player player, @NotNull ItemStack cursorItem) @Override protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean sendPacket) { itemStacks[slot] = itemStack; - if (sendPacket) sendPacketToViewers(new SetSlotPacket(getWindowId(), 0, (short) slot, itemStack)); + if (sendPacket) sendPacketToViewers(serverSettings, new SetSlotPacket(getWindowId(), 0, (short) slot, itemStack)); } private @NotNull WindowItemsPacket createNewWindowItemsPacket(Player player) { @@ -209,7 +213,7 @@ protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean * @see https://wiki.vg/Protocol#Window_Property */ protected void sendProperty(@NotNull InventoryProperty property, short value) { - sendPacketToViewers(new WindowPropertyPacket(getWindowId(), property.getProperty(), value)); + sendPacketToViewers(serverSettings, new WindowPropertyPacket(getWindowId(), property.getProperty(), value)); } @Override @@ -231,7 +235,7 @@ public boolean leftClick(@NotNull Player player, int slot) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } this.cursorPlayersItem.put(player, clickResult.getCursor()); - callClickEvent(getServerProcess().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.LEFT_CLICK, clicked, cursor); + callClickEvent(globalEventHandler, player, isInWindow ? this : null, slot, ClickType.LEFT_CLICK, clicked, cursor); return true; } @@ -254,7 +258,7 @@ public boolean rightClick(@NotNull Player player, int slot) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } this.cursorPlayersItem.put(player, clickResult.getCursor()); - callClickEvent(getServerProcess().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.RIGHT_CLICK, clicked, cursor); + callClickEvent(globalEventHandler, player, isInWindow ? this : null, slot, ClickType.RIGHT_CLICK, clicked, cursor); return true; } @@ -304,7 +308,7 @@ public boolean changeHeld(@NotNull Player player, int slot, int key) { playerInventory.setItemStack(clickSlot, clickResult.getClicked()); } playerInventory.setItemStack(convertedKey, clickResult.getCursor()); - callClickEvent(getServerProcess().getGlobalEventHandler(), player, isInWindow ? this : null, slot, ClickType.CHANGE_HELD, clicked, getCursorItem(player)); + callClickEvent(globalEventHandler, player, isInWindow ? this : null, slot, ClickType.CHANGE_HELD, clicked, getCursorItem(player)); return true; } diff --git a/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java b/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java index 77ee58f48a5..569157c79c3 100644 --- a/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java +++ b/src/main/java/net/minestom/server/inventory/InventoryClickHandler.java @@ -1,7 +1,8 @@ package net.minestom.server.inventory; import net.minestom.server.entity.Player; -import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.inventory.InventoryClickEvent; import net.minestom.server.inventory.click.ClickType; import net.minestom.server.item.ItemStack; @@ -76,7 +77,7 @@ public sealed interface InventoryClickHandler permits AbstractInventory { */ boolean doubleClick(@NotNull Player player, int slot); - default void callClickEvent(@NotNull GlobalEventHandler globalEventHandler, @NotNull Player player, Inventory inventory, int slot, + default void callClickEvent(@NotNull EventNode globalEventHandler, @NotNull Player player, Inventory inventory, int slot, @NotNull ClickType clickType, @NotNull ItemStack clicked, @NotNull ItemStack cursor) { globalEventHandler.call(new InventoryClickEvent(inventory, player, slot, clickType, clicked, cursor)); } diff --git a/src/main/java/net/minestom/server/inventory/PlayerInventory.java b/src/main/java/net/minestom/server/inventory/PlayerInventory.java index 27c45cfe1d6..0aecd565866 100644 --- a/src/main/java/net/minestom/server/inventory/PlayerInventory.java +++ b/src/main/java/net/minestom/server/inventory/PlayerInventory.java @@ -1,8 +1,10 @@ package net.minestom.server.inventory; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.item.EntityEquipEvent; import net.minestom.server.inventory.click.ClickType; import net.minestom.server.inventory.click.InventoryClickResult; @@ -22,11 +24,13 @@ public non-sealed class PlayerInventory extends AbstractInventory implements Equ public static final int INVENTORY_SIZE = 46; public static final int INNER_INVENTORY_SIZE = 36; + private final ServerSettings serverSettings; protected final Player player; private ItemStack cursorItem = ItemStack.AIR; - public PlayerInventory(@NotNull ServerProcess serverProcess, @NotNull Player player) { - super(serverProcess, INVENTORY_SIZE); + public PlayerInventory(ServerSettings serverSettings, @NotNull EventNode globalEventHandler, @NotNull Player player) { + super(globalEventHandler, INVENTORY_SIZE); + this.serverSettings = serverSettings; this.player = player; } @@ -35,7 +39,7 @@ public synchronized void clear() { cursorItem = ItemStack.AIR; super.clear(); // Update equipments - this.player.sendPacketToViewersAndSelf(player.getEquipmentsPacket()); + this.player.sendPacketToViewersAndSelf(serverSettings, player.getEquipmentsPacket()); } @Override @@ -103,6 +107,11 @@ public void setBoots(@NotNull ItemStack itemStack) { safeItemInsert(BOOTS_SLOT, itemStack); } + @Override + public ServerSettings getServerSettings() { + return serverSettings; + } + /** * Refreshes the player inventory by sending a {@link WindowItemsPacket} containing all. * the inventory items @@ -145,7 +154,7 @@ protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean }; if (equipmentSlot != null) { EntityEquipEvent entityEquipEvent = new EntityEquipEvent(player, itemStack, equipmentSlot); - getServerProcess().getGlobalEventHandler().call(entityEquipEvent); + globalEventHandler.call(entityEquipEvent); itemStack = entityEquipEvent.getEquippedItem(); } this.itemStacks[slot] = itemStack; @@ -195,7 +204,7 @@ public boolean leftClick(@NotNull Player player, int slot) { } setItemStack(convertedSlot, clickResult.getClicked()); setCursorItem(clickResult.getCursor()); - callClickEvent(getServerProcess().getGlobalEventHandler(), player, null, convertedSlot, ClickType.LEFT_CLICK, clicked, cursor); + callClickEvent(globalEventHandler, player, null, convertedSlot, ClickType.LEFT_CLICK, clicked, cursor); return true; } @@ -211,7 +220,7 @@ public boolean rightClick(@NotNull Player player, int slot) { } setItemStack(convertedSlot, clickResult.getClicked()); setCursorItem(clickResult.getCursor()); - callClickEvent(getServerProcess().getGlobalEventHandler(), player, null, convertedSlot, ClickType.RIGHT_CLICK, clicked, cursor); + callClickEvent(globalEventHandler, player, null, convertedSlot, ClickType.RIGHT_CLICK, clicked, cursor); return true; } @@ -279,7 +288,7 @@ public boolean changeHeld(@NotNull Player player, int slot, int key) { } setItemStack(convertedSlot, clickResult.getClicked()); setItemStack(convertedKey, clickResult.getCursor()); - callClickEvent(getServerProcess().getGlobalEventHandler(), player, null, convertedSlot, ClickType.CHANGE_HELD, clicked, cursorItem); + callClickEvent(globalEventHandler, player, null, convertedSlot, ClickType.CHANGE_HELD, clicked, cursorItem); return true; } diff --git a/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java b/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java index 51170481012..0b5b251d487 100644 --- a/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java +++ b/src/main/java/net/minestom/server/inventory/click/InventoryClickProcessor.java @@ -1,8 +1,9 @@ package net.minestom.server.inventory.click; -import net.minestom.server.ServerProcess; import net.minestom.server.entity.EquipmentSlot; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.inventory.InventoryClickEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.AbstractInventory; @@ -31,10 +32,11 @@ public final class InventoryClickProcessor { private final Map> leftDraggingMap = new ConcurrentHashMap<>(); private final Map> rightDraggingMap = new ConcurrentHashMap<>(); - private final ServerProcess serverProcess; + private final EventNode globalEventHandler; - public InventoryClickProcessor(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + + public InventoryClickProcessor(EventNode globalEventHandler) { + this.globalEventHandler = globalEventHandler; } public @NotNull InventoryClickResult leftClick(@NotNull Player player, @NotNull AbstractInventory inventory, @@ -433,7 +435,7 @@ public InventoryClickProcessor(ServerProcess serverProcess) { { InventoryPreClickEvent inventoryPreClickEvent = new InventoryPreClickEvent(eventInventory, player, slot, clickType, clickResult.getClicked(), clickResult.getCursor()); - serverProcess.getGlobalEventHandler().call(inventoryPreClickEvent); + globalEventHandler.call(inventoryPreClickEvent); clickResult.setCursor(inventoryPreClickEvent.getCursorItem()); clickResult.setClicked(inventoryPreClickEvent.getClickedItem()); if (inventoryPreClickEvent.isCancelled()) { @@ -469,7 +471,7 @@ public InventoryClickProcessor(ServerProcess serverProcess) { private void callClickEvent(@NotNull Player player, @Nullable AbstractInventory inventory, int slot, @NotNull ClickType clickType, @NotNull ItemStack clicked, @NotNull ItemStack cursor) { final Inventory eventInventory = inventory instanceof Inventory ? (Inventory) inventory : null; - serverProcess.getGlobalEventHandler().call(new InventoryClickEvent(eventInventory, player, slot, clickType, clicked, cursor)); + globalEventHandler.call(new InventoryClickEvent(eventInventory, player, slot, clickType, clicked, cursor)); } public void clearCache(@NotNull Player player) { diff --git a/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java b/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java index 55bb753869c..836d9b09e5f 100644 --- a/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/AnvilInventory.java @@ -1,7 +1,9 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -11,12 +13,12 @@ public class AnvilInventory extends Inventory { private short repairCost; - public AnvilInventory(ServerProcess serverProcess, @NotNull Component title) { - super(serverProcess, InventoryType.ANVIL, title); + public AnvilInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { + super(globalEventHandler, serverSettings, InventoryType.ANVIL, title); } - public AnvilInventory(ServerProcess serverProcess, @NotNull String title) { - super(serverProcess, InventoryType.ANVIL, title); + public AnvilInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { + super(globalEventHandler, serverSettings, InventoryType.ANVIL, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java b/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java index 0f1fa57666a..c5810f74851 100644 --- a/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/BeaconInventory.java @@ -1,7 +1,9 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -14,12 +16,12 @@ public class BeaconInventory extends Inventory { private PotionEffect firstPotionEffect; private PotionEffect secondPotionEffect; - public BeaconInventory(ServerProcess serverProcess, @NotNull Component title) { - super(serverProcess, InventoryType.BEACON, title); + public BeaconInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { + super(globalEventHandler, serverSettings, InventoryType.BEACON, title); } - public BeaconInventory(ServerProcess serverProcess, @NotNull String title) { - super(serverProcess, InventoryType.BEACON, title); + public BeaconInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { + super(globalEventHandler, serverSettings, InventoryType.BEACON, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java b/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java index 34ac8202440..b84fe2a3045 100644 --- a/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/BrewingStandInventory.java @@ -1,7 +1,9 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -12,12 +14,12 @@ public class BrewingStandInventory extends Inventory { private short brewTime; private short fuelTime; - public BrewingStandInventory(ServerProcess serverProcess, @NotNull Component title) { - super(serverProcess, InventoryType.BREWING_STAND, title); + public BrewingStandInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { + super(globalEventHandler, serverSettings, InventoryType.BREWING_STAND, title); } - public BrewingStandInventory(ServerProcess serverProcess, @NotNull String title) { - super(serverProcess, InventoryType.BREWING_STAND, title); + public BrewingStandInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { + super(globalEventHandler, serverSettings, InventoryType.BREWING_STAND, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java b/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java index fd9b19c7ff3..6e239b6b741 100644 --- a/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/EnchantmentTableInventory.java @@ -1,7 +1,9 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -15,12 +17,12 @@ public class EnchantmentTableInventory extends Inventory { private final short[] enchantmentShown = new short[EnchantmentSlot.values().length]; private final short[] enchantmentLevel = new short[EnchantmentSlot.values().length]; - public EnchantmentTableInventory(ServerProcess serverProcess, @NotNull Component title) { - super(serverProcess, InventoryType.ENCHANTMENT, title); + public EnchantmentTableInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { + super(globalEventHandler, serverSettings, InventoryType.ENCHANTMENT, title); } - public EnchantmentTableInventory(ServerProcess serverProcess, @NotNull String title) { - super(serverProcess, InventoryType.ENCHANTMENT, title); + public EnchantmentTableInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { + super(globalEventHandler, serverSettings, InventoryType.ENCHANTMENT, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java b/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java index 07f0f391ecc..cb1304f2cdd 100644 --- a/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/FurnaceInventory.java @@ -1,7 +1,9 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryProperty; import net.minestom.server.inventory.InventoryType; @@ -14,12 +16,12 @@ public class FurnaceInventory extends Inventory { private short progressArrow; private short maximumProgress; - public FurnaceInventory(ServerProcess serverProcess, @NotNull Component title) { - super(serverProcess, InventoryType.FURNACE, title); + public FurnaceInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { + super(globalEventHandler, serverSettings, InventoryType.FURNACE, title); } - public FurnaceInventory(ServerProcess serverProcess, @NotNull String title) { - super(serverProcess, InventoryType.FURNACE, title); + public FurnaceInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { + super(globalEventHandler, serverSettings, InventoryType.FURNACE, title); } /** diff --git a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java index 4f6e0ebbd7c..ac19071cec9 100644 --- a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java @@ -1,8 +1,10 @@ package net.minestom.server.inventory.type; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.network.packet.server.CachedPacket; @@ -21,14 +23,14 @@ public class VillagerInventory extends Inventory { private boolean regularVillager; private boolean canRestock; - public VillagerInventory(ServerProcess serverProcess, @NotNull Component title) { - super(serverProcess, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(serverProcess.getServerSetting(), this::createTradePacket); + public VillagerInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { + super(globalEventHandler, serverSettings, InventoryType.MERCHANT, title); + tradeCache = new CachedPacket(serverSettings, this::createTradePacket); } - public VillagerInventory(ServerProcess serverProcess, @NotNull String title) { - super(serverProcess, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(serverProcess.getServerSetting(), this::createTradePacket); + public VillagerInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { + super(globalEventHandler, serverSettings, InventoryType.MERCHANT, title); + tradeCache = new CachedPacket(serverSettings, this::createTradePacket); } public List getTrades() { @@ -85,7 +87,7 @@ public void setCanRestock(boolean canRestock) { public void update() { super.update(); this.tradeCache.invalidate(); - sendPacketToViewers(tradeCache); + sendPacketToViewers(serverSettings, tradeCache); } @Override diff --git a/src/main/java/net/minestom/server/listener/AbilitiesListener.java b/src/main/java/net/minestom/server/listener/AbilitiesListener.java index 5f066f2b785..574c36a9470 100644 --- a/src/main/java/net/minestom/server/listener/AbilitiesListener.java +++ b/src/main/java/net/minestom/server/listener/AbilitiesListener.java @@ -17,10 +17,10 @@ public static void listener(ClientPlayerAbilitiesPacket packet, Player player) { if (isFlying) { PlayerStartFlyingEvent startFlyingEvent = new PlayerStartFlyingEvent(player); - player.getServerProcess().getGlobalEventHandler().call(startFlyingEvent); + player.getGlobalEventHandler().call(startFlyingEvent); } else { PlayerStopFlyingEvent stopFlyingEvent = new PlayerStopFlyingEvent(player); - player.getServerProcess().getGlobalEventHandler().call(stopFlyingEvent); + player.getGlobalEventHandler().call(stopFlyingEvent); } } } diff --git a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java index 22333aa3513..403dbaf3354 100644 --- a/src/main/java/net/minestom/server/listener/AdvancementTabListener.java +++ b/src/main/java/net/minestom/server/listener/AdvancementTabListener.java @@ -9,7 +9,7 @@ public class AdvancementTabListener { public static void listener(ClientAdvancementTabPacket packet, Player player) { final String tabIdentifier = packet.tabIdentifier(); if (tabIdentifier != null) { - player.getServerProcess().getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); + player.getGlobalEventHandler().call(new AdvancementTabEvent(player, packet.action(), tabIdentifier)); } } } diff --git a/src/main/java/net/minestom/server/listener/AnimationListener.java b/src/main/java/net/minestom/server/listener/AnimationListener.java index 1ce605b014e..a808ff33127 100644 --- a/src/main/java/net/minestom/server/listener/AnimationListener.java +++ b/src/main/java/net/minestom/server/listener/AnimationListener.java @@ -12,7 +12,7 @@ public static void animationListener(ClientAnimationPacket packet, Player player final ItemStack itemStack = player.getItemInHand(hand); //itemStack.onLeftClick(player, hand); PlayerHandAnimationEvent handAnimationEvent = new PlayerHandAnimationEvent(player, hand); - player.getServerProcess().getGlobalEventHandler().callCancellable(handAnimationEvent, () -> { + player.getGlobalEventHandler().callCancellable(handAnimationEvent, () -> { switch (hand) { case MAIN -> player.swingMainHand(); case OFF -> player.swingOffHand(); diff --git a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java index 985fa2be729..6681cf93be7 100644 --- a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java +++ b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java @@ -51,7 +51,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Interact at block // FIXME: onUseOnBlock PlayerBlockInteractEvent playerBlockInteractEvent = new PlayerBlockInteractEvent(player, hand, interactedBlock, blockPosition, cursorPosition, blockFace); - player.getServerProcess().getGlobalEventHandler().call(playerBlockInteractEvent); + player.getGlobalEventHandler().call(playerBlockInteractEvent); boolean blockUse = playerBlockInteractEvent.isBlockingItemUse(); if (!playerBlockInteractEvent.isCancelled()) { final var handler = interactedBlock.handler(); @@ -70,7 +70,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play if (!useMaterial.isBlock()) { // Player didn't try to place a block but interacted with one PlayerUseItemOnBlockEvent event = new PlayerUseItemOnBlockEvent(player, hand, usedItem, blockPosition, cursorPosition, blockFace); - player.getServerProcess().getGlobalEventHandler().call(event); + player.getGlobalEventHandler().call(event); // Ack the block change. This is required to reset the client prediction to the server state. player.sendPacket(new AcknowledgeBlockChangePacket(packet.sequence())); return; @@ -90,7 +90,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Get the newly placed block position //todo it feels like it should be possible to have better replacement rules than this, feels pretty scuffed. Point placementPosition = blockPosition; - var interactedPlacementRule = player.getServerProcess().getBlockManager().getBlockPlacementRule(interactedBlock); + var interactedPlacementRule = player.getBlockManager().getBlockPlacementRule(interactedBlock); if (!interactedBlock.isAir() && (interactedPlacementRule == null || !interactedPlacementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(interactedBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is not replaceable, try to place next to it. @@ -100,7 +100,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play placementPosition = blockPosition.add(offsetX, offsetY, offsetZ); var placementBlock = instance.getBlock(placementPosition); - var placementRule = player.getServerProcess().getBlockManager().getBlockPlacementRule(placementBlock); + var placementRule = player.getBlockManager().getBlockPlacementRule(placementBlock); if (!placementBlock.registry().isReplaceable() && !(placementRule != null && placementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(placementBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is still not replaceable, cancel the placement @@ -149,7 +149,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // BlockPlaceEvent check PlayerBlockPlaceEvent playerBlockPlaceEvent = new PlayerBlockPlaceEvent(player, placedBlock, blockFace, placementPosition, packet.hand()); playerBlockPlaceEvent.consumeBlock(player.getGameMode() != GameMode.CREATIVE); - player.getServerProcess().getGlobalEventHandler().call(playerBlockPlaceEvent); + player.getGlobalEventHandler().call(playerBlockPlaceEvent); if (playerBlockPlaceEvent.isCancelled()) { refresh(player, chunk); return; diff --git a/src/main/java/net/minestom/server/listener/BookListener.java b/src/main/java/net/minestom/server/listener/BookListener.java index 6a204602fdb..2597c1ebf23 100644 --- a/src/main/java/net/minestom/server/listener/BookListener.java +++ b/src/main/java/net/minestom/server/listener/BookListener.java @@ -11,7 +11,7 @@ public class BookListener { public static void listener(ClientEditBookPacket packet, Player player) { int slot = PlayerInventoryUtils.convertClientInventorySlot(packet.slot()); ItemStack itemStack = player.getInventory().getItemStack(slot); - player.getServerProcess().getGlobalEventHandler().call(new EditBookEvent(player, itemStack, packet.pages(), packet.title())); + player.getGlobalEventHandler().call(new EditBookEvent(player, itemStack, packet.pages(), packet.title())); } } diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index 6d8c427819a..9801eff6750 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -18,7 +18,7 @@ public class ChatMessageListener { public static void commandChatListener(ClientCommandChatPacket packet, Player player) { final String command = packet.message(); if (Messenger.canReceiveCommand(player)) { - player.getServerProcess().getCommandManager().execute(player, command); + player.getCommandManager().execute(player, command); } else { Messenger.sendRejectionMessage(player); } @@ -31,11 +31,11 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl return; } - final Collection players = player.getServerProcess().getConnectionManager().getOnlinePlayers(); + final Collection players = player.getConnectionManager().getOnlinePlayers(); PlayerChatEvent playerChatEvent = new PlayerChatEvent(player, players, () -> buildDefaultChatMessage(player, message), message); // Call the event - player.getServerProcess().getGlobalEventHandler().callCancellable(playerChatEvent, () -> { + player.getGlobalEventHandler().callCancellable(playerChatEvent, () -> { final Function formatFunction = playerChatEvent.getChatFormatFunction(); Component textObject; @@ -51,7 +51,7 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl final Collection recipients = playerChatEvent.getRecipients(); if (!recipients.isEmpty()) { // delegate to the messenger to avoid sending messages we shouldn't be - Messenger.sendMessage(player.getServerProcess().getServerSetting(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); + Messenger.sendMessage(player.getServerSettings(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); } }); } diff --git a/src/main/java/net/minestom/server/listener/EntityActionListener.java b/src/main/java/net/minestom/server/listener/EntityActionListener.java index 1e84659e2bd..e2fc801d429 100644 --- a/src/main/java/net/minestom/server/listener/EntityActionListener.java +++ b/src/main/java/net/minestom/server/listener/EntityActionListener.java @@ -24,9 +24,9 @@ private static void setSneaking(Player player, boolean sneaking) { if (oldState != sneaking) { if (sneaking) { - player.getServerProcess().getGlobalEventHandler().call(new PlayerStartSneakingEvent(player)); + player.getGlobalEventHandler().call(new PlayerStartSneakingEvent(player)); } else { - player.getServerProcess().getGlobalEventHandler().call(new PlayerStopSneakingEvent(player)); + player.getGlobalEventHandler().call(new PlayerStopSneakingEvent(player)); } } } @@ -38,15 +38,15 @@ private static void setSprinting(Player player, boolean sprinting) { if (oldState != sprinting) { if (sprinting) { - player.getServerProcess().getGlobalEventHandler().call(new PlayerStartSprintingEvent(player)); + player.getGlobalEventHandler().call(new PlayerStartSprintingEvent(player)); } else { - player.getServerProcess().getGlobalEventHandler().call(new PlayerStopSprintingEvent(player)); + player.getGlobalEventHandler().call(new PlayerStopSprintingEvent(player)); } } } private static void startFlyingElytra(Player player) { player.setFlyingWithElytra(true); - player.getServerProcess().getGlobalEventHandler().call(new PlayerStartFlyingWithElytraEvent(player)); + player.getGlobalEventHandler().call(new PlayerStartFlyingWithElytraEvent(player)); } } diff --git a/src/main/java/net/minestom/server/listener/PlayConfigListener.java b/src/main/java/net/minestom/server/listener/PlayConfigListener.java index dca5dfc74cd..fd615224d17 100644 --- a/src/main/java/net/minestom/server/listener/PlayConfigListener.java +++ b/src/main/java/net/minestom/server/listener/PlayConfigListener.java @@ -6,6 +6,6 @@ public class PlayConfigListener { public static void configAckListener(@NotNull ClientConfigurationAckPacket packet, @NotNull Player player) { - player.getServerProcess().getConnectionManager().doConfiguration(player, false); + player.getConnectionManager().doConfiguration(player, false); } } diff --git a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java index 47b218fe80b..606009d3643 100644 --- a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java @@ -58,7 +58,7 @@ public static void playerDiggingListener(ClientPlayerDiggingPacket packet, Playe var registry = diggingResult.block().registry(); if (registry.isBlockEntity()) { final NBTCompound data = BlockUtils.extractClientNbt(diggingResult.block()); - player.sendPacketToViewersAndSelf(new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); + player.sendPacketToViewersAndSelf(player.getServerSettings(), new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); } } } @@ -82,7 +82,7 @@ private static DiggingResult startDigging(Player player, Instance instance, Poin final boolean instantBreak = player.isInstantBreak() || block.registry().hardness() == 0; if (!instantBreak) { PlayerStartDiggingEvent playerStartDiggingEvent = new PlayerStartDiggingEvent(player, block, blockPosition, blockFace); - player.getServerProcess().getGlobalEventHandler().call(playerStartDiggingEvent); + player.getGlobalEventHandler().call(playerStartDiggingEvent); return new DiggingResult(block, !playerStartDiggingEvent.isCancelled()); } // Client only send a single STARTED_DIGGING when insta-break is enabled @@ -92,7 +92,7 @@ private static DiggingResult startDigging(Player player, Instance instance, Poin private static DiggingResult cancelDigging(Player player, Instance instance, Point blockPosition) { final Block block = instance.getBlock(blockPosition); PlayerCancelDiggingEvent playerCancelDiggingEvent = new PlayerCancelDiggingEvent(player, block, blockPosition); - player.getServerProcess().getGlobalEventHandler().call(playerCancelDiggingEvent); + player.getGlobalEventHandler().call(playerCancelDiggingEvent); return new DiggingResult(block, true); } @@ -104,7 +104,7 @@ private static DiggingResult finishDigging(Player player, Instance instance, Poi } PlayerFinishDiggingEvent playerFinishDiggingEvent = new PlayerFinishDiggingEvent(player, block, blockPosition); - player.getServerProcess().getGlobalEventHandler().call(playerFinishDiggingEvent); + player.getGlobalEventHandler().call(playerFinishDiggingEvent); return breakBlock(instance, player, blockPosition, playerFinishDiggingEvent.getBlock(), blockFace); } @@ -166,7 +166,7 @@ private static void swapItemHand(Player player) { final ItemStack mainHand = inventory.getItemInMainHand(); final ItemStack offHand = inventory.getItemInOffHand(); PlayerSwapItemEvent swapItemEvent = new PlayerSwapItemEvent(player, offHand, mainHand); - player.getServerProcess().getGlobalEventHandler().callCancellable(swapItemEvent, () -> { + player.getGlobalEventHandler().callCancellable(swapItemEvent, () -> { inventory.setItemInMainHand(swapItemEvent.getMainHandItem()); inventory.setItemInOffHand(swapItemEvent.getOffHandItem()); }); diff --git a/src/main/java/net/minestom/server/listener/PlayerHeldListener.java b/src/main/java/net/minestom/server/listener/PlayerHeldListener.java index 8c15fa76501..3ccdd77b4c9 100644 --- a/src/main/java/net/minestom/server/listener/PlayerHeldListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerHeldListener.java @@ -16,7 +16,7 @@ public static void heldListener(ClientHeldItemChangePacket packet, Player player final byte slot = (byte) packet.slot(); PlayerChangeHeldSlotEvent changeHeldSlotEvent = new PlayerChangeHeldSlotEvent(player, slot); - player.getServerProcess().getGlobalEventHandler().call(changeHeldSlotEvent); + player.getGlobalEventHandler().call(changeHeldSlotEvent); if (!changeHeldSlotEvent.isCancelled()) { // Event hasn't been canceled, process it diff --git a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java index ef15a749d39..98bdbfd4ff4 100644 --- a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java @@ -53,7 +53,7 @@ private static void processMovement(@NotNull Player player, @NotNull Pos packetP } PlayerMoveEvent playerMoveEvent = new PlayerMoveEvent(player, packetPosition, onGround); - player.getServerProcess().getGlobalEventHandler().call(playerMoveEvent); + player.getGlobalEventHandler().call(playerMoveEvent); if (!currentPosition.equals(player.getPosition())) { // Player has been teleported in the event return; diff --git a/src/main/java/net/minestom/server/listener/SpectateListener.java b/src/main/java/net/minestom/server/listener/SpectateListener.java index cb758f3a1e6..dd3f684d645 100644 --- a/src/main/java/net/minestom/server/listener/SpectateListener.java +++ b/src/main/java/net/minestom/server/listener/SpectateListener.java @@ -41,7 +41,7 @@ public static void listener(ClientSpectatePacket packet, Player player) { // Despite the name of this packet being spectate, it is sent when the player // uses their hotbar to switch between entities, which actually performs a teleport // instead of a spectate. - player.getServerProcess().getGlobalEventHandler().call(new PlayerSpectateEvent(player, target)); + player.getGlobalEventHandler().call(new PlayerSpectateEvent(player, target)); } } diff --git a/src/main/java/net/minestom/server/listener/TabCompleteListener.java b/src/main/java/net/minestom/server/listener/TabCompleteListener.java index d8078719f7d..4215b75795a 100644 --- a/src/main/java/net/minestom/server/listener/TabCompleteListener.java +++ b/src/main/java/net/minestom/server/listener/TabCompleteListener.java @@ -12,7 +12,7 @@ public class TabCompleteListener { public static void listener(ClientTabCompletePacket packet, Player player) { final String text = packet.text(); - final Suggestion suggestion = getSuggestion(player.getServerProcess().getCommandManager(), player, text); + final Suggestion suggestion = getSuggestion(player.getCommandManager(), player, text); if (suggestion != null) { player.sendPacket(new TabCompletePacket( packet.transactionId(), diff --git a/src/main/java/net/minestom/server/listener/UseEntityListener.java b/src/main/java/net/minestom/server/listener/UseEntityListener.java index 4722ba77ce8..5db432ebc97 100644 --- a/src/main/java/net/minestom/server/listener/UseEntityListener.java +++ b/src/main/java/net/minestom/server/listener/UseEntityListener.java @@ -20,10 +20,10 @@ public static void useEntityListener(ClientInteractEntityPacket packet, Player p if (type instanceof ClientInteractEntityPacket.Attack) { if (entity instanceof LivingEntity && ((LivingEntity) entity).isDead()) // Can't attack dead entities return; - player.getServerProcess().getGlobalEventHandler().call(new EntityAttackEvent(player, entity)); + player.getGlobalEventHandler().call(new EntityAttackEvent(player, entity)); } else if (type instanceof ClientInteractEntityPacket.InteractAt interactAt) { Point interactPosition = new Vec(interactAt.targetX(), interactAt.targetY(), interactAt.targetZ()); - player.getServerProcess().getGlobalEventHandler().call(new PlayerEntityInteractEvent(player, entity, interactAt.hand(), interactPosition)); + player.getGlobalEventHandler().call(new PlayerEntityInteractEvent(player, entity, interactAt.hand(), interactPosition)); } } } diff --git a/src/main/java/net/minestom/server/listener/UseItemListener.java b/src/main/java/net/minestom/server/listener/UseItemListener.java index 3abf77e7f6c..f16f8547a40 100644 --- a/src/main/java/net/minestom/server/listener/UseItemListener.java +++ b/src/main/java/net/minestom/server/listener/UseItemListener.java @@ -18,7 +18,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { ItemStack itemStack = hand == Player.Hand.MAIN ? inventory.getItemInMainHand() : inventory.getItemInOffHand(); //itemStack.onRightClick(player, hand); PlayerUseItemEvent useItemEvent = new PlayerUseItemEvent(player, hand, itemStack); - player.getServerProcess().getGlobalEventHandler().call(useItemEvent); + player.getGlobalEventHandler().call(useItemEvent); final PlayerInventory playerInventory = player.getInventory(); if (useItemEvent.isCancelled()) { @@ -56,7 +56,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { // Eating code, contains the eating time customisation PlayerPreEatEvent playerPreEatEvent = new PlayerPreEatEvent(player, itemStack, hand, player.getDefaultEatingTime()); - player.getServerProcess().getGlobalEventHandler().callCancellable(playerPreEatEvent, () -> player.refreshEating(hand, playerPreEatEvent.getEatingTime())); + player.getGlobalEventHandler().callCancellable(playerPreEatEvent, () -> player.refreshEating(hand, playerPreEatEvent.getEatingTime())); if (playerPreEatEvent.isCancelled()) { cancelAnimation = true; @@ -65,9 +65,9 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { if (!cancelAnimation && itemAnimationType != null) { PlayerItemAnimationEvent playerItemAnimationEvent = new PlayerItemAnimationEvent(player, itemAnimationType, hand); - player.getServerProcess().getGlobalEventHandler().callCancellable(playerItemAnimationEvent, () -> { + player.getGlobalEventHandler().callCancellable(playerItemAnimationEvent, () -> { player.refreshActiveHand(true, hand == Player.Hand.OFF, false); - player.sendPacketToViewers(player.getMetadataPacket()); + player.sendPacketToViewers(player.getServerSettings(), player.getMetadataPacket()); }); } } diff --git a/src/main/java/net/minestom/server/listener/WindowListener.java b/src/main/java/net/minestom/server/listener/WindowListener.java index 91b32fa1c91..7d4207daa6a 100644 --- a/src/main/java/net/minestom/server/listener/WindowListener.java +++ b/src/main/java/net/minestom/server/listener/WindowListener.java @@ -85,7 +85,7 @@ public static void pong(ClientPongPacket packet, Player player) { public static void closeWindowListener(ClientCloseWindowPacket packet, Player player) { // if windowId == 0 then it is player's inventory, meaning that they hadn't been any open inventory packet InventoryCloseEvent inventoryCloseEvent = new InventoryCloseEvent(player.getOpenInventory(), player); - player.getServerProcess().getGlobalEventHandler().call(inventoryCloseEvent); + player.getGlobalEventHandler().call(inventoryCloseEvent); player.closeInventory(true); diff --git a/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java b/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java index 0047cea0257..09752a07c2c 100644 --- a/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java +++ b/src/main/java/net/minestom/server/listener/common/PluginMessageListener.java @@ -8,7 +8,7 @@ public class PluginMessageListener { public static void listener(ClientPluginMessagePacket packet, Player player) { PlayerPluginMessageEvent pluginMessageEvent = new PlayerPluginMessageEvent(player, packet.channel(), packet.data()); - player.getServerProcess().getGlobalEventHandler().call(pluginMessageEvent); + player.getGlobalEventHandler().call(pluginMessageEvent); } } diff --git a/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java b/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java index ba30b544c48..570dd4b9542 100644 --- a/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java +++ b/src/main/java/net/minestom/server/listener/common/ResourcePackListener.java @@ -7,7 +7,7 @@ public class ResourcePackListener { public static void listener(ClientResourcePackStatusPacket packet, Player player) { - player.getServerProcess().getGlobalEventHandler().call(new PlayerResourcePackStatusEvent(player, packet.status())); + player.getGlobalEventHandler().call(new PlayerResourcePackStatusEvent(player, packet.status())); // Run adventure callbacks for the resource pack player.onResourcePackStatus(packet.id(), packet.status()); diff --git a/src/main/java/net/minestom/server/listener/common/SettingsListener.java b/src/main/java/net/minestom/server/listener/common/SettingsListener.java index 5b68c3fcef9..567e540b024 100644 --- a/src/main/java/net/minestom/server/listener/common/SettingsListener.java +++ b/src/main/java/net/minestom/server/listener/common/SettingsListener.java @@ -9,6 +9,6 @@ public static void listener(ClientSettingsPacket packet, Player player) { Player.PlayerSettings settings = player.getSettings(); // Since viewDistance bounds checking is performed in the refresh function, it is not necessary to check it here settings.refresh(packet.locale(), packet.viewDistance(), packet.chatMessageType(), packet.chatColors(), packet.displayedSkinParts(), packet.mainHand(), packet.enableTextFiltering(), packet.allowsListing()); - player.getServerProcess().getGlobalEventHandler().call(new PlayerSettingsChangeEvent(player)); + player.getGlobalEventHandler().call(new PlayerSettingsChangeEvent(player)); } } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java index 513dd3c957c..aa5b8b5fc07 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManager.java @@ -1,110 +1,11 @@ package net.minestom.server.listener.manager; -import net.minestom.server.ServerProcess; -import net.minestom.server.event.GlobalEventHandler; -import net.minestom.server.event.player.PlayerPacketEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.listener.*; -import net.minestom.server.listener.common.KeepAliveListener; -import net.minestom.server.listener.common.PluginMessageListener; -import net.minestom.server.listener.common.ResourcePackListener; -import net.minestom.server.listener.common.SettingsListener; -import net.minestom.server.listener.preplay.ConfigListener; -import net.minestom.server.listener.preplay.HandshakeListener; -import net.minestom.server.listener.preplay.LoginListener; -import net.minestom.server.listener.preplay.StatusListener; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.ClientPacket; -import net.minestom.server.network.packet.client.common.*; -import net.minestom.server.network.packet.client.configuration.ClientFinishConfigurationPacket; -import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; -import net.minestom.server.network.packet.client.login.ClientEncryptionResponsePacket; -import net.minestom.server.network.packet.client.login.ClientLoginAcknowledgedPacket; -import net.minestom.server.network.packet.client.login.ClientLoginPluginResponsePacket; -import net.minestom.server.network.packet.client.login.ClientLoginStartPacket; -import net.minestom.server.network.packet.client.play.*; -import net.minestom.server.network.packet.client.status.PingPacket; -import net.minestom.server.network.packet.client.status.StatusRequestPacket; import net.minestom.server.network.player.PlayerConnection; import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public final class PacketListenerManager { - - private final static Logger LOGGER = LoggerFactory.getLogger(PacketListenerManager.class); - - private final Map, PacketPrePlayListenerConsumer>[] listeners = new Map[ConnectionState.values().length]; - private final GlobalEventHandler globalEventHandler; - private final ExceptionHandler exceptionHandler; - - public PacketListenerManager(ServerProcess serverProcess) { - this(serverProcess.getGlobalEventHandler(), serverProcess.getExceptionHandler()); - } - - public PacketListenerManager(GlobalEventHandler globalEventHandler, ExceptionHandler exceptionHandler) { - this.globalEventHandler = globalEventHandler; - this.exceptionHandler = exceptionHandler; - for (int i = 0; i < listeners.length; i++) { - listeners[i] = new ConcurrentHashMap<>(); - } - - setListener(ConnectionState.HANDSHAKE, ClientHandshakePacket.class, HandshakeListener::listener); - - setListener(ConnectionState.STATUS, StatusRequestPacket.class, StatusListener::requestListener); - setListener(ConnectionState.STATUS, PingPacket.class, StatusListener::pingListener); - - setListener(ConnectionState.LOGIN, ClientLoginStartPacket.class, LoginListener::loginStartListener); - setListener(ConnectionState.LOGIN, ClientEncryptionResponsePacket.class, LoginListener::loginEncryptionResponseListener); - setListener(ConnectionState.LOGIN, ClientLoginPluginResponsePacket.class, LoginListener::loginPluginResponseListener); - setListener(ConnectionState.LOGIN, ClientLoginAcknowledgedPacket.class, LoginListener::loginAckListener); - - setConfigurationListener(ClientSettingsPacket.class, SettingsListener::listener); - setConfigurationListener(ClientPluginMessagePacket.class, PluginMessageListener::listener); - setConfigurationListener(ClientKeepAlivePacket.class, KeepAliveListener::listener); - setConfigurationListener(ClientPongPacket.class, (packet, player) -> {/* empty */}); - setConfigurationListener(ClientResourcePackStatusPacket.class, ResourcePackListener::listener); - setConfigurationListener(ClientFinishConfigurationPacket.class, ConfigListener::finishConfigListener); - - setPlayListener(ClientKeepAlivePacket.class, KeepAliveListener::listener); - setPlayListener(ClientCommandChatPacket.class, ChatMessageListener::commandChatListener); - setPlayListener(ClientChatMessagePacket.class, ChatMessageListener::chatMessageListener); - setPlayListener(ClientClickWindowPacket.class, WindowListener::clickWindowListener); - setPlayListener(ClientCloseWindowPacket.class, WindowListener::closeWindowListener); - setPlayListener(ClientConfigurationAckPacket.class, PlayConfigListener::configAckListener); - setPlayListener(ClientPongPacket.class, WindowListener::pong); - setPlayListener(ClientEntityActionPacket.class, EntityActionListener::listener); - setPlayListener(ClientHeldItemChangePacket.class, PlayerHeldListener::heldListener); - setPlayListener(ClientPlayerBlockPlacementPacket.class, BlockPlacementListener::listener); - setPlayListener(ClientSteerVehiclePacket.class, PlayerVehicleListener::steerVehicleListener); - setPlayListener(ClientVehicleMovePacket.class, PlayerVehicleListener::vehicleMoveListener); - setPlayListener(ClientSteerBoatPacket.class, PlayerVehicleListener::boatSteerListener); - setPlayListener(ClientPlayerPacket.class, PlayerPositionListener::playerPacketListener); - setPlayListener(ClientPlayerRotationPacket.class, PlayerPositionListener::playerLookListener); - setPlayListener(ClientPlayerPositionPacket.class, PlayerPositionListener::playerPositionListener); - setPlayListener(ClientPlayerPositionAndRotationPacket.class, PlayerPositionListener::playerPositionAndLookListener); - setPlayListener(ClientTeleportConfirmPacket.class, PlayerPositionListener::teleportConfirmListener); - setPlayListener(ClientPlayerDiggingPacket.class, PlayerDiggingListener::playerDiggingListener); - setPlayListener(ClientAnimationPacket.class, AnimationListener::animationListener); - setPlayListener(ClientInteractEntityPacket.class, UseEntityListener::useEntityListener); - setPlayListener(ClientUseItemPacket.class, UseItemListener::useItemListener); - setPlayListener(ClientStatusPacket.class, PlayStatusListener::listener); - setPlayListener(ClientSettingsPacket.class, SettingsListener::listener); - setPlayListener(ClientCreativeInventoryActionPacket.class, CreativeInventoryActionListener::listener); - setPlayListener(ClientCraftRecipeRequest.class, RecipeListener::listener); - setPlayListener(ClientTabCompletePacket.class, TabCompleteListener::listener); - setPlayListener(ClientPluginMessagePacket.class, PluginMessageListener::listener); - setPlayListener(ClientPlayerAbilitiesPacket.class, AbilitiesListener::listener); - setPlayListener(ClientResourcePackStatusPacket.class, ResourcePackListener::listener); - setPlayListener(ClientAdvancementTabPacket.class, AdvancementTabListener::listener); - setPlayListener(ClientSpectatePacket.class, SpectateListener::listener); - setPlayListener(ClientEditBookPacket.class, BookListener::listener); - setPlayListener(ClientChatSessionUpdatePacket.class, (packet, player) -> {/* empty */}); - setPlayListener(ClientChunkBatchReceivedPacket.class, ChunkBatchListener::batchReceivedListener); - } +public interface PacketListenerManager { /** * Processes a packet by getting its {@link PacketPlayListenerConsumer} and calling all the packet listeners. @@ -113,34 +14,7 @@ public PacketListenerManager(GlobalEventHandler globalEventHandler, ExceptionHan * @param connection the connection of the player who sent the packet * @param the packet type */ - public void processClientPacket(@NotNull T packet, @NotNull PlayerConnection connection) { - final ConnectionState state = connection.getConnectionState(); - final Class clazz = packet.getClass(); - PacketPrePlayListenerConsumer packetListenerConsumer = listeners[state.ordinal()].get(clazz); - - // Listener can be null if none has been set before, call PacketConsumer anyway - if (packetListenerConsumer == null) { - LOGGER.warn("Packet " + clazz + " does not have any default listener! (The issue comes from Minestom)"); - return; - } - - // Event - if (state == ConnectionState.PLAY) { - PlayerPacketEvent playerPacketEvent = new PlayerPacketEvent(connection.getPlayer(), packet); - globalEventHandler.call(playerPacketEvent); - if (playerPacketEvent.isCancelled()) { - return; - } - } - - // Finally execute the listener - try { - packetListenerConsumer.accept(packet, connection); - } catch (Exception e) { - // Packet is likely invalid - exceptionHandler.handleException(e); - } - } + void processClientPacket(@NotNull T packet, @NotNull PlayerConnection connection); /** * Sets the listener of a packet. @@ -152,9 +26,7 @@ public void processClientPacket(@NotNull T packet, @Not * @param consumer the new packet's listener * @param the type of the packet */ - public void setListener(@NotNull ConnectionState state, @NotNull Class packetClass, @NotNull PacketPrePlayListenerConsumer consumer) { - this.listeners[state.ordinal()].put(packetClass, consumer); - } + void setListener(@NotNull ConnectionState state, @NotNull Class packetClass, @NotNull PacketPrePlayListenerConsumer consumer); /** * Sets the listener of a packet. @@ -165,13 +37,9 @@ public void setListener(@NotNull ConnectionState state, * @param consumer the new packet's listener * @param the type of the packet */ - public void setPlayListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer) { - setListener(ConnectionState.PLAY, packetClass, (packet, playerConnection) -> consumer.accept(packet, playerConnection.getPlayer())); - } + void setPlayListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer); - public void setConfigurationListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer) { - setListener(ConnectionState.CONFIGURATION, packetClass, (packet, playerConnection) -> consumer.accept(packet, playerConnection.getPlayer())); - } + void setConfigurationListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer); /** * Sets the listener of a packet. @@ -183,8 +51,5 @@ public void setConfigurationListener(@NotNull Class * @param the type of the packet */ @Deprecated - public void setListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer) { - setPlayListener(packetClass, consumer); - } - + void setListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer); } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java new file mode 100644 index 00000000000..67e0d7f2c5e --- /dev/null +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java @@ -0,0 +1,158 @@ +package net.minestom.server.listener.manager; + +import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.event.player.PlayerPacketEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.extras.MojangAuthProvider; +import net.minestom.server.listener.*; +import net.minestom.server.listener.common.KeepAliveListener; +import net.minestom.server.listener.common.PluginMessageListener; +import net.minestom.server.listener.common.ResourcePackListener; +import net.minestom.server.listener.common.SettingsListener; +import net.minestom.server.listener.preplay.ConfigListener; +import net.minestom.server.listener.preplay.HandshakeListener; +import net.minestom.server.listener.preplay.LoginListener; +import net.minestom.server.listener.preplay.StatusListener; +import net.minestom.server.network.ConnectionManagerProvider; +import net.minestom.server.network.ConnectionState; +import net.minestom.server.network.packet.client.ClientPacket; +import net.minestom.server.network.packet.client.common.*; +import net.minestom.server.network.packet.client.configuration.ClientFinishConfigurationPacket; +import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; +import net.minestom.server.network.packet.client.login.ClientEncryptionResponsePacket; +import net.minestom.server.network.packet.client.login.ClientLoginAcknowledgedPacket; +import net.minestom.server.network.packet.client.login.ClientLoginPluginResponsePacket; +import net.minestom.server.network.packet.client.login.ClientLoginStartPacket; +import net.minestom.server.network.packet.client.play.*; +import net.minestom.server.network.packet.client.status.PingPacket; +import net.minestom.server.network.packet.client.status.StatusRequestPacket; +import net.minestom.server.network.player.PlayerConnection; +import net.minestom.server.network.socket.ServerProvider; +import net.minestom.server.timer.SchedulerManagerProvider; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class PacketListenerManagerImpl implements PacketListenerManager { + + private final static Logger LOGGER = LoggerFactory.getLogger(PacketListenerManagerImpl.class); + + private final Map, PacketPrePlayListenerConsumer>[] listeners = new Map[ConnectionState.values().length]; + private final GlobalEventHandler globalEventHandler; + private final ExceptionHandler exceptionHandler; + + public PacketListenerManagerImpl(GlobalEventHandler globalEventHandler, ExceptionHandler exceptionHandler, MojangAuthProvider mojangAuthProvider, ConnectionManagerProvider connectionManagerProvider, SchedulerManagerProvider schedulerManagerProvider, ServerProvider serverProvider) { + this.globalEventHandler = globalEventHandler; + this.exceptionHandler = exceptionHandler; + for (int i = 0; i < listeners.length; i++) { + listeners[i] = new ConcurrentHashMap<>(); + } + + setListener(ConnectionState.HANDSHAKE, ClientHandshakePacket.class, HandshakeListener::listener); + + setListener(ConnectionState.STATUS, StatusRequestPacket.class, (packet, connection) -> StatusListener.requestListener(connectionManagerProvider.getConnectionManager(), globalEventHandler, serverProvider.getServer(), packet, connection)); + setListener(ConnectionState.STATUS, PingPacket.class, (packet, connection) -> StatusListener.pingListener(globalEventHandler, schedulerManagerProvider.getSchedulerManager(), packet, connection)); + + setListener(ConnectionState.LOGIN, ClientLoginStartPacket.class, (packet, connection) -> LoginListener.loginStartListener(mojangAuthProvider.getMojangAuth(), connectionManagerProvider.getConnectionManager(), packet, connection)); + setListener(ConnectionState.LOGIN, ClientEncryptionResponsePacket.class, (packet, connection) -> LoginListener.loginEncryptionResponseListener(mojangAuthProvider.getMojangAuth(), exceptionHandler, connectionManagerProvider.getConnectionManager(), packet, connection)); + setListener(ConnectionState.LOGIN, ClientLoginPluginResponsePacket.class, (packet, connection) -> LoginListener.loginPluginResponseListener(exceptionHandler, connectionManagerProvider.getConnectionManager(), packet, connection)); + setListener(ConnectionState.LOGIN, ClientLoginAcknowledgedPacket.class, (packet, connection) -> LoginListener.loginAckListener(connectionManagerProvider.getConnectionManager(), packet, connection)); + + setConfigurationListener(ClientSettingsPacket.class, SettingsListener::listener); + setConfigurationListener(ClientPluginMessagePacket.class, PluginMessageListener::listener); + setConfigurationListener(ClientKeepAlivePacket.class, KeepAliveListener::listener); + setConfigurationListener(ClientPongPacket.class, (packet, player) -> {/* empty */}); + setConfigurationListener(ClientResourcePackStatusPacket.class, ResourcePackListener::listener); + setConfigurationListener(ClientFinishConfigurationPacket.class, ConfigListener::finishConfigListener); + + setPlayListener(ClientKeepAlivePacket.class, KeepAliveListener::listener); + setPlayListener(ClientCommandChatPacket.class, ChatMessageListener::commandChatListener); + setPlayListener(ClientChatMessagePacket.class, ChatMessageListener::chatMessageListener); + setPlayListener(ClientClickWindowPacket.class, WindowListener::clickWindowListener); + setPlayListener(ClientCloseWindowPacket.class, WindowListener::closeWindowListener); + setPlayListener(ClientConfigurationAckPacket.class, PlayConfigListener::configAckListener); + setPlayListener(ClientPongPacket.class, WindowListener::pong); + setPlayListener(ClientEntityActionPacket.class, EntityActionListener::listener); + setPlayListener(ClientHeldItemChangePacket.class, PlayerHeldListener::heldListener); + setPlayListener(ClientPlayerBlockPlacementPacket.class, BlockPlacementListener::listener); + setPlayListener(ClientSteerVehiclePacket.class, PlayerVehicleListener::steerVehicleListener); + setPlayListener(ClientVehicleMovePacket.class, PlayerVehicleListener::vehicleMoveListener); + setPlayListener(ClientSteerBoatPacket.class, PlayerVehicleListener::boatSteerListener); + setPlayListener(ClientPlayerPacket.class, PlayerPositionListener::playerPacketListener); + setPlayListener(ClientPlayerRotationPacket.class, PlayerPositionListener::playerLookListener); + setPlayListener(ClientPlayerPositionPacket.class, PlayerPositionListener::playerPositionListener); + setPlayListener(ClientPlayerPositionAndRotationPacket.class, PlayerPositionListener::playerPositionAndLookListener); + setPlayListener(ClientTeleportConfirmPacket.class, PlayerPositionListener::teleportConfirmListener); + setPlayListener(ClientPlayerDiggingPacket.class, PlayerDiggingListener::playerDiggingListener); + setPlayListener(ClientAnimationPacket.class, AnimationListener::animationListener); + setPlayListener(ClientInteractEntityPacket.class, UseEntityListener::useEntityListener); + setPlayListener(ClientUseItemPacket.class, UseItemListener::useItemListener); + setPlayListener(ClientStatusPacket.class, PlayStatusListener::listener); + setPlayListener(ClientSettingsPacket.class, SettingsListener::listener); + setPlayListener(ClientCreativeInventoryActionPacket.class, CreativeInventoryActionListener::listener); + setPlayListener(ClientCraftRecipeRequest.class, RecipeListener::listener); + setPlayListener(ClientTabCompletePacket.class, TabCompleteListener::listener); + setPlayListener(ClientPluginMessagePacket.class, PluginMessageListener::listener); + setPlayListener(ClientPlayerAbilitiesPacket.class, AbilitiesListener::listener); + setPlayListener(ClientResourcePackStatusPacket.class, ResourcePackListener::listener); + setPlayListener(ClientAdvancementTabPacket.class, AdvancementTabListener::listener); + setPlayListener(ClientSpectatePacket.class, SpectateListener::listener); + setPlayListener(ClientEditBookPacket.class, BookListener::listener); + setPlayListener(ClientChatSessionUpdatePacket.class, (packet, player) -> {/* empty */}); + setPlayListener(ClientChunkBatchReceivedPacket.class, ChunkBatchListener::batchReceivedListener); + } + + @Override + public void processClientPacket(@NotNull T packet, @NotNull PlayerConnection connection) { + final ConnectionState state = connection.getConnectionState(); + final Class clazz = packet.getClass(); + PacketPrePlayListenerConsumer packetListenerConsumer = listeners[state.ordinal()].get(clazz); + + // Listener can be null if none has been set before, call PacketConsumer anyway + if (packetListenerConsumer == null) { + LOGGER.warn("Packet " + clazz + " does not have any default listener! (The issue comes from Minestom)"); + return; + } + + // Event + if (state == ConnectionState.PLAY) { + PlayerPacketEvent playerPacketEvent = new PlayerPacketEvent(connection.getPlayer(), packet); + globalEventHandler.call(playerPacketEvent); + if (playerPacketEvent.isCancelled()) { + return; + } + } + + // Finally execute the listener + try { + packetListenerConsumer.accept(packet, connection); + } catch (Exception e) { + // Packet is likely invalid + exceptionHandler.handleException(e); + } + } + + @Override + public void setListener(@NotNull ConnectionState state, @NotNull Class packetClass, @NotNull PacketPrePlayListenerConsumer consumer) { + this.listeners[state.ordinal()].put(packetClass, consumer); + } + + @Override + public void setPlayListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer) { + setListener(ConnectionState.PLAY, packetClass, (packet, playerConnection) -> consumer.accept(packet, playerConnection.getPlayer())); + } + + @Override + public void setConfigurationListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer) { + setListener(ConnectionState.CONFIGURATION, packetClass, (packet, playerConnection) -> consumer.accept(packet, playerConnection.getPlayer())); + } + + @Override + @Deprecated + public void setListener(@NotNull Class packetClass, @NotNull PacketPlayListenerConsumer consumer) { + setPlayListener(packetClass, consumer); + } +} diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerProvider.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerProvider.java new file mode 100644 index 00000000000..6d08ee26e37 --- /dev/null +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.listener.manager; + +public interface PacketListenerManagerProvider { + PacketListenerManager getPacketListenerManager(); +} diff --git a/src/main/java/net/minestom/server/listener/manager/PacketPlayListenerConsumer.java b/src/main/java/net/minestom/server/listener/manager/PacketPlayListenerConsumer.java index d0f86ef1a48..ec34c3b7468 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketPlayListenerConsumer.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketPlayListenerConsumer.java @@ -4,7 +4,7 @@ import net.minestom.server.network.packet.client.ClientPacket; /** - * Small convenient interface to use method references with {@link PacketListenerManager#setListener(Class, PacketPlayListenerConsumer)}. + * Small convenient interface to use method references with {@link PacketListenerManagerImpl#setListener(Class, PacketPlayListenerConsumer)}. * * @param the packet type */ diff --git a/src/main/java/net/minestom/server/listener/manager/PacketPrePlayListenerConsumer.java b/src/main/java/net/minestom/server/listener/manager/PacketPrePlayListenerConsumer.java index 0d3ce4ec522..443994723c4 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketPrePlayListenerConsumer.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketPrePlayListenerConsumer.java @@ -1,12 +1,11 @@ package net.minestom.server.listener.manager; -import net.minestom.server.entity.Player; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.player.PlayerConnection; /** - * Small convenient interface to use method references with {@link PacketListenerManager#setListener(ConnectionState, Class, PacketPrePlayListenerConsumer)}. + * Small convenient interface to use method references with {@link PacketListenerManagerImpl#setListener(ConnectionState, Class, PacketPrePlayListenerConsumer)}. * * @param the packet type */ diff --git a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java index b2430586691..3156dfb3426 100644 --- a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java @@ -7,6 +7,6 @@ public final class ConfigListener { public static void finishConfigListener(@NotNull ClientFinishConfigurationPacket packet, @NotNull Player player) { - player.getServerProcess().getConnectionManager().transitionConfigToPlay(player); + player.getConnectionManager().transitionConfigToPlay(player); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java index e6e001acab0..f128bacf175 100644 --- a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java @@ -5,11 +5,13 @@ import com.google.gson.JsonObject; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.entity.Player; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.extras.MojangAuth; import net.minestom.server.extras.bungee.BungeeCordProxy; import net.minestom.server.extras.velocity.VelocityProxy; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.client.login.ClientEncryptionResponsePacket; import net.minestom.server.network.packet.client.login.ClientLoginAcknowledgedPacket; @@ -43,8 +45,7 @@ public final class LoginListener { private static final Component ALREADY_CONNECTED = Component.text("You are already on this server", NamedTextColor.RED); public static final Component INVALID_PROXY_RESPONSE = Component.text("Invalid proxy response!", NamedTextColor.RED); - public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @NotNull PlayerConnection connection) { - MojangAuth mojangAuth = connection.getServerProcess().getMojangAuth(); + public static void loginStartListener(MojangAuth mojangAuth, ConnectionManager connectionManager, @NotNull ClientLoginStartPacket packet, @NotNull PlayerConnection connection) { final boolean isSocketConnection = connection instanceof PlayerSocketConnection; // Proxy support (only for socket clients) and cache the login username if (isSocketConnection) { @@ -63,7 +64,7 @@ public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @N if (mojangAuth.isEnabled() && isSocketConnection) { // Mojang auth - if (connection.getServerProcess().getConnectionManager().getOnlinePlayerByUsername(packet.username()) != null) { + if (connectionManager.getOnlinePlayerByUsername(packet.username()) != null) { connection.sendPacket(new LoginDisconnectPacket(ALREADY_CONNECTED)); connection.disconnect(); return; @@ -80,16 +81,15 @@ public static void loginStartListener(@NotNull ClientLoginStartPacket packet, @N // Offline final UUID playerUuid = bungee && isSocketConnection ? ((PlayerSocketConnection) connection).gameProfile().uuid() : - connection.getServerProcess().getConnectionManager().getPlayerConnectionUuid(connection, packet.username()); - connection.getServerProcess().getConnectionManager().createPlayer(connection, playerUuid, packet.username()); + connectionManager.getPlayerConnectionUuid(connection, packet.username()); + connectionManager.createPlayer(connection, playerUuid, packet.username()); } } - public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResponsePacket packet, @NotNull PlayerConnection connection) { + public static void loginEncryptionResponseListener(MojangAuth mojangAuth, ExceptionHandler exceptionHandler, ConnectionManager connectionManager, @NotNull ClientEncryptionResponsePacket packet, @NotNull PlayerConnection connection) { // Encryption is only support for socket connection - MojangAuth mojangAuth = connection.getServerProcess().getMojangAuth(); if (!(connection instanceof PlayerSocketConnection socketConnection)) return; - AsyncUtils.runAsync(connection.getServerProcess(), () -> { + AsyncUtils.runAsync(exceptionHandler, () -> { final String loginUsername = socketConnection.getLoginUsername(); if (loginUsername == null || loginUsername.isEmpty()) { // Shouldn't happen @@ -101,14 +101,14 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp mojangAuth.getMojangCrypt().decryptUsingKey(mojangAuth.getKeyPair().getPrivate(), packet.encryptedVerifyToken())); if (verificationFailed) { - ServerProcess.LOGGER.error("Encryption failed for {}", loginUsername); + ServerFacade.LOGGER.error("Encryption failed for {}", loginUsername); return; } final byte[] digestedData = mojangAuth.getMojangCrypt().digestData("", mojangAuth.getKeyPair().getPublic(), getSecretKey(mojangAuth, packet.sharedSecret())); if (digestedData == null) { // Incorrect key, probably because of the client - ServerProcess.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); + ServerFacade.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); connection.disconnect(); return; } @@ -126,7 +126,7 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp if (!ok) { if (throwable != null) { - connection.getServerProcess().getExceptionHandler().handleException(throwable); + exceptionHandler.handleException(throwable); } if (socketConnection.getPlayer() != null) { socketConnection.getPlayer().kick(Component.text("Failed to contact Mojang's Session Servers (Are they down?)")); @@ -142,8 +142,8 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp .replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); final String profileName = gameProfile.get("name").getAsString(); - ServerProcess.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); - connection.getServerProcess().getConnectionManager().createPlayer(connection, profileUUID, profileName); + ServerFacade.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); + connectionManager.createPlayer(connection, profileUUID, profileName); List propertyList = new ArrayList<>(); for (JsonElement element : gameProfile.get("properties").getAsJsonArray()) { JsonObject object = element.getAsJsonObject(); @@ -151,7 +151,7 @@ public static void loginEncryptionResponseListener(@NotNull ClientEncryptionResp } socketConnection.UNSAFE_setProfile(new GameProfile(profileUUID, profileName, propertyList)); } catch (Exception e) { - connection.getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } }); }); @@ -161,7 +161,7 @@ private static SecretKey getSecretKey(MojangAuth mojangAuth, byte[] sharedSecret return mojangAuth.getMojangCrypt().decryptByteToSecretKey(mojangAuth.getKeyPair().getPrivate(), sharedSecret); } - public static void loginPluginResponseListener(@NotNull ClientLoginPluginResponsePacket packet, @NotNull PlayerConnection connection) { + public static void loginPluginResponseListener(ExceptionHandler exceptionHandler, ConnectionManager connectionManager, @NotNull ClientLoginPluginResponsePacket packet, @NotNull PlayerConnection connection) { // Proxy support if (connection instanceof PlayerSocketConnection socketConnection) { final String channel = socketConnection.getPluginRequestChannel(packet.messageId()); @@ -183,7 +183,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons try { address = InetAddress.getByName(buffer.read(STRING)); } catch (UnknownHostException e) { - connection.getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); return; } final int port = ((java.net.InetSocketAddress) connection.getRemoteAddress()).getPort(); @@ -196,7 +196,7 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons if (success) { socketConnection.setRemoteAddress(socketAddress); socketConnection.UNSAFE_setProfile(gameProfile); - connection.getServerProcess().getConnectionManager().createPlayer(connection, gameProfile.uuid(), gameProfile.name()); + connectionManager.createPlayer(connection, gameProfile.uuid(), gameProfile.name()); } else { LoginDisconnectPacket disconnectPacket = new LoginDisconnectPacket(INVALID_PROXY_RESPONSE); socketConnection.sendPacket(disconnectPacket); @@ -205,9 +205,9 @@ public static void loginPluginResponseListener(@NotNull ClientLoginPluginRespons } } - public static void loginAckListener(@NotNull ClientLoginAcknowledgedPacket ignored, @NotNull PlayerConnection connection) { + public static void loginAckListener(ConnectionManager connectionManager, @NotNull ClientLoginAcknowledgedPacket ignored, @NotNull PlayerConnection connection) { final Player player = Objects.requireNonNull(connection.getPlayer()); - connection.getServerProcess().getConnectionManager().doConfiguration(player, true); + connectionManager.doConfiguration(player, true); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java index b13258db43b..f3835769376 100644 --- a/src/main/java/net/minestom/server/listener/preplay/StatusListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/StatusListener.java @@ -1,27 +1,31 @@ package net.minestom.server.listener.preplay; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ClientPingServerEvent; import net.minestom.server.event.server.ServerListPingEvent; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.client.status.PingPacket; import net.minestom.server.network.packet.client.status.StatusRequestPacket; import net.minestom.server.network.packet.server.status.PongPacket; import net.minestom.server.network.packet.server.status.ResponsePacket; import net.minestom.server.network.player.PlayerConnection; +import net.minestom.server.network.socket.Server; import net.minestom.server.ping.ServerListPingType; +import net.minestom.server.timer.SchedulerManager; import org.jetbrains.annotations.NotNull; public final class StatusListener { - public static void requestListener(@NotNull StatusRequestPacket packet, @NotNull PlayerConnection connection) { + public static void requestListener(ConnectionManager connectionManager, GlobalEventHandler globalEventHandler, Server server, @NotNull StatusRequestPacket packet, @NotNull PlayerConnection connection) { final ServerListPingType pingVersion = ServerListPingType.fromModernProtocolVersion(connection.getProtocolVersion()); - final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connection.getServerProcess(), connection, pingVersion); - connection.getServerProcess().getGlobalEventHandler().callCancellable(statusRequestEvent, () -> + final ServerListPingEvent statusRequestEvent = new ServerListPingEvent(connectionManager, server, connection, pingVersion); + globalEventHandler.callCancellable(statusRequestEvent, () -> connection.sendPacket(new ResponsePacket(pingVersion.getPingResponse(statusRequestEvent.getResponseData())))); } - public static void pingListener(@NotNull PingPacket packet, @NotNull PlayerConnection connection) { + public static void pingListener(GlobalEventHandler globalEventHandler, SchedulerManager schedulerManager, @NotNull PingPacket packet, @NotNull PlayerConnection connection) { final ClientPingServerEvent clientPingEvent = new ClientPingServerEvent(connection, packet.number()); - connection.getServerProcess().getGlobalEventHandler().call(clientPingEvent); + globalEventHandler.call(clientPingEvent); if (clientPingEvent.isCancelled()) { connection.disconnect(); @@ -30,7 +34,7 @@ public static void pingListener(@NotNull PingPacket packet, @NotNull PlayerConne connection.sendPacket(new PongPacket(clientPingEvent.getPayload())); connection.disconnect(); } else { - connection.getServerProcess().getSchedulerManager().buildTask(() -> { + schedulerManager.buildTask(() -> { connection.sendPacket(new PongPacket(clientPingEvent.getPayload())); connection.disconnect(); }).delay(clientPingEvent.getDelay()).schedule(); diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java index e49febaeb5e..27f09259c50 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManager.java @@ -1,117 +1,45 @@ package net.minestom.server.monitoring; -import it.unimi.dsi.fastutil.longs.Long2LongMap; -import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerConsts; -import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.utils.MathUtils; -import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; import java.time.Duration; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** * Small monitoring tools that can be used to check the current memory usage and Minestom threads CPU usage. *

        * Needs to be enabled with {@link #enable(Duration)}. Memory can then be accessed with {@link #getUsedMemory()} - * and the CPUs usage with {@link #getResultMap()} or {@link #getCpuMonitoringMessage()}. + * and the CPUs usage with {@link #getResultMap()} or {@link #getCpuMonitoringMessage(BenchmarkManager)}. *

        * Be aware that this is not the most accurate method, you should use a proper java profiler depending on your needs. */ -public final class BenchmarkManager { - private final static Logger LOGGER = LoggerFactory.getLogger(BenchmarkManager.class); - private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); - private static final List THREADS = new ArrayList<>(); +public interface BenchmarkManager { + boolean isEnabled(); - static { - THREADS.add(ServerConsts.THREAD_NAME_TICK_SCHEDULER); - THREADS.add(ServerConsts.THREAD_NAME_TICK); - } - - private final Long2LongMap lastCpuTimeMap = new Long2LongOpenHashMap(); - private final Long2LongMap lastUserTimeMap = new Long2LongOpenHashMap(); - private final Long2LongMap lastWaitedMap = new Long2LongOpenHashMap(); - private final Long2LongMap lastBlockedMap = new Long2LongOpenHashMap(); - private final Map resultMap = new ConcurrentHashMap<>(); - - private boolean enabled = false; - private volatile boolean stop = false; - private long time; - private final ExceptionHandler exceptionHandler; - - public BenchmarkManager(ExceptionHandler exceptionHandler) { - this.exceptionHandler = exceptionHandler; - } - - public void enable(@NotNull Duration duration) { - Check.stateCondition(enabled, "A benchmark is already running, please disable it first."); - try { - THREAD_MX_BEAN.setThreadContentionMonitoringEnabled(true); - THREAD_MX_BEAN.setThreadCpuTimeEnabled(true); - } catch (Throwable e) { - // Likely unsupported by the JVM (e.g. Substrate VM) - LOGGER.warn("Could not enable thread monitoring", e); - return; - } + void enable(@NotNull Duration duration); - this.time = duration.toMillis(); + void disable(); - final Thread thread = new Thread(null, () -> { - while (!stop) { - refreshData(); - try { - Thread.sleep(time); - } catch (InterruptedException e) { - exceptionHandler.handleException(e); - } - } - stop = false; - }, ServerConsts.THREAD_NAME_BENCHMARK); - thread.setDaemon(true); - thread.start(); - - this.enabled = true; - } - - public void disable() { - this.stop = true; - this.enabled = false; - } - - public void addThreadMonitor(@NotNull String threadName) { - THREADS.add(threadName); - } + void addThreadMonitor(@NotNull String threadName); /** * Gets the heap memory used by the server in bytes. * * @return the memory used by the server */ - public long getUsedMemory() { - return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); - } + long getUsedMemory(); - public @NotNull Map getResultMap() { - return Collections.unmodifiableMap(resultMap); - } + @NotNull Map getResultMap(); - public @NotNull Component getCpuMonitoringMessage() { - if (!enabled) return Component.text("CPU monitoring is disabled"); + + static @NotNull Component getCpuMonitoringMessage(BenchmarkManager benchmarkManager) { + if (!benchmarkManager.isEnabled()) return Component.text("CPU monitoring is disabled"); TextComponent.Builder benchmarkMessage = Component.text(); - for (var resultEntry : resultMap.entrySet()) { + for (var resultEntry : benchmarkManager.getResultMap().entrySet()) { final String name = resultEntry.getKey(); final ThreadResult result = resultEntry.getValue(); @@ -129,43 +57,4 @@ public long getUsedMemory() { } return benchmarkMessage.build(); } - - private void refreshData() { - ThreadInfo[] threadInfo = THREAD_MX_BEAN.getThreadInfo(THREAD_MX_BEAN.getAllThreadIds()); - for (ThreadInfo threadInfo2 : threadInfo) { - if (threadInfo2 == null) continue; // Can happen if the thread does not exist - final String name = threadInfo2.getThreadName(); - if (THREADS.stream().noneMatch(name::startsWith)) continue; - - final long id = threadInfo2.getThreadId(); - - final long lastCpuTime = lastCpuTimeMap.getOrDefault(id, 0L); - final long lastUserTime = lastUserTimeMap.getOrDefault(id, 0L); - final long lastWaitedTime = lastWaitedMap.getOrDefault(id, 0L); - final long lastBlockedTime = lastBlockedMap.getOrDefault(id, 0L); - - final long blockedTime = threadInfo2.getBlockedTime(); - final long waitedTime = threadInfo2.getWaitedTime(); - final long cpuTime = THREAD_MX_BEAN.getThreadCpuTime(id); - final long userTime = THREAD_MX_BEAN.getThreadUserTime(id); - - lastCpuTimeMap.put(id, cpuTime); - lastUserTimeMap.put(id, userTime); - lastWaitedMap.put(id, waitedTime); - lastBlockedMap.put(id, blockedTime); - - final double totalCpuTime = (double) (cpuTime - lastCpuTime) / 1000000D; - final double totalUserTime = (double) (userTime - lastUserTime) / 1000000D; - final long totalBlocked = blockedTime - lastBlockedTime; - final long totalWaited = waitedTime - lastWaitedTime; - - final double cpuPercentage = totalCpuTime / (double) time * 100L; - final double userPercentage = totalUserTime / (double) time * 100L; - final double waitedPercentage = totalWaited / (double) time * 100L; - final double blockedPercentage = totalBlocked / (double) time * 100L; - - ThreadResult threadResult = new ThreadResult(cpuPercentage, userPercentage, waitedPercentage, blockedPercentage); - resultMap.put(name, threadResult); - } - } } diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java new file mode 100644 index 00000000000..499d7faa4c5 --- /dev/null +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java @@ -0,0 +1,142 @@ +package net.minestom.server.monitoring; + +import it.unimi.dsi.fastutil.longs.Long2LongMap; +import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import net.minestom.server.ServerConsts; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.utils.validate.Check; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class BenchmarkManagerImpl implements BenchmarkManager { + private final static Logger LOGGER = LoggerFactory.getLogger(BenchmarkManagerImpl.class); + private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); + private static final List THREADS = new ArrayList<>(); + + static { + THREADS.add(ServerConsts.THREAD_NAME_TICK_SCHEDULER); + THREADS.add(ServerConsts.THREAD_NAME_TICK); + } + + private final Long2LongMap lastCpuTimeMap = new Long2LongOpenHashMap(); + private final Long2LongMap lastUserTimeMap = new Long2LongOpenHashMap(); + private final Long2LongMap lastWaitedMap = new Long2LongOpenHashMap(); + private final Long2LongMap lastBlockedMap = new Long2LongOpenHashMap(); + private final Map resultMap = new ConcurrentHashMap<>(); + + private boolean enabled = false; + private volatile boolean stop = false; + private long time; + private final ExceptionHandler exceptionHandler; + + public BenchmarkManagerImpl(ExceptionHandler exceptionHandler) { + this.exceptionHandler = exceptionHandler; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + @Override + public void enable(@NotNull Duration duration) { + Check.stateCondition(enabled, "A benchmark is already running, please disable it first."); + try { + THREAD_MX_BEAN.setThreadContentionMonitoringEnabled(true); + THREAD_MX_BEAN.setThreadCpuTimeEnabled(true); + } catch (Throwable e) { + // Likely unsupported by the JVM (e.g. Substrate VM) + LOGGER.warn("Could not enable thread monitoring", e); + return; + } + + this.time = duration.toMillis(); + + final Thread thread = new Thread(null, () -> { + while (!stop) { + refreshData(); + try { + Thread.sleep(time); + } catch (InterruptedException e) { + exceptionHandler.handleException(e); + } + } + stop = false; + }, ServerConsts.THREAD_NAME_BENCHMARK); + thread.setDaemon(true); + thread.start(); + + this.enabled = true; + } + + @Override + public void disable() { + this.stop = true; + this.enabled = false; + } + + @Override + public void addThreadMonitor(@NotNull String threadName) { + THREADS.add(threadName); + } + + @Override + public long getUsedMemory() { + return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); + } + + @Override + public @NotNull Map getResultMap() { + return Collections.unmodifiableMap(resultMap); + } + + private void refreshData() { + ThreadInfo[] threadInfo = THREAD_MX_BEAN.getThreadInfo(THREAD_MX_BEAN.getAllThreadIds()); + for (ThreadInfo threadInfo2 : threadInfo) { + if (threadInfo2 == null) continue; // Can happen if the thread does not exist + final String name = threadInfo2.getThreadName(); + if (THREADS.stream().noneMatch(name::startsWith)) continue; + + final long id = threadInfo2.getThreadId(); + + final long lastCpuTime = lastCpuTimeMap.getOrDefault(id, 0L); + final long lastUserTime = lastUserTimeMap.getOrDefault(id, 0L); + final long lastWaitedTime = lastWaitedMap.getOrDefault(id, 0L); + final long lastBlockedTime = lastBlockedMap.getOrDefault(id, 0L); + + final long blockedTime = threadInfo2.getBlockedTime(); + final long waitedTime = threadInfo2.getWaitedTime(); + final long cpuTime = THREAD_MX_BEAN.getThreadCpuTime(id); + final long userTime = THREAD_MX_BEAN.getThreadUserTime(id); + + lastCpuTimeMap.put(id, cpuTime); + lastUserTimeMap.put(id, userTime); + lastWaitedMap.put(id, waitedTime); + lastBlockedMap.put(id, blockedTime); + + final double totalCpuTime = (double) (cpuTime - lastCpuTime) / 1000000D; + final double totalUserTime = (double) (userTime - lastUserTime) / 1000000D; + final long totalBlocked = blockedTime - lastBlockedTime; + final long totalWaited = waitedTime - lastWaitedTime; + + final double cpuPercentage = totalCpuTime / (double) time * 100L; + final double userPercentage = totalUserTime / (double) time * 100L; + final double waitedPercentage = totalWaited / (double) time * 100L; + final double blockedPercentage = totalBlocked / (double) time * 100L; + + ThreadResult threadResult = new ThreadResult(cpuPercentage, userPercentage, waitedPercentage, blockedPercentage); + resultMap.put(name, threadResult); + } + } +} diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerProvider.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerProvider.java new file mode 100644 index 00000000000..05cf3241a22 --- /dev/null +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.monitoring; + +public interface BenchmarkManagerProvider { + BenchmarkManager getBenchmarkManager(); +} diff --git a/src/main/java/net/minestom/server/network/ConnectionManager.java b/src/main/java/net/minestom/server/network/ConnectionManager.java index e924e2f81a1..1c966b7ed50 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManager.java +++ b/src/main/java/net/minestom/server/network/ConnectionManager.java @@ -1,114 +1,37 @@ package net.minestom.server.network; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; -import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; -import net.minestom.server.entity.damage.DamageType; -import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; -import net.minestom.server.event.player.AsyncPlayerPreLoginEvent; -import net.minestom.server.gamedata.tags.TagManager; -import net.minestom.server.instance.Instance; -import net.minestom.server.message.Messenger; import net.minestom.server.network.packet.client.login.ClientLoginStartPacket; -import net.minestom.server.network.packet.server.CachedPacket; -import net.minestom.server.network.packet.server.common.KeepAlivePacket; -import net.minestom.server.network.packet.server.common.PluginMessagePacket; -import net.minestom.server.network.packet.server.common.TagsPacket; -import net.minestom.server.network.packet.server.configuration.FinishConfigurationPacket; -import net.minestom.server.network.packet.server.configuration.RegistryDataPacket; -import net.minestom.server.network.packet.server.login.LoginSuccessPacket; -import net.minestom.server.network.packet.server.play.StartConfigurationPacket; import net.minestom.server.network.player.PlayerConnection; -import net.minestom.server.network.player.PlayerSocketConnection; -import net.minestom.server.utils.StringUtils; -import net.minestom.server.utils.async.AsyncUtils; -import net.minestom.server.utils.debug.DebugUtils; -import net.minestom.server.utils.validate.Check; -import org.jctools.queues.MessagePassingQueue; -import org.jctools.queues.MpscUnboundedArrayQueue; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jglrxavpok.hephaistos.nbt.NBT; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.*; +import java.util.Collection; +import java.util.UUID; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.function.Function; /** * Manages the connected clients. */ -public final class ConnectionManager { - private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class); - - public final CachedPacket defaultTags; - private final ServerProcess serverProcess; - - private static final long KEEP_ALIVE_DELAY = 10_000; - private static final long KEEP_ALIVE_KICK = 30_000; - private static final Component TIMEOUT_TEXT = Component.text("Timeout", NamedTextColor.RED); - - - // All players once their Player object has been instantiated. - private final Map connectionPlayerMap = new ConcurrentHashMap<>(); - // Players waiting to be spawned (post configuration state) - private final MessagePassingQueue waitingPlayers = new MpscUnboundedArrayQueue<>(64); - // Players in configuration state - private final Set configurationPlayers = new CopyOnWriteArraySet<>(); - // Players in play state - private final Set playPlayers = new CopyOnWriteArraySet<>(); - - // The players who need keep alive ticks. This was added because we may not send a keep alive in - // the time after sending finish configuration but before receiving configuration end (to swap to play). - // I(mattw) could not come up with a better way to express this besides completely splitting client/server - // states. Perhaps there will be an improvement in the future. - private final Set keepAlivePlayers = new CopyOnWriteArraySet<>(); - - private final Set unmodifiableConfigurationPlayers = Collections.unmodifiableSet(configurationPlayers); - private final Set unmodifiablePlayPlayers = Collections.unmodifiableSet(playPlayers); - - - // The uuid provider once a player login - private volatile UuidProvider uuidProvider = (playerConnection, username) -> UUID.randomUUID(); - // The player provider to have your own Player implementation - private final PlayerProvider defaultPlayerProvider; - private volatile PlayerProvider playerProvider; - - public ConnectionManager(ServerProcess serverProcess, ServerSettings serverSettings, TagManager tagManager) { - this.serverProcess = serverProcess; - this.defaultTags = new CachedPacket(serverSettings, new TagsPacket(tagManager.getTagMap())); - defaultPlayerProvider = (uuid, username, connection) -> new Player(serverProcess, uuid, username, connection); - playerProvider = defaultPlayerProvider; - } +public interface ConnectionManager { /** * Gets the number of "online" players, eg for the query response. * *

        Only includes players in the play state, not players in configuration.

        */ - public int getOnlinePlayerCount() { - return playPlayers.size(); - } + int getOnlinePlayerCount(); /** * Returns an unmodifiable set containing the players currently in the play state. */ - public @NotNull Collection<@NotNull Player> getOnlinePlayers() { - return unmodifiablePlayPlayers; - } + @NotNull Collection<@NotNull Player> getOnlinePlayers(); /** * Returns an unmodifiable set containing the players currently in the configuration state. */ - public @NotNull Collection<@NotNull Player> getConfigPlayers() { - return unmodifiableConfigurationPlayers; - } + @NotNull Collection<@NotNull Player> getConfigPlayers(); /** * Gets the {@link Player} linked to a {@link PlayerConnection}. @@ -119,9 +42,7 @@ public int getOnlinePlayerCount() { * @param connection the player connection * @return the player linked to the connection */ - public Player getPlayer(@NotNull PlayerConnection connection) { - return connectionPlayerMap.get(connection); - } + Player getPlayer(@NotNull PlayerConnection connection); /** * Gets the first player in the play state which validates {@link String#equalsIgnoreCase(String)}. @@ -131,13 +52,7 @@ public Player getPlayer(@NotNull PlayerConnection connection) { * @param username the player username (case-insensitive) * @return the first player who validate the username condition, null if none was found */ - public @Nullable Player getOnlinePlayerByUsername(@NotNull String username) { - for (Player player : getOnlinePlayers()) { - if (player.getUsername().equalsIgnoreCase(username)) - return player; - } - return null; - } + @Nullable Player getOnlinePlayerByUsername(@NotNull String username); /** * Gets the first player in the play state which validates {@link UUID#equals(Object)}. @@ -147,13 +62,7 @@ public Player getPlayer(@NotNull PlayerConnection connection) { * @param uuid the player UUID * @return the first player who validate the UUID condition, null if none was found */ - public @Nullable Player getOnlinePlayerByUuid(@NotNull UUID uuid) { - for (Player player : getOnlinePlayers()) { - if (player.getUuid().equals(uuid)) - return player; - } - return null; - } + @Nullable Player getOnlinePlayerByUuid(@NotNull UUID uuid); /** * Finds the closest player in the play state matching a given username. @@ -161,20 +70,7 @@ public Player getPlayer(@NotNull PlayerConnection connection) { * @param username the player username (can be partial) * @return the closest match, null if no players are online */ - public @Nullable Player findOnlinePlayer(@NotNull String username) { - Player exact = getOnlinePlayerByUsername(username); - if (exact != null) return exact; - final String username1 = username.toLowerCase(Locale.ROOT); - - Function distanceFunction = player -> { - final String username2 = player.getUsername().toLowerCase(Locale.ROOT); - return StringUtils.jaroWinklerScore(username1, username2); - }; - return getOnlinePlayers().stream() - .min(Comparator.comparingDouble(distanceFunction::apply)) - .filter(player -> distanceFunction.apply(player) > 0) - .orElse(null); - } + @Nullable Player findOnlinePlayer(@NotNull String username); /** * Changes how {@link UUID} are attributed to players. @@ -187,9 +83,7 @@ public Player getPlayer(@NotNull PlayerConnection connection) { * setting it to null would apply a random UUID for each player connection * @see #getPlayerConnectionUuid(PlayerConnection, String) */ - public void setUuidProvider(@Nullable UuidProvider uuidProvider) { - this.uuidProvider = uuidProvider != null ? uuidProvider : (playerConnection, username) -> UUID.randomUUID(); - } + void setUuidProvider(@Nullable UuidProvider uuidProvider); /** * Computes the UUID of the specified connection. @@ -201,116 +95,32 @@ public void setUuidProvider(@Nullable UuidProvider uuidProvider) { * @return the uuid based on {@code playerConnection} * return a random UUID if no UUID provider is defined see {@link #setUuidProvider(UuidProvider)} */ - public @NotNull UUID getPlayerConnectionUuid(@NotNull PlayerConnection playerConnection, @NotNull String username) { - return uuidProvider.provide(playerConnection, username); - } + @NotNull UUID getPlayerConnectionUuid(@NotNull PlayerConnection playerConnection, @NotNull String username); /** * Changes the {@link Player} provider, to change which object to link to him. * * @param playerProvider the new {@link PlayerProvider}, can be set to null to apply the default provider */ - public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { - this.playerProvider = playerProvider != null ? playerProvider : defaultPlayerProvider; - } + void setPlayerProvider(@Nullable PlayerProvider playerProvider); /** * Creates a player object and begins the transition from the login state to the config state. */ @ApiStatus.Internal - public @NotNull Player createPlayer(@NotNull PlayerConnection connection, @NotNull UUID uuid, @NotNull String username) { - final Player player = playerProvider.createPlayer(uuid, username, connection); - this.connectionPlayerMap.put(connection, player); - var future = transitionLoginToConfig(player); - if (DebugUtils.INSIDE_TEST) future.join(); - return player; - } + @NotNull Player createPlayer(@NotNull PlayerConnection connection, @NotNull UUID uuid, @NotNull String username); @ApiStatus.Internal - public @NotNull CompletableFuture transitionLoginToConfig(@NotNull Player player) { - return AsyncUtils.runAsync(serverProcess, () -> { - final PlayerConnection playerConnection = player.getPlayerConnection(); - - // Compression - if (playerConnection instanceof PlayerSocketConnection socketConnection) { - final int threshold = serverProcess.getServerSetting().getCompressionThreshold(); - if (threshold > 0) socketConnection.startCompression(); - } - - // Call pre login event - AsyncPlayerPreLoginEvent asyncPlayerPreLoginEvent = new AsyncPlayerPreLoginEvent(player); - serverProcess.getGlobalEventHandler().call(asyncPlayerPreLoginEvent); - if (!player.isOnline()) - return; // Player has been kicked - - // Change UUID/Username based on the event - { - final String eventUsername = asyncPlayerPreLoginEvent.getUsername(); - final UUID eventUuid = asyncPlayerPreLoginEvent.getPlayerUuid(); - if (!player.getUsername().equals(eventUsername)) { - player.setUsernameField(eventUsername); - } - if (!player.getUuid().equals(eventUuid)) { - player.setUuid(eventUuid); - } - } - - // Send login success packet (and switch to configuration phase) - LoginSuccessPacket loginSuccessPacket = new LoginSuccessPacket(player.getUuid(), player.getUsername(), 0); - playerConnection.sendPacket(loginSuccessPacket); - }); - } + @NotNull CompletableFuture transitionLoginToConfig(@NotNull Player player); @ApiStatus.Internal - public void transitionPlayToConfig(@NotNull Player player) { - player.sendPacket(new StartConfigurationPacket()); - configurationPlayers.add(player); - } + void transitionPlayToConfig(@NotNull Player player); @ApiStatus.Internal - public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { - if (isFirstConfig) { - configurationPlayers.add(player); - keepAlivePlayers.add(player); - } - - player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); - CompletableFuture configFuture = AsyncUtils.runAsync(serverProcess, () -> { - player.sendPacket(PluginMessagePacket.getBrandPacket(serverProcess.getServerSetting())); - - var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); - serverProcess.getGlobalEventHandler().call(event); - - final Instance spawningInstance = event.getSpawningInstance(); - Check.notNull(spawningInstance, "You need to specify a spawning instance in the AsyncPlayerConfigurationEvent"); - - // Registry data (if it should be sent) - if (event.willSendRegistryData()) { - var registry = new HashMap(); - registry.put("minecraft:chat_type", Messenger.chatRegistry()); - registry.put("minecraft:dimension_type", serverProcess.getDimensionTypeManager().toNBT()); - registry.put("minecraft:worldgen/biome", serverProcess.getBiomeManager().toNBT()); - registry.put("minecraft:damage_type", DamageType.getNBT()); - player.sendPacket(new RegistryDataPacket(NBT.Compound(registry))); - - player.sendPacket(defaultTags); - } - - // Wait for pending resource packs if any - var packFuture = player.getResourcePackFuture(); - if (packFuture != null) packFuture.join(); - - keepAlivePlayers.remove(player); - player.setPendingOptions(spawningInstance, event.isHardcore()); - player.sendPacket(new FinishConfigurationPacket()); - }); - if (DebugUtils.INSIDE_TEST) configFuture.join(); - } + void doConfiguration(@NotNull Player player, boolean isFirstConfig); @ApiStatus.Internal - public void transitionConfigToPlay(@NotNull Player player) { - this.waitingPlayers.relaxedOffer(player); - } + void transitionConfigToPlay(@NotNull Player player); /** * Removes a {@link Player} from the players list. @@ -321,68 +131,12 @@ public void transitionConfigToPlay(@NotNull Player player) { * @see PlayerConnection#disconnect() to properly disconnect a player */ @ApiStatus.Internal - public synchronized void removePlayer(@NotNull PlayerConnection connection) { - final Player player = this.connectionPlayerMap.remove(connection); - if (player == null) return; - this.configurationPlayers.remove(player); - this.playPlayers.remove(player); - this.keepAlivePlayers.remove(player); - } - - /** - * Shutdowns the connection manager by kicking all the currently connected players. - */ - public synchronized void shutdown() { - this.configurationPlayers.clear(); - this.playPlayers.clear(); - this.keepAlivePlayers.clear(); - this.connectionPlayerMap.clear(); - } - - public void tick(long tickStart) { - // Let waiting players into their instances - updateWaitingPlayers(); + void removePlayer(@NotNull PlayerConnection connection); - // Send keep alive packets - handleKeepAlive(keepAlivePlayers, tickStart); + void shutdown(); - // Interpret packets for configuration players - configurationPlayers.forEach(Player::interpretPacketQueue); - } + void tick(long tickStart); - /** - * Connects waiting players. - */ @ApiStatus.Internal - public void updateWaitingPlayers() { - this.waitingPlayers.drain(player -> { - player.getPlayerConnection().setConnectionState(ConnectionState.PLAY); - playPlayers.add(player); - keepAlivePlayers.add(player); - - // Spawn the player at Player#getRespawnPoint - CompletableFuture spawnFuture = player.UNSAFE_init(); - - // Required to get the exact moment the player spawns - if (DebugUtils.INSIDE_TEST) spawnFuture.join(); - }); - } - - /** - * Updates keep alive by checking the last keep alive packet and send a new one if needed. - * - * @param tickStart the time of the update in milliseconds, forwarded to the packet - */ - private void handleKeepAlive(@NotNull Collection playerGroup, long tickStart) { - final KeepAlivePacket keepAlivePacket = new KeepAlivePacket(tickStart); - for (Player player : playerGroup) { - final long lastKeepAlive = tickStart - player.getLastKeepAlive(); - if (lastKeepAlive > KEEP_ALIVE_DELAY && player.didAnswerKeepAlive()) { - player.refreshKeepAlive(tickStart); - player.sendPacket(keepAlivePacket); - } else if (lastKeepAlive >= KEEP_ALIVE_KICK) { - player.kick(TIMEOUT_TEXT); - } - } - } + void updateWaitingPlayers(); } diff --git a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java new file mode 100644 index 00000000000..c8ce9251ab2 --- /dev/null +++ b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java @@ -0,0 +1,360 @@ +package net.minestom.server.network; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.minestom.server.ServerSettings; +import net.minestom.server.adventure.bossbar.BossBarManager; +import net.minestom.server.command.CommandManager; +import net.minestom.server.entity.Player; +import net.minestom.server.entity.damage.DamageType; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; +import net.minestom.server.event.player.AsyncPlayerPreLoginEvent; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.gamedata.tags.TagManager; +import net.minestom.server.instance.Chunk; +import net.minestom.server.instance.Instance; +import net.minestom.server.instance.block.BlockManager; +import net.minestom.server.listener.manager.PacketListenerManager; +import net.minestom.server.message.Messenger; +import net.minestom.server.network.packet.server.CachedPacket; +import net.minestom.server.network.packet.server.common.KeepAlivePacket; +import net.minestom.server.network.packet.server.common.PluginMessagePacket; +import net.minestom.server.network.packet.server.common.TagsPacket; +import net.minestom.server.network.packet.server.configuration.FinishConfigurationPacket; +import net.minestom.server.network.packet.server.configuration.RegistryDataPacket; +import net.minestom.server.network.packet.server.login.LoginSuccessPacket; +import net.minestom.server.network.packet.server.play.StartConfigurationPacket; +import net.minestom.server.network.player.PlayerConnection; +import net.minestom.server.network.player.PlayerSocketConnection; +import net.minestom.server.recipe.RecipeManager; +import net.minestom.server.scoreboard.TeamManager; +import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.utils.StringUtils; +import net.minestom.server.utils.async.AsyncUtils; +import net.minestom.server.utils.debug.DebugUtils; +import net.minestom.server.utils.validate.Check; +import net.minestom.server.world.DimensionTypeManager; +import net.minestom.server.world.biomes.BiomeManager; +import org.jctools.queues.MessagePassingQueue; +import org.jctools.queues.MpscUnboundedArrayQueue; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jglrxavpok.hephaistos.nbt.NBT; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.function.Function; + +public final class ConnectionManagerImpl implements ConnectionManager { + private static final Logger logger = LoggerFactory.getLogger(ConnectionManagerImpl.class); + + public final CachedPacket defaultTags; + + private static final long KEEP_ALIVE_DELAY = 10_000; + private static final long KEEP_ALIVE_KICK = 30_000; + private static final Component TIMEOUT_TEXT = Component.text("Timeout", NamedTextColor.RED); + + + // All players once their Player object has been instantiated. + private final Map connectionPlayerMap = new ConcurrentHashMap<>(); + // Players waiting to be spawned (post configuration state) + private final MessagePassingQueue waitingPlayers = new MpscUnboundedArrayQueue<>(64); + // Players in configuration state + private final Set configurationPlayers = new CopyOnWriteArraySet<>(); + // Players in play state + private final Set playPlayers = new CopyOnWriteArraySet<>(); + + // The players who need keep alive ticks. This was added because we may not send a keep alive in + // the time after sending finish configuration but before receiving configuration end (to swap to play). + // I(mattw) could not come up with a better way to express this besides completely splitting client/server + // states. Perhaps there will be an improvement in the future. + private final Set keepAlivePlayers = new CopyOnWriteArraySet<>(); + + private final Set unmodifiableConfigurationPlayers = Collections.unmodifiableSet(configurationPlayers); + private final Set unmodifiablePlayPlayers = Collections.unmodifiableSet(playPlayers); + private final ExceptionHandler exceptionHandler; + private final ServerSettings serverSettings; + private final BiomeManager biomeManager; + private final DimensionTypeManager dimensionTypeManager; + private final EventNode globalEventHandler; + + + // The uuid provider once a player login + private volatile UuidProvider uuidProvider = (playerConnection, username) -> UUID.randomUUID(); + // The player provider to have your own Player implementation + private final PlayerProvider defaultPlayerProvider; + private volatile PlayerProvider playerProvider; + + public ConnectionManagerImpl( + ServerSettings serverSettings, + EventNode globalEventHandler, + ThreadDispatcher dispatcher, + ExceptionHandler exceptionHandler, + TeamManager teamManager, + RecipeManager recipeManager, + CommandManager commandManager, + BossBarManager bossBarManager, + SchedulerManager schedulerManager, + PacketListenerManager packetListenerManager, + BiomeManager biomeManager, + DimensionTypeManager dimensionTypeManager, + TagManager tagManager, + BlockManager blockManager + ) { + this.exceptionHandler = exceptionHandler; + this.serverSettings = serverSettings; + this.biomeManager = biomeManager; + this.dimensionTypeManager = dimensionTypeManager; + this.globalEventHandler = globalEventHandler; + this.defaultTags = new CachedPacket(serverSettings, new TagsPacket(tagManager.getTagMap())); + defaultPlayerProvider = (uuid, username, connection) -> new Player(serverSettings, globalEventHandler, dispatcher, exceptionHandler, this, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, connection); + playerProvider = defaultPlayerProvider; + } + + @Override + public int getOnlinePlayerCount() { + return playPlayers.size(); + } + + @Override + public @NotNull Collection<@NotNull Player> getOnlinePlayers() { + return unmodifiablePlayPlayers; + } + + @Override + public @NotNull Collection<@NotNull Player> getConfigPlayers() { + return unmodifiableConfigurationPlayers; + } + + @Override + public Player getPlayer(@NotNull PlayerConnection connection) { + return connectionPlayerMap.get(connection); + } + + @Override + public @Nullable Player getOnlinePlayerByUsername(@NotNull String username) { + for (Player player : getOnlinePlayers()) { + if (player.getUsername().equalsIgnoreCase(username)) + return player; + } + return null; + } + + @Override + public @Nullable Player getOnlinePlayerByUuid(@NotNull UUID uuid) { + for (Player player : getOnlinePlayers()) { + if (player.getUuid().equals(uuid)) + return player; + } + return null; + } + + @Override + public @Nullable Player findOnlinePlayer(@NotNull String username) { + Player exact = getOnlinePlayerByUsername(username); + if (exact != null) return exact; + final String username1 = username.toLowerCase(Locale.ROOT); + + Function distanceFunction = player -> { + final String username2 = player.getUsername().toLowerCase(Locale.ROOT); + return StringUtils.jaroWinklerScore(username1, username2); + }; + return getOnlinePlayers().stream() + .min(Comparator.comparingDouble(distanceFunction::apply)) + .filter(player -> distanceFunction.apply(player) > 0) + .orElse(null); + } + + @Override + public void setUuidProvider(@Nullable UuidProvider uuidProvider) { + this.uuidProvider = uuidProvider != null ? uuidProvider : (playerConnection, username) -> UUID.randomUUID(); + } + + @Override + public @NotNull UUID getPlayerConnectionUuid(@NotNull PlayerConnection playerConnection, @NotNull String username) { + return uuidProvider.provide(playerConnection, username); + } + + @Override + public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { + this.playerProvider = playerProvider != null ? playerProvider : defaultPlayerProvider; + } + + @Override + @ApiStatus.Internal + public @NotNull Player createPlayer(@NotNull PlayerConnection connection, @NotNull UUID uuid, @NotNull String username) { + final Player player = playerProvider.createPlayer(uuid, username, connection); + this.connectionPlayerMap.put(connection, player); + var future = transitionLoginToConfig(player); + if (DebugUtils.INSIDE_TEST) future.join(); + return player; + } + + @Override + @ApiStatus.Internal + public @NotNull CompletableFuture transitionLoginToConfig(@NotNull Player player) { + return AsyncUtils.runAsync(exceptionHandler, () -> { + final PlayerConnection playerConnection = player.getPlayerConnection(); + + // Compression + if (playerConnection instanceof PlayerSocketConnection socketConnection) { + final int threshold = serverSettings.getCompressionThreshold(); + if (threshold > 0) socketConnection.startCompression(); + } + + // Call pre login event + AsyncPlayerPreLoginEvent asyncPlayerPreLoginEvent = new AsyncPlayerPreLoginEvent(player); + globalEventHandler.call(asyncPlayerPreLoginEvent); + if (!player.isOnline()) + return; // Player has been kicked + + // Change UUID/Username based on the event + { + final String eventUsername = asyncPlayerPreLoginEvent.getUsername(); + final UUID eventUuid = asyncPlayerPreLoginEvent.getPlayerUuid(); + if (!player.getUsername().equals(eventUsername)) { + player.setUsernameField(eventUsername); + } + if (!player.getUuid().equals(eventUuid)) { + player.setUuid(eventUuid); + } + } + + // Send login success packet (and switch to configuration phase) + LoginSuccessPacket loginSuccessPacket = new LoginSuccessPacket(player.getUuid(), player.getUsername(), 0); + playerConnection.sendPacket(loginSuccessPacket); + }); + } + + @Override + @ApiStatus.Internal + public void transitionPlayToConfig(@NotNull Player player) { + player.sendPacket(new StartConfigurationPacket()); + configurationPlayers.add(player); + } + + @Override + @ApiStatus.Internal + public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { + if (isFirstConfig) { + configurationPlayers.add(player); + keepAlivePlayers.add(player); + } + + player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); + CompletableFuture configFuture = AsyncUtils.runAsync(exceptionHandler, () -> { + player.sendPacket(PluginMessagePacket.getBrandPacket(serverSettings)); + + var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); + globalEventHandler.call(event); + + final Instance spawningInstance = event.getSpawningInstance(); + Check.notNull(spawningInstance, "You need to specify a spawning instance in the AsyncPlayerConfigurationEvent"); + + // Registry data (if it should be sent) + if (event.willSendRegistryData()) { + var registry = new HashMap(); + registry.put("minecraft:chat_type", Messenger.chatRegistry()); + registry.put("minecraft:dimension_type", dimensionTypeManager.toNBT()); + registry.put("minecraft:worldgen/biome", biomeManager.toNBT()); + registry.put("minecraft:damage_type", DamageType.getNBT()); + player.sendPacket(new RegistryDataPacket(NBT.Compound(registry))); + + player.sendPacket(defaultTags); + } + + // Wait for pending resource packs if any + var packFuture = player.getResourcePackFuture(); + if (packFuture != null) packFuture.join(); + + keepAlivePlayers.remove(player); + player.setPendingOptions(spawningInstance, event.isHardcore()); + player.sendPacket(new FinishConfigurationPacket()); + }); + if (DebugUtils.INSIDE_TEST) configFuture.join(); + } + + @Override + @ApiStatus.Internal + public void transitionConfigToPlay(@NotNull Player player) { + this.waitingPlayers.relaxedOffer(player); + } + + @Override + @ApiStatus.Internal + public synchronized void removePlayer(@NotNull PlayerConnection connection) { + final Player player = this.connectionPlayerMap.remove(connection); + if (player == null) return; + this.configurationPlayers.remove(player); + this.playPlayers.remove(player); + this.keepAlivePlayers.remove(player); + } + + /** + * Shutdowns the connection manager by kicking all the currently connected players. + */ + @Override + public synchronized void shutdown() { + this.configurationPlayers.clear(); + this.playPlayers.clear(); + this.keepAlivePlayers.clear(); + this.connectionPlayerMap.clear(); + } + + @Override + public void tick(long tickStart) { + // Let waiting players into their instances + updateWaitingPlayers(); + + // Send keep alive packets + handleKeepAlive(keepAlivePlayers, tickStart); + + // Interpret packets for configuration players + configurationPlayers.forEach(Player::interpretPacketQueue); + } + + /** + * Connects waiting players. + */ + @Override + @ApiStatus.Internal + public void updateWaitingPlayers() { + this.waitingPlayers.drain(player -> { + player.getPlayerConnection().setConnectionState(ConnectionState.PLAY); + playPlayers.add(player); + keepAlivePlayers.add(player); + + // Spawn the player at Player#getRespawnPoint + CompletableFuture spawnFuture = player.UNSAFE_init(); + + // Required to get the exact moment the player spawns + if (DebugUtils.INSIDE_TEST) spawnFuture.join(); + }); + } + + /** + * Updates keep alive by checking the last keep alive packet and send a new one if needed. + * + * @param tickStart the time of the update in milliseconds, forwarded to the packet + */ + private void handleKeepAlive(@NotNull Collection playerGroup, long tickStart) { + final KeepAlivePacket keepAlivePacket = new KeepAlivePacket(tickStart); + for (Player player : playerGroup) { + final long lastKeepAlive = tickStart - player.getLastKeepAlive(); + if (lastKeepAlive > KEEP_ALIVE_DELAY && player.didAnswerKeepAlive()) { + player.refreshKeepAlive(tickStart); + player.sendPacket(keepAlivePacket); + } else if (lastKeepAlive >= KEEP_ALIVE_KICK) { + player.kick(TIMEOUT_TEXT); + } + } + } +} diff --git a/src/main/java/net/minestom/server/network/ConnectionManagerProvider.java b/src/main/java/net/minestom/server/network/ConnectionManagerProvider.java new file mode 100644 index 00000000000..7fb64427431 --- /dev/null +++ b/src/main/java/net/minestom/server/network/ConnectionManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.network; + +public interface ConnectionManagerProvider { + ConnectionManager getConnectionManager(); +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/network/PacketProcessor.java b/src/main/java/net/minestom/server/network/PacketProcessor.java index fd8e82f7490..ceac8712294 100644 --- a/src/main/java/net/minestom/server/network/PacketProcessor.java +++ b/src/main/java/net/minestom/server/network/PacketProcessor.java @@ -1,10 +1,7 @@ package net.minestom.server.network; -import net.minestom.server.entity.Player; -import net.minestom.server.listener.manager.PacketListenerManager; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacketsHandler; -import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; import net.minestom.server.network.player.PlayerConnection; import org.jetbrains.annotations.NotNull; @@ -16,52 +13,8 @@ * You can retrieve the different packet handlers per state (status/login/play) * from the {@link ClientPacketsHandler} classes. */ -public class PacketProcessor { - private final ClientPacketsHandler statusHandler; - private final ClientPacketsHandler loginHandler; - private final ClientPacketsHandler configurationHandler; - private final ClientPacketsHandler playHandler; +public interface PacketProcessor { + @NotNull ClientPacket create(@NotNull ConnectionState connectionState, int packetId, ByteBuffer body); - private final PacketListenerManager packetListenerManager; - - public PacketProcessor(@NotNull PacketListenerManager packetListenerManager) { - statusHandler = new ClientPacketsHandler.Status(); - loginHandler = new ClientPacketsHandler.Login(); - configurationHandler = new ClientPacketsHandler.Configuration(); - playHandler = new ClientPacketsHandler.Play(); - - this.packetListenerManager = packetListenerManager; - } - - public @NotNull ClientPacket create(@NotNull ConnectionState connectionState, int packetId, ByteBuffer body) { - NetworkBuffer buffer = new NetworkBuffer(body); - final ClientPacket clientPacket = switch (connectionState) { - case HANDSHAKE -> { - assert packetId == 0; - yield new ClientHandshakePacket(buffer); - } - case STATUS -> statusHandler.create(packetId, buffer); - case LOGIN -> loginHandler.create(packetId, buffer); - case CONFIGURATION -> configurationHandler.create(packetId, buffer); - case PLAY -> playHandler.create(packetId, buffer); - }; - body.position(buffer.readIndex()); - return clientPacket; - } - - public ClientPacket process(@NotNull PlayerConnection connection, int packetId, ByteBuffer body) { - final ClientPacket packet = create(connection.getConnectionState(), packetId, body); - - switch (connection.getConnectionState()) { - // Process all pre-config packets immediately - case HANDSHAKE, STATUS, LOGIN -> packetListenerManager.processClientPacket(packet, connection); - // Process config and play packets on the next tick - case CONFIGURATION, PLAY -> { - final Player player = connection.getPlayer(); - assert player != null; - player.addPacketToQueue(packet); - } - } - return packet; - } + ClientPacket process(@NotNull PlayerConnection connection, int packetId, ByteBuffer body); } diff --git a/src/main/java/net/minestom/server/network/PacketProcessorImpl.java b/src/main/java/net/minestom/server/network/PacketProcessorImpl.java new file mode 100644 index 00000000000..2404c332317 --- /dev/null +++ b/src/main/java/net/minestom/server/network/PacketProcessorImpl.java @@ -0,0 +1,64 @@ +package net.minestom.server.network; + +import net.minestom.server.entity.Player; +import net.minestom.server.listener.manager.PacketListenerManager; +import net.minestom.server.network.packet.client.ClientPacket; +import net.minestom.server.network.packet.client.ClientPacketsHandler; +import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; +import net.minestom.server.network.player.PlayerConnection; +import org.jetbrains.annotations.NotNull; + +import java.nio.ByteBuffer; + + +public class PacketProcessorImpl implements PacketProcessor { + private final ClientPacketsHandler statusHandler; + private final ClientPacketsHandler loginHandler; + private final ClientPacketsHandler configurationHandler; + private final ClientPacketsHandler playHandler; + + private final PacketListenerManager packetListenerManager; + + public PacketProcessorImpl(@NotNull PacketListenerManager packetListenerManager) { + statusHandler = new ClientPacketsHandler.Status(); + loginHandler = new ClientPacketsHandler.Login(); + configurationHandler = new ClientPacketsHandler.Configuration(); + playHandler = new ClientPacketsHandler.Play(); + + this.packetListenerManager = packetListenerManager; + } + + @Override + public @NotNull ClientPacket create(@NotNull ConnectionState connectionState, int packetId, ByteBuffer body) { + NetworkBuffer buffer = new NetworkBuffer(body); + final ClientPacket clientPacket = switch (connectionState) { + case HANDSHAKE -> { + assert packetId == 0; + yield new ClientHandshakePacket(buffer); + } + case STATUS -> statusHandler.create(packetId, buffer); + case LOGIN -> loginHandler.create(packetId, buffer); + case CONFIGURATION -> configurationHandler.create(packetId, buffer); + case PLAY -> playHandler.create(packetId, buffer); + }; + body.position(buffer.readIndex()); + return clientPacket; + } + + @Override + public ClientPacket process(@NotNull PlayerConnection connection, int packetId, ByteBuffer body) { + final ClientPacket packet = create(connection.getConnectionState(), packetId, body); + + switch (connection.getConnectionState()) { + // Process all pre-config packets immediately + case HANDSHAKE, STATUS, LOGIN -> packetListenerManager.processClientPacket(packet, connection); + // Process config and play packets on the next tick + case CONFIGURATION, PLAY -> { + final Player player = connection.getPlayer(); + assert player != null; + player.addPacketToQueue(packet); + } + } + return packet; + } +} diff --git a/src/main/java/net/minestom/server/network/PacketProcessorProvider.java b/src/main/java/net/minestom/server/network/PacketProcessorProvider.java new file mode 100644 index 00000000000..9705b67f1d2 --- /dev/null +++ b/src/main/java/net/minestom/server/network/PacketProcessorProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.network; + +public interface PacketProcessorProvider { + PacketProcessor getPacketProcessor(); +} diff --git a/src/main/java/net/minestom/server/network/PlayerProvider.java b/src/main/java/net/minestom/server/network/PlayerProvider.java index e967daacb2c..9fd394d3f12 100644 --- a/src/main/java/net/minestom/server/network/PlayerProvider.java +++ b/src/main/java/net/minestom/server/network/PlayerProvider.java @@ -9,7 +9,7 @@ /** * Used when you want to provide your own player object instead of using the default one. *

        - * Sets with {@link ConnectionManager#setPlayerProvider(PlayerProvider)}. + * Sets with {@link ConnectionManagerImpl#setPlayerProvider(PlayerProvider)}. */ @FunctionalInterface public interface PlayerProvider { diff --git a/src/main/java/net/minestom/server/network/UuidProvider.java b/src/main/java/net/minestom/server/network/UuidProvider.java index 8f2da5f5762..6b02a4de6f3 100644 --- a/src/main/java/net/minestom/server/network/UuidProvider.java +++ b/src/main/java/net/minestom/server/network/UuidProvider.java @@ -7,7 +7,7 @@ /** * Used when you want to provide your own {@link UUID} object for players instead of using the default one. *

        - * Sets with {@link ConnectionManager#setUuidProvider(UuidProvider)}. + * Sets with {@link ConnectionManagerImpl#setUuidProvider(UuidProvider)}. */ @FunctionalInterface public interface UuidProvider { diff --git a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java index ea935f16761..66a1eb9a999 100644 --- a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java @@ -1,11 +1,12 @@ package net.minestom.server.network.player; -import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.entity.fakeplayer.FakePlayer; import net.minestom.server.entity.fakeplayer.FakePlayerController; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.server.SendablePacket; import net.minestom.server.network.packet.server.ServerPacket; +import net.minestom.server.network.socket.Server; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -14,8 +15,8 @@ public class FakePlayerConnection extends PlayerConnection { - public FakePlayerConnection(ServerProcess serverProcess) { - super(serverProcess); + public FakePlayerConnection(Server server, ConnectionManager connectionManager) { + super(server, connectionManager); } @Override diff --git a/src/main/java/net/minestom/server/network/player/PlayerConnection.java b/src/main/java/net/minestom/server/network/player/PlayerConnection.java index 1083a975781..ab11602dfe3 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerConnection.java @@ -1,13 +1,13 @@ package net.minestom.server.network.player; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerObject; -import net.minestom.server.ServerProcess; import net.minestom.server.crypto.PlayerPublicKey; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.server.SendablePacket; +import net.minestom.server.network.socket.Server; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -20,15 +20,17 @@ * A PlayerConnection is an object needed for all created {@link Player}. * It can be extended to create a new kind of player (NPC for instance). */ -public abstract class PlayerConnection implements ServerObject { - private final ServerProcess serverProcess; +public abstract class PlayerConnection { + private final Server server; + private final ConnectionManager connectionManager; private Player player; private volatile ConnectionState connectionState; private PlayerPublicKey playerPublicKey; volatile boolean online; - public PlayerConnection(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public PlayerConnection(Server server, ConnectionManager connectionManager) { + this.server = server; + this.connectionManager = connectionManager; this.online = true; this.connectionState = ConnectionState.HANDSHAKE; } @@ -87,7 +89,7 @@ public int getProtocolVersion() { * @return the server address used */ public @Nullable String getServerAddress() { - return serverProcess.getServer().getAddress(); + return server.getAddress(); } @@ -99,7 +101,7 @@ public int getProtocolVersion() { * @return the server port used */ public int getServerPort() { - return serverProcess.getServer().getPort(); + return server.getPort(); } /** @@ -107,7 +109,7 @@ public int getServerPort() { */ public void disconnect() { this.online = false; - serverProcess.getConnectionManager().removePlayer(this); + connectionManager.removePlayer(this); final Player player = getPlayer(); if (player != null && !player.isRemoved()) { player.scheduleNextTick(Entity::remove); @@ -171,9 +173,4 @@ public String toString() { ", identifier=" + getIdentifier() + '}'; } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java index 8313064a9e2..889fbf99f44 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java @@ -1,17 +1,22 @@ package net.minestom.server.network.player; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.entity.Player; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; import net.minestom.server.event.ListenerHandle; import net.minestom.server.event.player.PlayerPacketOutEvent; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.extras.mojangAuth.MojangCrypt; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.PacketProcessor; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; import net.minestom.server.network.packet.server.*; import net.minestom.server.network.packet.server.login.SetCompressionPacket; +import net.minestom.server.network.socket.Server; import net.minestom.server.network.socket.Worker; import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.PacketUtils; @@ -47,6 +52,8 @@ public class PlayerSocketConnection extends PlayerConnection { private final static Logger LOGGER = LoggerFactory.getLogger(PlayerSocketConnection.class); private static final ObjectPool POOL = ObjectPool.BUFFER_POOL; + private final ExceptionHandler exceptionHandler; + private final ServerSettings serverSettings; private final Worker worker; private final MessagePassingQueue workerQueue; private final SocketChannel channel; @@ -75,13 +82,15 @@ public class PlayerSocketConnection extends PlayerConnection { private final ListenerHandle outgoing; - public PlayerSocketConnection(@NotNull ServerProcess serverProcess, @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { - super(serverProcess); + public PlayerSocketConnection(Server server, ConnectionManager connectionManager, EventNode globalEventHandler, ExceptionHandler exceptionHandler, ServerSettings serverSettings, @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { + super(server, connectionManager); + this.exceptionHandler = exceptionHandler; + this.serverSettings = serverSettings; this.worker = worker; this.workerQueue = worker.queue(); this.channel = channel; this.remoteAddress = remoteAddress; - this.outgoing = serverProcess.getGlobalEventHandler().getHandle(PlayerPacketOutEvent.class); + this.outgoing = globalEventHandler.getHandle(PlayerPacketOutEvent.class); } public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProcessor) { @@ -93,7 +102,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces try { encryptionContext.decrypt().update(input, input.duplicate()); } catch (ShortBufferException e) { - getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); return; } } @@ -109,7 +118,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces packet = packetProcessor.process(this, id, payload); } catch (Exception e) { // Error while reading the packet - getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } finally { if (payload.position() != payload.limit()) { LOGGER.warn("WARNING: Packet ({}) 0x{} not fully read ({}) {}", getConnectionState(), Integer.toHexString(id), payload, packet); @@ -117,7 +126,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces } }); } catch (DataFormatException e) { - getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); disconnect(); } } @@ -138,8 +147,7 @@ public void consumeCache(BinaryBuffer buffer) { */ public void setEncryptionKey(@NotNull SecretKey secretKey) { Check.stateCondition(encryptionContext != null, "Encryption is already enabled!"); - MojangCrypt mojangCrypt = getServerProcess().getMojangAuth().getMojangCrypt(); - this.encryptionContext = new EncryptionContext(mojangCrypt.getCipher(1, secretKey), mojangCrypt.getCipher(2, secretKey)); + this.encryptionContext = new EncryptionContext(MojangCrypt.getCipher(1, secretKey), MojangCrypt.getCipher(2, secretKey)); } /** @@ -149,7 +157,7 @@ public void setEncryptionKey(@NotNull SecretKey secretKey) { */ public void startCompression() { Check.stateCondition(compressed, "Compression is already enabled!"); - final int threshold = getServerProcess().getServerSetting().getCompressionThreshold(); + final int threshold = serverSettings.getCompressionThreshold(); Check.stateCondition(threshold == 0, "Compression cannot be enabled because the threshold is equal to 0"); sendPacket(new SetCompressionPacket(threshold)); this.compressed = true; @@ -370,7 +378,7 @@ private void writeServerPacketSync(ServerPacket serverPacket, boolean compressed } } try (var hold = ObjectPool.PACKET_POOL.hold()) { - var buffer = PacketUtils.createFramedPacket(getServerProcess().getServerSetting(), getConnectionState(), hold.get(), serverPacket, compressed); + var buffer = PacketUtils.createFramedPacket(serverSettings, getConnectionState(), hold.get(), serverPacket, compressed); writeBufferSync(buffer, 0, buffer.limit()); } } @@ -385,7 +393,7 @@ private void writeBufferSync(@NotNull ByteBuffer buffer, int index, int length) length = encryptionContext.encrypt().update(buffer.slice(index, length), output); writeBufferSync0(output, 0, length); } catch (ShortBufferException e) { - getServerProcess().getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } return; } diff --git a/src/main/java/net/minestom/server/network/socket/Server.java b/src/main/java/net/minestom/server/network/socket/Server.java index 99e92a0b7c7..5da979361eb 100644 --- a/src/main/java/net/minestom/server/network/socket/Server.java +++ b/src/main/java/net/minestom/server/network/socket/Server.java @@ -1,150 +1,33 @@ package net.minestom.server.network.socket; -import net.minestom.server.ServerProcess; import net.minestom.server.network.PacketProcessor; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.io.IOException; -import java.net.*; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; +import java.net.SocketAddress; -public final class Server { - public static final int WORKER_COUNT = Integer.getInteger("minestom.workers", Runtime.getRuntime().availableProcessors()); - public static final int MAX_PACKET_SIZE = Integer.getInteger("minestom.max-packet-size", 2_097_151); // 3 bytes var-int - public static final int SOCKET_SEND_BUFFER_SIZE = Integer.getInteger("minestom.send-buffer-size", 262_143); - public static final int SOCKET_RECEIVE_BUFFER_SIZE = Integer.getInteger("minestom.receive-buffer-size", 32_767); - - public static final boolean NO_DELAY = true; - - private volatile boolean stop; - - private final Selector selector; - private final ServerProcess serverProcess; - private final PacketProcessor packetProcessor; - private final List workers; - private int index; - - private ServerSocketChannel serverSocket; - private SocketAddress socketAddress; - private String address; - private int port; - - public Server(ServerProcess serverProcess, PacketProcessor packetProcessor) { - this.serverProcess = serverProcess; - this.packetProcessor = packetProcessor; - Worker[] workers = new Worker[WORKER_COUNT]; - Arrays.setAll(workers, value -> new Worker(serverProcess,this)); - this.workers = List.of(workers); - try { - this.selector = Selector.open(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } +public interface Server { + int MAX_PACKET_SIZE = Integer.getInteger("minestom.max-packet-size", 2_097_151); // 3 bytes var-int @ApiStatus.Internal - public void init(SocketAddress address) throws IOException { - ProtocolFamily family; - if (address instanceof InetSocketAddress inetSocketAddress) { - this.address = inetSocketAddress.getHostString(); - this.port = inetSocketAddress.getPort(); - family = inetSocketAddress.getAddress().getAddress().length == 4 ? StandardProtocolFamily.INET : StandardProtocolFamily.INET6; - } else if (address instanceof UnixDomainSocketAddress unixDomainSocketAddress) { - this.address = "unix://" + unixDomainSocketAddress.getPath(); - this.port = 0; - family = StandardProtocolFamily.UNIX; - } else { - throw new IllegalArgumentException("Address must be an InetSocketAddress or a UnixDomainSocketAddress"); - } - - ServerSocketChannel server = ServerSocketChannel.open(family); - server.bind(address); - server.configureBlocking(false); - server.register(selector, SelectionKey.OP_ACCEPT); - this.serverSocket = server; - this.socketAddress = address; - - if (address instanceof InetSocketAddress && port == 0) { - port = server.socket().getLocalPort(); - } - } + void init(SocketAddress address) throws IOException; @ApiStatus.Internal - public void start() { - this.workers.forEach(Thread::start); - new Thread(() -> { - while (!stop) { - // Busy wait for connections - try { - this.selector.select(key -> { - if (!key.isAcceptable()) return; - try { - // Register socket and forward to thread - Worker worker = findWorker(); - final SocketChannel client = serverSocket.accept(); - worker.receiveConnection(client); - } catch (IOException e) { - e.printStackTrace(); - } - }); - } catch (IOException e) { - serverProcess.getExceptionHandler().handleException(e); - } - } - }, "Ms-entrypoint").start(); - } + void start(); - public void tick() { - this.workers.forEach(Worker::tick); - } + void tick(); - public boolean isOpen() { - return !stop; - } + boolean isOpen(); - public void stop() { - this.stop = true; - try { - if(serverSocket != null) { - this.serverSocket.close(); - } - - if (socketAddress instanceof UnixDomainSocketAddress unixDomainSocketAddress) { - Files.deleteIfExists(unixDomainSocketAddress.getPath()); - } - } catch (IOException e) { - serverProcess.getExceptionHandler().handleException(e); - } - this.selector.wakeup(); - this.workers.forEach(worker -> worker.selector.wakeup()); - } + void stop(); @ApiStatus.Internal - public @NotNull PacketProcessor packetProcessor() { - return packetProcessor; - } - - public SocketAddress socketAddress() { - return socketAddress; - } + @NotNull PacketProcessor packetProcessor(); - public String getAddress() { - return address; - } + SocketAddress socketAddress(); - public int getPort() { - return port; - } + String getAddress(); - private Worker findWorker() { - this.index = ++index % WORKER_COUNT; - return workers.get(index); - } + int getPort(); } diff --git a/src/main/java/net/minestom/server/network/socket/ServerImpl.java b/src/main/java/net/minestom/server/network/socket/ServerImpl.java new file mode 100644 index 00000000000..f5d1c0ce313 --- /dev/null +++ b/src/main/java/net/minestom/server/network/socket/ServerImpl.java @@ -0,0 +1,159 @@ +package net.minestom.server.network.socket; + +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.PacketProcessor; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.*; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +public final class ServerImpl implements Server { + + private volatile boolean stop; + + private final Selector selector; + private final ServerSettings serverSettings; + private final ExceptionHandler exceptionHandler; + private final PacketProcessor packetProcessor; + private final List workers; + private int index; + + private ServerSocketChannel serverSocket; + private SocketAddress socketAddress; + private String address; + private int port; + + public ServerImpl(ConnectionManager connectionManager, EventNode globalEventHandler, ExceptionHandler exceptionHandler, ServerSettings serverSettings, PacketProcessor packetProcessor) { + this.serverSettings = serverSettings; + this.exceptionHandler = exceptionHandler; + this.packetProcessor = packetProcessor; + Worker[] workers = new Worker[serverSettings.getWorkers()]; + Arrays.setAll(workers, value -> new Worker(this, connectionManager, globalEventHandler, exceptionHandler, serverSettings)); + this.workers = List.of(workers); + try { + this.selector = Selector.open(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + @ApiStatus.Internal + public void init(SocketAddress address) throws IOException { + ProtocolFamily family; + if (address instanceof InetSocketAddress inetSocketAddress) { + this.address = inetSocketAddress.getHostString(); + this.port = inetSocketAddress.getPort(); + family = inetSocketAddress.getAddress().getAddress().length == 4 ? StandardProtocolFamily.INET : StandardProtocolFamily.INET6; + } else if (address instanceof UnixDomainSocketAddress unixDomainSocketAddress) { + this.address = "unix://" + unixDomainSocketAddress.getPath(); + this.port = 0; + family = StandardProtocolFamily.UNIX; + } else { + throw new IllegalArgumentException("Address must be an InetSocketAddress or a UnixDomainSocketAddress"); + } + + ServerSocketChannel server = ServerSocketChannel.open(family); + server.bind(address); + server.configureBlocking(false); + server.register(selector, SelectionKey.OP_ACCEPT); + this.serverSocket = server; + this.socketAddress = address; + + if (address instanceof InetSocketAddress && port == 0) { + port = server.socket().getLocalPort(); + } + } + + @Override + @ApiStatus.Internal + public void start() { + this.workers.forEach(Thread::start); + new Thread(() -> { + while (!stop) { + // Busy wait for connections + try { + this.selector.select(key -> { + if (!key.isAcceptable()) return; + try { + // Register socket and forward to thread + Worker worker = findWorker(); + final SocketChannel client = serverSocket.accept(); + worker.receiveConnection(client); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } catch (IOException e) { + exceptionHandler.handleException(e); + } + } + }, "Ms-entrypoint").start(); + } + + @Override + public void tick() { + this.workers.forEach(Worker::tick); + } + + @Override + public boolean isOpen() { + return !stop; + } + + @Override + public void stop() { + this.stop = true; + try { + if(serverSocket != null) { + this.serverSocket.close(); + } + + if (socketAddress instanceof UnixDomainSocketAddress unixDomainSocketAddress) { + Files.deleteIfExists(unixDomainSocketAddress.getPath()); + } + } catch (IOException e) { + exceptionHandler.handleException(e); + } + this.selector.wakeup(); + this.workers.forEach(worker -> worker.selector.wakeup()); + } + + @Override + @ApiStatus.Internal + public @NotNull PacketProcessor packetProcessor() { + return packetProcessor; + } + + @Override + public SocketAddress socketAddress() { + return socketAddress; + } + + @Override + public String getAddress() { + return address; + } + + @Override + public int getPort() { + return port; + } + + private Worker findWorker() { + this.index = ++index % serverSettings.getWorkers(); + return workers.get(index); + } +} diff --git a/src/main/java/net/minestom/server/network/socket/ServerProvider.java b/src/main/java/net/minestom/server/network/socket/ServerProvider.java new file mode 100644 index 00000000000..7431a68517e --- /dev/null +++ b/src/main/java/net/minestom/server/network/socket/ServerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.network.socket; + +public interface ServerProvider { + Server getServer(); +} diff --git a/src/main/java/net/minestom/server/network/socket/Worker.java b/src/main/java/net/minestom/server/network/socket/Worker.java index b67d9c14548..8ec2c1f3b53 100644 --- a/src/main/java/net/minestom/server/network/socket/Worker.java +++ b/src/main/java/net/minestom/server/network/socket/Worker.java @@ -1,6 +1,10 @@ package net.minestom.server.network.socket; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.event.Event; +import net.minestom.server.event.EventNode; +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.thread.MinestomThread; import net.minestom.server.utils.ObjectPool; @@ -25,13 +29,20 @@ public final class Worker extends MinestomThread { final Selector selector; private final Map connectionMap = new ConcurrentHashMap<>(); - private final ServerProcess serverProcess; + + private final ConnectionManager connectionManager; + private final EventNode globalEventHandler; + private final ExceptionHandler exceptionHandler; + private final ServerSettings serverSettings; private final Server server; private final MpscUnboundedXaddArrayQueue queue = new MpscUnboundedXaddArrayQueue<>(1024); - Worker(ServerProcess serverProcess, Server server) { + Worker(Server server, ConnectionManager connectionManager, EventNode globalEventHandler, ExceptionHandler exceptionHandler, ServerSettings serverSettings) { super("Ms-worker-" + COUNTER.getAndIncrement()); - this.serverProcess = serverProcess; + this.connectionManager = connectionManager; + this.globalEventHandler = globalEventHandler; + this.exceptionHandler = exceptionHandler; + this.serverSettings = serverSettings; this.server = server; try { this.selector = Selector.open(); @@ -51,7 +62,7 @@ public void run() { try { this.queue.drain(Runnable::run); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } // Flush all connections if needed for (PlayerSocketConnection connection : connectionMap.values()) { @@ -88,12 +99,12 @@ public void run() { // TODO print exception? (should ignore disconnection) connection.disconnect(); } catch (Throwable t) { - serverProcess.getExceptionHandler().handleException(t); + exceptionHandler.handleException(t); connection.disconnect(); } }); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } } } @@ -113,14 +124,15 @@ public void disconnect(PlayerSocketConnection connection, SocketChannel channel) } void receiveConnection(SocketChannel channel) throws IOException { - this.connectionMap.put(channel, new PlayerSocketConnection(serverProcess, this, channel, channel.getRemoteAddress())); + this.connectionMap.put(channel, new PlayerSocketConnection(server, connectionManager, globalEventHandler, exceptionHandler, serverSettings, this, channel, channel.getRemoteAddress())); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); if (channel.getLocalAddress() instanceof InetSocketAddress) { Socket socket = channel.socket(); - socket.setSendBufferSize(Server.SOCKET_SEND_BUFFER_SIZE); - socket.setReceiveBufferSize(Server.SOCKET_RECEIVE_BUFFER_SIZE); - socket.setTcpNoDelay(Server.NO_DELAY); + + socket.setSendBufferSize(serverSettings.getSendBufferSize()); + socket.setReceiveBufferSize(serverSettings.getReceiveBufferSize()); + socket.setTcpNoDelay(serverSettings.isTcpNoDelay()); socket.setSoTimeout(30 * 1000); // 30 seconds } } diff --git a/src/main/java/net/minestom/server/ping/ResponseData.java b/src/main/java/net/minestom/server/ping/ResponseData.java index 188e7992927..b225ed404c7 100644 --- a/src/main/java/net/minestom/server/ping/ResponseData.java +++ b/src/main/java/net/minestom/server/ping/ResponseData.java @@ -1,13 +1,15 @@ package net.minestom.server.ping; import com.google.gson.JsonObject; +import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerProcess; import net.minestom.server.entity.Player; import net.minestom.server.event.server.ServerListPingEvent; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.socket.Server; import net.minestom.server.utils.identity.NamedAndIdentified; import org.jetbrains.annotations.NotNull; @@ -22,8 +24,8 @@ public class ResponseData { private static final Component DEFAULT_DESCRIPTION = Component.text("Minestom Server"); private final List entries; - @NotNull - private final ServerProcess serverProcess; + @Getter + private final Server server; private String version; private int protocol; @@ -36,12 +38,12 @@ public class ResponseData { /** * Constructs a new {@link ResponseData}. */ - public ResponseData(ServerProcess serverProcess) { - this.serverProcess = serverProcess; + public ResponseData(ConnectionManager connectionManager, Server server) { + this.server = server; this.entries = new ArrayList<>(); this.version = ServerConsts.VERSION_NAME; this.protocol = ServerConsts.PROTOCOL_VERSION; - this.online = serverProcess.getConnectionManager().getOnlinePlayerCount(); + this.online = connectionManager.getOnlinePlayerCount(); this.maxPlayer = this.online + 1; this.description = DEFAULT_DESCRIPTION; this.favicon = ""; @@ -317,10 +319,6 @@ public boolean arePlayersHidden() { return playersHidden; } - public ServerProcess getServerProcess() { - return serverProcess; - } - /** * Converts the response data into a {@link JsonObject}. * diff --git a/src/main/java/net/minestom/server/ping/ServerListPingType.java b/src/main/java/net/minestom/server/ping/ServerListPingType.java index 473a206936d..b0f07e83b48 100644 --- a/src/main/java/net/minestom/server/ping/ServerListPingType.java +++ b/src/main/java/net/minestom/server/ping/ServerListPingType.java @@ -74,7 +74,7 @@ public enum ServerListPingType { * @see OpenToLAN */ public static @NotNull String getOpenToLANPing(@NotNull ResponseData data) { - return String.format(LAN_PING_FORMAT, SECTION.serialize(data.getDescription()), data.getServerProcess().getServer().getPort()); + return String.format(LAN_PING_FORMAT, SECTION.serialize(data.getDescription()), data.getServer().getPort()); } /** diff --git a/src/main/java/net/minestom/server/potion/Potion.java b/src/main/java/net/minestom/server/potion/Potion.java index 6ad326aa0ad..d3d4a4bd633 100644 --- a/src/main/java/net/minestom/server/potion/Potion.java +++ b/src/main/java/net/minestom/server/potion/Potion.java @@ -114,7 +114,7 @@ public boolean hasIcon() { * @param entity the entity to add the effect to */ public void sendAddPacket(@NotNull Entity entity) { - entity.sendPacketToViewersAndSelf(new EntityEffectPacket(entity.getEntityId(), this, null)); + entity.sendPacketToViewersAndSelf(entity.getServerSettings(), new EntityEffectPacket(entity.getEntityId(), this, null)); } /** @@ -125,7 +125,7 @@ public void sendAddPacket(@NotNull Entity entity) { * @param entity the entity to remove the effect from */ public void sendRemovePacket(@NotNull Entity entity) { - entity.sendPacketToViewersAndSelf(new RemoveEntityEffectPacket(entity.getEntityId(), effect)); + entity.sendPacketToViewersAndSelf(entity.getServerSettings(), new RemoveEntityEffectPacket(entity.getEntityId(), effect)); } @Override diff --git a/src/main/java/net/minestom/server/recipe/RecipeManager.java b/src/main/java/net/minestom/server/recipe/RecipeManager.java index 3f6db289851..ac55db748c5 100644 --- a/src/main/java/net/minestom/server/recipe/RecipeManager.java +++ b/src/main/java/net/minestom/server/recipe/RecipeManager.java @@ -3,151 +3,16 @@ import net.minestom.server.network.packet.server.play.DeclareRecipesPacket; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -public class RecipeManager { - private DeclareRecipesPacket declareRecipesPacket = new DeclareRecipesPacket(List.of()); - private final Set recipes = new CopyOnWriteArraySet<>(); +public interface RecipeManager { + void addRecipes(@NotNull Recipe... recipe); - public void addRecipes(@NotNull Recipe... recipe) { - if (recipes.addAll(List.of(recipe))) { - refreshRecipesPacket(); - } - } + void addRecipe(@NotNull Recipe recipe); - public void addRecipe(@NotNull Recipe recipe) { - if (this.recipes.add(recipe)) { - refreshRecipesPacket(); - } - } + void removeRecipe(@NotNull Recipe recipe); - public void removeRecipe(@NotNull Recipe recipe) { - if (this.recipes.remove(recipe)) { - refreshRecipesPacket(); - } - } - - @NotNull - public Set getRecipes() { - return recipes; - } - - @NotNull - public DeclareRecipesPacket getDeclareRecipesPacket() { - return declareRecipesPacket; - } - - private void refreshRecipesPacket() { - List recipesCache = new ArrayList<>(); - for (Recipe recipe : recipes) { - switch (recipe.recipeType) { - case SHAPELESS -> { - ShapelessRecipe shapelessRecipe = (ShapelessRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredShapelessCraftingRecipe( - shapelessRecipe.getRecipeId(), - shapelessRecipe.getGroup(), - shapelessRecipe.getCategory(), - shapelessRecipe.getIngredients(), - shapelessRecipe.getResult())); - } - case SHAPED -> { - ShapedRecipe shapedRecipe = (ShapedRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredShapedCraftingRecipe( - shapedRecipe.getRecipeId(), - shapedRecipe.getGroup(), - shapedRecipe.getCategory(), - shapedRecipe.getWidth(), - shapedRecipe.getHeight(), - shapedRecipe.getIngredients(), - shapedRecipe.getResult(), - shapedRecipe.getShowNotification())); - } - case SMELTING -> { - SmeltingRecipe smeltingRecipe = (SmeltingRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredSmeltingRecipe( - smeltingRecipe.getRecipeId(), - smeltingRecipe.getGroup(), - smeltingRecipe.getCategory(), - smeltingRecipe.getIngredient(), - smeltingRecipe.getResult(), - smeltingRecipe.getExperience(), - smeltingRecipe.getCookingTime())); - } - case BLASTING -> { - BlastingRecipe blastingRecipe = (BlastingRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredBlastingRecipe( - blastingRecipe.getRecipeId(), - blastingRecipe.getGroup(), - blastingRecipe.getCategory(), - blastingRecipe.getIngredient(), - blastingRecipe.getResult(), - blastingRecipe.getExperience(), - blastingRecipe.getCookingTime())); - } - case SMOKING -> { - SmokingRecipe smokingRecipe = (SmokingRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredSmokingRecipe( - smokingRecipe.getRecipeId(), - smokingRecipe.getGroup(), - smokingRecipe.getCategory(), - smokingRecipe.getIngredient(), - smokingRecipe.getResult(), - smokingRecipe.getExperience(), - smokingRecipe.getCookingTime())); - } - case CAMPFIRE_COOKING -> { - CampfireCookingRecipe campfireCookingRecipe = (CampfireCookingRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredCampfireCookingRecipe( - campfireCookingRecipe.getRecipeId(), - campfireCookingRecipe.getGroup(), - campfireCookingRecipe.getCategory(), - campfireCookingRecipe.getIngredient(), - campfireCookingRecipe.getResult(), - campfireCookingRecipe.getExperience(), - campfireCookingRecipe.getCookingTime())); - } - case STONECUTTING -> { - StonecutterRecipe stonecuttingRecipe = (StonecutterRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredStonecutterRecipe( - stonecuttingRecipe.getRecipeId(), - stonecuttingRecipe.getGroup(), - stonecuttingRecipe.getIngredient(), - stonecuttingRecipe.getResult())); - } - case SMITHING_TRANSFORM -> { - SmithingTransformRecipe smithingTransformRecipe = (SmithingTransformRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredSmithingTransformRecipe( - smithingTransformRecipe.getRecipeId(), - smithingTransformRecipe.getTemplate(), - smithingTransformRecipe.getBaseIngredient(), - smithingTransformRecipe.getAdditionIngredient(), - smithingTransformRecipe.getResult())); - } - case SMITHING_TRIM -> { - SmithingTrimRecipe smithingTrimRecipe = (SmithingTrimRecipe) recipe; - recipesCache.add( - new DeclareRecipesPacket.DeclaredSmithingTrimRecipe( - smithingTrimRecipe.getRecipeId(), - smithingTrimRecipe.getTemplate(), - smithingTrimRecipe.getBaseIngredient(), - smithingTrimRecipe.getAdditionIngredient())); - } - } - } - - declareRecipesPacket = new DeclareRecipesPacket(recipesCache); - // TODO; refresh and update players recipes - } + @NotNull Set getRecipes(); + @NotNull DeclareRecipesPacket getDeclareRecipesPacket(); } diff --git a/src/main/java/net/minestom/server/recipe/RecipeManagerImpl.java b/src/main/java/net/minestom/server/recipe/RecipeManagerImpl.java new file mode 100644 index 00000000000..ead037943e2 --- /dev/null +++ b/src/main/java/net/minestom/server/recipe/RecipeManagerImpl.java @@ -0,0 +1,158 @@ +package net.minestom.server.recipe; + +import net.minestom.server.network.packet.server.play.DeclareRecipesPacket; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; + +public class RecipeManagerImpl implements RecipeManager { + private DeclareRecipesPacket declareRecipesPacket = new DeclareRecipesPacket(List.of()); + private final Set recipes = new CopyOnWriteArraySet<>(); + + @Override + public void addRecipes(@NotNull Recipe... recipe) { + if (recipes.addAll(List.of(recipe))) { + refreshRecipesPacket(); + } + } + + @Override + public void addRecipe(@NotNull Recipe recipe) { + if (this.recipes.add(recipe)) { + refreshRecipesPacket(); + } + } + + @Override + public void removeRecipe(@NotNull Recipe recipe) { + if (this.recipes.remove(recipe)) { + refreshRecipesPacket(); + } + } + + @Override + @NotNull + public Set getRecipes() { + return recipes; + } + + @Override + @NotNull + public DeclareRecipesPacket getDeclareRecipesPacket() { + return declareRecipesPacket; + } + + private void refreshRecipesPacket() { + List recipesCache = new ArrayList<>(); + for (Recipe recipe : recipes) { + switch (recipe.recipeType) { + case SHAPELESS -> { + ShapelessRecipe shapelessRecipe = (ShapelessRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredShapelessCraftingRecipe( + shapelessRecipe.getRecipeId(), + shapelessRecipe.getGroup(), + shapelessRecipe.getCategory(), + shapelessRecipe.getIngredients(), + shapelessRecipe.getResult())); + } + case SHAPED -> { + ShapedRecipe shapedRecipe = (ShapedRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredShapedCraftingRecipe( + shapedRecipe.getRecipeId(), + shapedRecipe.getGroup(), + shapedRecipe.getCategory(), + shapedRecipe.getWidth(), + shapedRecipe.getHeight(), + shapedRecipe.getIngredients(), + shapedRecipe.getResult(), + shapedRecipe.getShowNotification())); + } + case SMELTING -> { + SmeltingRecipe smeltingRecipe = (SmeltingRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredSmeltingRecipe( + smeltingRecipe.getRecipeId(), + smeltingRecipe.getGroup(), + smeltingRecipe.getCategory(), + smeltingRecipe.getIngredient(), + smeltingRecipe.getResult(), + smeltingRecipe.getExperience(), + smeltingRecipe.getCookingTime())); + } + case BLASTING -> { + BlastingRecipe blastingRecipe = (BlastingRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredBlastingRecipe( + blastingRecipe.getRecipeId(), + blastingRecipe.getGroup(), + blastingRecipe.getCategory(), + blastingRecipe.getIngredient(), + blastingRecipe.getResult(), + blastingRecipe.getExperience(), + blastingRecipe.getCookingTime())); + } + case SMOKING -> { + SmokingRecipe smokingRecipe = (SmokingRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredSmokingRecipe( + smokingRecipe.getRecipeId(), + smokingRecipe.getGroup(), + smokingRecipe.getCategory(), + smokingRecipe.getIngredient(), + smokingRecipe.getResult(), + smokingRecipe.getExperience(), + smokingRecipe.getCookingTime())); + } + case CAMPFIRE_COOKING -> { + CampfireCookingRecipe campfireCookingRecipe = (CampfireCookingRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredCampfireCookingRecipe( + campfireCookingRecipe.getRecipeId(), + campfireCookingRecipe.getGroup(), + campfireCookingRecipe.getCategory(), + campfireCookingRecipe.getIngredient(), + campfireCookingRecipe.getResult(), + campfireCookingRecipe.getExperience(), + campfireCookingRecipe.getCookingTime())); + } + case STONECUTTING -> { + StonecutterRecipe stonecuttingRecipe = (StonecutterRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredStonecutterRecipe( + stonecuttingRecipe.getRecipeId(), + stonecuttingRecipe.getGroup(), + stonecuttingRecipe.getIngredient(), + stonecuttingRecipe.getResult())); + } + case SMITHING_TRANSFORM -> { + SmithingTransformRecipe smithingTransformRecipe = (SmithingTransformRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredSmithingTransformRecipe( + smithingTransformRecipe.getRecipeId(), + smithingTransformRecipe.getTemplate(), + smithingTransformRecipe.getBaseIngredient(), + smithingTransformRecipe.getAdditionIngredient(), + smithingTransformRecipe.getResult())); + } + case SMITHING_TRIM -> { + SmithingTrimRecipe smithingTrimRecipe = (SmithingTrimRecipe) recipe; + recipesCache.add( + new DeclareRecipesPacket.DeclaredSmithingTrimRecipe( + smithingTrimRecipe.getRecipeId(), + smithingTrimRecipe.getTemplate(), + smithingTrimRecipe.getBaseIngredient(), + smithingTrimRecipe.getAdditionIngredient())); + } + } + } + + declareRecipesPacket = new DeclareRecipesPacket(recipesCache); + // TODO; refresh and update players recipes + } + +} diff --git a/src/main/java/net/minestom/server/recipe/RecipeManagerProvider.java b/src/main/java/net/minestom/server/recipe/RecipeManagerProvider.java new file mode 100644 index 00000000000..dcca2b6521a --- /dev/null +++ b/src/main/java/net/minestom/server/recipe/RecipeManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.recipe; + +public interface RecipeManagerProvider { + RecipeManager getRecipeManager(); +} diff --git a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java index 24755820131..610a4038fae 100644 --- a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java +++ b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java @@ -1,7 +1,8 @@ package net.minestom.server.scoreboard; +import lombok.Getter; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket; import org.jetbrains.annotations.NotNull; @@ -22,21 +23,22 @@ public class BelowNameTag implements Scoreboard { private final Set viewers = new CopyOnWriteArraySet<>(); private final Set unmodifiableViewers = Collections.unmodifiableSet(viewers); - private final ServerProcess serverProcess; private final String objectiveName; private final ScoreboardObjectivePacket scoreboardObjectivePacket; + @Getter + private final ServerSettings serverSettings; /** * Creates a new below name scoreboard. * * @param name The objective name of the scoreboard * @param value The value of the scoreboard - * @deprecated Use {@link #BelowNameTag(ServerProcess, String, Component)} + * @deprecated Use {@link #BelowNameTag(ServerSettings, String, Component)} */ @Deprecated - public BelowNameTag(ServerProcess serverProcess, String name, String value) { - this(serverProcess, name, Component.text(value)); + public BelowNameTag(ServerSettings serverSettings, String name, String value) { + this(serverSettings, name, Component.text(value)); } /** @@ -45,8 +47,8 @@ public BelowNameTag(ServerProcess serverProcess, String name, String value) { * @param name The objective name of the scoreboard * @param value The value of the scoreboard */ - public BelowNameTag(ServerProcess serverProcess, String name, Component value) { - this.serverProcess = serverProcess; + public BelowNameTag(ServerSettings serverSettings, String name, Component value) { + this.serverSettings = serverSettings; this.objectiveName = BELOW_NAME_TAG_PREFIX + name; this.scoreboardObjectivePacket = this.getCreationObjectivePacket(value, ScoreboardObjectivePacket.Type.INTEGER); } @@ -82,9 +84,4 @@ public boolean removeViewer(@NotNull Player player) { public Set getViewers() { return unmodifiableViewers; } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/scoreboard/Sidebar.java b/src/main/java/net/minestom/server/scoreboard/Sidebar.java index de26e753ab5..72eff95cec5 100644 --- a/src/main/java/net/minestom/server/scoreboard/Sidebar.java +++ b/src/main/java/net/minestom/server/scoreboard/Sidebar.java @@ -3,7 +3,7 @@ import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.network.packet.server.play.*; @@ -20,7 +20,7 @@ /** * Represents a sidebar which can contain up to 16 {@link ScoreboardLine}. *

        - * In order to use it you need to create a new instance using the constructor {@link #Sidebar(ServerProcess, String)} and create new lines + * In order to use it you need to create a new instance using the constructor {@link #Sidebar(ServerSettings, String)} and create new lines * with {@link #createLine(ScoreboardLine)}. You can then add a {@link Player} to the viewing list using {@link #addViewer(Player)} * and remove him later with {@link #removeViewer(Player)}. *

        @@ -49,18 +49,18 @@ public class Sidebar implements Scoreboard { private final String objectiveName; - private final ServerProcess serverProcess; + private final ServerSettings serverSettings; private Component title; /** * Creates a new sidebar * * @param title The title of the sidebar - * @deprecated Use {@link #Sidebar(ServerProcess, Component)} + * @deprecated Use {@link #Sidebar(ServerSettings, Component)} */ @Deprecated - public Sidebar(ServerProcess serverProcess, @NotNull String title) { - this(serverProcess, Component.text(title)); + public Sidebar(ServerSettings serverSettings, @NotNull String title) { + this(serverSettings, Component.text(title)); } /** @@ -68,8 +68,8 @@ public Sidebar(ServerProcess serverProcess, @NotNull String title) { * * @param title The title of the sidebar */ - public Sidebar(ServerProcess serverProcess, @NotNull Component title) { - this.serverProcess = serverProcess; + public Sidebar(ServerSettings serverSettings, @NotNull Component title) { + this.serverSettings = serverSettings; this.title = title; this.objectiveName = SCOREBOARD_PREFIX + COUNTER.incrementAndGet(); @@ -98,7 +98,7 @@ public void setTitle(@NotNull String title) { */ public void setTitle(@NotNull Component title) { this.title = title; - sendPacketToViewers(new ScoreboardObjectivePacket(objectiveName, (byte) 2, title, + sendPacketToViewers(serverSettings, new ScoreboardObjectivePacket(objectiveName, (byte) 2, title, ScoreboardObjectivePacket.Type.INTEGER, null)); } @@ -129,7 +129,7 @@ public void createLine(@NotNull ScoreboardLine scoreboardLine) { this.lines.add(scoreboardLine); // Send to current viewers - sendPacketsToViewers(scoreboardLine.sidebarTeam.getCreationPacket(), scoreboardLine.getScoreCreationPacket(objectiveName)); + sendPacketsToViewers(serverSettings, scoreboardLine.sidebarTeam.getCreationPacket(), scoreboardLine.getScoreCreationPacket(objectiveName)); } } @@ -143,7 +143,7 @@ public void updateLineContent(@NotNull String id, @NotNull Component content) { final ScoreboardLine scoreboardLine = getLine(id); if (scoreboardLine != null) { scoreboardLine.refreshContent(content); - sendPacketToViewers(scoreboardLine.sidebarTeam.updatePrefix(content)); + sendPacketToViewers(serverSettings, scoreboardLine.sidebarTeam.updatePrefix(content)); } } @@ -157,7 +157,7 @@ public void updateLineScore(@NotNull String id, int score) { final ScoreboardLine scoreboardLine = getLine(id); if (scoreboardLine != null) { scoreboardLine.line = score; - sendPacketToViewers(scoreboardLine.getLineScoreUpdatePacket(objectiveName, score)); + sendPacketToViewers(serverSettings, scoreboardLine.getLineScoreUpdatePacket(objectiveName, score)); } } @@ -196,7 +196,7 @@ public void removeLine(@NotNull String id) { if (line.id.equals(id)) { // Remove the line for current viewers - sendPacketsToViewers(line.getScoreDestructionPacket(objectiveName), line.sidebarTeam.getDestructionPacket()); + sendPacketsToViewers(serverSettings, line.getScoreDestructionPacket(objectiveName), line.sidebarTeam.getDestructionPacket()); line.returnName(availableColors); return true; @@ -245,8 +245,8 @@ public Set getViewers() { } @Override - public ServerProcess getServerProcess() { - return serverProcess; + public ServerSettings getServerSettings() { + return serverSettings; } /** diff --git a/src/main/java/net/minestom/server/scoreboard/TabList.java b/src/main/java/net/minestom/server/scoreboard/TabList.java index 34171d17527..929705691bd 100644 --- a/src/main/java/net/minestom/server/scoreboard/TabList.java +++ b/src/main/java/net/minestom/server/scoreboard/TabList.java @@ -1,7 +1,7 @@ package net.minestom.server.scoreboard; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.PlayerListHeaderAndFooterPacket; import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket; @@ -27,7 +27,7 @@ public class TabList implements Scoreboard { private final Set viewers = new CopyOnWriteArraySet<>(); private final Set unmodifiableViewers = Collections.unmodifiableSet(viewers); - private final ServerProcess serverProcess; + private final ServerSettings serverSettings; private final String objectiveName; private Component header = Component.empty(); @@ -35,8 +35,8 @@ public class TabList implements Scoreboard { private ScoreboardObjectivePacket.Type type; - public TabList(ServerProcess serverProcess, String name, ScoreboardObjectivePacket.Type type) { - this.serverProcess = serverProcess; + public TabList(ServerSettings serverSettings, String name, ScoreboardObjectivePacket.Type type) { + this.serverSettings = serverSettings; this.objectiveName = TAB_LIST_PREFIX + name; this.type = type; @@ -62,12 +62,12 @@ public void setType(ScoreboardObjectivePacket.Type type) { public void setHeader(@NotNull Component header) { this.header = header; - sendPacketToViewers(new PlayerListHeaderAndFooterPacket(header, footer)); + sendPacketToViewers(serverSettings, new PlayerListHeaderAndFooterPacket(header, footer)); } public void setFooter(@NotNull Component footer) { this.footer = footer; - sendPacketToViewers(new PlayerListHeaderAndFooterPacket(header, footer)); + sendPacketToViewers(serverSettings, new PlayerListHeaderAndFooterPacket(header, footer)); } @Override @@ -102,7 +102,7 @@ public String getObjectiveName() { } @Override - public ServerProcess getServerProcess() { - return serverProcess; + public ServerSettings getServerSettings() { + return serverSettings; } } diff --git a/src/main/java/net/minestom/server/scoreboard/Team.java b/src/main/java/net/minestom/server/scoreboard/Team.java index 8e38a0debf1..c8e988d7cf6 100644 --- a/src/main/java/net/minestom/server/scoreboard/Team.java +++ b/src/main/java/net/minestom/server/scoreboard/Team.java @@ -4,10 +4,11 @@ import net.kyori.adventure.pointer.Pointers; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; import net.minestom.server.adventure.audience.PacketGroupingAudience; import net.minestom.server.entity.LivingEntity; import net.minestom.server.entity.Player; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.server.play.TeamsPacket; import net.minestom.server.network.packet.server.play.TeamsPacket.CollisionRule; import net.minestom.server.network.packet.server.play.TeamsPacket.NameTagVisibility; @@ -33,6 +34,8 @@ public class Team implements PacketGroupingAudience { */ private final Set members; + private final ConnectionManager connectionManager; + private final ServerSettings serverSettings; /** * The registry name of the team. */ @@ -75,15 +78,15 @@ public class Team implements PacketGroupingAudience { // Adventure private final Pointers pointers; - private final ServerProcess serverProcess; /** * Default constructor to creates a team. * * @param teamName The registry name for the team */ - protected Team(ServerProcess serverProcess, @NotNull String teamName) { - this.serverProcess = serverProcess; + protected Team(ConnectionManager connectionManager, ServerSettings serverSettings, @NotNull String teamName) { + this.connectionManager = connectionManager; + this.serverSettings = serverSettings; this.teamName = teamName; this.teamDisplayName = Component.empty(); @@ -131,7 +134,7 @@ public void addMembers(@NotNull Collection<@NotNull String> toAdd) { final TeamsPacket addPlayerPacket = new TeamsPacket(teamName, new TeamsPacket.AddEntitiesToTeamAction(toAdd)); // Sends to all online players the add player packet - PacketUtils.broadcastPlayPacket(serverProcess, addPlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, addPlayerPacket); // invalidate player members this.isPlayerMembersUpToDate = false; @@ -162,7 +165,7 @@ public void removeMembers(@NotNull Collection<@NotNull String> toRemove) { final TeamsPacket removePlayerPacket = new TeamsPacket(teamName, new TeamsPacket.RemoveEntitiesToTeamAction(toRemove)); // Sends to all online player the remove player packet - PacketUtils.broadcastPlayPacket(getServerProcess(), removePlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, removePlayerPacket); // Removes the member from the team this.members.removeAll(toRemove); @@ -466,7 +469,12 @@ public Component getSuffix() { public void sendUpdatePacket() { final var info = new TeamsPacket.UpdateTeamAction(teamDisplayName, friendlyFlags, nameTagVisibility, collisionRule, teamColor, prefix, suffix); - PacketUtils.broadcastPlayPacket(serverProcess, new TeamsPacket(teamName, info)); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new TeamsPacket(teamName, info)); + } + + @Override + public ServerSettings getServerSettings() { + return serverSettings; } @Override @@ -475,7 +483,7 @@ public void sendUpdatePacket() { this.playerMembers.clear(); for (String member : this.members) { - Player player = getServerProcess().getConnectionManager().getOnlinePlayerByUsername(member); + Player player = connectionManager.getOnlinePlayerByUsername(member); if (player != null) { this.playerMembers.add(player); @@ -492,9 +500,4 @@ public void sendUpdatePacket() { public @NotNull Pointers pointers() { return this.pointers; } - - @Override - public ServerProcess getServerProcess() { - return serverProcess; - } } diff --git a/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java b/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java index d5fa2874b02..b85acc23319 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamBuilder.java @@ -2,7 +2,8 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.server.play.TeamsPacket.CollisionRule; import net.minestom.server.network.packet.server.play.TeamsPacket.NameTagVisibility; @@ -14,7 +15,8 @@ public class TeamBuilder { /** * The management for the teams */ - private final TeamManager teamManager; + private final TeamManagerImpl teamManager; + private final ConnectionManager connectionManager; /** * The team to create */ @@ -30,8 +32,8 @@ public class TeamBuilder { * @param name The name of the new team * @param teamManager The manager for the team */ - public TeamBuilder(ServerProcess serverProcess, String name, TeamManager teamManager) { - this(teamManager.exists(name) ? teamManager.getTeam(name) : new Team(serverProcess, name), teamManager); + public TeamBuilder(ConnectionManager connectionManager, ServerSettings serverSettings, String name, TeamManagerImpl teamManager) { + this(connectionManager, teamManager.exists(name) ? teamManager.getTeam(name) : new Team(connectionManager, serverSettings, name), teamManager); } /** @@ -40,7 +42,8 @@ public TeamBuilder(ServerProcess serverProcess, String name, TeamManager teamMan * @param team The new team * @param teamManager The manager for the team */ - private TeamBuilder(Team team, TeamManager teamManager) { + private TeamBuilder(ConnectionManager connectionManager, Team team, TeamManagerImpl teamManager) { + this.connectionManager = connectionManager; this.team = team; this.teamManager = teamManager; this.updateTeam = false; @@ -274,7 +277,7 @@ public TeamBuilder updateTeamPacket() { * @return the built team */ public Team build() { - if (!this.teamManager.exists(this.team)) this.teamManager.registerNewTeam(this.team); + if (!this.teamManager.exists(this.team)) this.teamManager.registerNewTeam(this.team, connectionManager); if (this.updateTeam) { this.team.sendUpdatePacket(); this.updateTeam = false; diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManager.java b/src/main/java/net/minestom/server/scoreboard/TeamManager.java index 5523d63afe1..3a282d8dc20 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamManager.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamManager.java @@ -2,46 +2,26 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; import net.minestom.server.entity.LivingEntity; import net.minestom.server.entity.Player; -import net.minestom.server.utils.PacketUtils; -import net.minestom.server.utils.UniqueIdUtils; +import net.minestom.server.network.ConnectionManager; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; import java.util.List; import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; /** * An object which manages all the {@link Team}'s */ -public final class TeamManager { +public interface TeamManager { /** - * Represents all registered teams - */ - private final Set teams; - private final ServerProcess serverProcess; - - /** - * Default constructor - */ - public TeamManager(ServerProcess serverProcess) { - this.serverProcess = serverProcess; - this.teams = new CopyOnWriteArraySet<>(); - } - - /** - * Registers a new {@link Team} + * Deletes a {@link Team} * - * @param team The team to be registered + * @param team The team to be deleted + * @return {@code true} if the team was deleted, otherwise {@code false} */ - protected void registerNewTeam(@NotNull Team team) { - this.teams.add(team); - PacketUtils.broadcastPlayPacket(serverProcess, team.createTeamsCreationPacket()); - } + boolean deleteTeam(@NotNull Team team, ConnectionManager connectionManager); /** * Deletes a {@link Team} @@ -49,22 +29,10 @@ protected void registerNewTeam(@NotNull Team team) { * @param registryName The registry name of team * @return {@code true} if the team was deleted, otherwise {@code false} */ - public boolean deleteTeam(@NotNull String registryName) { + default boolean deleteTeam(@NotNull String registryName, ConnectionManager connectionManager) { Team team = this.getTeam(registryName); if (team == null) return false; - return this.deleteTeam(team); - } - - /** - * Deletes a {@link Team} - * - * @param team The team to be deleted - * @return {@code true} if the team was deleted, otherwise {@code false} - */ - public boolean deleteTeam(@NotNull Team team) { - // Sends to all online players a team destroy packet - PacketUtils.broadcastPlayPacket(serverProcess, team.createTeamDestructionPacket()); - return this.teams.remove(team); + return this.deleteTeam(team, connectionManager); } /** @@ -73,9 +41,7 @@ public boolean deleteTeam(@NotNull Team team) { * @param name The registry name of the team * @return the team builder */ - public TeamBuilder createBuilder(@NotNull String name) { - return new TeamBuilder(serverProcess, name, this); - } + TeamBuilder createBuilder(@NotNull String name, ConnectionManager connectionManager); /** * Creates a {@link Team} with only the registry name @@ -83,8 +49,8 @@ public TeamBuilder createBuilder(@NotNull String name) { * @param name The registry name * @return the created {@link Team} */ - public Team createTeam(@NotNull String name) { - return this.createBuilder(name).build(); + default Team createTeam(@NotNull String name, ConnectionManager connectionManager) { + return this.createBuilder(name, connectionManager).build(); } /** @@ -96,8 +62,8 @@ public Team createTeam(@NotNull String name) { * @param suffix The team suffix * @return the created {@link Team} with a prefix, teamColor and suffix */ - public Team createTeam(String name, Component prefix, NamedTextColor teamColor, Component suffix) { - return this.createBuilder(name).prefix(prefix).teamColor(teamColor).suffix(suffix).updateTeamPacket().build(); + default Team createTeam(String name, Component prefix, NamedTextColor teamColor, Component suffix, ConnectionManager connectionManager) { + return this.createBuilder(name, connectionManager).prefix(prefix).teamColor(teamColor).suffix(suffix).updateTeamPacket().build(); } /** @@ -110,8 +76,8 @@ public Team createTeam(String name, Component prefix, NamedTextColor teamColor, * @param suffix The team suffix * @return the created {@link Team} with a prefix, teamColor, suffix and the display name */ - public Team createTeam(String name, Component displayName, Component prefix, NamedTextColor teamColor, Component suffix) { - return this.createBuilder(name).teamDisplayName(displayName).prefix(prefix).teamColor(teamColor).suffix(suffix).updateTeamPacket().build(); + default Team createTeam(String name, Component displayName, Component prefix, NamedTextColor teamColor, Component suffix, ConnectionManager connectionManager) { + return this.createBuilder(name, connectionManager).teamDisplayName(displayName).prefix(prefix).teamColor(teamColor).suffix(suffix).updateTeamPacket().build(); } /** @@ -120,12 +86,7 @@ public Team createTeam(String name, Component displayName, Component prefix, Nam * @param teamName The registry name of the team * @return a registered {@link Team} or {@code null} */ - public Team getTeam(String teamName) { - for (Team team : this.teams) { - if (team.getTeamName().equals(teamName)) return team; - } - return null; - } + Team getTeam(String teamName); /** * Checks if the given name a registry name of a registered {@link Team} @@ -133,11 +94,8 @@ public Team getTeam(String teamName) { * @param teamName The name of the team * @return {@code true} if the team is registered, otherwise {@code false} */ - public boolean exists(String teamName) { - for (Team team : this.teams) { - if (team.getTeamName().equals(teamName)) return true; - } - return false; + default boolean exists(String teamName) { + return getTeam(teamName) != null; } /** @@ -146,7 +104,7 @@ public boolean exists(String teamName) { * @param team The searched team * @return {@code true} if the team is registered, otherwise {@code false} */ - public boolean exists(Team team) { + default boolean exists(Team team) { return this.exists(team.getTeamName()); } @@ -158,15 +116,7 @@ public boolean exists(Team team) { * @param team The team * @return a {@link List} with all registered {@link Player} */ - public List getPlayers(Team team) { - List players = new ArrayList<>(); - for (String member : team.getMembers()) { - boolean match = UniqueIdUtils.isUniqueId(member); - - if (!match) players.add(member); - } - return players; - } + List getPlayers(Team team); /** * Gets a {@link List} with all registered {@link LivingEntity} in the team @@ -176,22 +126,12 @@ public List getPlayers(Team team) { * @param team The team * @return a {@link List} with all registered {@link LivingEntity} */ - public List getEntities(Team team) { - List entities = new ArrayList<>(); - for (String member : team.getMembers()) { - boolean match = UniqueIdUtils.isUniqueId(member); - - if (match) entities.add(member); - } - return entities; - } + List getEntities(Team team); /** * Gets a {@link Set} with all registered {@link Team}'s * * @return a {@link Set} with all registered {@link Team}'s */ - public Set getTeams() { - return this.teams; - } + Set getTeams(); } diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java b/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java new file mode 100644 index 00000000000..bfa19523dc2 --- /dev/null +++ b/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java @@ -0,0 +1,82 @@ +package net.minestom.server.scoreboard; + +import lombok.RequiredArgsConstructor; +import net.minestom.server.ServerSettings; +import net.minestom.server.network.ConnectionManager; +import net.minestom.server.utils.PacketUtils; +import net.minestom.server.utils.UniqueIdUtils; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; + +@RequiredArgsConstructor +public final class TeamManagerImpl implements TeamManager { + + /** + * Represents all registered teams + */ + private final Set teams = new CopyOnWriteArraySet<>(); + + private final ServerSettings serverSettings; + + /** + * Registers a new {@link Team} + * + * @param team The team to be registered + */ + void registerNewTeam(@NotNull Team team, ConnectionManager connectionManager) { + this.teams.add(team); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, team.createTeamsCreationPacket()); + } + + @Override + public boolean deleteTeam(@NotNull Team team, ConnectionManager connectionManager) { + // Sends to all online players a team destroy packet + PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, team.createTeamDestructionPacket()); + return this.teams.remove(team); + } + + + @Override + public TeamBuilder createBuilder(@NotNull String name, ConnectionManager connectionManager) { + return new TeamBuilder(connectionManager, serverSettings, name, this); + } + + @Override + public Team getTeam(String teamName) { + for (Team team : this.teams) { + if (team.getTeamName().equals(teamName)) return team; + } + return null; + } + + @Override + public List getPlayers(Team team) { + List players = new ArrayList<>(); + for (String member : team.getMembers()) { + boolean match = UniqueIdUtils.isUniqueId(member); + + if (!match) players.add(member); + } + return players; + } + + @Override + public List getEntities(Team team) { + List entities = new ArrayList<>(); + for (String member : team.getMembers()) { + boolean match = UniqueIdUtils.isUniqueId(member); + + if (match) entities.add(member); + } + return entities; + } + + @Override + public Set getTeams() { + return this.teams; + } +} diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManagerProvider.java b/src/main/java/net/minestom/server/scoreboard/TeamManagerProvider.java new file mode 100644 index 00000000000..a877136e0cc --- /dev/null +++ b/src/main/java/net/minestom/server/scoreboard/TeamManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.scoreboard; + +public interface TeamManagerProvider { + TeamManager getTeamManager(); +} diff --git a/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java b/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java index 6bf75e3e9df..9cc70bdb037 100644 --- a/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java +++ b/src/main/java/net/minestom/server/snapshot/ServerSnapshot.java @@ -1,6 +1,5 @@ package net.minestom.server.snapshot; -import net.minestom.server.ServerProcess; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.UnknownNullability; @@ -18,7 +17,7 @@ public sealed interface ServerSnapshot extends Snapshot permits SnapshotImpl.Ser @UnknownNullability EntitySnapshot entity(int id); @ApiStatus.Experimental - static ServerSnapshot update(ServerProcess serverProcess) { + static ServerSnapshot update(Snapshotable serverProcess) { return SnapshotUpdater.update(serverProcess); } } diff --git a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java index d0fbd45860f..baf7a1fcbbd 100644 --- a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java +++ b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java @@ -1,7 +1,6 @@ package net.minestom.server.snapshot; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.ServerProcess; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.EntityType; @@ -14,6 +13,7 @@ import net.minestom.server.utils.collection.MappedCollection; import net.minestom.server.world.DimensionType; import net.minestom.server.world.biomes.Biome; +import net.minestom.server.world.biomes.BiomeManager; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -75,7 +75,7 @@ public record Instance(AtomicReference serverRef, } } - public record Chunk(ServerProcess serverProcess, + public record Chunk(BiomeManager biomeManager, int minSection, int chunkX, int chunkZ, Section[] sections, Int2ObjectOpenHashMap blockEntries, @@ -104,7 +104,7 @@ public record Chunk(ServerProcess serverProcess, final Section section = sections[getChunkCoordinate(y) - minSection]; final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return serverProcess.getBiomeManager().getById(id); + return biomeManager.getById(id); } @Override diff --git a/src/main/java/net/minestom/server/snapshot/SnapshotUpdater.java b/src/main/java/net/minestom/server/snapshot/SnapshotUpdater.java index e200fac59a9..2f5ba0e82af 100644 --- a/src/main/java/net/minestom/server/snapshot/SnapshotUpdater.java +++ b/src/main/java/net/minestom/server/snapshot/SnapshotUpdater.java @@ -2,11 +2,17 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.minestom.server.entity.Entity; +import net.minestom.server.instance.Instance; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.utils.collection.MappedCollection; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -23,6 +29,19 @@ */ @ApiStatus.Experimental public sealed interface SnapshotUpdater permits SnapshotUpdaterImpl { + + static @NotNull ServerSnapshot updateSnapshot(@NotNull SnapshotUpdater updater, @NotNull InstanceManager instanceManager) { + List> instanceRefs = new ArrayList<>(); + Int2ObjectOpenHashMap> entityRefs = new Int2ObjectOpenHashMap<>(); + for (Instance instance : instanceManager.getInstances()) { + instanceRefs.add(updater.reference(instance)); + for (Entity entity : instance.getEntities()) { + entityRefs.put(entity.getEntityId(), updater.reference(entity)); + } + } + return new SnapshotImpl.Server(MappedCollection.plainReferences(instanceRefs), entityRefs); + } + /** * Updates the snapshot of the given snapshotable. *

        diff --git a/src/main/java/net/minestom/server/thread/Acquirable.java b/src/main/java/net/minestom/server/thread/Acquirable.java index 52718866dcd..ae967a8e3de 100644 --- a/src/main/java/net/minestom/server/thread/Acquirable.java +++ b/src/main/java/net/minestom/server/thread/Acquirable.java @@ -1,7 +1,7 @@ package net.minestom.server.thread; -import net.minestom.server.ServerProcess; import net.minestom.server.entity.Entity; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -99,7 +99,7 @@ default boolean isLocal() { * Free if the element is already present in the current thread, blocking otherwise. * * @param consumer the callback to execute once the element has been safely acquired - * @see #async(ServerProcess, Consumer) + * @see #async(ExceptionHandler, Consumer) */ default void sync(@NotNull Consumer consumer) { Acquired acquired = lock(); @@ -113,9 +113,9 @@ default void sync(@NotNull Consumer consumer) { * @param consumer the callback to execute once the element has been safely acquired * @see #sync(Consumer) */ - default void async(ServerProcess serverProcess, @NotNull Consumer consumer) { + default void async(ExceptionHandler exceptionHandler, @NotNull Consumer consumer) { // TODO per-thread list - AsyncUtils.runAsync(serverProcess, () -> sync(consumer)); + AsyncUtils.runAsync(exceptionHandler, () -> sync(consumer)); } /** diff --git a/src/main/java/net/minestom/server/thread/AcquirableCollection.java b/src/main/java/net/minestom/server/thread/AcquirableCollection.java index a63ac25e031..e6ecab26419 100644 --- a/src/main/java/net/minestom/server/thread/AcquirableCollection.java +++ b/src/main/java/net/minestom/server/thread/AcquirableCollection.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.utils.async.AsyncUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -36,8 +36,8 @@ public void acquireSync(@NotNull Consumer consumer) { } } - public void acquireAsync(ServerProcess serverProcess, @NotNull Consumer consumer) { - AsyncUtils.runAsync(serverProcess, () -> acquireSync(consumer)); + public void acquireAsync(ExceptionHandler exceptionHandler, @NotNull Consumer consumer) { + AsyncUtils.runAsync(exceptionHandler, () -> acquireSync(consumer)); } public @NotNull Stream unwrap() { diff --git a/src/main/java/net/minestom/server/thread/ChunkDispatcher.java b/src/main/java/net/minestom/server/thread/ChunkDispatcher.java new file mode 100644 index 00000000000..58da8d4289a --- /dev/null +++ b/src/main/java/net/minestom/server/thread/ChunkDispatcher.java @@ -0,0 +1,15 @@ +package net.minestom.server.thread; + +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; +import org.jetbrains.annotations.NotNull; + +public interface ChunkDispatcher extends ThreadDispatcher{ + static @NotNull ChunkDispatcher of(ExceptionHandler exceptionHandler, @NotNull ThreadProvider provider, int threadCount) { + return new ChunkDispatcherImpl(exceptionHandler, provider, threadCount); + } + + static @NotNull ChunkDispatcher singleThread(ExceptionHandler exceptionHandler) { + return of(exceptionHandler, ThreadProvider.counter(), 1); + } +} diff --git a/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java b/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java new file mode 100644 index 00000000000..52561a704c4 --- /dev/null +++ b/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java @@ -0,0 +1,10 @@ +package net.minestom.server.thread; + +import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.instance.Chunk; + +public class ChunkDispatcherImpl extends ThreadDispatcherImpl implements ChunkDispatcher{ + ChunkDispatcherImpl(ExceptionHandler exceptionHandler, ThreadProvider provider, int threadCount) { + super(exceptionHandler, provider, threadCount); + } +} diff --git a/src/main/java/net/minestom/server/thread/ChunkDispatcherProvider.java b/src/main/java/net/minestom/server/thread/ChunkDispatcherProvider.java new file mode 100644 index 00000000000..02858a28b88 --- /dev/null +++ b/src/main/java/net/minestom/server/thread/ChunkDispatcherProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.thread; + +public interface ChunkDispatcherProvider { + ChunkDispatcher getChunkDispatcher(); +} diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java index 3dd12894a6f..b081f91701d 100644 --- a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java @@ -1,243 +1,37 @@ package net.minestom.server.thread; import net.minestom.server.Tickable; -import net.minestom.server.entity.Entity; import net.minestom.server.exception.ExceptionHandler; -import org.jctools.queues.MessagePassingQueue; -import org.jctools.queues.MpscUnboundedArrayQueue; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.*; -import java.util.concurrent.CountDownLatch; +import java.util.List; -/** - * Used to link chunks into multiple groups. - * Then executed into a thread pool. - */ -public final class ThreadDispatcher

        { - private final ThreadProvider

        provider; - private final List threads; - - // Partition -> dispatching context - // Defines how computation is dispatched to the threads - private final Map partitions = new WeakHashMap<>(); - // Cache to retrieve the threading context from a tickable element - private final Map elements = new WeakHashMap<>(); - // Queue to update chunks linked thread - private final ArrayDeque

        partitionUpdateQueue = new ArrayDeque<>(); - - // Requests consumed at the end of each tick - private final MessagePassingQueue> updates = new MpscUnboundedArrayQueue<>(1024); - - private ThreadDispatcher(ExceptionHandler exceptionHandler, ThreadProvider

        provider, int threadCount) { - this.provider = provider; - TickThread[] threads = new TickThread[threadCount]; - Arrays.setAll(threads, (i) -> new TickThread(exceptionHandler, i)); - this.threads = List.of(threads); - this.threads.forEach(Thread::start); - } - - public static

        @NotNull ThreadDispatcher

        of(ExceptionHandler exceptionHandler, @NotNull ThreadProvider

        provider, int threadCount) { - return new ThreadDispatcher<>(exceptionHandler, provider, threadCount); +public interface ThreadDispatcher

        { + static

        @NotNull ThreadDispatcher

        of(ExceptionHandler exceptionHandler, @NotNull ThreadProvider

        provider, int threadCount) { + return new ThreadDispatcherImpl<>(exceptionHandler, provider, threadCount); } - public static

        @NotNull ThreadDispatcher

        singleThread(ExceptionHandler exceptionHandler) { + static

        @NotNull ThreadDispatcher

        singleThread(ExceptionHandler exceptionHandler) { return of(exceptionHandler, ThreadProvider.counter(), 1); } @Unmodifiable - public @NotNull List<@NotNull TickThread> threads() { - return threads; - } + @NotNull List<@NotNull TickThread> threads(); - /** - * Prepares the update by creating the {@link TickThread} tasks. - * - * @param time the tick time in milliseconds - */ - public synchronized void updateAndAwait(long time) { - // Update dispatcher - this.updates.drain(update -> { - if (update instanceof DispatchUpdate.PartitionLoad

        chunkUpdate) { - processLoadedPartition(chunkUpdate.partition()); - } else if (update instanceof DispatchUpdate.PartitionUnload

        partitionUnload) { - processUnloadedPartition(partitionUnload.partition()); - } else if (update instanceof DispatchUpdate.ElementUpdate

        elementUpdate) { - processUpdatedElement(elementUpdate.tickable(), elementUpdate.partition()); - } else if (update instanceof DispatchUpdate.ElementRemove elementRemove) { - processRemovedElement(elementRemove.tickable()); - } else { - throw new IllegalStateException("Unknown update type: " + update.getClass().getSimpleName()); - } - }); - // Tick all partitions - CountDownLatch latch = new CountDownLatch(threads.size()); - for (TickThread thread : threads) thread.startTick(latch, time); - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } + void updateAndAwait(long time); - /** - * Called at the end of each tick to clear removed entities, - * refresh the chunk linked to an entity, and chunk threads based on {@link ThreadProvider#findThread(Object)}. - * - * @param nanoTimeout max time in nanoseconds to update partitions - */ - public void refreshThreads(long nanoTimeout) { - switch (provider.refreshType()) { - case NEVER -> { - // Do nothing - } - case ALWAYS -> { - final long currentTime = System.nanoTime(); - int counter = partitionUpdateQueue.size(); - while (true) { - final P partition = partitionUpdateQueue.pollFirst(); - if (partition == null) break; - // Update chunk's thread - Partition partitionEntry = partitions.get(partition); - assert partitionEntry != null; - final TickThread previous = partitionEntry.thread; - final TickThread next = retrieveThread(partition); - if (next != previous) { - partitionEntry.thread = next; - previous.entries().remove(partitionEntry); - next.entries().add(partitionEntry); - } - this.partitionUpdateQueue.addLast(partition); - if (--counter <= 0 || System.nanoTime() - currentTime >= nanoTimeout) { - break; - } - } - } - } - } + void refreshThreads(long nanoTimeout); - public void refreshThreads() { - refreshThreads(Long.MAX_VALUE); - } + void refreshThreads(); - public void createPartition(P partition) { - signalUpdate(new DispatchUpdate.PartitionLoad<>(partition)); - } + void createPartition(P partition); - public void deletePartition(P partition) { - signalUpdate(new DispatchUpdate.PartitionUnload<>(partition)); - } + void deletePartition(P partition); - public void updateElement(Tickable tickable, P partition) { - signalUpdate(new DispatchUpdate.ElementUpdate<>(tickable, partition)); - } + void updateElement(Tickable tickable, P partition); - public void removeElement(Tickable tickable) { - signalUpdate(new DispatchUpdate.ElementRemove<>(tickable)); - } - - /** - * Shutdowns all the {@link TickThread tick threads}. - *

        - * Action is irreversible. - */ - public void shutdown() { - this.threads.forEach(TickThread::shutdown); - } - - private TickThread retrieveThread(P partition) { - final int threadId = provider.findThread(partition); - final int index = Math.abs(threadId) % threads.size(); - return threads.get(index); - } - - private void signalUpdate(@NotNull DispatchUpdate

        update) { - this.updates.relaxedOffer(update); - } + void removeElement(Tickable tickable); - private void processLoadedPartition(P partition) { - if (partitions.containsKey(partition)) return; - final TickThread thread = retrieveThread(partition); - final Partition partitionEntry = new Partition(thread); - thread.entries().add(partitionEntry); - this.partitions.put(partition, partitionEntry); - this.partitionUpdateQueue.add(partition); - if (partition instanceof Tickable tickable) { - processUpdatedElement(tickable, partition); - } - } - - private void processUnloadedPartition(P partition) { - final Partition partitionEntry = partitions.remove(partition); - if (partitionEntry != null) { - TickThread thread = partitionEntry.thread; - thread.entries().remove(partitionEntry); - } - this.partitionUpdateQueue.remove(partition); - if (partition instanceof Tickable tickable) { - processRemovedElement(tickable); - } - } - - private void processRemovedElement(Tickable tickable) { - Partition partition = elements.get(tickable); - if (partition != null) { - partition.elements.remove(tickable); - } - } - - private void processUpdatedElement(Tickable tickable, P partition) { - Partition partitionEntry; - - partitionEntry = elements.get(tickable); - // Remove from previous list - if (partitionEntry != null) { - partitionEntry.elements.remove(tickable); - } - // Add to new list - partitionEntry = partitions.get(partition); - if (partitionEntry != null) { - this.elements.put(tickable, partitionEntry); - partitionEntry.elements.add(tickable); - if (tickable instanceof Entity entity) { // TODO support other types - ((AcquirableImpl) entity.getAcquirable()).updateThread(partitionEntry.thread()); - } - } - } - - public static final class Partition { - private TickThread thread; - private final List elements = new ArrayList<>(); - - private Partition(TickThread thread) { - this.thread = thread; - } - - public @NotNull TickThread thread() { - return thread; - } - - public @NotNull List elements() { - return elements; - } - } - - @ApiStatus.Internal - sealed interface DispatchUpdate

        permits - DispatchUpdate.PartitionLoad, DispatchUpdate.PartitionUnload, - DispatchUpdate.ElementUpdate, DispatchUpdate.ElementRemove { - record PartitionLoad

        (@NotNull P partition) implements DispatchUpdate

        { - } - - record PartitionUnload

        (@NotNull P partition) implements DispatchUpdate

        { - } - - record ElementUpdate

        (@NotNull Tickable tickable, P partition) implements DispatchUpdate

        { - } - - record ElementRemove

        (@NotNull Tickable tickable) implements DispatchUpdate

        { - } - } + void shutdown(); } diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java b/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java new file mode 100644 index 00000000000..b40f0b8d95c --- /dev/null +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java @@ -0,0 +1,244 @@ +package net.minestom.server.thread; + +import net.minestom.server.Tickable; +import net.minestom.server.entity.Entity; +import net.minestom.server.exception.ExceptionHandler; +import org.jctools.queues.MessagePassingQueue; +import org.jctools.queues.MpscUnboundedArrayQueue; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.*; +import java.util.concurrent.CountDownLatch; + +/** + * Used to link chunks into multiple groups. + * Then executed into a thread pool. + */ +public class ThreadDispatcherImpl

        implements ThreadDispatcher

        { + private final ThreadProvider

        provider; + private final List threads; + + // Partition -> dispatching context + // Defines how computation is dispatched to the threads + private final Map partitions = new WeakHashMap<>(); + // Cache to retrieve the threading context from a tickable element + private final Map elements = new WeakHashMap<>(); + // Queue to update chunks linked thread + private final ArrayDeque

        partitionUpdateQueue = new ArrayDeque<>(); + + // Requests consumed at the end of each tick + private final MessagePassingQueue> updates = new MpscUnboundedArrayQueue<>(1024); + + ThreadDispatcherImpl(ExceptionHandler exceptionHandler, ThreadProvider

        provider, int threadCount) { + this.provider = provider; + TickThread[] threads = new TickThread[threadCount]; + Arrays.setAll(threads, (i) -> new TickThread(exceptionHandler, i)); + this.threads = List.of(threads); + this.threads.forEach(Thread::start); + } + + @Override + @Unmodifiable + public @NotNull List<@NotNull TickThread> threads() { + return threads; + } + + /** + * Prepares the update by creating the {@link TickThread} tasks. + * + * @param time the tick time in milliseconds + */ + @Override + public synchronized void updateAndAwait(long time) { + // Update dispatcher + this.updates.drain(update -> { + if (update instanceof DispatchUpdate.PartitionLoad

        chunkUpdate) { + processLoadedPartition(chunkUpdate.partition()); + } else if (update instanceof DispatchUpdate.PartitionUnload

        partitionUnload) { + processUnloadedPartition(partitionUnload.partition()); + } else if (update instanceof DispatchUpdate.ElementUpdate

        elementUpdate) { + processUpdatedElement(elementUpdate.tickable(), elementUpdate.partition()); + } else if (update instanceof DispatchUpdate.ElementRemove elementRemove) { + processRemovedElement(elementRemove.tickable()); + } else { + throw new IllegalStateException("Unknown update type: " + update.getClass().getSimpleName()); + } + }); + // Tick all partitions + CountDownLatch latch = new CountDownLatch(threads.size()); + for (TickThread thread : threads) thread.startTick(latch, time); + try { + latch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + /** + * Called at the end of each tick to clear removed entities, + * refresh the chunk linked to an entity, and chunk threads based on {@link ThreadProvider#findThread(Object)}. + * + * @param nanoTimeout max time in nanoseconds to update partitions + */ + @Override + public void refreshThreads(long nanoTimeout) { + switch (provider.refreshType()) { + case NEVER -> { + // Do nothing + } + case ALWAYS -> { + final long currentTime = System.nanoTime(); + int counter = partitionUpdateQueue.size(); + while (true) { + final P partition = partitionUpdateQueue.pollFirst(); + if (partition == null) break; + // Update chunk's thread + Partition partitionEntry = partitions.get(partition); + assert partitionEntry != null; + final TickThread previous = partitionEntry.thread; + final TickThread next = retrieveThread(partition); + if (next != previous) { + partitionEntry.thread = next; + previous.entries().remove(partitionEntry); + next.entries().add(partitionEntry); + } + this.partitionUpdateQueue.addLast(partition); + if (--counter <= 0 || System.nanoTime() - currentTime >= nanoTimeout) { + break; + } + } + } + } + } + + @Override + public void refreshThreads() { + refreshThreads(Long.MAX_VALUE); + } + + @Override + public void createPartition(P partition) { + signalUpdate(new DispatchUpdate.PartitionLoad<>(partition)); + } + + @Override + public void deletePartition(P partition) { + signalUpdate(new DispatchUpdate.PartitionUnload<>(partition)); + } + + @Override + public void updateElement(Tickable tickable, P partition) { + signalUpdate(new DispatchUpdate.ElementUpdate<>(tickable, partition)); + } + + @Override + public void removeElement(Tickable tickable) { + signalUpdate(new DispatchUpdate.ElementRemove<>(tickable)); + } + + /** + * Shutdowns all the {@link TickThread tick threads}. + *

        + * Action is irreversible. + */ + @Override + public void shutdown() { + this.threads.forEach(TickThread::shutdown); + } + + private TickThread retrieveThread(P partition) { + final int threadId = provider.findThread(partition); + final int index = Math.abs(threadId) % threads.size(); + return threads.get(index); + } + + private void signalUpdate(@NotNull DispatchUpdate

        update) { + this.updates.relaxedOffer(update); + } + + private void processLoadedPartition(P partition) { + if (partitions.containsKey(partition)) return; + final TickThread thread = retrieveThread(partition); + final Partition partitionEntry = new Partition(thread); + thread.entries().add(partitionEntry); + this.partitions.put(partition, partitionEntry); + this.partitionUpdateQueue.add(partition); + if (partition instanceof Tickable tickable) { + processUpdatedElement(tickable, partition); + } + } + + private void processUnloadedPartition(P partition) { + final Partition partitionEntry = partitions.remove(partition); + if (partitionEntry != null) { + TickThread thread = partitionEntry.thread; + thread.entries().remove(partitionEntry); + } + this.partitionUpdateQueue.remove(partition); + if (partition instanceof Tickable tickable) { + processRemovedElement(tickable); + } + } + + private void processRemovedElement(Tickable tickable) { + Partition partition = elements.get(tickable); + if (partition != null) { + partition.elements.remove(tickable); + } + } + + private void processUpdatedElement(Tickable tickable, P partition) { + Partition partitionEntry; + + partitionEntry = elements.get(tickable); + // Remove from previous list + if (partitionEntry != null) { + partitionEntry.elements.remove(tickable); + } + // Add to new list + partitionEntry = partitions.get(partition); + if (partitionEntry != null) { + this.elements.put(tickable, partitionEntry); + partitionEntry.elements.add(tickable); + if (tickable instanceof Entity entity) { // TODO support other types + ((AcquirableImpl) entity.getAcquirable()).updateThread(partitionEntry.thread()); + } + } + } + + public static final class Partition { + private TickThread thread; + private final List elements = new ArrayList<>(); + + private Partition(TickThread thread) { + this.thread = thread; + } + + public @NotNull TickThread thread() { + return thread; + } + + public @NotNull List elements() { + return elements; + } + } + + @ApiStatus.Internal + sealed interface DispatchUpdate

        permits + DispatchUpdate.PartitionLoad, DispatchUpdate.PartitionUnload, + DispatchUpdate.ElementUpdate, DispatchUpdate.ElementRemove { + record PartitionLoad

        (@NotNull P partition) implements DispatchUpdate

        { + } + + record PartitionUnload

        (@NotNull P partition) implements DispatchUpdate

        { + } + + record ElementUpdate

        (@NotNull Tickable tickable, P partition) implements DispatchUpdate

        { + } + + record ElementRemove

        (@NotNull Tickable tickable) implements DispatchUpdate

        { + } + } +} diff --git a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java index 9887c7c82c6..016075e5120 100644 --- a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java +++ b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java @@ -1,32 +1,41 @@ package net.minestom.server.thread; import net.minestom.server.ServerConsts; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerSettings; +import net.minestom.server.ServerStarter; +import net.minestom.server.Ticker; +import net.minestom.server.exception.ExceptionHandler; import org.jetbrains.annotations.ApiStatus; import java.util.concurrent.locks.LockSupport; @ApiStatus.Internal public final class TickSchedulerThread extends MinestomThread { - private final ServerProcess serverProcess; private final long startTickNs = System.nanoTime(); + private final ServerSettings serverSettings; + private final Ticker ticker; + private final ServerStarter serverStarter; + private final ExceptionHandler exceptionHandler; private long tick = 1; - public TickSchedulerThread(ServerProcess serverProcess) { + public TickSchedulerThread(ServerSettings serverSettings, Ticker ticker, ServerStarter serverStarter, ExceptionHandler exceptionHandler) { super(ServerConsts.THREAD_NAME_TICK_SCHEDULER); - this.serverProcess = serverProcess; + this.serverSettings = serverSettings; + this.ticker = ticker; + this.serverStarter = serverStarter; + this.exceptionHandler = exceptionHandler; } @Override public void run() { - final long tickNs = (long) (serverProcess.getServerSetting().getTickMs() * 1e6); - while (serverProcess.isAlive()) { + final long tickNs = (long) (serverSettings.getTickMs() * 1e6); + while (serverStarter.isAlive()) { final long tickStart = System.nanoTime(); try { - serverProcess.ticker().tick(tickStart); + ticker.tick(tickStart); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } fixTickRate(tickNs); } diff --git a/src/main/java/net/minestom/server/thread/TickThread.java b/src/main/java/net/minestom/server/thread/TickThread.java index 1e31a77f56c..71a512ba1bd 100644 --- a/src/main/java/net/minestom/server/thread/TickThread.java +++ b/src/main/java/net/minestom/server/thread/TickThread.java @@ -19,7 +19,7 @@ /** * Thread responsible for ticking {@link Chunk chunks} and {@link Entity entities}. *

        - * Created in {@link ThreadDispatcher}, and awaken every tick with a task to execute. + * Created in {@link ThreadDispatcherImpl}, and awaken every tick with a task to execute. */ @ApiStatus.Internal public final class TickThread extends MinestomThread { @@ -30,7 +30,7 @@ public final class TickThread extends MinestomThread { private CountDownLatch latch; private long tickTime; private long tickNum = 0; - private final List entries = new ArrayList<>(); + private final List entries = new ArrayList<>(); public TickThread(ExceptionHandler exceptionHandler, int number) { super(ServerConsts.THREAD_NAME_TICK + "-" + number); @@ -63,7 +63,7 @@ public void run() { private void tick() { final ReentrantLock lock = this.lock; final long tickTime = this.tickTime; - for (ThreadDispatcher.Partition entry : entries) { + for (ThreadDispatcherImpl.Partition entry : entries) { assert entry.thread() == this; final List elements = entry.elements(); if (elements.isEmpty()) continue; @@ -95,7 +95,7 @@ void startTick(CountDownLatch latch, long tickTime) { LockSupport.unpark(this); } - public Collection entries() { + public Collection entries() { return entries; } diff --git a/src/main/java/net/minestom/server/timer/Scheduler.java b/src/main/java/net/minestom/server/timer/Scheduler.java index bd5eee9e295..6130e6ee41b 100644 --- a/src/main/java/net/minestom/server/timer/Scheduler.java +++ b/src/main/java/net/minestom/server/timer/Scheduler.java @@ -10,7 +10,7 @@ *

        * Tasks are by default executed in the caller thread. */ -public sealed interface Scheduler permits SchedulerImpl, SchedulerManager { +public interface Scheduler { static @NotNull Scheduler newScheduler() { return new SchedulerImpl(); } diff --git a/src/main/java/net/minestom/server/timer/SchedulerManager.java b/src/main/java/net/minestom/server/timer/SchedulerManager.java index bd694fbe1f2..4f1c5c991d5 100644 --- a/src/main/java/net/minestom/server/timer/SchedulerManager.java +++ b/src/main/java/net/minestom/server/timer/SchedulerManager.java @@ -1,35 +1,9 @@ package net.minestom.server.timer; -import org.jctools.queues.MpmcUnboundedXaddArrayQueue; import org.jetbrains.annotations.NotNull; -import java.util.function.Supplier; +public interface SchedulerManager extends Scheduler { + void shutdown(); -public final class SchedulerManager implements Scheduler { - private final Scheduler scheduler = Scheduler.newScheduler(); - private final MpmcUnboundedXaddArrayQueue shutdownTasks = new MpmcUnboundedXaddArrayQueue<>(1024); - - @Override - public void process() { - this.scheduler.process(); - } - - @Override - public void processTick() { - this.scheduler.processTick(); - } - - @Override - public @NotNull Task submitTask(@NotNull Supplier task, - @NotNull ExecutionType executionType) { - return scheduler.submitTask(task, executionType); - } - - public void shutdown() { - this.shutdownTasks.drain(Runnable::run); - } - - public void buildShutdownTask(@NotNull Runnable runnable) { - this.shutdownTasks.relaxedOffer(runnable); - } + void buildShutdownTask(@NotNull Runnable runnable); } diff --git a/src/main/java/net/minestom/server/timer/SchedulerManagerImpl.java b/src/main/java/net/minestom/server/timer/SchedulerManagerImpl.java new file mode 100644 index 00000000000..c0b60206d48 --- /dev/null +++ b/src/main/java/net/minestom/server/timer/SchedulerManagerImpl.java @@ -0,0 +1,37 @@ +package net.minestom.server.timer; + +import org.jctools.queues.MpmcUnboundedXaddArrayQueue; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +public final class SchedulerManagerImpl implements SchedulerManager { + private final Scheduler scheduler = Scheduler.newScheduler(); + private final MpmcUnboundedXaddArrayQueue shutdownTasks = new MpmcUnboundedXaddArrayQueue<>(1024); + + @Override + public void process() { + this.scheduler.process(); + } + + @Override + public void processTick() { + this.scheduler.processTick(); + } + + @Override + public @NotNull Task submitTask(@NotNull Supplier task, + @NotNull ExecutionType executionType) { + return scheduler.submitTask(task, executionType); + } + + @Override + public void shutdown() { + this.shutdownTasks.drain(Runnable::run); + } + + @Override + public void buildShutdownTask(@NotNull Runnable runnable) { + this.shutdownTasks.relaxedOffer(runnable); + } +} diff --git a/src/main/java/net/minestom/server/timer/SchedulerManagerProvider.java b/src/main/java/net/minestom/server/timer/SchedulerManagerProvider.java new file mode 100644 index 00000000000..11b9dd94f79 --- /dev/null +++ b/src/main/java/net/minestom/server/timer/SchedulerManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.timer; + +public interface SchedulerManagerProvider { + SchedulerManager getSchedulerManager(); +} diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index 3a0389e2cb0..fe04a5cf27f 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -10,7 +10,7 @@ import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TranslatableComponent; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.Viewable; import net.minestom.server.adventure.ComponentHolder; @@ -82,16 +82,16 @@ private PacketUtils() { * @param packet the packet */ @SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience - public static void sendPacket(ServerProcess serverProcess, @NotNull Audience audience, @NotNull ServerPacket packet) { + public static void sendPacket(ServerFacade serverFacade, @NotNull Audience audience, @NotNull ServerPacket packet) { if (audience instanceof Player player) { player.sendPacket(packet); } else if (audience instanceof PacketGroupingAudience groupingAudience) { - PacketUtils.sendGroupedPacket(serverProcess.getServerSetting(), groupingAudience.getPlayers(), packet); + PacketUtils.sendGroupedPacket(serverFacade.getServerSettings(), groupingAudience.getPlayers(), packet); } else if (audience instanceof ForwardingAudience.Single singleAudience) { - PacketUtils.sendPacket(serverProcess, singleAudience.audience(), packet); + PacketUtils.sendPacket(serverFacade, singleAudience.audience(), packet); } else if (audience instanceof ForwardingAudience forwardingAudience) { for (Audience member : forwardingAudience.audiences()) { - PacketUtils.sendPacket(serverProcess, member, packet); + PacketUtils.sendPacket(serverFacade, member, packet); } } } @@ -161,16 +161,12 @@ public static void broadcastPlayPacket(ConnectionManager connectionManager, Serv sendGroupedPacket(serverSettings, connectionManager.getOnlinePlayers(), packet); } - public static void broadcastPlayPacket(ServerProcess serverProcess, @NotNull ServerPacket packet) { - sendGroupedPacket(serverProcess.getServerSetting(), serverProcess.getConnectionManager().getOnlinePlayers(), packet); - } - @ApiStatus.Experimental public static void prepareViewablePacket(ServerSettings serverSettings, @NotNull Viewable viewable, @NotNull ServerPacket serverPacket, @Nullable Entity entity) { if (entity != null && !entity.hasPredictableViewers()) { // Operation cannot be optimized - entity.sendPacketToViewers(serverPacket); + entity.sendPacketToViewers(serverSettings, serverPacket); return; } if (!VIEWABLE_PACKET) { diff --git a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java index 0547c6fd6d3..6433173305f 100644 --- a/src/main/java/net/minestom/server/utils/async/AsyncUtils.java +++ b/src/main/java/net/minestom/server/utils/async/AsyncUtils.java @@ -1,6 +1,6 @@ package net.minestom.server.utils.async; -import net.minestom.server.ServerProcess; +import net.minestom.server.exception.ExceptionHandler; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -15,12 +15,12 @@ public static CompletableFuture empty() { return (CompletableFuture) VOID_FUTURE; } - public static @NotNull CompletableFuture runAsync(ServerProcess serverProcess, @NotNull Runnable runnable) { + public static @NotNull CompletableFuture runAsync(ExceptionHandler exceptionHandler, @NotNull Runnable runnable) { return CompletableFuture.runAsync(() -> { try { runnable.run(); } catch (Exception e) { - serverProcess.getExceptionHandler().handleException(e); + exceptionHandler.handleException(e); } }); } diff --git a/src/main/java/net/minestom/server/utils/callback/CommandCallback.java b/src/main/java/net/minestom/server/utils/callback/CommandCallback.java index b19eb90171e..bf9cc2fcf45 100644 --- a/src/main/java/net/minestom/server/utils/callback/CommandCallback.java +++ b/src/main/java/net/minestom/server/utils/callback/CommandCallback.java @@ -1,12 +1,13 @@ package net.minestom.server.utils.callback; +import net.minestom.server.command.CommandManagerImpl; import net.minestom.server.command.CommandSender; import org.jetbrains.annotations.NotNull; /** - * Functional interface used by the {@link net.minestom.server.command.CommandManager} + * Functional interface used by the {@link CommandManagerImpl} * to execute a callback if an unknown command is run. - * You can set it with {@link net.minestom.server.command.CommandManager#setUnknownCommandCallback(CommandCallback)}. + * You can set it with {@link CommandManagerImpl#setUnknownCommandCallback(CommandCallback)}. */ @FunctionalInterface public interface CommandCallback { diff --git a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java index 0e6aabd7648..f7d5fc90d6b 100644 --- a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java +++ b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.objects.Object2BooleanMaps; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; +import lombok.RequiredArgsConstructor; import net.minestom.server.command.CommandSender; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -10,6 +11,8 @@ import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; import net.minestom.server.instance.Instance; +import net.minestom.server.instance.InstanceManager; +import net.minestom.server.network.ConnectionManager; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.math.IntRange; import net.minestom.server.utils.validate.Check; @@ -25,7 +28,10 @@ * Represents a query which can be call to find one or multiple entities. * It is based on the target selectors used in commands. */ +@RequiredArgsConstructor public class EntityFinder { + private final InstanceManager instanceManager; + private final ConnectionManager connectionManager; private TargetSelector targetSelector; @@ -127,7 +133,7 @@ public EntityFinder setDifference(float dx, float dy, float dz) { public @NotNull List<@NotNull Entity> find(@Nullable Instance instance, @Nullable Entity self) { if (targetSelector == TargetSelector.MINESTOM_USERNAME) { Check.notNull(constantName, "The player name should not be null when searching for it"); - final Player player = instance.getServerProcess().getConnectionManager().getOnlinePlayerByUsername(constantName); + final Player player = connectionManager.getOnlinePlayerByUsername(constantName); return player != null ? List.of(player) : List.of(); } else if (targetSelector == TargetSelector.MINESTOM_UUID) { Check.notNull(constantUuid, "The UUID should not be null when searching for it"); @@ -303,10 +309,10 @@ public boolean getValue() { private static class ToggleableMap extends Object2BooleanOpenHashMap { } - private static @NotNull List<@NotNull Entity> findTarget(@Nullable Instance instance, + private @NotNull List<@NotNull Entity> findTarget(@Nullable Instance instance, @NotNull TargetSelector targetSelector, @NotNull Point startPosition, @Nullable Entity self) { - final var players = instance != null ? instance.getPlayers() : instance.getServerProcess().getConnectionManager().getOnlinePlayers(); + final var players = instance != null ? instance.getPlayers() : connectionManager.getOnlinePlayers(); if (targetSelector == TargetSelector.NEAREST_PLAYER) { return players.stream() .min(Comparator.comparingDouble(p -> p.getPosition().distanceSquared(startPosition))) @@ -322,7 +328,7 @@ private static class ToggleableMap extends Object2BooleanOpenHashMap { return List.copyOf(instance.getEntities()); } // Get entities from every instance - var instances = instance.getServerProcess().getInstanceManager().getInstances(); + var instances = instanceManager.getInstances(); List entities = new ArrayList<>(); for (Instance inst : instances) { entities.addAll(inst.getEntities()); diff --git a/src/main/java/net/minestom/server/world/Difficulty.java b/src/main/java/net/minestom/server/world/Difficulty.java index 64e2c4a6af1..0117f51db75 100644 --- a/src/main/java/net/minestom/server/world/Difficulty.java +++ b/src/main/java/net/minestom/server/world/Difficulty.java @@ -1,12 +1,11 @@ package net.minestom.server.world; -import net.minestom.server.ServerProcess; import net.minestom.server.ServerSettings; /** * Those are all the difficulties which can be displayed in the player menu. *

        - * Sets with {@link ServerSettings#setDifficulty(Difficulty, ServerProcess)}. + * Sets with {@link ServerSettings#setDifficulty(Difficulty)}. */ public enum Difficulty { diff --git a/src/main/java/net/minestom/server/world/DimensionTypeManager.java b/src/main/java/net/minestom/server/world/DimensionTypeManager.java index 0c38fac887e..32a844bc2d3 100644 --- a/src/main/java/net/minestom/server/world/DimensionTypeManager.java +++ b/src/main/java/net/minestom/server/world/DimensionTypeManager.java @@ -3,36 +3,23 @@ import net.minestom.server.utils.NamespaceID; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jglrxavpok.hephaistos.nbt.NBT; import org.jglrxavpok.hephaistos.nbt.NBTCompound; -import org.jglrxavpok.hephaistos.nbt.NBTType; -import java.util.Collections; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; /** * Allows servers to register custom dimensions. Also used during player login to send the list of all existing dimensions. *

        * Contains {@link DimensionType#OVERWORLD} by default but can be removed. */ -public final class DimensionTypeManager { - - private final List dimensionTypes = new CopyOnWriteArrayList<>(); - - public DimensionTypeManager() { - addDimension(DimensionType.OVERWORLD); - } +public interface DimensionTypeManager { /** * Adds a new dimension type. This does NOT send the new list to players. * * @param dimensionType the dimension to add */ - public void addDimension(@NotNull DimensionType dimensionType) { - dimensionType.registered = true; - this.dimensionTypes.add(dimensionType); - } + void addDimension(@NotNull DimensionType dimensionType); /** * Removes a dimension type. This does NOT send the new list to players. @@ -40,25 +27,20 @@ public void addDimension(@NotNull DimensionType dimensionType) { * @param dimensionType the dimension to remove * @return if the dimension type was removed, false if it was not present before */ - public boolean removeDimension(@NotNull DimensionType dimensionType) { - dimensionType.registered = false; - return dimensionTypes.remove(dimensionType); - } + boolean removeDimension(@NotNull DimensionType dimensionType); /** - * @param namespaceID The dimension name + * @param dimensionType dimension to check if is registered * @return true if the dimension is registered */ - public boolean isRegistered(@NotNull NamespaceID namespaceID) { - return isRegistered(getDimension(namespaceID)); - } + boolean isRegistered(@Nullable DimensionType dimensionType); /** - * @param dimensionType dimension to check if is registered + * @param namespaceID The dimension name * @return true if the dimension is registered */ - public boolean isRegistered(@Nullable DimensionType dimensionType) { - return dimensionType != null && dimensionTypes.contains(dimensionType) && dimensionType.isRegistered(); + default boolean isRegistered(@NotNull NamespaceID namespaceID) { + return isRegistered(getDimension(namespaceID)); } /** @@ -67,18 +49,14 @@ public boolean isRegistered(@Nullable DimensionType dimensionType) { * @param namespaceID The Dimension Name * @return a DimensionType if it is present and registered */ - public @Nullable DimensionType getDimension(@NotNull NamespaceID namespaceID) { - return unmodifiableList().stream().filter(dimensionType -> dimensionType.getName().equals(namespaceID)).filter(DimensionType::isRegistered).findFirst().orElse(null); - } + @Nullable DimensionType getDimension(@NotNull NamespaceID namespaceID); /** * Returns an immutable copy of the dimension types already registered. * * @return an unmodifiable {@link List} containing all the added dimensions */ - public @NotNull List unmodifiableList() { - return Collections.unmodifiableList(dimensionTypes); - } + @NotNull List unmodifiableList(); /** * Creates the {@link NBTCompound} containing all the registered dimensions. @@ -87,15 +65,5 @@ public boolean isRegistered(@Nullable DimensionType dimensionType) { * * @return an nbt compound containing the registered dimensions */ - public @NotNull NBTCompound toNBT() { - return NBT.Compound(dimensions -> { - dimensions.setString("type", "minecraft:dimension_type"); - dimensions.set("value", NBT.List( - NBTType.TAG_Compound, - dimensionTypes.stream() - .map(DimensionType::toIndexedNBT) - .toList() - )); - }); - } + @NotNull NBTCompound toNBT(); } diff --git a/src/main/java/net/minestom/server/world/DimensionTypeManagerImpl.java b/src/main/java/net/minestom/server/world/DimensionTypeManagerImpl.java new file mode 100644 index 00000000000..8a0fb093b33 --- /dev/null +++ b/src/main/java/net/minestom/server/world/DimensionTypeManagerImpl.java @@ -0,0 +1,61 @@ +package net.minestom.server.world; + +import net.minestom.server.utils.NamespaceID; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jglrxavpok.hephaistos.nbt.NBT; +import org.jglrxavpok.hephaistos.nbt.NBTCompound; +import org.jglrxavpok.hephaistos.nbt.NBTType; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +public final class DimensionTypeManagerImpl implements DimensionTypeManager { + + private final List dimensionTypes = new CopyOnWriteArrayList<>(); + + public DimensionTypeManagerImpl() { + addDimension(DimensionType.OVERWORLD); + } + + @Override + public void addDimension(@NotNull DimensionType dimensionType) { + dimensionType.registered = true; + this.dimensionTypes.add(dimensionType); + } + + @Override + public boolean removeDimension(@NotNull DimensionType dimensionType) { + dimensionType.registered = false; + return dimensionTypes.remove(dimensionType); + } + + @Override + public boolean isRegistered(@Nullable DimensionType dimensionType) { + return dimensionType != null && dimensionTypes.contains(dimensionType) && dimensionType.isRegistered(); + } + + @Override + public @Nullable DimensionType getDimension(@NotNull NamespaceID namespaceID) { + return unmodifiableList().stream().filter(dimensionType -> dimensionType.getName().equals(namespaceID)).filter(DimensionType::isRegistered).findFirst().orElse(null); + } + + @Override + public @NotNull List unmodifiableList() { + return Collections.unmodifiableList(dimensionTypes); + } + + @Override + public @NotNull NBTCompound toNBT() { + return NBT.Compound(dimensions -> { + dimensions.setString("type", "minecraft:dimension_type"); + dimensions.set("value", NBT.List( + NBTType.TAG_Compound, + dimensionTypes.stream() + .map(DimensionType::toIndexedNBT) + .toList() + )); + }); + } +} diff --git a/src/main/java/net/minestom/server/world/DimensionTypeManagerProvider.java b/src/main/java/net/minestom/server/world/DimensionTypeManagerProvider.java new file mode 100644 index 00000000000..bd6a7404081 --- /dev/null +++ b/src/main/java/net/minestom/server/world/DimensionTypeManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.world; + +public interface DimensionTypeManagerProvider { + DimensionTypeManager getDimensionTypeManager(); +} diff --git a/src/main/java/net/minestom/server/world/biomes/BiomeManager.java b/src/main/java/net/minestom/server/world/biomes/BiomeManager.java index 3c7ffdbe624..710b00ee6ee 100644 --- a/src/main/java/net/minestom/server/world/biomes/BiomeManager.java +++ b/src/main/java/net/minestom/server/world/biomes/BiomeManager.java @@ -1,54 +1,37 @@ package net.minestom.server.world.biomes; import net.minestom.server.utils.NamespaceID; -import org.jglrxavpok.hephaistos.nbt.NBT; import org.jglrxavpok.hephaistos.nbt.NBTCompound; -import org.jglrxavpok.hephaistos.nbt.NBTType; import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - /** * Allows servers to register custom dimensions. Also used during player joining to send the list of all existing dimensions. *

        * Contains {@link Biome#PLAINS} by default but can be removed. */ -public final class BiomeManager { - private final Map biomes = new ConcurrentHashMap<>(); - - public BiomeManager() { - addBiome(Biome.PLAINS); - } +public interface BiomeManager { /** * Adds a new biome. This does NOT send the new list to players. * * @param biome the biome to add */ - public void addBiome(Biome biome) { - this.biomes.put(biome.id(), biome); - } + void addBiome(Biome biome); /** * Removes a biome. This does NOT send the new list to players. * * @param biome the biome to remove */ - public void removeBiome(Biome biome) { - this.biomes.remove(biome.id()); - } + void removeBiome(Biome biome); /** * Returns an immutable copy of the biomes already registered. * * @return an immutable copy of the biomes already registered */ - public Collection unmodifiableCollection() { - return Collections.unmodifiableCollection(biomes.values()); - } + Collection unmodifiableCollection(); /** * Gets a biome by its id. @@ -56,24 +39,9 @@ public Collection unmodifiableCollection() { * @param id the id of the biome * @return the {@link Biome} linked to this id */ - public Biome getById(int id) { - return biomes.get(id); - } + Biome getById(int id); - public Biome getByName(NamespaceID namespaceID) { - Biome biome = null; - for (final Biome biomeT : biomes.values()) { - if (biomeT.name().equals(namespaceID)) { - biome = biomeT; - break; - } - } - return biome; - } + Biome getByName(NamespaceID namespaceID); - public NBTCompound toNBT() { - return NBT.Compound(Map.of( - "type", NBT.String("minecraft:worldgen/biome"), - "value", NBT.List(NBTType.TAG_Compound, biomes.values().stream().map(Biome::toNbt).toList()))); - } + NBTCompound toNBT(); } diff --git a/src/main/java/net/minestom/server/world/biomes/BiomeManagerImpl.java b/src/main/java/net/minestom/server/world/biomes/BiomeManagerImpl.java new file mode 100644 index 00000000000..4f990b5d4aa --- /dev/null +++ b/src/main/java/net/minestom/server/world/biomes/BiomeManagerImpl.java @@ -0,0 +1,58 @@ +package net.minestom.server.world.biomes; + +import net.minestom.server.utils.NamespaceID; +import org.jglrxavpok.hephaistos.nbt.NBT; +import org.jglrxavpok.hephaistos.nbt.NBTCompound; +import org.jglrxavpok.hephaistos.nbt.NBTType; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class BiomeManagerImpl implements BiomeManager { + private final Map biomes = new ConcurrentHashMap<>(); + + public BiomeManagerImpl() { + addBiome(Biome.PLAINS); + } + + @Override + public void addBiome(Biome biome) { + this.biomes.put(biome.id(), biome); + } + + @Override + public void removeBiome(Biome biome) { + this.biomes.remove(biome.id()); + } + + @Override + public Collection unmodifiableCollection() { + return Collections.unmodifiableCollection(biomes.values()); + } + + @Override + public Biome getById(int id) { + return biomes.get(id); + } + + @Override + public Biome getByName(NamespaceID namespaceID) { + Biome biome = null; + for (final Biome biomeT : biomes.values()) { + if (biomeT.name().equals(namespaceID)) { + biome = biomeT; + break; + } + } + return biome; + } + + @Override + public NBTCompound toNBT() { + return NBT.Compound(Map.of( + "type", NBT.String("minecraft:worldgen/biome"), + "value", NBT.List(NBTType.TAG_Compound, biomes.values().stream().map(Biome::toNbt).toList()))); + } +} diff --git a/src/main/java/net/minestom/server/world/biomes/BiomeManagerProvider.java b/src/main/java/net/minestom/server/world/biomes/BiomeManagerProvider.java new file mode 100644 index 00000000000..1d7fbac64c6 --- /dev/null +++ b/src/main/java/net/minestom/server/world/biomes/BiomeManagerProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server.world.biomes; + +public interface BiomeManagerProvider { + BiomeManager getBiomeManager(); +} diff --git a/src/test/java/net/minestom/server/ServerProcessTest.java b/src/test/java/net/minestom/server/ServerProcessTest.java index 9e9a2e1a28c..8a6cc973b61 100644 --- a/src/test/java/net/minestom/server/ServerProcessTest.java +++ b/src/test/java/net/minestom/server/ServerProcessTest.java @@ -16,8 +16,8 @@ public void init() { // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); - AtomicReference process = new AtomicReference<>(); - assertDoesNotThrow(() -> process.set(ServerProcess.of(ServerSettings.builder().build()))); + AtomicReference process = new AtomicReference<>(); + assertDoesNotThrow(() -> process.set(ServerFacade.of(ServerSettings.builder().build()))); assertDoesNotThrow(() -> process.get().start(new InetSocketAddress("localhost", 25565))); assertThrows(Exception.class, () -> process.get().start(new InetSocketAddress("localhost", 25566))); assertDoesNotThrow(() -> process.get().stop()); @@ -28,9 +28,9 @@ public void tick() { // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); - var process = ServerProcess.of(ServerSettings.builder().build()); + var process = ServerFacade.of(ServerSettings.builder().build()); process.start(new InetSocketAddress("localhost", 25565)); - var ticker = process.ticker(); + var ticker = process.getTicker(); assertDoesNotThrow(() -> ticker.tick(System.currentTimeMillis())); assertDoesNotThrow(process::stop); } diff --git a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java index 7fc892c540e..ba37fa0875f 100644 --- a/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java +++ b/src/test/java/net/minestom/server/collision/EntityProjectileCollisionIntegrationTest.java @@ -44,8 +44,8 @@ public void blockShootAndBlockRemoval(Env env) { final var eventRef = new AtomicReference(); env.process().getGlobalEventHandler().addListener(ProjectileCollideWithBlockEvent.class, eventRef::set); - final long tick = TimeUnit.getServerTick(env.process().getServerSetting()).getDuration().toMillis(); - for (int i = 0; i < env.process().getServerSetting().getTickPerSecond(); ++i) { + final long tick = TimeUnit.getServerTick(env.process().getServerSettings()).getDuration().toMillis(); + for (int i = 0; i < env.process().getServerSettings().getTickPerSecond(); ++i) { projectile.tick(i * tick); } @@ -59,8 +59,8 @@ public void blockShootAndBlockRemoval(Env env) { eventRef.set(null); instance.setBlock(blockPosition, Block.AIR); - for (int i = 0; i < env.process().getServerSetting().getTickPerSecond(); ++i) { - projectile.tick((env.process().getServerSetting().getTickPerSecond() + i) * tick); + for (int i = 0; i < env.process().getServerSettings().getTickPerSecond(); ++i) { + projectile.tick((env.process().getServerSettings().getTickPerSecond() + i) * tick); } event = eventRef.get(); final var event2 = eventRef2.get(); @@ -103,8 +103,8 @@ private void singleEntityShoot( }); shooter.getServerProcess().getGlobalEventHandler().addChild(eventNode); - final long tick = TimeUnit.getServerTick(instance.getServerProcess().getServerSetting()).getDuration().toMillis(); - for (int i = 0; i < instance.getServerProcess().getServerSetting().getTickPerSecond(); ++i) { + final long tick = TimeUnit.getServerTick(instance.getServerProcess().getServerSettings()).getDuration().toMillis(); + for (int i = 0; i < instance.getServerProcess().getServerSettings().getTickPerSecond(); ++i) { if (!projectile.isRemoved()) { projectile.tick(i * tick); } @@ -136,8 +136,8 @@ public void entitySelfShoot(Env env) { eventRef.set(event); }); - final long tick = TimeUnit.getServerTick(env.process().getServerSetting()).getDuration().toMillis(); - for (int i = 0; i < env.process().getServerSetting().getTickPerSecond() * 5; ++i) { + final long tick = TimeUnit.getServerTick(env.process().getServerSettings()).getDuration().toMillis(); + for (int i = 0; i < env.process().getServerSettings().getTickPerSecond() * 5; ++i) { if (!projectile.isRemoved()) { projectile.tick(i * tick); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTest.java b/src/test/java/net/minestom/server/command/ArgumentTest.java index c80c87d62b2..63a92f30bbf 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.Argument; @@ -17,9 +17,9 @@ public class ArgumentTest { @Test public void testParseSelf() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertEquals("example", Argument.parse(new ServerSender(serverProcess), ArgumentType.String("example"))); - assertEquals(55, Argument.parse(new ServerSender(serverProcess), ArgumentType.Integer("55"))); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + assertEquals("example", Argument.parse(new ServerSender(serverFacade), ArgumentType.String("example"))); + assertEquals(55, Argument.parse(new ServerSender(serverFacade), ArgumentType.Integer("55"))); } @Test @@ -34,18 +34,18 @@ public void testCallback() { @Test public void testDefaultValue() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var arg = ArgumentType.String("id"); assertFalse(arg.isOptional()); arg.setDefaultValue("default value"); assertTrue(arg.isOptional()); - assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(serverProcess))); + assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(serverFacade))); } @Test public void testSuggestionCallback() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var arg = ArgumentType.String("id"); assertFalse(arg.hasSuggestion()); @@ -54,7 +54,7 @@ public void testSuggestionCallback() { assertTrue(arg.hasSuggestion()); Suggestion suggestion = new Suggestion("input", 2, 4); - arg.getSuggestionCallback().apply(new ServerSender(serverProcess), new CommandContext("input"), suggestion); + arg.getSuggestionCallback().apply(new ServerSender(serverFacade), new CommandContext("input"), suggestion); assertEquals(suggestion.getEntries(), List.of(new SuggestionEntry("entry"))); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java index f9a2466546d..0e529078832 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java @@ -5,7 +5,7 @@ import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentEnum; @@ -378,17 +378,17 @@ enum ExampleEnum {FIRST, SECOND, Third, fourth} @Test public void testArgumentGroup() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var arg = ArgumentType.Group("group", ArgumentType.Integer("integer"), ArgumentType.String("string"), ArgumentType.Double("double")); // Test normal input - var context1 = arg.parse(new ServerSender(serverProcess), "1234 1234 1234"); + var context1 = arg.parse(new ServerSender(serverFacade), "1234 1234 1234"); assertEquals(1234, context1.get("integer")); assertEquals("1234", context1.get("string")); assertEquals(1234.0, context1.get("double")); // Test different input + trailing spaces - var context2 = arg.parse(new ServerSender(serverProcess), "1234 abcd 1234.5678 "); + var context2 = arg.parse(new ServerSender(serverFacade), "1234 abcd 1234.5678 "); assertEquals(1234, context2.get("integer")); assertEquals("abcd", context2.get("string")); assertEquals(1234.5678, context2.get("double")); @@ -455,8 +455,8 @@ public void testArgumentWord() { @Test public void testArgumentMapWithSender() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var serverSender = new ServerSender(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var serverSender = new ServerSender(serverFacade); var arg = ArgumentType.Word("word").from("word1", "word2", "word3") .map((sender, s) -> { @@ -468,22 +468,22 @@ public void testArgumentMapWithSender() { } private static void assertArg(Argument arg, T expected, String input) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertEquals(expected, arg.parse(new ServerSender(serverProcess), input)); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + assertEquals(expected, arg.parse(new ServerSender(serverFacade), input)); } private static void assertArrayArg(Argument arg, T[] expected, String input) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertArrayEquals(expected, arg.parse(new ServerSender(serverProcess), input)); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + assertArrayEquals(expected, arg.parse(new ServerSender(serverFacade), input)); } private static void assertValidArg(Argument arg, String input) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertDoesNotThrow(() -> arg.parse(new ServerSender(serverProcess), input)); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + assertDoesNotThrow(() -> arg.parse(new ServerSender(serverFacade), input)); } private static void assertInvalidArg(Argument arg, String input) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(serverProcess), input)); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(serverFacade), input)); } } diff --git a/src/test/java/net/minestom/server/command/CommandConditionTest.java b/src/test/java/net/minestom/server/command/CommandConditionTest.java index d3c020b557c..c37a3759661 100644 --- a/src/test/java/net/minestom/server/command/CommandConditionTest.java +++ b/src/test/java/net/minestom/server/command/CommandConditionTest.java @@ -1,7 +1,7 @@ package net.minestom.server.command; import net.kyori.adventure.identity.Identity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; @@ -19,8 +19,8 @@ public class CommandConditionTest { @Test public void mainCondition() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var dispatcher = new CommandDispatcher(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(serverFacade); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -43,8 +43,8 @@ public void mainCondition() { @Test public void subCondition() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var dispatcher = new CommandDispatcher(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(serverFacade); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -88,8 +88,8 @@ public void subCondition() { @Test public void subConditionOverride() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var dispatcher = new CommandDispatcher(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(serverFacade); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -147,7 +147,7 @@ private static final class Sender implements CommandSender { } @Override - public ServerProcess getServerProcess() { + public ServerFacade getServerProcess() { return null; } } diff --git a/src/test/java/net/minestom/server/command/CommandManagerTest.java b/src/test/java/net/minestom/server/command/CommandManagerTest.java index 8074fa46e80..41a7016b7e7 100644 --- a/src/test/java/net/minestom/server/command/CommandManagerTest.java +++ b/src/test/java/net/minestom/server/command/CommandManagerTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandResult; @@ -16,8 +16,8 @@ public class CommandManagerTest { @Test public void testCommandRegistration() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); var command = new Command("name1", "name2"); @@ -36,8 +36,8 @@ public void testCommandRegistration() { @Test public void testUnknownCommandCallback() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); AtomicBoolean check = new AtomicBoolean(false); manager.setUnknownCommandCallback((sender, command) -> check.set(true)); @@ -53,8 +53,8 @@ public void testUnknownCommandCallback() { @Test public void testSharedArgumentSyntaxABFirst() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); @@ -82,8 +82,8 @@ public void testSharedArgumentSyntaxABFirst() { @Test public void testSharedArgumentSyntaxAFirst() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java index adf151c0da7..1da4df2f121 100644 --- a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java +++ b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -13,8 +13,8 @@ @SuppressWarnings("ConstantConditions") public class CommandPacketFilteringTest { - private static final ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - private static final Player PLAYER = new Player(serverProcess, UUID.randomUUID(), "", null); + private static final ServerFacade SERVER_FACADE = ServerFacade.of(ServerSettings.builder().build()); + private static final Player PLAYER = new Player(SERVER_FACADE, UUID.randomUUID(), "", null); @Test public void singleCommandFilteredFalse() { diff --git a/src/test/java/net/minestom/server/command/CommandParseTest.java b/src/test/java/net/minestom/server/command/CommandParseTest.java index eb5a0f19a5c..b7ef9762b35 100644 --- a/src/test/java/net/minestom/server/command/CommandParseTest.java +++ b/src/test/java/net/minestom/server/command/CommandParseTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.arguments.ArgumentType; import org.jetbrains.annotations.NotNull; @@ -145,8 +145,8 @@ private static void assertValid(Graph graph, String input, AtomicBoolean executo } private static CommandParser.Result parseCommand(Graph graph, String input) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - return CommandParser.parser().parse(new ServerSender(serverProcess), graph, input); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + return CommandParser.parser().parse(new ServerSender(serverFacade), graph, input); } @NotNull diff --git a/src/test/java/net/minestom/server/command/CommandSenderTest.java b/src/test/java/net/minestom/server/command/CommandSenderTest.java index 1297886c450..d4805b73d41 100644 --- a/src/test/java/net/minestom/server/command/CommandSenderTest.java +++ b/src/test/java/net/minestom/server/command/CommandSenderTest.java @@ -4,7 +4,7 @@ import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -85,7 +85,7 @@ public void sendMessage(@NotNull Identity source, @NotNull Component message, @N } @Override - public ServerProcess getServerProcess() { + public ServerFacade getServerProcess() { return null; } } diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java index 7441b1f069d..f3943e3b0f6 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.Argument; @@ -46,10 +46,10 @@ public void similarArgs() { } private static void assertSyntax(List>> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); final String commandName = "name"; - var manager = new CommandManager(serverProcess); + var manager = new CommandManagerImpl(serverFacade); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java index adcd7bc0cb1..cecf85f2141 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -148,10 +148,10 @@ public void singleLoopDoubleGroup() { } private static void assertSyntax(List> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); final String commandName = "name"; - var manager = new CommandManager(serverProcess); + var manager = new CommandManagerImpl(serverFacade); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandTest.java b/src/test/java/net/minestom/server/command/CommandTest.java index e8fdcec81a9..b9d7afb6587 100644 --- a/src/test/java/net/minestom/server/command/CommandTest.java +++ b/src/test/java/net/minestom/server/command/CommandTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -30,8 +30,8 @@ public void testNames() { @Test public void testGlobalListener() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); AtomicBoolean hasRun = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/SubcommandTest.java b/src/test/java/net/minestom/server/command/SubcommandTest.java index 8365100946d..732bc0de300 100644 --- a/src/test/java/net/minestom/server/command/SubcommandTest.java +++ b/src/test/java/net/minestom/server/command/SubcommandTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import org.junit.jupiter.api.Test; @@ -14,8 +14,8 @@ public class SubcommandTest { @Test public void testSubCommands() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); var parent = new Command("parent"); var child = new Command("child"); @@ -37,8 +37,8 @@ public void testSubCommands() { @Test public void testSubCommandConditions() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var manager = new CommandManager(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(serverFacade); var parent = new Command("parent"); var child = new Command("child"); diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index d305e9bf10f..5cf943b0b16 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.entity.EntityTickEvent; import net.minestom.server.network.packet.server.play.DestroyEntitiesPacket; @@ -48,7 +48,7 @@ public void instanceRemoval(Env env) { @Test public void tickTimedRemoval(Env env) throws InterruptedException { var instance = env.createFlatInstance(); - var entity = new TestEntity(env.process(), 2, TimeUnit.getServerTick(env.process().getServerSetting())); + var entity = new TestEntity(env.process(), 2, TimeUnit.getServerTick(env.process().getServerSettings())); entity.setInstance(instance, new Pos(0, 40, 0)).join(); assertFalse(entity.isRemoved()); @@ -98,8 +98,8 @@ public void entityNodeGC(Env env) { } static final class TestEntity extends Entity { - public TestEntity(ServerProcess serverProcess, long delay, TemporalUnit unit) { - super(serverProcess, EntityType.ZOMBIE); + public TestEntity(ServerFacade serverFacade, long delay, TemporalUnit unit) { + super(serverFacade, EntityType.ZOMBIE); scheduleRemove(delay, unit); } } diff --git a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java index 2f57d4cd7c2..c9590d6d234 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerMovementIntegrationTest.java @@ -63,7 +63,7 @@ public void singleTickMovementUpdate(Env env) { @Test public void chunkUpdateDebounceTest(Env env) { final Instance flatInstance = env.createFlatInstance(); - final int viewDiameter = env.process().getServerSetting().getChunkViewDistance() * 2 + 1; + final int viewDiameter = env.process().getServerSettings().getChunkViewDistance() * 2 + 1; // Preload all possible chunks to avoid issues due to async loading Set> chunks = new HashSet<>(); ChunkUtils.forChunksInRange(0, 0, viewDiameter+2, (x, z) -> chunks.add(flatInstance.loadChunk(x, z))); diff --git a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java index 77f4132d242..b384809675f 100644 --- a/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/player/PlayerRespawnChunkIntegrationTest.java @@ -45,7 +45,7 @@ public void testChunkReloadCount(Env env) { player.setHealth(0); player.respawn(); // Player should have all their chunks reloaded - int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.process().getServerSetting().getChunkViewDistance(), player.getSettings().getViewDistance())); + int chunkLoads = ChunkUtils.getChunkCount(Math.min(env.process().getServerSettings().getChunkViewDistance(), player.getSettings().getViewDistance())); loadChunkTracker.assertCount(chunkLoads); } @@ -61,7 +61,7 @@ public void testPlayerTryRespawn(Env env) { player.interpretPacketQueue(); List dataPacketList = loadChunkTracker.collect(); Set duplicateCheck = new HashSet<>(); - int actualViewDistance = Math.min(env.process().getServerSetting().getChunkViewDistance(), player.getSettings().getViewDistance()); + int actualViewDistance = Math.min(env.process().getServerSettings().getChunkViewDistance(), player.getSettings().getViewDistance()); int chunkLoads = ChunkUtils.getChunkCount(actualViewDistance); loadChunkTracker.assertCount(chunkLoads); for (ChunkDataPacket packet : dataPacketList) { diff --git a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java index cf352b0220d..6a511ea269a 100644 --- a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import org.junit.jupiter.api.Test; @@ -12,16 +12,16 @@ public class EventNodeGraphTest { @Test public void single() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - EventNode node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + EventNode node = EventNode.all(serverFacade,"main"); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of())); } @Test public void singleChild() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - EventNode node = EventNode.all(serverProcess,"main"); - node.addChild(EventNode.all(serverProcess,"child")); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + EventNode node = EventNode.all(serverFacade,"main"); + node.addChild(EventNode.all(serverFacade,"child")); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child", "Event", 0, List.of()) ))); @@ -29,20 +29,20 @@ public void singleChild() { @Test public void childrenPriority() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); { - EventNode node = EventNode.all(serverProcess,"main"); - node.addChild(EventNode.all(serverProcess,"child1").setPriority(5)); - node.addChild(EventNode.all(serverProcess,"child2").setPriority(10)); + EventNode node = EventNode.all(serverFacade,"main"); + node.addChild(EventNode.all(serverFacade,"child1").setPriority(5)); + node.addChild(EventNode.all(serverFacade,"child2").setPriority(10)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) ))); } { - EventNode node = EventNode.all(serverProcess, "main"); - node.addChild(EventNode.all(serverProcess,"child2").setPriority(10)); - node.addChild(EventNode.all(serverProcess,"child1").setPriority(5)); + EventNode node = EventNode.all(serverFacade, "main"); + node.addChild(EventNode.all(serverFacade,"child2").setPriority(10)); + node.addChild(EventNode.all(serverFacade,"child1").setPriority(5)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) diff --git a/src/test/java/net/minestom/server/event/EventNodeMapTest.java b/src/test/java/net/minestom/server/event/EventNodeMapTest.java index 528da5d6672..d7c9c52e058 100644 --- a/src/test/java/net/minestom/server/event/EventNodeMapTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeMapTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -18,9 +18,9 @@ public class EventNodeMapTest { @Test public void uniqueMapping() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(serverProcess,"main"); + var node = EventNode.all(serverFacade,"main"); var itemNode1 = node.map(item, EventFilter.ITEM); var itemNode2 = node.map(item, EventFilter.ITEM); assertNotNull(itemNode1); @@ -34,9 +34,9 @@ public void uniqueMapping() { @Test public void lazyRegistration() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all(serverProcess,"main"); + var node = (EventNodeImpl) EventNode.all(serverFacade,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertFalse(node.registeredMappedNode.containsKey(item)); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { @@ -46,9 +46,9 @@ public void lazyRegistration() { @Test public void secondMap() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all(serverProcess,"main"); + var node = (EventNodeImpl) EventNode.all(serverFacade,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertSame(itemNode, itemNode.map(item, EventFilter.ITEM)); assertThrows(Exception.class, () -> itemNode.map(ItemStack.AIR, EventFilter.ITEM)); @@ -56,9 +56,9 @@ public void secondMap() { @Test public void map() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(serverProcess, "main"); + var node = EventNode.all(serverFacade, "main"); AtomicBoolean result = new AtomicBoolean(false); var itemNode = node.map(item, EventFilter.ITEM); @@ -82,9 +82,9 @@ public void map() { @Test public void entityLocal() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = serverProcess.getGlobalEventHandler(); - var entity = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = serverFacade.getGlobalEventHandler(); + var entity = new Entity(serverFacade, EntityType.ZOMBIE); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventNodeTest.EntityTestEvent.class, event -> result.set(true)); @@ -108,10 +108,10 @@ public void entityLocal() { @Test public void ownerGC() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // Ensure that the mapped object gets GCed var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(serverProcess,"main"); + var node = EventNode.all(serverFacade,"main"); var itemNode = node.map(item, EventFilter.ITEM); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { }); diff --git a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java index 49044e3fbc2..871e9b7d4df 100644 --- a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.event.trait.EntityEvent; import net.minestom.server.event.trait.PlayerEvent; @@ -15,13 +15,13 @@ public class EventNodeQueryTest { @Test public void find() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess, "main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade, "main"); assertEquals(List.of(), node.findChildren("test")); - var child1 = EventNode.all(serverProcess,"test"); - var child2 = EventNode.all(serverProcess,"test"); - var child3 = EventNode.all(serverProcess,"test3"); + var child1 = EventNode.all(serverFacade,"test"); + var child2 = EventNode.all(serverFacade,"test"); + var child3 = EventNode.all(serverFacade,"test3"); node.addChild(child1); node.addChild(child2); @@ -37,13 +37,13 @@ public void find() { @Test public void findType() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); assertEquals(List.of(), node.findChildren("test", Event.class)); - var child1 = EventNode.type(serverProcess, "test", EventFilter.PLAYER); - var child2 = EventNode.type(serverProcess, "test", EventFilter.ENTITY); - var child3 = EventNode.type(serverProcess, "test3", EventFilter.ENTITY); + var child1 = EventNode.type(serverFacade, "test", EventFilter.PLAYER); + var child2 = EventNode.type(serverFacade, "test", EventFilter.ENTITY); + var child3 = EventNode.type(serverFacade, "test3", EventFilter.ENTITY); node.addChild(child1); node.addChild(child2); @@ -63,19 +63,19 @@ public void findType() { @Test public void replace() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); - var child1 = EventNode.all(serverProcess,"test"); - var child2 = EventNode.all(serverProcess,"test"); - var child3 = EventNode.all(serverProcess,"test3"); + var child1 = EventNode.all(serverFacade,"test"); + var child2 = EventNode.all(serverFacade,"test"); + var child3 = EventNode.all(serverFacade,"test3"); node.addChild(child1); node.addChild(child2); node.addChild(child3); - var tmp1 = EventNode.all(serverProcess,"tmp1"); - var tmp2 = EventNode.all(serverProcess,"tmp2"); + var tmp1 = EventNode.all(serverFacade,"tmp1"); + var tmp2 = EventNode.all(serverFacade,"tmp2"); node.replaceChildren("test", tmp1); assertEqualsIgnoreOrder(List.of(child2), node.findChildren("test")); diff --git a/src/test/java/net/minestom/server/event/EventNodeTest.java b/src/test/java/net/minestom/server/event/EventNodeTest.java index 055f498fc1b..db63e2a7235 100644 --- a/src/test/java/net/minestom/server/event/EventNodeTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.event.trait.CancellableEvent; @@ -60,8 +60,8 @@ record EntityTestEvent(Entity entity) implements EntityEvent { @Test public void testCall() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventTest.class, eventTest -> result.set(true)); node.addListener(listener); @@ -78,8 +78,8 @@ public void testCall() { @Test public void testHandle() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); var handle = node.getHandle(EventTest.class); assertSame(handle, node.getHandle(EventTest.class)); @@ -89,8 +89,8 @@ public void testHandle() { @Test public void testCancellable() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.builder(CancellableTest.class) .handler(event -> { @@ -109,8 +109,8 @@ public void testCancellable() { @Test public void recursiveSub() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); AtomicBoolean result1 = new AtomicBoolean(false); AtomicBoolean result2 = new AtomicBoolean(false); var listener1 = EventListener.of(Recursive1.class, event -> result1.set(true)); @@ -151,15 +151,15 @@ public void recursiveSub() { @Test public void testChildren() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); AtomicInteger result = new AtomicInteger(0); - var child1 = EventNode.all(serverProcess,"child1").setPriority(1) + var child1 = EventNode.all(serverFacade,"child1").setPriority(1) .addListener(EventTest.class, eventTest -> { assertEquals(0, result.get(), "child1 should be called before child2"); result.set(1); }); - var child2 = EventNode.all(serverProcess,"child2").setPriority(2) + var child2 = EventNode.all(serverFacade,"child2").setPriority(2) .addListener(EventTest.class, eventTest -> { assertEquals(1, result.get(), "child2 should be called after child1"); result.set(2); @@ -186,13 +186,13 @@ public void testChildren() { @Test public void testFiltering() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); AtomicBoolean result = new AtomicBoolean(false); AtomicBoolean childResult = new AtomicBoolean(false); - var node = EventNode.type(serverProcess,"item_node", EventFilter.ITEM, + var node = EventNode.type(serverFacade,"item_node", EventFilter.ITEM, (event, item) -> item.material() == Material.DIAMOND); - var child = EventNode.type(serverProcess,"item_node2", EventFilter.ITEM) + var child = EventNode.type(serverFacade,"item_node2", EventFilter.ITEM) .addListener(ItemTestEvent.class, event -> childResult.set(true)); node.addChild(child); @@ -211,8 +211,8 @@ public void testFiltering() { @Test public void testBinding() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); AtomicBoolean result = new AtomicBoolean(false); var binding = EventBinding.filtered(EventFilter.ITEM, itemStack -> itemStack.material() == Material.DIAMOND) @@ -234,8 +234,8 @@ public void testBinding() { @Test public void nodeEmptyGC() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); var ref = new WeakReference<>(node); //noinspection UnusedAssignment @@ -245,8 +245,8 @@ public void nodeEmptyGC() { @Test public void nodeGC() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); var ref = new WeakReference<>(node); node.addListener(EventTest.class, event -> { }); @@ -273,8 +273,8 @@ public void nodeGC() { @Test public void nodeMapGC() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var node = EventNode.all(serverProcess,"main"); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var node = EventNode.all(serverFacade,"main"); var handler = ItemStack.AIR; var mapped = node.map(handler, EventFilter.ITEM); diff --git a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java index 902ee850736..def04a6f0af 100644 --- a/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/ChunkViewerIntegrationTest.java @@ -36,7 +36,7 @@ public void basicJoin(boolean sharedInstance, Env env) { @Test public void renderDistance(Env env) { - final int viewRadius = env.process().getServerSetting().getChunkViewDistance(); + final int viewRadius = env.process().getServerSettings().getChunkViewDistance(); final int count = ChunkUtils.getChunkCount(viewRadius); var instance = env.createFlatInstance(); var connection = env.createConnection(); diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java index 6c780b3d8d6..4157ed3d26c 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -27,7 +27,7 @@ public void maxDistance(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = env.process().getServerSetting().getEntityViewDistance(); + final int viewDistanceInChunks = env.process().getServerSettings().getEntityViewDistance(); final Player viewer = createTestPlayer(env.process()); final AtomicInteger viewersCount = new AtomicInteger(); @@ -59,7 +59,7 @@ public void cornerInstanceSwap(Env env) { final Instance instance = env.createFlatInstance(); final Instance anotherInstance = env.createFlatInstance(); final Pos spawnPos = new Pos(0, 41, 0); - final int viewDistanceInChunks = env.process().getServerSetting().getEntityViewDistance(); + final int viewDistanceInChunks = env.process().getServerSettings().getEntityViewDistance(); final Player viewer = createTestPlayer(env.process()); final AtomicInteger viewersCount = new AtomicInteger(); @@ -129,8 +129,8 @@ public void viewableShared(Env env) { assertEquals(1, viewable.getViewers().size()); } - private Player createTestPlayer(ServerProcess serverProcess) { - return new Player(serverProcess, UUID.randomUUID(), "TestPlayer", new PlayerConnection(serverProcess) { + private Player createTestPlayer(ServerFacade serverFacade) { + return new Player(serverFacade, UUID.randomUUID(), "TestPlayer", new PlayerConnection(serverFacade) { @Override public void sendPacket(@NotNull SendablePacket packet) { // nothing diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java index 294906238ac..51c30305a71 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; @@ -16,8 +16,8 @@ public class EntityTrackerTest { @Test public void register() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -31,7 +31,7 @@ public void remove(@NotNull Entity entity) { fail("No other entity should be registered yet"); } }; - EntityTracker tracker = EntityTracker.newTracker(serverProcess); + EntityTracker tracker = EntityTracker.newTracker(serverFacade); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); assertTrue(chunkEntities.isEmpty()); @@ -44,8 +44,8 @@ public void remove(@NotNull Entity entity) { @Test public void move() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -58,7 +58,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverProcess); + EntityTracker tracker = EntityTracker.newTracker(serverFacade); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, updater); assertEquals(1, tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES).size()); @@ -70,11 +70,11 @@ public void remove(@NotNull Entity entity) { @Test public void tracking() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); - var ent2 = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); + var ent2 = new Entity(serverFacade, EntityType.ZOMBIE); - EntityTracker tracker = EntityTracker.newTracker(serverProcess); + EntityTracker tracker = EntityTracker.newTracker(serverFacade); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -130,10 +130,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearby() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); - var ent2 = new Entity(serverProcess, EntityType.ZOMBIE); - var ent3 = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); + var ent2 = new Entity(serverFacade, EntityType.ZOMBIE); + var ent3 = new Entity(serverFacade, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -146,7 +146,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverProcess); + EntityTracker tracker = EntityTracker.newTracker(serverFacade); tracker.register(ent2, new Vec(5, 0, 0), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(50, 0, 0), EntityTracker.Target.ENTITIES, updater); @@ -184,10 +184,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearbySingleChunk() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); - var ent2 = new Entity(serverProcess, EntityType.ZOMBIE); - var ent3 = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); + var ent2 = new Entity(serverFacade, EntityType.ZOMBIE); + var ent3 = new Entity(serverFacade, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -200,7 +200,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverProcess); + EntityTracker tracker = EntityTracker.newTracker(serverFacade); tracker.register(ent1, new Vec(5, 0, 5), EntityTracker.Target.ENTITIES, updater); tracker.register(ent2, new Vec(8, 0, 8), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(17, 0, 17), EntityTracker.Target.ENTITIES, updater); @@ -225,8 +225,8 @@ public void remove(@NotNull Entity entity) { @Test public void collectionView() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverProcess, EntityType.ZOMBIE); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -241,7 +241,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverProcess); + EntityTracker tracker = EntityTracker.newTracker(serverFacade); var entities = tracker.entities(); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); @@ -251,7 +251,7 @@ public void remove(@NotNull Entity entity) { assertEquals(1, entities.size()); assertEquals(1, chunkEntities.size()); - assertThrows(Exception.class, () -> entities.add(new Entity(serverProcess, EntityType.ZOMBIE))); - assertThrows(Exception.class, () -> chunkEntities.add(new Entity(serverProcess, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> entities.add(new Entity(serverFacade, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> chunkEntities.add(new Entity(serverFacade, EntityType.ZOMBIE))); } } diff --git a/src/test/java/net/minestom/server/instance/GeneratorTest.java b/src/test/java/net/minestom/server/instance/GeneratorTest.java index 91dfeecb58b..4a53ede725c 100644 --- a/src/test/java/net/minestom/server/instance/GeneratorTest.java +++ b/src/test/java/net/minestom/server/instance/GeneratorTest.java @@ -1,7 +1,5 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; -import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -31,13 +29,12 @@ public class GeneratorTest { @Test public void unitSize() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertDoesNotThrow(() -> dummyUnit(serverProcess, Vec.ZERO, new Vec(16))); - assertDoesNotThrow(() -> dummyUnit(serverProcess, new Vec(16), new Vec(32))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, new Vec(15), Vec.ZERO)); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, new Vec(15), new Vec(32))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, new Vec(15), new Vec(31))); - assertThrows(IllegalArgumentException.class, () -> dummyUnit(serverProcess, Vec.ZERO, new Vec(15))); + assertDoesNotThrow(() -> dummyUnit(Vec.ZERO, new Vec(16))); + assertDoesNotThrow(() -> dummyUnit(new Vec(16), new Vec(32))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(new Vec(15), Vec.ZERO)); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(new Vec(15), new Vec(32))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(new Vec(15), new Vec(31))); + assertThrows(IllegalArgumentException.class, () -> dummyUnit(Vec.ZERO, new Vec(15))); } @ParameterizedTest @@ -80,15 +77,14 @@ private static Stream sectionCeilParam() { @Test public void chunkSize() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - GenerationUnit chunk = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); assertEquals(new Vec(16, sectionCount * 16, 16), chunk.size()); assertEquals(new Vec(chunkX * 16, minSection * 16, chunkZ * 16), chunk.absoluteStart()); assertEquals(new Vec(chunkX * 16 + 16, maxSection * 16, chunkZ * 16 + 16), chunk.absoluteEnd()); @@ -96,15 +92,14 @@ public void chunkSize() { @Test public void chunkSizeNeg() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - GenerationUnit chunk = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); assertEquals(new Vec(16, sectionCount * 16, 16), chunk.size()); assertEquals(new Vec(chunkX * 16, minSection * 16, chunkZ * 16), chunk.absoluteStart()); assertEquals(new Vec(chunkX * 16 + 16, maxSection * 16, chunkZ * 16 + 16), chunk.absoluteEnd()); @@ -112,11 +107,10 @@ public void chunkSizeNeg() { @Test public void sectionSize() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int sectionX = 3; final int sectionY = -5; final int sectionZ = -2; - GenerationUnit section = GeneratorImpl.section(serverProcess, new Section(serverProcess), sectionX, sectionY, sectionZ); + GenerationUnit section = GeneratorImpl.section(new Section(), sectionX, sectionY, sectionZ); assertEquals(new Vec(16), section.size()); assertEquals(new Vec(sectionX * 16, sectionY * 16, sectionZ * 16), section.absoluteStart()); assertEquals(new Vec(sectionX * 16 + 16, sectionY * 16 + 16, sectionZ * 16 + 16), section.absoluteEnd()); @@ -124,15 +118,14 @@ public void sectionSize() { @Test public void chunkSubdivide() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - GenerationUnit chunk = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + GenerationUnit chunk = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); var subUnits = chunk.subdivide(); assertEquals(sectionCount, subUnits.size()); for (int i = 0; i < sectionCount; i++) { @@ -145,15 +138,14 @@ public void chunkSubdivide() { @Test public void chunkAbsolute() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); assertThrows(Exception.class, () -> modifier.setBlock(0, 0, 0, Block.STONE), "Block outside of chunk"); @@ -167,15 +159,14 @@ public void chunkAbsolute() { @Test public void chunkAbsoluteAll() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = 0; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); Set points = new HashSet<>(); @@ -196,15 +187,14 @@ public void chunkAbsoluteAll() { @Test public void chunkRelative() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); assertThrows(Exception.class, () -> modifier.setRelative(-1, 0, 0, Block.STONE)); @@ -224,15 +214,14 @@ public void chunkRelative() { @Test public void chunkRelativeAll() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); Set points = new HashSet<>(); @@ -254,15 +243,14 @@ public void chunkRelativeAll() { @Test public void chunkBiomeSet() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); modifier.setBiome(48, 0, -32, Biome.PLAINS); @@ -276,15 +264,14 @@ public void chunkBiomeSet() { @Test public void chunkBiomeFill() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int chunkX = 3; final int chunkZ = -2; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), chunkX, chunkZ); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), chunkX, chunkZ); Generator generator = chunk -> { var modifier = chunk.modifier(); modifier.fillBiome(Biome.PLAINS); @@ -298,13 +285,12 @@ public void chunkBiomeFill() { @Test public void chunkFillHeightExact() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), 3, -2); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), 3, -2); Generator generator = chunk -> chunk.modifier().fillHeight(0, 32, Block.STONE); generator.generate(chunkUnits); @@ -323,13 +309,12 @@ public void chunkFillHeightExact() { @Test public void chunkFillHeightOneOff() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); final int minSection = -1; final int maxSection = 5; final int sectionCount = maxSection - minSection; Section[] sections = new Section[sectionCount]; - Arrays.setAll(sections, i -> new Section(serverProcess)); - var chunkUnits = GeneratorImpl.chunk(serverProcess, minSection, maxSection, List.of(sections), 3, -2); + Arrays.setAll(sections, i -> new Section()); + var chunkUnits = GeneratorImpl.chunk(minSection, maxSection, List.of(sections), 3, -2); Generator generator = chunk -> chunk.modifier().fillHeight(1, 33, Block.STONE); generator.generate(chunkUnits); @@ -362,16 +347,15 @@ public void chunkFillHeightOneOff() { @Test public void sectionFill() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - Section section = new Section(serverProcess); - var chunkUnit = GeneratorImpl.section(serverProcess, section, -1, -1, 0); + Section section = new Section(); + var chunkUnit = GeneratorImpl.section(section, -1, -1, 0); Generator generator = chunk -> chunk.modifier().fill(Block.STONE); generator.generate(chunkUnit); section.blockPalette().getAll((x, y, z, value) -> assertEquals(Block.STONE.stateId(), value)); } - static GenerationUnit dummyUnit(ServerProcess serverProcess, Point start, Point end) { - return unit(serverProcess,null, start, end, null); + static GenerationUnit dummyUnit(Point start, Point end) { + return unit(null, start, end, null); } } diff --git a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java index e9e9cb2d2e6..fc2d0926647 100644 --- a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java @@ -1,10 +1,10 @@ package net.minestom.server.instance; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.tag.Tag; import net.minestom.server.world.DimensionType; -import net.minestom.server.world.DimensionTypeManager; +import net.minestom.server.world.DimensionTypeManagerImpl; import org.junit.jupiter.api.Test; import java.util.UUID; @@ -14,14 +14,14 @@ public class InstanceContainerTest { static { - new DimensionTypeManager().addDimension(DimensionType.OVERWORLD); + new DimensionTypeManagerImpl().addDimension(DimensionType.OVERWORLD); } @Test public void copyPreservesTag() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var tag = Tag.String("test"); - var instance = new InstanceContainer(serverProcess, UUID.randomUUID(), DimensionType.OVERWORLD); + var instance = new InstanceContainer(serverFacade, UUID.randomUUID(), DimensionType.OVERWORLD); instance.setTag(tag, "123"); var copyInstance = instance.copy(); diff --git a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java index 903ddb446b7..2317d4f4188 100644 --- a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java +++ b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -19,8 +19,8 @@ public class BlockLightTest { @Test public void empty() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); var result = LightCompute.compute(palette); for (byte light : result.light()) { assertEquals(0, light); @@ -29,8 +29,8 @@ public void empty() { @Test public void glowstone() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -41,8 +41,8 @@ public void glowstone() { @Test public void doubleGlowstone() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); @@ -56,8 +56,8 @@ public void doubleGlowstone() { @Test public void glowstoneBorder() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -75,8 +75,8 @@ public void glowstoneBorder() { @Test public void glowstoneBlock() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(0, 1, 1, Block.STONE.stateId()); var result = LightCompute.compute(palette); @@ -88,8 +88,8 @@ public void glowstoneBlock() { @Test public void isolated() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.STONE.stateId()); @@ -116,8 +116,8 @@ public void isolated() { @Test public void isolatedStair() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "east", @@ -139,8 +139,8 @@ public void isolatedStair() { @Test public void isolatedStairOpposite() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -167,8 +167,8 @@ public void isolatedStairOpposite() { @Test public void isolatedStairWest() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -198,8 +198,8 @@ public void isolatedStairWest() { @Test public void isolatedStairSouth() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.blocks(serverFacade); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "south", diff --git a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java index 03c54f70fa2..352389a8c8c 100644 --- a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.*; import net.minestom.server.instance.block.Block; @@ -127,7 +127,7 @@ public void test(Env env) throws URISyntaxException, IOException, AnvilException record SectionEntry(Palette blocks, byte[] sky, byte[] block) { } - private static Map retrieveSections(ServerProcess serverProcess) throws IOException, URISyntaxException, AnvilException { + private static Map retrieveSections(ServerFacade serverFacade) throws IOException, URISyntaxException, AnvilException { URL defaultImage = LightParityIntegrationTest.class.getResource("/net/minestom/server/instance/lighting/region/r.0.0.mca"); assert defaultImage != null; File imageFile = new File(defaultImage.toURI()); @@ -143,7 +143,7 @@ private static Map retrieveSections(ServerProcess serverProce for (int yLevel = chunk.getMinY(); yLevel <= chunk.getMaxY(); yLevel += 16) { var section = chunk.getSection((byte) (yLevel/16)); - var palette = loadBlocks(serverProcess, section); + var palette = loadBlocks(serverFacade, section); var sky = section.getSkyLights(); var block = section.getBlockLights(); sections.put(new Vec(x, section.getY(), z), new SectionEntry(palette, sky, block)); @@ -153,8 +153,8 @@ private static Map retrieveSections(ServerProcess serverProce return sections; } - private static Palette loadBlocks(ServerProcess serverProcess, ChunkSection section) throws AnvilException { - var palette = Palette.blocks(serverProcess); + private static Palette loadBlocks(ServerFacade serverFacade, ChunkSection section) throws AnvilException { + var palette = Palette.blocks(serverFacade); for (int x = 0; x < Chunk.CHUNK_SECTION_SIZE; x++) { for (int z = 0; z < Chunk.CHUNK_SECTION_SIZE; z++) { for (int y = 0; y < Chunk.CHUNK_SECTION_SIZE; y++) { diff --git a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java index 3bdfb525b43..ecdce962a8e 100644 --- a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.Instance; import net.minestom.server.instance.LightingChunk; @@ -17,7 +17,7 @@ @EnvTest public class WorldRelightIntegrationTest { - private @NotNull Instance createLightingInstance(@NotNull ServerProcess process) { + private @NotNull Instance createLightingInstance(@NotNull ServerFacade process) { var instance = process.getInstanceManager().createInstanceContainer(process); instance.setGenerator(unit -> { unit.modifier().fillHeight(39, 40, Block.STONE); diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java index 60dab1b3f5f..cbed9307d1e 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.palette; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.network.NetworkBuffer; import org.junit.jupiter.api.Test; @@ -14,24 +14,24 @@ public class PaletteOptimizationTest { @Test public void empty() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = createPalette(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = createPalette(serverFacade); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void single() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = createPalette(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = createPalette(serverFacade); palette.set(0, 0, 0, 1); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void random() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); var random = new Random(12345); - var palette = createPalette(serverProcess); + var palette = createPalette(serverFacade); palette.setAll((x, y, z) -> random.nextInt(256)); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> random.nextInt(2)); @@ -40,8 +40,8 @@ public void random() { @Test public void manualFill() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = createPalette(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = createPalette(serverFacade); palette.setAll((x, y, z) -> 1); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> 2); @@ -50,8 +50,8 @@ public void manualFill() { paletteEquals(palette.palette, palette.optimizedPalette()); } - AdaptivePalette createPalette(ServerProcess serverProcess) { - return (AdaptivePalette) Palette.blocks(serverProcess); + AdaptivePalette createPalette(ServerFacade serverFacade) { + return (AdaptivePalette) Palette.blocks(serverFacade); } void paletteEquals(Palette palette, Palette optimized) { diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java index 30bb0833cbb..9a2881908cb 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.palette; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -17,16 +17,15 @@ public class PaletteTest { @Test public void singlePlacement() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverProcess); + var palette = Palette.blocks(); palette.set(0, 0, 1, 1); assertEquals(1, palette.get(0, 0, 1)); } @Test public void placement() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { final int dimension = palette.dimension(); assertEquals(0, palette.get(0, 0, 0), "Default value should be 0"); @@ -61,9 +60,9 @@ public void placement() { @Test public void placementHighValue() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); final int value = 250_000; - for (Palette palette : testPalettes(serverProcess)) { + for (Palette palette : testPalettes(serverFacade)) { palette.set(0, 0, 1, value); assertEquals(value, palette.get(0, 0, 1)); } @@ -71,8 +70,8 @@ public void placementHighValue() { @Test public void negPlacement() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { assertThrows(IllegalArgumentException.class, () -> palette.set(-1, 0, 0, 64)); assertThrows(IllegalArgumentException.class, () -> palette.set(0, -1, 0, 64)); @@ -86,8 +85,7 @@ public void negPlacement() { @Test public void resize() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - Palette palette = Palette.newPalette(serverProcess,16, 5, 2); + Palette palette = Palette.newPalette(16, 5, 2); palette.set(0, 0, 0, 1); assertEquals(2, palette.bitsPerEntry()); palette.set(0, 0, 1, 2); @@ -106,8 +104,8 @@ public void resize() { @Test public void fill() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { assertEquals(0, palette.count()); palette.set(0, 0, 0, 5); @@ -138,8 +136,8 @@ public void fill() { @Test public void bulk() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { final int dimension = palette.dimension(); // Place @@ -164,8 +162,8 @@ public void bulk() { @Test public void bulkAll() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { // Fill all entries palette.setAll((x, y, z) -> x + y + z + 1); @@ -183,8 +181,8 @@ public void bulkAll() { @Test public void bulkAllOrder() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { AtomicInteger count = new AtomicInteger(); @@ -222,8 +220,8 @@ public void bulkAllOrder() { @Test public void setAllConstant() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { palette.setAll((x, y, z) -> 1); palette.getAll((x, y, z, value) -> assertEquals(1, value)); @@ -232,8 +230,8 @@ public void setAllConstant() { @Test public void getAllPresent() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { palette.getAllPresent((x, y, z, value) -> fail("The palette should be empty")); palette.set(0, 0, 1, 1); @@ -248,8 +246,8 @@ public void getAllPresent() { @Test public void replaceAll() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { palette.setAll((x, y, z) -> x + y + z + 1); palette.replaceAll((x, y, z, value) -> { @@ -262,8 +260,8 @@ public void replaceAll() { @Test public void replace() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverProcess); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palettes = testPalettes(serverFacade); for (Palette palette : palettes) { palette.set(0, 0, 0, 1); palette.replace(0, 0, 0, operand -> { @@ -276,8 +274,8 @@ public void replace() { @Test public void replaceLoop() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var palette = Palette.newPalette(serverProcess,2, 15, 4); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var palette = Palette.newPalette(2, 15, 4); palette.setAll((x, y, z) -> x + y + z); final int dimension = palette.dimension(); for (int x = 0; x < dimension; x++) { @@ -291,22 +289,22 @@ public void replaceLoop() { @Test public void dimension() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,-4, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,0, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,1, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(serverProcess,2, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,3, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(serverProcess,4, 5, 3)); - assertThrows(Exception.class, () -> Palette.newPalette(serverProcess,6, 5, 3)); - assertDoesNotThrow(() -> Palette.newPalette(serverProcess,16, 5, 3)); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + assertThrows(Exception.class, () -> Palette.newPalette(-4, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(0, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(1, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(2, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(3, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(4, 5, 3)); + assertThrows(Exception.class, () -> Palette.newPalette(6, 5, 3)); + assertDoesNotThrow(() -> Palette.newPalette(16, 5, 3)); } - private static List testPalettes(ServerProcess serverProcess) { + private static List testPalettes(ServerFacade serverFacade) { return List.of( - Palette.newPalette(serverProcess,2, 5, 3), - Palette.newPalette(serverProcess,4, 5, 3), - Palette.newPalette(serverProcess,8, 5, 3), - Palette.newPalette(serverProcess,16, 5, 3)); + Palette.newPalette(2, 5, 3), + Palette.newPalette(4, 5, 3), + Palette.newPalette(8, 5, 3), + Palette.newPalette(16, 5, 3)); } } diff --git a/src/test/java/net/minestom/server/inventory/InventoryTest.java b/src/test/java/net/minestom/server/inventory/InventoryTest.java index 377d701ebef..0c2b544011a 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryTest.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; @@ -11,11 +11,11 @@ public class InventoryTest { - private static ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + private static ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); @Test public void testCreation() { - Inventory inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title"); assertEquals(InventoryType.CHEST_1_ROW, inventory.getInventoryType()); assertEquals(Component.text("title"), inventory.getTitle()); @@ -28,7 +28,7 @@ public void testEntry() { var item1 = ItemStack.of(Material.DIAMOND); var item2 = ItemStack.of(Material.GOLD_INGOT); - Inventory inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title"); assertSame(ItemStack.AIR, inventory.getItemStack(0)); inventory.setItemStack(0, item1); assertSame(item1, inventory.getItemStack(0)); @@ -52,7 +52,7 @@ public void testEntry() { @Test public void testTake() { ItemStack item = ItemStack.of(Material.DIAMOND, 32); - Inventory inventory = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title"); inventory.setItemStack(0, item); assertTrue(inventory.takeItemStack(item, TransactionOption.DRY_RUN)); assertTrue(inventory.takeItemStack(item.withAmount(31), TransactionOption.DRY_RUN)); @@ -65,7 +65,7 @@ public void testTake() { @Test public void testAdd() { - Inventory inventory = new Inventory(serverProcess, InventoryType.HOPPER, "title"); + Inventory inventory = new Inventory(serverFacade, InventoryType.HOPPER, "title"); assertTrue(inventory.addItemStack(ItemStack.of(Material.DIAMOND, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.GOLD_BLOCK, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.MAP, 32), TransactionOption.ALL_OR_NOTHING)); @@ -77,7 +77,7 @@ public void testAdd() { @Test public void testIds() { for (int i = 0; i <= 1000; ++i) { - final byte windowId = new Inventory(serverProcess, InventoryType.CHEST_1_ROW, "title").getWindowId(); + final byte windowId = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title").getWindowId(); assertTrue(windowId > 0); } } diff --git a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java index a7c20bfb041..12b0aad8e9c 100644 --- a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java +++ b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java @@ -1,9 +1,9 @@ package net.minestom.server.network.socket; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; -import net.minestom.server.listener.manager.PacketListenerManager; -import net.minestom.server.network.PacketProcessor; +import net.minestom.server.listener.manager.PacketListenerManagerImpl; +import net.minestom.server.network.PacketProcessorImpl; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -18,12 +18,12 @@ public class ServerAddressTest { @Test public void inetAddressTest() throws IOException { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 25565); - var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); + var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -35,12 +35,12 @@ public void inetAddressTest() throws IOException { @Test public void inetAddressDynamicTest() throws IOException { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 0); - var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); + var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -52,12 +52,12 @@ public void inetAddressDynamicTest() throws IOException { @Test public void unixAddressTest() throws IOException { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); UnixDomainSocketAddress address = UnixDomainSocketAddress.of("minestom.sock"); - var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); + var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); server.init(address); assertTrue(Files.exists(address.getPath())); assertSame(address, server.socketAddress()); @@ -71,8 +71,8 @@ public void unixAddressTest() throws IOException { @Test public void noAddressTest() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); - var server = new Server(serverProcess, new PacketProcessor(new PacketListenerManager(serverProcess))); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); assertDoesNotThrow(server::stop); } } diff --git a/src/test/java/net/minestom/server/permission/TestPermissions.java b/src/test/java/net/minestom/server/permission/TestPermissions.java index dafc4280267..7ffbdff68ce 100644 --- a/src/test/java/net/minestom/server/permission/TestPermissions.java +++ b/src/test/java/net/minestom/server/permission/TestPermissions.java @@ -1,6 +1,6 @@ package net.minestom.server.permission; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import org.jglrxavpok.hephaistos.nbt.NBT; @@ -20,12 +20,12 @@ public class TestPermissions { private Player player; private Permission permission1, permission2, permission3, wildcard; - private ServerProcess serverProcess; + private ServerFacade serverFacade; @BeforeEach public void init() { - serverProcess = ServerProcess.of(ServerSettings.builder().build()); - player = new Player(serverProcess, UUID.randomUUID(), "TestPlayer", null) { + serverFacade = ServerFacade.of(ServerSettings.builder().build()); + player = new Player(serverFacade, UUID.randomUUID(), "TestPlayer", null) { @Override protected void playerConnectionInit() { } diff --git a/src/test/java/net/minestom/server/thread/AcquirableTest.java b/src/test/java/net/minestom/server/thread/AcquirableTest.java index 86fc7bf26d0..e133229ab9e 100644 --- a/src/test/java/net/minestom/server/thread/AcquirableTest.java +++ b/src/test/java/net/minestom/server/thread/AcquirableTest.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -15,9 +15,9 @@ public class AcquirableTest { @Test public void assignation() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); AtomicReference tickThread = new AtomicReference<>(); - Entity entity = new Entity(serverProcess, EntityType.ZOMBIE) { + Entity entity = new Entity(serverFacade, EntityType.ZOMBIE) { @Override public void tick(long time) { super.tick(time); @@ -27,7 +27,7 @@ public void tick(long time) { Object first = new Object(); Object second = new Object(); - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess.getExceptionHandler(), ThreadProvider.counter(), 2); + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverFacade.getExceptionHandler(), ThreadProvider.counter(), 2); dispatcher.createPartition(first); dispatcher.createPartition(second); diff --git a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java index 3aed29f731f..93824fc1912 100644 --- a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java +++ b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.Tickable; import org.jetbrains.annotations.NotNull; @@ -20,11 +20,11 @@ public class ThreadDispatcherTest { @Test public void elementTick() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); final AtomicInteger counter = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess.getExceptionHandler()); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverFacade.getExceptionHandler()); assertEquals(1, dispatcher.threads().size()); - assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(serverProcess.getExceptionHandler(),1))); + assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(serverFacade.getExceptionHandler(),1))); var partition = new Object(); Tickable element = (time) -> counter.incrementAndGet(); @@ -49,11 +49,11 @@ public void elementTick() { @Test public void partitionTick() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // Partitions implementing Tickable should be ticked same as elements final AtomicInteger counter1 = new AtomicInteger(); final AtomicInteger counter2 = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverProcess.getExceptionHandler()); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverFacade.getExceptionHandler()); assertEquals(1, dispatcher.threads().size()); Tickable partition = (time) -> counter1.incrementAndGet(); @@ -79,10 +79,10 @@ public void partitionTick() { @Test public void uniqueThread() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // Ensure that partitions are properly dispatched across threads final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess.getExceptionHandler(), ThreadProvider.counter(), threadCount); + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverFacade.getExceptionHandler(), ThreadProvider.counter(), threadCount); assertEquals(threadCount, dispatcher.threads().size()); final AtomicInteger counter = new AtomicInteger(); @@ -109,7 +109,7 @@ public void uniqueThread() { @Test public void threadUpdate() { - ServerProcess serverProcess = ServerProcess.of(ServerSettings.builder().build()); + ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); // Ensure that partitions threads are properly updated every tick // when RefreshType.ALWAYS is used interface Updater extends Tickable { @@ -117,7 +117,7 @@ interface Updater extends Tickable { } final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverProcess.getExceptionHandler(), new ThreadProvider<>() { + ThreadDispatcher dispatcher = ThreadDispatcher.of(serverFacade.getExceptionHandler(), new ThreadProvider<>() { @Override public int findThread(@NotNull Updater partition) { return partition.getValue(); diff --git a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java index fc71f8346be..fcb9a7fcf82 100644 --- a/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java +++ b/src/test/java/net/minestom/server/utils/TranslationIntegrationTest.java @@ -39,7 +39,7 @@ public void testTranslationEnabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(env.process().getServerSetting(), List.of(player), packet); + PacketUtils.sendGroupedPacket(env.process().getServerSettings(), List.of(player), packet); // the message should not be changed if translations are enabled. // the translation of the message itself will be proceeded in PlayerConnectionImpl class @@ -58,7 +58,7 @@ public void testTranslationDisabled(final Env env) { MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = false; final var message = Component.translatable("test.key"); final var packet = new SystemChatPacket(message, false); - PacketUtils.sendGroupedPacket(env.process().getServerSetting(), List.of(player), packet); + PacketUtils.sendGroupedPacket(env.process().getServerSettings(), List.of(player), packet); collector.assertSingle(received -> { assertEquals(message, received.message()); diff --git a/testing/src/main/java/net/minestom/testing/Env.java b/testing/src/main/java/net/minestom/testing/Env.java index e41c8fea7b9..4a3d6c2b534 100644 --- a/testing/src/main/java/net/minestom/testing/Env.java +++ b/testing/src/main/java/net/minestom/testing/Env.java @@ -1,6 +1,6 @@ package net.minestom.testing; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; import net.minestom.server.event.Event; @@ -15,7 +15,7 @@ public interface Env { - @NotNull ServerProcess process(); + @NotNull ServerFacade process(); @NotNull TestConnection createConnection(); @@ -24,11 +24,11 @@ public interface Env { @NotNull FlexibleListener listen(@NotNull Class eventType); default void tick() { - process().ticker().tick(System.nanoTime()); + process().getTicker().tick(System.nanoTime()); } default boolean tickWhile(BooleanSupplier condition, Duration timeout) { - var ticker = process().ticker(); + var ticker = process().getTicker(); final long start = System.nanoTime(); while (condition.getAsBoolean()) { final long tick = System.nanoTime(); diff --git a/testing/src/main/java/net/minestom/testing/EnvImpl.java b/testing/src/main/java/net/minestom/testing/EnvImpl.java index a2a1ccc3438..c03092a71e4 100644 --- a/testing/src/main/java/net/minestom/testing/EnvImpl.java +++ b/testing/src/main/java/net/minestom/testing/EnvImpl.java @@ -1,6 +1,6 @@ package net.minestom.testing; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.event.Event; import net.minestom.server.event.EventFilter; @@ -15,15 +15,15 @@ import static org.junit.jupiter.api.Assertions.fail; final class EnvImpl implements Env { - private final ServerProcess process; + private final ServerFacade process; private final List> listeners = new CopyOnWriteArrayList<>(); public EnvImpl() { - this.process = ServerProcess.of(ServerSettings.builder().build()); + this.process = ServerFacade.of(ServerSettings.builder().build()); } @Override - public @NotNull ServerProcess process() { + public @NotNull ServerFacade process() { return process; } diff --git a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java index 857c30374ca..dc5744b9cc5 100644 --- a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java @@ -1,7 +1,7 @@ package net.minestom.testing; import net.kyori.adventure.translation.GlobalTranslator; -import net.minestom.server.ServerProcess; +import net.minestom.server.ServerFacade; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; @@ -24,7 +24,7 @@ final class TestConnectionImpl implements TestConnection { private final Env env; - private final ServerProcess process; + private final ServerFacade process; private final PlayerConnectionImpl playerConnection; private final List> incomingTrackers = new CopyOnWriteArrayList<>(); @@ -63,8 +63,8 @@ final class TestConnectionImpl implements TestConnection { final class PlayerConnectionImpl extends PlayerConnection { - PlayerConnectionImpl(ServerProcess serverProcess) { - super(serverProcess); + PlayerConnectionImpl(ServerFacade serverFacade) { + super(serverFacade); } @Override From 253970b8d0afad251c6a54f8545b287f16bb4716 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Wed, 31 Jan 2024 19:45:17 +0300 Subject: [PATCH 10/16] little improvements --- .../java/net/minestom/demo/PlayerInit.java | 2 +- .../demo/commands/DisplayCommand.java | 7 +- .../minestom/demo/commands/HorseCommand.java | 3 +- .../net/minestom/server/ServerFacadeImpl.java | 14 +- .../net/minestom/server/ServerSettings.java | 8 +- .../java/net/minestom/server/Viewable.java | 18 +- .../server/advancements/Advancement.java | 2 +- .../server/advancements/AdvancementTab.java | 2 +- .../audience/PacketGroupingAudience.java | 5 +- .../adventure/bossbar/BossBarListener.java | 14 +- .../adventure/bossbar/BossBarManagerImpl.java | 16 +- .../net/minestom/server/entity/Entity.java | 97 ++++---- .../server/entity/EntityCreature.java | 14 +- .../server/entity/EntityProjectile.java | 22 +- .../minestom/server/entity/EntityView.java | 2 +- .../minestom/server/entity/ExperienceOrb.java | 18 +- .../minestom/server/entity/ItemEntity.java | 14 +- .../minestom/server/entity/LivingEntity.java | 39 ++-- .../net/minestom/server/entity/Metadata.java | 4 +- .../net/minestom/server/entity/Player.java | 91 ++++---- .../server/entity/PlayerProjectile.java | 16 +- .../server/entity/fakeplayer/FakePlayer.java | 45 ++-- .../server/entity/hologram/Hologram.java | 18 +- .../minestom/server/event/EventHandler.java | 2 +- .../net/minestom/server/event/EventNode.java | 9 +- .../minestom/server/event/EventNodeImpl.java | 12 +- .../server/event/EventNodeLazyImpl.java | 6 +- .../server/event/GlobalEventHandlerImpl.java | 6 +- .../minestom/server/instance/AnvilLoader.java | 48 ++-- .../server/instance/DynamicChunk.java | 16 +- .../server/instance/EntityTracker.java | 6 +- .../server/instance/EntityTrackerImpl.java | 12 +- .../minestom/server/instance/Explosion.java | 2 +- .../minestom/server/instance/Instance.java | 208 +++++------------- .../server/instance/InstanceContainer.java | 107 +++++---- .../server/instance/InstanceManagerImpl.java | 42 ++-- .../server/instance/LightingChunk.java | 31 +-- .../server/instance/SharedInstance.java | 13 +- .../minestom/server/instance/WorldBorder.java | 2 +- .../server/inventory/EquipmentHandler.java | 2 +- .../minestom/server/inventory/Inventory.java | 6 +- .../server/inventory/PlayerInventory.java | 2 +- .../inventory/type/VillagerInventory.java | 6 +- .../server/listener/ChatMessageListener.java | 2 +- .../listener/PlayerDiggingListener.java | 2 +- .../server/listener/UseItemListener.java | 2 +- .../manager/PacketListenerManagerImpl.java | 31 +-- .../minestom/server/message/Messenger.java | 6 +- .../server/network/ConnectionManagerImpl.java | 24 +- .../server/network/PacketProcessorImpl.java | 10 +- .../network/packet/server/CachedPacket.java | 14 +- .../net/minestom/server/potion/Potion.java | 4 +- .../minestom/server/scoreboard/Sidebar.java | 10 +- .../minestom/server/scoreboard/TabList.java | 4 +- .../net/minestom/server/scoreboard/Team.java | 6 +- .../server/scoreboard/TeamManagerImpl.java | 4 +- .../server/snapshot/SnapshotImpl.java | 6 +- .../server/thread/ChunkDispatcher.java | 10 +- .../server/thread/ChunkDispatcherImpl.java | 6 +- .../server/thread/ThreadDispatcher.java | 10 +- .../server/thread/ThreadDispatcherImpl.java | 6 +- .../minestom/server/thread/TickThread.java | 12 +- .../minestom/server/timer/Schedulable.java | 2 +- .../minestom/server/utils/PacketUtils.java | 25 ++- .../entity/EntityRemovalIntegrationTest.java | 2 +- .../server/event/EventNodeMapTest.java | 4 +- .../InstanceUnregisterIntegrationTest.java | 4 +- .../minestom/testing/TestConnectionImpl.java | 2 +- 68 files changed, 594 insertions(+), 623 deletions(-) diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index 5a672c03a31..7752170383a 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -55,7 +55,7 @@ public PlayerInit(ServerFacade serverFacade) { InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); instanceContainer.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); - instanceContainer.setChunkSupplier((instance, chunkX, chunkZ) -> new LightingChunk(serverFacade.getBiomeManager(), serverFacade.getServerSettings(), serverFacade.getSchedulerManager(), instance, chunkX, chunkZ)); + instanceContainer.setChunkSupplier((instance, chunkX, chunkZ) -> new LightingChunk(serverFacade, instance, chunkX, chunkZ)); // var i2 = new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD, null, NamespaceID.from("minestom:demo")); // instanceManager.registerInstance(i2); diff --git a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java index 8e4704a4246..45059ef2ef8 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java @@ -20,7 +20,6 @@ import org.jetbrains.annotations.NotNull; import java.time.temporal.TemporalUnit; -import java.util.UUID; public class DisplayCommand extends Command { @@ -45,7 +44,7 @@ public void spawnItem(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.ITEM_DISPLAY, UUID.randomUUID()); + var entity = new Entity(serverFacade, EntityType.ITEM_DISPLAY); var meta = (ItemDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setItemStack(ItemStack.of(Material.STICK)); @@ -60,7 +59,7 @@ public void spawnBlock(@NotNull CommandSender sender, @NotNull CommandContext co if (!(sender instanceof Player player)) return; - var entity = new Entity(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.BLOCK_DISPLAY, UUID.randomUUID()); + var entity = new Entity(serverFacade, EntityType.BLOCK_DISPLAY); var meta = (BlockDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBlockState(Block.ORANGE_CANDLE_CAKE.stateId()); @@ -75,7 +74,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.TEXT_DISPLAY, UUID.randomUUID()); + var entity = new Entity(serverFacade, EntityType.TEXT_DISPLAY); var meta = (TextDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBillboardRenderConstraints(AbstractDisplayMeta.BillboardConstraints.CENTER); diff --git a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java index 797be4eff26..60c79aa035e 100644 --- a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java @@ -14,7 +14,6 @@ import net.minestom.server.entity.metadata.animal.HorseMeta; import java.util.Locale; -import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -64,7 +63,7 @@ private void onHorseCommand(CommandSender sender, CommandContext context) { boolean baby = context.get("baby"); HorseMeta.Marking marking = context.get("marking"); HorseMeta.Color color = context.get("color"); - var horse = new EntityCreature(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), EntityType.HORSE, UUID.randomUUID()); + var horse = new EntityCreature(serverFacade, EntityType.HORSE); var meta = (HorseMeta) horse.getEntityMeta(); meta.setBaby(baby); meta.setVariant(new HorseMeta.Variant(marking, color)); diff --git a/src/main/java/net/minestom/server/ServerFacadeImpl.java b/src/main/java/net/minestom/server/ServerFacadeImpl.java index ef92f8fc95a..7b6658ce506 100644 --- a/src/main/java/net/minestom/server/ServerFacadeImpl.java +++ b/src/main/java/net/minestom/server/ServerFacadeImpl.java @@ -76,14 +76,14 @@ final class ServerFacadeImpl implements ServerFacade { public ServerFacadeImpl(ServerSettings serverSettings) { this.serverSettings = serverSettings; this.exceptionHandler = new ExceptionHandlerImpl(); - this.globalEventHandler = new GlobalEventHandlerImpl(exceptionHandler); - this.packetListenerManager = new PacketListenerManagerImpl(globalEventHandler, exceptionHandler, this, this, this, this); - this.packetProcessor = new PacketProcessorImpl(packetListenerManager); - this.chunkDispatcher = ChunkDispatcher.singleThread(exceptionHandler); + this.globalEventHandler = new GlobalEventHandlerImpl(this); + this.packetListenerManager = new PacketListenerManagerImpl(this); + this.packetProcessor = new PacketProcessorImpl(this); + this.chunkDispatcher = ChunkDispatcher.singleThread(this); this.blockManager = new BlockManagerImpl(); - this.bossBarManager = new BossBarManagerImpl(serverSettings); + this.bossBarManager = new BossBarManagerImpl(this); this.biomeManager = new BiomeManagerImpl(); - this.instanceManager = new InstanceManagerImpl(chunkDispatcher, globalEventHandler, serverSettings, exceptionHandler, blockManager, biomeManager); + this.instanceManager = new InstanceManagerImpl(this); this.commandManager = new CommandManagerImpl(exceptionHandler, globalEventHandler); this.recipeManager = new RecipeManagerImpl(); @@ -94,7 +94,7 @@ public ServerFacadeImpl(ServerSettings serverSettings) { this.advancementManager = new AdvancementManagerImpl(serverSettings); this.tagManager = new TagManagerImpl(); this.teamManager = new TeamManagerImpl(serverSettings); - this.connectionManager = new ConnectionManagerImpl(serverSettings, globalEventHandler, chunkDispatcher, exceptionHandler, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, biomeManager, dimensionTypeManager, tagManager, blockManager); + this.connectionManager = new ConnectionManagerImpl(serverSettings, globalEventHandler, this, this, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, biomeManager, dimensionTypeManager, tagManager, blockManager); this.server = new ServerImpl(connectionManager, globalEventHandler, exceptionHandler, serverSettings, packetProcessor); this.audienceManager = new AudienceManagerImpl(connectionManager, commandManager, serverSettings); this.ticker = new TickerImpl(connectionManager, schedulerManager, server, globalEventHandler, exceptionHandler, instanceManager, chunkDispatcher); diff --git a/src/main/java/net/minestom/server/ServerSettings.java b/src/main/java/net/minestom/server/ServerSettings.java index 11b8bd1fa83..22f1c99f9a7 100644 --- a/src/main/java/net/minestom/server/ServerSettings.java +++ b/src/main/java/net/minestom/server/ServerSettings.java @@ -47,13 +47,13 @@ public int getTickMs() { return 1000 / tickPerSecond; } - public void updateBrandName(@NotNull String brandName, @NotNull ConnectionManager connectionManager, ServerSettings serverSettings) { + public void updateBrandName(@NotNull String brandName, @NotNull ConnectionManager connectionManager, ServerSettingsProvider serverSettingsProvider) { setBrandName(brandName); - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, PluginMessagePacket.getBrandPacket(this)); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, PluginMessagePacket.getBrandPacket(this)); } - public void updateDifficulty(@NotNull Difficulty difficulty, @NotNull ConnectionManager connectionManager, ServerSettings serverSettings) { + public void updateDifficulty(@NotNull Difficulty difficulty, @NotNull ConnectionManager connectionManager, ServerSettingsProvider serverSettingsProvider) { setDifficulty(difficulty); - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new ServerDifficultyPacket(difficulty, true)); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new ServerDifficultyPacket(difficulty, true)); } } diff --git a/src/main/java/net/minestom/server/Viewable.java b/src/main/java/net/minestom/server/Viewable.java index e4dee734ff2..8f3e32ecbb7 100644 --- a/src/main/java/net/minestom/server/Viewable.java +++ b/src/main/java/net/minestom/server/Viewable.java @@ -58,33 +58,33 @@ default boolean isViewer(@NotNull Player player) { * * @param packet the packet to send to all viewers */ - default void sendPacketToViewers(ServerSettings serverSettings, @NotNull SendablePacket packet) { + default void sendPacketToViewers(ServerSettingsProvider serverSettingsProvider, @NotNull SendablePacket packet) { if (packet instanceof ServerPacket serverPacket) { - PacketUtils.sendGroupedPacket(serverSettings, getViewers(), serverPacket); + PacketUtils.sendGroupedPacket(serverSettingsProvider, getViewers(), serverPacket); } else { getViewers().forEach(player -> player.sendPacket(packet)); } } - default void sendPacketsToViewers(ServerSettings serverSettings, @NotNull Collection packets) { + default void sendPacketsToViewers(ServerSettingsProvider serverSettingsProvider, @NotNull Collection packets) { for (SendablePacket packet : packets) { - sendPacketToViewers(serverSettings, packet); + sendPacketToViewers(serverSettingsProvider, packet); } } - default void sendPacketsToViewers(ServerSettings serverSettings, @NotNull SendablePacket... packets) { - sendPacketsToViewers(serverSettings, List.of(packets)); + default void sendPacketsToViewers(ServerSettingsProvider serverSettingsProvider, @NotNull SendablePacket... packets) { + sendPacketsToViewers(serverSettingsProvider, List.of(packets)); } /** * Sends a packet to all viewers and the viewable element if it is a player. *

        - * If 'this' isn't a player, then only {@link #sendPacketToViewers(ServerSettings, SendablePacket)} is called. + * If 'this' isn't a player, then only {@link #sendPacketToViewers(ServerSettingsProvider, SendablePacket)} is called. * * @param packet the packet to send */ - default void sendPacketToViewersAndSelf(ServerSettings serverSettings, @NotNull SendablePacket packet) { - sendPacketToViewers(serverSettings, packet); + default void sendPacketToViewersAndSelf(ServerSettingsProvider serverSettingsProvider, @NotNull SendablePacket packet) { + sendPacketToViewers(serverSettingsProvider, packet); } /** diff --git a/src/main/java/net/minestom/server/advancements/Advancement.java b/src/main/java/net/minestom/server/advancements/Advancement.java index 9b5e6cb352c..cddd43a4546 100644 --- a/src/main/java/net/minestom/server/advancements/Advancement.java +++ b/src/main/java/net/minestom/server/advancements/Advancement.java @@ -332,7 +332,7 @@ protected AdvancementsPacket getUpdatePacket() { protected void update() { updateCriteria(); if (tab != null) { - tab.sendPacketsToViewers(serverSettings, tab.removePacket, tab.createPacket()); + tab.sendPacketsToViewers(() -> serverSettings, tab.removePacket, tab.createPacket()); } } diff --git a/src/main/java/net/minestom/server/advancements/AdvancementTab.java b/src/main/java/net/minestom/server/advancements/AdvancementTab.java index da2a8005d0a..2e04304cd58 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementTab.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementTab.java @@ -77,7 +77,7 @@ public void createAdvancement(@NotNull String identifier, @NotNull Advancement a "You tried to set a parent which doesn't exist or isn't registered"); cacheAdvancement(identifier, advancement, parent); if (!getViewers().isEmpty()) { - sendPacketToViewers(serverSettings, advancement.getUpdatePacket()); + sendPacketToViewers(() -> serverSettings, advancement.getUpdatePacket()); } } diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index 6e74a495822..9b74ade4e43 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -66,12 +66,13 @@ public ServerSettings getServerSettings() { * @param packet the packet to broadcast */ default void sendGroupedPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(getServerSettings(), getPlayers(), packet); + PacketUtils.sendGroupedPacket(this::getServerSettings, getPlayers(), packet); } + @SuppressWarnings("UnstableApiUsage") @Override default void sendMessage(@NotNull Identity source, @NotNull Component message, @NotNull MessageType type) { - Messenger.sendMessage(getServerSettings(), this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); + Messenger.sendMessage(this::getServerSettings, this.getPlayers(), message, ChatPosition.fromMessageType(type), source.uuid()); } @Override diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java index 45e0c0a3124..4144b46e5fa 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java @@ -4,7 +4,7 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; @@ -20,34 +20,34 @@ @RequiredArgsConstructor class BossBarListener implements BossBar.Listener { - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; private final BossBarManagerImpl manager; @Override public void bossBarNameChanged(@NotNull BossBar bar, @NotNull Component oldName, @NotNull Component newName) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createTitleUpdate(newName))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createTitleUpdate(newName))); } @Override public void bossBarProgressChanged(@NotNull BossBar bar, float oldProgress, float newProgress) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createPercentUpdate(newProgress))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createPercentUpdate(newProgress))); } @Override public void bossBarColorChanged(@NotNull BossBar bar, @NotNull BossBar.Color oldColor, @NotNull BossBar.Color newColor) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createColorUpdate(newColor))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createColorUpdate(newColor))); } @Override public void bossBarOverlayChanged(@NotNull BossBar bar, BossBar.@NotNull Overlay oldOverlay, BossBar.@NotNull Overlay newOverlay) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createOverlayUpdate(newOverlay))); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createOverlayUpdate(newOverlay))); } @Override public void bossBarFlagsChanged(@NotNull BossBar bar, @NotNull Set flagsAdded, @NotNull Set flagsRemoved) { - this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createFlagsUpdate())); + this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createFlagsUpdate())); } private void doIfRegistered(@NotNull BossBar bar, @NotNull Consumer consumer) { diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java index a62f1c9a671..a906e3e375e 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarManagerImpl.java @@ -1,7 +1,7 @@ package net.minestom.server.adventure.bossbar; import net.kyori.adventure.bossbar.BossBar; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.entity.Player; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.NotNull; @@ -13,14 +13,14 @@ public class BossBarManagerImpl implements BossBarManager { private final BossBarListener listener; private final Map> playerBars = new ConcurrentHashMap<>(); final Map bars = new ConcurrentHashMap<>(); - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; /** * Creates a new boss bar manager. */ - public BossBarManagerImpl(ServerSettings serverSettings) { - this.serverSettings = serverSettings; - this.listener = new BossBarListener(serverSettings,this); + public BossBarManagerImpl(ServerSettingsProvider serverSettingsProvider) { + this.serverSettingsProvider = serverSettingsProvider; + this.listener = new BossBarListener(serverSettingsProvider,this); } @Override @@ -46,7 +46,7 @@ public void addBossBar(@NotNull Collection players, @NotNull BossBar bar BossBarHolder holder = this.getOrCreateHandler(bar); Collection addedPlayers = players.stream().filter(holder::addViewer).toList(); if (!addedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(serverSettings, addedPlayers, holder.createAddPacket()); + PacketUtils.sendGroupedPacket(serverSettingsProvider, addedPlayers, holder.createAddPacket()); } } @@ -56,7 +56,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar if (holder != null) { Collection removedPlayers = players.stream().filter(holder::removeViewer).toList(); if (!removedPlayers.isEmpty()) { - PacketUtils.sendGroupedPacket(serverSettings, removedPlayers, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(serverSettingsProvider, removedPlayers, holder.createRemovePacket()); } } } @@ -65,7 +65,7 @@ public void removeBossBar(@NotNull Collection players, @NotNull BossBar public void destroyBossBar(@NotNull BossBar bossBar) { BossBarHolder holder = this.bars.remove(bossBar); if (holder != null) { - PacketUtils.sendGroupedPacket(serverSettings, holder.players, holder.createRemovePacket()); + PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createRemovePacket()); for (Player player : holder.players) { this.removePlayer(player, holder); } diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index b3687593aed..dfb8814c85a 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -7,7 +7,7 @@ import net.kyori.adventure.text.event.HoverEvent.ShowEntity; import net.kyori.adventure.text.event.HoverEventSource; import net.minestom.server.ServerFacade; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Tickable; import net.minestom.server.Viewable; import net.minestom.server.collision.*; @@ -16,15 +16,15 @@ import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.EntityMeta; import net.minestom.server.entity.metadata.LivingEntityMeta; -import net.minestom.server.event.Event; import net.minestom.server.event.EventFilter; import net.minestom.server.event.EventHandler; import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.entity.*; import net.minestom.server.event.instance.AddEntityToInstanceEvent; import net.minestom.server.event.instance.RemoveEntityFromInstanceEvent; import net.minestom.server.event.trait.EntityEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.EntityTracker; import net.minestom.server.instance.Instance; @@ -48,7 +48,7 @@ import net.minestom.server.tag.TagHandler; import net.minestom.server.tag.Taggable; import net.minestom.server.thread.Acquirable; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.timer.Schedulable; import net.minestom.server.timer.Scheduler; import net.minestom.server.timer.TaskSchedule; @@ -97,11 +97,11 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev private final CachedPacket destroyPacketCache; @Getter // FIXME bad shit - protected final ServerSettings serverSettings; + protected final ServerSettingsProvider serverSettingsProvider; + protected final ChunkDispatcherProvider chunkDispatcherProvider; + protected final ExceptionHandlerProvider exceptionHandlerProvider; @Getter // FIXME bad shit - protected final EventNode globalEventHandler; - protected final ThreadDispatcher dispatcher; - protected final ExceptionHandler exceptionHandler; + protected final GlobalEventHandler globalEventHandler; protected Instance instance; protected Chunk currentChunk; @@ -189,19 +189,26 @@ public void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracke private final Acquirable acquirable = Acquirable.of(this); - public Entity(ServerFacade serverFacade, @NotNull EntityType entityType) { + public Entity(@NotNull ServerFacade serverFacade, @NotNull EntityType entityType) { this(serverFacade, entityType, UUID.randomUUID()); } - public Entity(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { - this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), entityType, uuid); + public Entity(@NotNull ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, entityType, uuid); } - public Entity(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull EntityType entityType, @NotNull UUID uuid) { - this.serverSettings = serverSettings; + public Entity( + @NotNull GlobalEventHandler globalEventHandler, + @NotNull ServerSettingsProvider serverSettingsProvider, + @NotNull ChunkDispatcherProvider chunkDispatcherProvider, + @NotNull ExceptionHandlerProvider exceptionHandlerProvider, + @NotNull EntityType entityType, + @NotNull UUID uuid + ) { this.globalEventHandler = globalEventHandler; - this.dispatcher = dispatcher; - this.exceptionHandler = exceptionHandler; + this.serverSettingsProvider = serverSettingsProvider; + this.chunkDispatcherProvider = chunkDispatcherProvider; + this.exceptionHandlerProvider = exceptionHandlerProvider; this.id = generateId(); this.entityType = entityType; this.uuid = uuid; @@ -218,10 +225,10 @@ public Entity(ServerSettings serverSettings, EventNode globalEventHandler this.gravityAcceleration = entityType.registry().acceleration(); this.gravityDragPerTick = entityType.registry().drag(); - + this.eventNode = globalEventHandler.map(this, EventFilter.ENTITY); - destroyPacketCache = new CachedPacket(serverSettings, () -> new DestroyEntitiesPacket(getEntityId())); + destroyPacketCache = new CachedPacket(serverSettingsProvider, () -> new DestroyEntitiesPacket(getEntityId())); } /** @@ -595,7 +602,7 @@ private void velocityTick() { if (!hasVelocity && noGravity) { return; } - final float tps = serverSettings.getTickPerSecond(); + final float tps = serverSettingsProvider.getServerSettings().getTickPerSecond(); final Pos positionBeforeMove = getPosition(); final Vec currentVelocity = getVelocity(); final boolean wasOnGround = this.onGround; @@ -633,7 +640,7 @@ private void velocityTick() { ); if (this.ticks % VELOCITY_UPDATE_INTERVAL == 0) { if (!isPlayer && !this.lastVelocityWasZero) { - sendPacketToViewers(serverSettings, getVelocityPacket()); + sendPacketToViewers(serverSettingsProvider, getVelocityPacket()); this.lastVelocityWasZero = !hasVelocity; } } @@ -666,7 +673,7 @@ private void velocityTick() { // Verify if velocity packet has to be sent if (this.ticks % VELOCITY_UPDATE_INTERVAL == 0) { if (!isPlayer && (hasVelocity || !lastVelocityWasZero)) { - sendPacketToViewers(serverSettings, getVelocityPacket()); + sendPacketToViewers(serverSettingsProvider, getVelocityPacket()); this.lastVelocityWasZero = !hasVelocity; } } @@ -694,7 +701,7 @@ protected void updateVelocity(boolean wasOnGround, boolean flying, Pos positionB z * drag )) // Convert from block/tick to block/sec - .mul(serverSettings.getTickPerSecond()) + .mul(serverSettingsProvider.getServerSettings().getTickPerSecond()) // Prevent infinitely decreasing velocity .apply(Vec.Operator.EPSILON); } @@ -739,7 +746,7 @@ private void effectTick(long time) { effects.removeIf(timedPotion -> { long duration = timedPotion.getPotion().duration(); if (duration == Potion.INFINITE_DURATION) return false; - final long potionTime = duration * serverSettings.getTickMs(); + final long potionTime = duration * serverSettingsProvider.getServerSettings().getTickMs(); // Remove if the potion should be expired if (time >= timedPotion.getStartingTime() + potionTime) { // Send the packet that the potion should no longer be applied @@ -859,7 +866,7 @@ public void setBoundingBox(BoundingBox boundingBox) { @ApiStatus.Internal protected void refreshCurrentChunk(Chunk currentChunk) { this.currentChunk = currentChunk; - dispatcher.updateElement(this, currentChunk); + chunkDispatcherProvider.getChunkDispatcher().updateElement(this, currentChunk); } /** @@ -909,7 +916,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull spawn(); globalEventHandler.call(new EntitySpawnEvent(this, instance)); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } }); } @@ -957,7 +964,7 @@ public void setVelocity(@NotNull Vec velocity) { EntityVelocityEvent entityVelocityEvent = new EntityVelocityEvent(this, velocity); globalEventHandler.callCancellable(entityVelocityEvent, () -> { this.velocity = entityVelocityEvent.getVelocity(); - sendPacketToViewersAndSelf(serverSettings, getVelocityPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getVelocityPacket()); }); } @@ -1069,7 +1076,7 @@ public void addPassenger(@NotNull Entity entity) { entity.setInstance(currentInstance, position).join(); this.passengers.add(entity); entity.vehicle = this; - sendPacketToViewersAndSelf(serverSettings, getPassengersPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getPassengersPacket()); // Updates the position of the new passenger, and then teleports the passenger updatePassengerPosition(position, entity); entity.synchronizePosition(false); @@ -1086,7 +1093,7 @@ public void removePassenger(@NotNull Entity entity) { Check.stateCondition(instance == null, "You need to set an instance using Entity#setInstance"); if (!passengers.remove(entity)) return; entity.vehicle = null; - sendPacketToViewersAndSelf(serverSettings, getPassengersPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getPassengersPacket()); entity.synchronizePosition(false); } @@ -1118,7 +1125,7 @@ public boolean hasPassenger() { * @param status the status to trigger */ public void triggerStatus(byte status) { - sendPacketToViewersAndSelf(serverSettings, new EntityStatusPacket(getEntityId(), status)); + sendPacketToViewersAndSelf(serverSettingsProvider, new EntityStatusPacket(getEntityId(), status)); } /** @@ -1344,21 +1351,21 @@ public void refreshPosition(@NotNull final Pos newPosition, boolean ignoreView) final Chunk chunk = getChunk(); if (distanceX > 8 || distanceY > 8 || distanceZ > 8) { - PacketUtils.prepareViewablePacket(serverSettings, chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); } else if (positionChange && viewChange) { - PacketUtils.prepareViewablePacket(serverSettings, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); // Fix head rotation - PacketUtils.prepareViewablePacket(serverSettings, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); } else if (positionChange) { // This is a confusing fix for a confusing issue. If rotation is only sent when the entity actually changes, then spawning an entity // on the ground causes the entity not to update its rotation correctly. It works fine if the entity is spawned in the air. Very weird. - PacketUtils.prepareViewablePacket(serverSettings, chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, onGround), this); } else if (viewChange) { - PacketUtils.prepareViewablePacket(serverSettings, chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); - PacketUtils.prepareViewablePacket(serverSettings,chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), chunk, new EntityHeadLookPacket(getEntityId(), position.yaw()), this); + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), chunk, EntityPositionAndRotationPacket.getPacket(getEntityId(), position, lastSyncedPosition, isOnGround()), this); } this.lastSyncedPosition = position; @@ -1548,7 +1555,7 @@ protected void remove(boolean permanent) { try { despawn(); } catch (Throwable t) { - exceptionHandler.handleException(t); + exceptionHandlerProvider.getExceptionHandler().handleException(t); } // Remove passengers if any (also done with LivingEntity#kill) @@ -1557,7 +1564,7 @@ protected void remove(boolean permanent) { final Entity vehicle = this.vehicle; if (vehicle != null) vehicle.removePassenger(this); - dispatcher.removeElement(this); + chunkDispatcherProvider.getChunkDispatcher().removeElement(this); this.removed = true; if (permanent) { Entity.ENTITY_BY_ID.remove(id); @@ -1593,7 +1600,7 @@ public boolean isRemoved() { * @param temporalUnit the unit of the delay */ public void scheduleRemove(long delay, @NotNull TemporalUnit temporalUnit) { - if (temporalUnit.equals(TimeUnit.getServerTick(serverSettings))) { + if (temporalUnit.equals(TimeUnit.getServerTick(serverSettingsProvider.getServerSettings()))) { scheduleRemove(TaskSchedule.tick((int) delay)); } else { scheduleRemove(Duration.of(delay, temporalUnit)); @@ -1614,7 +1621,7 @@ private void scheduleRemove(TaskSchedule schedule) { } protected @NotNull Vec getVelocityForPacket() { - return this.velocity.mul(8000f / serverSettings.getTickPerSecond()); + return this.velocity.mul(8000f / serverSettingsProvider.getServerSettings().getTickPerSecond()); } protected @NotNull EntityVelocityPacket getVelocityPacket() { @@ -1643,14 +1650,14 @@ private void scheduleRemove(TaskSchedule schedule) { protected void synchronizePosition(boolean includeSelf) { final Pos posCache = this.position; final ServerPacket packet = new EntityTeleportPacket(getEntityId(), posCache, isOnGround()); - PacketUtils.prepareViewablePacket(serverSettings, currentChunk, packet, this); + PacketUtils.prepareViewablePacket(serverSettingsProvider.getServerSettings(), currentChunk, packet, this); this.lastAbsoluteSynchronizationTime = System.currentTimeMillis(); this.lastSyncedPosition = posCache; } private void synchronizeView() { - sendPacketToViewersAndSelf(serverSettings, new EntityHeadLookPacket(getEntityId(), position.yaw())); - sendPacketToViewersAndSelf(serverSettings, new EntityRotationPacket(getEntityId(), position.yaw(), position.pitch(), onGround)); + sendPacketToViewersAndSelf(serverSettingsProvider, new EntityHeadLookPacket(getEntityId(), position.yaw())); + sendPacketToViewersAndSelf(serverSettingsProvider, new EntityRotationPacket(getEntityId(), position.yaw(), position.pitch(), onGround)); } /** @@ -1689,7 +1696,7 @@ private Duration getSynchronizationCooldown() { } @Override - public @NotNull Scheduler scheduler() { + public @NotNull Scheduler getScheduler() { return scheduler; } @@ -1707,7 +1714,7 @@ private Duration getSynchronizationCooldown() { @Override @ApiStatus.Experimental - public @NotNull EventNode eventNode() { + public @NotNull EventNode getEventNode() { return eventNode; } @@ -1721,9 +1728,9 @@ private Duration getSynchronizationCooldown() { public void takeKnockback(float strength, final double x, final double z) { if (strength > 0) { //TODO check possible side effects of unnatural TPS (other than 20TPS) - strength *= serverSettings.getTickPerSecond(); + strength *= serverSettingsProvider.getServerSettings().getTickPerSecond(); final Vec velocityModifier = new Vec(x, z).normalize().mul(strength); - final double verticalLimit = .4d * serverSettings.getTickPerSecond(); + final double verticalLimit = .4d * serverSettingsProvider.getServerSettings().getTickPerSecond(); setVelocity(new Vec(velocity.x() / 2d - velocityModifier.x(), onGround ? Math.min(verticalLimit, velocity.y() / 2d + strength) : velocity.y(), diff --git a/src/main/java/net/minestom/server/entity/EntityCreature.java b/src/main/java/net/minestom/server/entity/EntityCreature.java index 69c1d448ddc..766355d38fc 100644 --- a/src/main/java/net/minestom/server/entity/EntityCreature.java +++ b/src/main/java/net/minestom/server/entity/EntityCreature.java @@ -8,13 +8,11 @@ import net.minestom.server.entity.ai.EntityAIGroup; import net.minestom.server.entity.pathfinding.NavigableEntity; import net.minestom.server.entity.pathfinding.Navigator; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.entity.EntityAttackEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Instance; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -41,14 +39,14 @@ public EntityCreature(ServerFacade serverFacade, @NotNull EntityType entityType) } public EntityCreature(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { - this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), entityType, uuid); + this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, entityType, uuid); } /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public EntityCreature(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull EntityType entityType, @NotNull UUID uuid) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, entityType, uuid); + public EntityCreature(GlobalEventHandler globalEventHandler, ServerSettings serverSettings, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, @NotNull EntityType entityType, @NotNull UUID uuid) { + super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, entityType, uuid); heal(); } diff --git a/src/main/java/net/minestom/server/entity/EntityProjectile.java b/src/main/java/net/minestom/server/entity/EntityProjectile.java index def815e528d..408873af123 100644 --- a/src/main/java/net/minestom/server/entity/EntityProjectile.java +++ b/src/main/java/net/minestom/server/entity/EntityProjectile.java @@ -1,22 +1,22 @@ package net.minestom.server.entity; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.collision.BoundingBox; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.projectile.ProjectileMeta; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.entity.EntityShootEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithEntityEvent; import net.minestom.server.event.entity.projectile.ProjectileUncollideEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,11 +36,15 @@ public class EntityProjectile extends Entity { private final Entity shooter; public EntityProjectile(@NotNull Entity shooter, @NotNull EntityType entityType) { - this(shooter.serverSettings, shooter.globalEventHandler, shooter.dispatcher, shooter.exceptionHandler, shooter, entityType); + this(shooter.globalEventHandler, shooter.serverSettingsProvider, shooter.chunkDispatcherProvider, shooter.exceptionHandlerProvider, shooter, entityType); } - public EntityProjectile(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @Nullable Entity shooter, @NotNull EntityType entityType) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, entityType, UUID.randomUUID()); + public EntityProjectile(ServerFacade serverFacade, @Nullable Entity shooter, @NotNull EntityType entityType) { + this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, shooter, entityType); + } + + public EntityProjectile(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, @Nullable Entity shooter, @NotNull EntityType entityType) { + super(globalEventHandler, serverSettingsProvider, chunkDispatcherProvider, exceptionHandlerProvider, entityType, UUID.randomUUID()); this.shooter = shooter; setup(); } @@ -106,7 +110,7 @@ public void tick(long time) { } super.onGround = true; this.velocity = Vec.ZERO; - sendPacketToViewersAndSelf(serverSettings, getVelocityPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getVelocityPacket()); setNoGravity(true); } else { if (!super.onGround) { diff --git a/src/main/java/net/minestom/server/entity/EntityView.java b/src/main/java/net/minestom/server/entity/EntityView.java index b96633c42b0..8a148d1d692 100644 --- a/src/main/java/net/minestom/server/entity/EntityView.java +++ b/src/main/java/net/minestom/server/entity/EntityView.java @@ -228,7 +228,7 @@ private Collection references() { final Point point = trackedLocation.point(); Int2ObjectOpenHashMap entityMap = new Int2ObjectOpenHashMap<>(lastSize); - instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.serverSettings.getEntityViewDistance(), target, + instance.getEntityTracker().nearbyEntitiesByChunkRange(point, entity.getServerSettingsProvider().getServerSettings().getEntityViewDistance(), target, (entity) -> entityMap.putIfAbsent(entity.getEntityId(), entity)); this.lastSize = entityMap.size(); return entityMap.values(); diff --git a/src/main/java/net/minestom/server/entity/ExperienceOrb.java b/src/main/java/net/minestom/server/entity/ExperienceOrb.java index 3b65f205ea9..700713e0f53 100644 --- a/src/main/java/net/minestom/server/entity/ExperienceOrb.java +++ b/src/main/java/net/minestom/server/entity/ExperienceOrb.java @@ -1,12 +1,11 @@ package net.minestom.server.entity; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.coordinate.Vec; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; +import net.minestom.server.thread.ChunkDispatcherProvider; import java.util.Comparator; import java.util.UUID; @@ -17,8 +16,11 @@ public class ExperienceOrb extends Entity { private Player target; private long lastTargetUpdateTick; - public ExperienceOrb(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, short experienceCount) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.EXPERIENCE_ORB, UUID.randomUUID()); + public ExperienceOrb(ServerFacade serverFacade, short experienceCount) { + this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, experienceCount); + } + public ExperienceOrb(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, short experienceCount) { + super(globalEventHandler, serverSettingsProvider, chunkDispatcherProvider, exceptionHandlerProvider, EntityType.EXPERIENCE_ORB, UUID.randomUUID()); setBoundingBox(0.5f, 0.5f, 0.5f); //todo vanilla sets random velocity here? this.experienceCount = experienceCount; diff --git a/src/main/java/net/minestom/server/entity/ItemEntity.java b/src/main/java/net/minestom/server/entity/ItemEntity.java index 678ddee1026..ab3e9e92571 100644 --- a/src/main/java/net/minestom/server/entity/ItemEntity.java +++ b/src/main/java/net/minestom/server/entity/ItemEntity.java @@ -3,15 +3,13 @@ import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; import net.minestom.server.entity.metadata.item.ItemEntityMeta; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.entity.EntityItemMergeEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.EntityTracker; import net.minestom.server.item.ItemStack; import net.minestom.server.item.StackingRule; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.utils.time.Cooldown; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; @@ -46,11 +44,11 @@ public class ItemEntity extends Entity { private long pickupDelay; public ItemEntity(ServerFacade serverFacade, @NotNull ItemStack itemStack) { - this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), itemStack); + this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, itemStack); } - public ItemEntity(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull ItemStack itemStack) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.ITEM, UUID.randomUUID()); + public ItemEntity(GlobalEventHandler globalEventHandler, ServerSettings serverSettings, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, @NotNull ItemStack itemStack) { + super(globalEventHandler, () -> serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, EntityType.ITEM, UUID.randomUUID()); setItemStack(itemStack); setBoundingBox(0.25f, 0.25f, 0.25f); mergeDelay = Duration.of(10, TimeUnit.getServerTick(serverSettings)); diff --git a/src/main/java/net/minestom/server/entity/LivingEntity.java b/src/main/java/net/minestom/server/entity/LivingEntity.java index f6b310b031e..38c6e8f3873 100644 --- a/src/main/java/net/minestom/server/entity/LivingEntity.java +++ b/src/main/java/net/minestom/server/entity/LivingEntity.java @@ -11,15 +11,13 @@ import net.minestom.server.entity.damage.Damage; import net.minestom.server.entity.damage.DamageType; import net.minestom.server.entity.metadata.LivingEntityMeta; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.entity.EntityDamageEvent; import net.minestom.server.event.entity.EntityDeathEvent; import net.minestom.server.event.entity.EntityFireEvent; import net.minestom.server.event.item.EntityEquipEvent; import net.minestom.server.event.item.PickupItemEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.EntityTracker; import net.minestom.server.inventory.EquipmentHandler; import net.minestom.server.item.ItemStack; @@ -32,7 +30,7 @@ import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.scoreboard.Team; import net.minestom.server.sound.SoundEvent; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.utils.block.BlockIterator; import net.minestom.server.utils.time.Cooldown; import net.minestom.server.utils.time.TimeUnit; @@ -94,14 +92,21 @@ public LivingEntity(ServerFacade serverFacade, @NotNull EntityType entityType) { } public LivingEntity(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { - this(serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), serverFacade.getChunkDispatcher(), serverFacade.getExceptionHandler(), entityType, uuid); + this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, entityType, uuid); } /** * Constructor which allows to specify an UUID. Only use if you know what you are doing! */ - public LivingEntity(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, @NotNull EntityType entityType, @NotNull UUID uuid) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, entityType, uuid); + public LivingEntity( + GlobalEventHandler globalEventHandler, + ServerSettings serverSettings, + ChunkDispatcherProvider chunkDispatcherProvider, + ExceptionHandlerProvider exceptionHandlerProvider, + @NotNull EntityType entityType, + @NotNull UUID uuid + ) { + super(globalEventHandler, () -> serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, entityType, uuid); initEquipments(); itemPickupCooldown = new Cooldown(Duration.of(5, TimeUnit.getServerTick(serverSettings))); } @@ -190,7 +195,7 @@ public void setBoots(@NotNull ItemStack itemStack) { @Override public ServerSettings getServerSettings() { - return serverSettings; + return serverSettingsProvider.getServerSettings(); } private ItemStack getEquipmentItem(@NotNull ItemStack itemStack, @NotNull EquipmentSlot slot) { @@ -217,7 +222,7 @@ public void update(long time) { PickupItemEvent pickupItemEvent = new PickupItemEvent(this, itemEntity); globalEventHandler.callCancellable(pickupItemEvent, () -> { final ItemStack item = itemEntity.getItemStack(); - sendPacketToViewersAndSelf(serverSettings, new CollectItemPacket(itemEntity.getEntityId(), getEntityId(), item.amount())); + sendPacketToViewersAndSelf(serverSettingsProvider, new CollectItemPacket(itemEntity.getEntityId(), getEntityId(), item.amount())); itemEntity.remove(); }); } @@ -292,7 +297,7 @@ public void kill() { * @param duration duration in ticks of the effect */ public void setFireForDuration(int duration) { - setFireForDuration(duration, TimeUnit.getServerTick(serverSettings)); + setFireForDuration(duration, TimeUnit.getServerTick(serverSettingsProvider.getServerSettings())); } /** @@ -352,7 +357,7 @@ public boolean damage(@NotNull Damage damage) { float remainingDamage = entityDamageEvent.getDamage().getAmount(); if (entityDamageEvent.shouldAnimate()) { - sendPacketToViewersAndSelf(serverSettings, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.TAKE_DAMAGE)); + sendPacketToViewersAndSelf(serverSettingsProvider, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.TAKE_DAMAGE)); } // Additional hearts support @@ -382,7 +387,7 @@ public boolean damage(@NotNull Damage damage) { // TODO: separate living entity categories soundCategory = Source.HOSTILE; } - sendPacketToViewersAndSelf(serverSettings, new SoundEffectPacket(sound, null, soundCategory, + sendPacketToViewersAndSelf(serverSettingsProvider, new SoundEffectPacket(sound, null, soundCategory, getPosition(), 1.0f, 1.0f, 0)); } }); @@ -477,9 +482,9 @@ protected void onAttributeChanged(@NotNull AttributeInstance attributeInstance) } EntityPropertiesPacket propertiesPacket = new EntityPropertiesPacket(getEntityId(), List.of(attributeInstance)); if (self) { - sendPacketToViewersAndSelf(serverSettings, propertiesPacket); + sendPacketToViewersAndSelf(serverSettingsProvider, propertiesPacket); } else { - sendPacketToViewers(serverSettings, propertiesPacket); + sendPacketToViewers(serverSettingsProvider, propertiesPacket); } } @@ -539,7 +544,7 @@ public void setBoundingBox(BoundingBox boundingBox) { * (can be used for attack animation). */ public void swingMainHand() { - sendPacketToViewers(serverSettings, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_MAIN_ARM)); + sendPacketToViewers(serverSettingsProvider, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_MAIN_ARM)); } /** @@ -547,7 +552,7 @@ public void swingMainHand() { * (can be used for attack animation). */ public void swingOffHand() { - sendPacketToViewers(serverSettings, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_OFF_HAND)); + sendPacketToViewers(serverSettingsProvider, new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.SWING_OFF_HAND)); } public void refreshActiveHand(boolean isHandActive, boolean offHand, boolean riptideSpinAttack) { diff --git a/src/main/java/net/minestom/server/entity/Metadata.java b/src/main/java/net/minestom/server/entity/Metadata.java index e4cbc12413d..244661ac9e8 100644 --- a/src/main/java/net/minestom/server/entity/Metadata.java +++ b/src/main/java/net/minestom/server/entity/Metadata.java @@ -204,7 +204,7 @@ public void setIndex(int index, @NotNull Entry entry) { this.notNotifiedChanges.put(index, entry); } } else { - entity.sendPacketToViewersAndSelf(entity.serverSettings, new EntityMetaDataPacket(entity.getEntityId(), Map.of(index, entry))); + entity.sendPacketToViewersAndSelf(entity.getServerSettingsProvider(), new EntityMetaDataPacket(entity.getEntityId(), Map.of(index, entry))); } } } @@ -225,7 +225,7 @@ public void setNotifyAboutChanges(boolean notifyAboutChanges) { entries = Map.copyOf(awaitingChanges); awaitingChanges.clear(); } - entity.sendPacketToViewersAndSelf(entity.serverSettings, new EntityMetaDataPacket(entity.getEntityId(), entries)); + entity.sendPacketToViewersAndSelf(entity.getServerSettingsProvider(), new EntityMetaDataPacket(entity.getEntityId(), entries)); } public @NotNull Map> getEntries() { diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 2f367aed1ab..4fcbc2c26d8 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -20,7 +20,9 @@ import net.kyori.adventure.text.event.HoverEventSource; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.title.TitlePart; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; @@ -39,14 +41,13 @@ import net.minestom.server.entity.metadata.LivingEntityMeta; import net.minestom.server.entity.metadata.PlayerMeta; import net.minestom.server.entity.vehicle.PlayerVehicleInformation; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.inventory.InventoryOpenEvent; import net.minestom.server.event.item.ItemDropEvent; import net.minestom.server.event.item.ItemUpdateStateEvent; import net.minestom.server.event.item.PickupExperienceEvent; import net.minestom.server.event.player.*; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.EntityTracker; import net.minestom.server.instance.Instance; @@ -85,7 +86,7 @@ import net.minestom.server.snapshot.SnapshotImpl; import net.minestom.server.snapshot.SnapshotUpdater; import net.minestom.server.statistic.PlayerStatistic; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.PacketUtils; @@ -245,11 +246,17 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // The future is non-null when a resource pack is in-flight, and completed when all statuses have been received. private CompletableFuture resourcePackFuture = null; + public Player(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { + this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, serverFacade.getConnectionManager(), serverFacade.getTeamManager(), serverFacade.getRecipeManager(), serverFacade.getCommandManager(), serverFacade.getBossBarManager(), serverFacade.getSchedulerManager(), serverFacade.getPacketListenerManager(), serverFacade.getBlockManager(), uuid, username, playerConnection); + } + public Player( + GlobalEventHandler globalEventHandler, ServerSettings serverSettings, - EventNode globalEventHandler, - ThreadDispatcher dispatcher, - ExceptionHandler exceptionHandler, + + ChunkDispatcherProvider chunkDispatcherProvider, + ExceptionHandlerProvider exceptionHandlerProvider, + ConnectionManager connectionManager, TeamManager teamManager, RecipeManager recipeManager, @@ -258,10 +265,12 @@ public Player( SchedulerManager schedulerManager, PacketListenerManager packetListenerManager, BlockManager blockManager, - - @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection + + @NotNull UUID uuid, + @NotNull String username, + @NotNull PlayerConnection playerConnection ) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.PLAYER, uuid); + super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, EntityType.PLAYER, uuid); this.connectionManager = connectionManager; this.teamManager = teamManager; this.recipeManager = recipeManager; @@ -277,7 +286,7 @@ public Player( setRespawnPoint(Pos.ZERO); this.settings = new PlayerSettings(); - this.inventory = new PlayerInventory(serverSettings, globalEventHandler, this); + this.inventory = new PlayerInventory(serverSettingsProvider.getServerSettings(), globalEventHandler, this); setCanPickupItem(true); // By default @@ -306,7 +315,7 @@ public Player( sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); globalEventHandler.call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); }; - experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(serverSettings))); + experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(serverSettingsProvider.getServerSettings()))); } @ApiStatus.Internal @@ -334,13 +343,13 @@ public CompletableFuture UNSAFE_init() { final JoinGamePacket joinGamePacket = new JoinGamePacket( getEntityId(), this.hardcore, List.of(), 0, - serverSettings.getChunkViewDistance(), serverSettings.getChunkViewDistance(), - false, true, false, dimensionType.toString(), spawnInstance.getDimensionName(), + serverSettingsProvider.getServerSettings().getChunkViewDistance(), serverSettingsProvider.getServerSettings().getChunkViewDistance(), + false, true, false, dimensionType.toString(), spawnInstance.getDimensionName().asString(), 0, gameMode, null, false, levelFlat, deathLocation, portalCooldown); sendPacket(joinGamePacket); // Difficulty - sendPacket(new ServerDifficultyPacket(serverSettings.getDifficulty(), true)); + sendPacket(new ServerDifficultyPacket(serverSettingsProvider.getServerSettings().getDifficulty(), true)); sendPacket(new SpawnPositionPacket(respawnPoint, 0)); @@ -365,7 +374,7 @@ public CompletableFuture UNSAFE_init() { globalEventHandler.call(skinInitEvent); this.skin = skinInitEvent.getSkin(); // FIXME: when using Geyser, this line remove the skin of the client - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, getAddPlayerToList()); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, getAddPlayerToList()); for (var player : connectionManager.getOnlinePlayers()) { if (player != this) { @@ -562,7 +571,7 @@ public void respawn() { setOnFire(false); refreshHealth(); - sendPacket(new RespawnPacket(getDimensionType().toString(), instance.getDimensionName(), + sendPacket(new RespawnPacket(getDimensionType().toString(), instance.getDimensionName().asString(), 0, gameMode, gameMode, false, levelFlat, deathLocation, portalCooldown, RespawnPacket.COPY_ALL)); PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this); @@ -577,7 +586,7 @@ public void respawn() { ChunkUtils.forChunksInRange(respawnPosition, settings.getEffectiveViewDistance(), chunkAdder); chunksLoadedByClient = new Vec(respawnPosition.chunkX(), respawnPosition.chunkZ()); // Client also needs all entities resent to them, since those are unloaded as well - this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(serverSettings.getChunkViewDistance(), settings.getViewDistance()), + this.instance.getEntityTracker().nearbyEntitiesByChunkRange(respawnPosition, Math.min(serverSettingsProvider.getServerSettings().getChunkViewDistance(), settings.getViewDistance()), EntityTracker.Target.ENTITIES, entity -> { // Skip refreshing self with a new viewer if (!entity.getUuid().equals(uuid) && entity.isViewer(this)) { @@ -592,7 +601,7 @@ public void respawn() { */ private void refreshClientStateAfterRespawn() { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.LEVEL_CHUNKS_LOAD_START, 0)); - sendPacket(new ServerDifficultyPacket(serverSettings.getDifficulty(), false)); + sendPacket(new ServerDifficultyPacket(serverSettingsProvider.getServerSettings().getDifficulty(), false)); sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation)); sendPacket(new SetExperiencePacket(exp, level, 0)); triggerStatus((byte) (24 + permissionLevel)); // Set permission level @@ -640,9 +649,9 @@ public void remove(boolean permanent) { final int chunkX = position.chunkX(); final int chunkZ = position.chunkZ(); // Clear all viewable chunks - ChunkUtils.forChunksInRange(chunkX, chunkZ, serverSettings.getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(chunkX, chunkZ, serverSettingsProvider.getServerSettings().getChunkViewDistance(), chunkRemover); // Remove from the tab-list - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, getRemovePlayerToList()); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, getRemovePlayerToList()); // Prevent the player from being stuck in loading screen, or just unable to interact with the server // This should be considered as a bug, since the player will ultimately time out anyway. @@ -659,9 +668,9 @@ public void updateOldViewer(@NotNull Player player) { } @Override - public void sendPacketToViewersAndSelf(ServerSettings serverSettings, @NotNull SendablePacket packet) { + public void sendPacketToViewersAndSelf(ServerSettingsProvider serverSettingsProvider, @NotNull SendablePacket packet) { sendPacket(packet); - super.sendPacketToViewersAndSelf(serverSettings, packet); + super.sendPacketToViewersAndSelf(serverSettingsProvider, packet); } /** @@ -692,7 +701,7 @@ public CompletableFuture setInstance(@NotNull Instance instance, @NotNull // Ensure that surrounding chunks are loaded List> futures = new ArrayList<>(); - ChunkUtils.forChunksInRange(spawnPosition, serverSettings.getChunkViewDistance(), (chunkX, chunkZ) -> { + ChunkUtils.forChunksInRange(spawnPosition, serverSettingsProvider.getServerSettings().getChunkViewDistance(), (chunkX, chunkZ) -> { final CompletableFuture future = instance.loadOptionalChunk(chunkX, chunkZ); if (!future.isDone()) futures.add(future); }); @@ -764,10 +773,10 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, if (!firstSpawn && !dimensionChange) { // Player instance changed, clear current viewable collections if (updateChunks) - ChunkUtils.forChunksInRange(spawnPosition, serverSettings.getChunkViewDistance(), chunkRemover); + ChunkUtils.forChunksInRange(spawnPosition, serverSettingsProvider.getServerSettings().getChunkViewDistance(), chunkRemover); } - if (dimensionChange) sendDimension(instance.getDimensionType(), instance.getDimensionName()); + if (dimensionChange) sendDimension(instance.getDimensionType(), instance.getDimensionName().asString()); super.setInstance(instance, spawnPosition); @@ -779,7 +788,7 @@ private void spawnPlayer(@NotNull Instance instance, @NotNull Pos spawnPosition, sendPacket(new UpdateViewPositionPacket(chunkX, chunkZ)); // Load the nearby chunks and queue them to be sent to them - ChunkUtils.forChunksInRange(spawnPosition, serverSettings.getChunkViewDistance(), chunkAdder); + ChunkUtils.forChunksInRange(spawnPosition, serverSettingsProvider.getServerSettings().getChunkViewDistance(), chunkAdder); } synchronizePosition(true); // So the player doesn't get stuck @@ -1197,7 +1206,7 @@ public double getEyeHeight() { */ public void setDisplayName(@Nullable Component displayName) { this.displayName = displayName; - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); } /** @@ -1228,7 +1237,7 @@ public synchronized void setSkin(@Nullable PlayerSkin skin) { final PlayerInfoRemovePacket removePlayerPacket = getRemovePlayerToList(); final PlayerInfoUpdatePacket addPlayerPacket = getAddPlayerToList(); - RespawnPacket respawnPacket = new RespawnPacket(getDimensionType().toString(), instance.getDimensionName(), + RespawnPacket respawnPacket = new RespawnPacket(getDimensionType().toString(), instance.getDimensionName().asString(), 0, gameMode, gameMode, false, levelFlat, deathLocation, portalCooldown, RespawnPacket.COPY_ALL); sendPacket(removePlayerPacket); @@ -1239,11 +1248,11 @@ public synchronized void setSkin(@Nullable PlayerSkin skin) { { // Remove player - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, removePlayerPacket); - sendPacketToViewers(serverSettings, destroyEntitiesPacket); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, removePlayerPacket); + sendPacketToViewers(serverSettingsProvider, destroyEntitiesPacket); // Show player again - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, addPlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, addPlayerPacket); getViewers().forEach(player -> showPlayer(player.getPlayerConnection())); } @@ -1449,13 +1458,13 @@ public void setRespawnPoint(@NotNull Pos respawnPoint) { * and send data to his new viewers. */ protected void refreshAfterTeleport() { - sendPacketsToViewers(serverSettings, getEntityType().registry().spawnType().getSpawnPacket(this)); + sendPacketsToViewers(serverSettingsProvider, getEntityType().registry().spawnType().getSpawnPacket(this)); // Update for viewers - sendPacketToViewersAndSelf(serverSettings, getVelocityPacket()); - sendPacketToViewersAndSelf(serverSettings, getMetadataPacket()); - sendPacketToViewersAndSelf(serverSettings, getPropertiesPacket()); - sendPacketToViewersAndSelf(serverSettings, getEquipmentsPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getVelocityPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getMetadataPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getPropertiesPacket()); + sendPacketToViewersAndSelf(serverSettingsProvider, getEquipmentsPacket()); getInventory().update(); } @@ -1621,7 +1630,7 @@ public boolean setGameMode(@NotNull GameMode gameMode) { // Condition to prevent sending the packets before spawning the player if (isActive()) { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.CHANGE_GAMEMODE, gameMode.id())); - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); } // The client updates their abilities based on the GameMode as follows @@ -2121,7 +2130,7 @@ public void interpretPacketQueue() { public void refreshLatency(int latency) { this.latency = latency; if (getPlayerConnection().getConnectionState() == ConnectionState.PLAY) { - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); } } @@ -2402,7 +2411,7 @@ protected void sendChunkUpdates(Chunk newChunk) { final Vec old = chunksLoadedByClient; sendPacket(new UpdateViewPositionPacket(newX, newZ)); ChunkUtils.forDifferingChunksInRange(newX, newZ, (int) old.x(), (int) old.z(), - serverSettings.getChunkViewDistance(), chunkAdder, chunkRemover); + serverSettingsProvider.getServerSettings().getChunkViewDistance(), chunkAdder, chunkRemover); this.chunksLoadedByClient = new Vec(newX, newZ); } } @@ -2470,7 +2479,7 @@ public byte getViewDistance() { } public int getEffectiveViewDistance() { - return Math.min(getViewDistance(), serverSettings.getChunkViewDistance()); + return Math.min(getViewDistance(), serverSettingsProvider.getServerSettings().getChunkViewDistance()); } /** diff --git a/src/main/java/net/minestom/server/entity/PlayerProjectile.java b/src/main/java/net/minestom/server/entity/PlayerProjectile.java index b97c4edbdd5..c3c592627ee 100644 --- a/src/main/java/net/minestom/server/entity/PlayerProjectile.java +++ b/src/main/java/net/minestom/server/entity/PlayerProjectile.java @@ -8,16 +8,14 @@ import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.metadata.projectile.ProjectileMeta; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.entity.EntityShootEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; import net.minestom.server.event.entity.projectile.ProjectileCollideWithEntityEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import org.jetbrains.annotations.NotNull; import java.util.Random; @@ -29,8 +27,12 @@ public class PlayerProjectile extends LivingEntity { private final Entity shooter; private long cooldown = 0; - public PlayerProjectile(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, Entity shooter, EntityType type) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, type, UUID.randomUUID()); + public PlayerProjectile(GlobalEventHandler globalEventHandler, + ServerSettings serverSettings, + ChunkDispatcherProvider chunkDispatcherProvider, + ExceptionHandlerProvider exceptionHandlerProvider, + Entity shooter, EntityType type) { + super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, type, UUID.randomUUID()); this.shooter = shooter; this.hasCollision = false; setup(); diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index a614d0071b9..197c2e03039 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -9,12 +9,10 @@ import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.NavigableEntity; import net.minestom.server.entity.pathfinding.Navigator; -import net.minestom.server.event.Event; import net.minestom.server.event.EventListener; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.player.PlayerSpawnEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.BlockManager; import net.minestom.server.listener.manager.PacketListenerManager; @@ -26,7 +24,7 @@ import net.minestom.server.network.socket.Server; import net.minestom.server.recipe.RecipeManager; import net.minestom.server.scoreboard.TeamManager; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; @@ -56,10 +54,10 @@ public class FakePlayer extends Player implements NavigableEntity { public FakePlayer(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { this( - serverFacade.getServerSettings(), serverFacade.getGlobalEventHandler(), - serverFacade.getChunkDispatcher(), - serverFacade.getExceptionHandler(), + serverFacade.getServerSettings(), + serverFacade, + serverFacade, serverFacade.getConnectionManager(), serverFacade.getTeamManager(), serverFacade.getRecipeManager(), @@ -80,24 +78,27 @@ public FakePlayer(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String * @param username The username for the fake player. * @param option Any option for the fake player. */ - public FakePlayer(ServerSettings serverSettings, - EventNode globalEventHandler, - ThreadDispatcher dispatcher, - ExceptionHandler exceptionHandler, - ConnectionManager connectionManager, - TeamManager teamManager, - RecipeManager recipeManager, - CommandManager commandManager, - BossBarManager bossBarManager, - SchedulerManager schedulerManager, - PacketListenerManager packetListenerManager, - BlockManager blockManager, + public FakePlayer( + GlobalEventHandler globalEventHandler, + ServerSettings serverSettings, + + ChunkDispatcherProvider chunkDispatcherProvider, + ExceptionHandlerProvider exceptionHandlerProvider, + + ConnectionManager connectionManager, + TeamManager teamManager, + RecipeManager recipeManager, + CommandManager commandManager, + BossBarManager bossBarManager, + SchedulerManager schedulerManager, + PacketListenerManager packetListenerManager, + BlockManager blockManager, Server server, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - super(serverSettings, globalEventHandler, dispatcher, exceptionHandler, connectionManager, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, new FakePlayerConnection(server, connectionManager)); + super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, connectionManager, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, new FakePlayerConnection(server, connectionManager)); this.scheduleManager = schedulerManager; this.option = option; @@ -209,7 +210,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - scheduleManager.buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(serverSettings)).schedule(); + scheduleManager.buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(serverSettingsProvider.getServerSettings())).schedule(); } } } diff --git a/src/main/java/net/minestom/server/entity/hologram/Hologram.java b/src/main/java/net/minestom/server/entity/hologram/Hologram.java index 6848b1bb9e2..ec4adb37e0f 100644 --- a/src/main/java/net/minestom/server/entity/hologram/Hologram.java +++ b/src/main/java/net/minestom/server/entity/hologram/Hologram.java @@ -1,19 +1,17 @@ package net.minestom.server.entity.hologram; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.Player; import net.minestom.server.entity.metadata.other.ArmorStandMeta; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Instance; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -44,8 +42,12 @@ public class Hologram implements Viewable { * @param text The text of this hologram. * @param autoViewable {@code true}if the hologram should be visible automatically, otherwise {@code false}. */ - public Hologram(ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, ExceptionHandler exceptionHandler, Instance instance, Pos spawnPosition, Component text, boolean autoViewable, boolean marker) { - this.entity = new Entity(serverSettings, globalEventHandler, dispatcher, exceptionHandler, EntityType.ARMOR_STAND, UUID.randomUUID()); + public Hologram(@NotNull GlobalEventHandler globalEventHandler, + @NotNull ServerSettingsProvider serverSettingsProvider, + @NotNull ChunkDispatcherProvider chunkDispatcherProvider, + @NotNull ExceptionHandlerProvider exceptionHandlerProvider, + Instance instance, Pos spawnPosition, Component text, boolean autoViewable, boolean marker) { + this.entity = new Entity(globalEventHandler, serverSettingsProvider, chunkDispatcherProvider, exceptionHandlerProvider, EntityType.ARMOR_STAND, UUID.randomUUID()); ArmorStandMeta armorStandMeta = (ArmorStandMeta) entity.getEntityMeta(); diff --git a/src/main/java/net/minestom/server/event/EventHandler.java b/src/main/java/net/minestom/server/event/EventHandler.java index b662f8f2743..cbce777bbed 100644 --- a/src/main/java/net/minestom/server/event/EventHandler.java +++ b/src/main/java/net/minestom/server/event/EventHandler.java @@ -9,5 +9,5 @@ @ApiStatus.Experimental @ApiStatus.NonExtendable public interface EventHandler { - @NotNull EventNode eventNode(); + @NotNull EventNode getEventNode(); } diff --git a/src/main/java/net/minestom/server/event/EventNode.java b/src/main/java/net/minestom/server/event/EventNode.java index 7125998676f..d89ac1a0758 100644 --- a/src/main/java/net/minestom/server/event/EventNode.java +++ b/src/main/java/net/minestom/server/event/EventNode.java @@ -2,6 +2,7 @@ import net.minestom.server.ServerFacade; import net.minestom.server.event.trait.CancellableEvent; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.tag.Tag; import net.minestom.server.tag.TagReadable; import org.jetbrains.annotations.ApiStatus; @@ -173,20 +174,20 @@ public interface EventNode { * @return A node with an event type filter as well as a handler with the provided tag */ @Contract(value = "_, _, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull ServerFacade serverFacade, + static @NotNull EventNode tag(@NotNull ExceptionHandlerProvider exceptionHandlerProvider, @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag, @NotNull Predicate<@Nullable V> consumer) { - return create(serverFacade, name, filter, (e, h) -> consumer.test(h.getTag(tag))); + return create(exceptionHandlerProvider, name, filter, (e, h) -> consumer.test(h.getTag(tag))); } - private static EventNode create(@NotNull ServerFacade serverFacade, + private static EventNode create(@NotNull ExceptionHandlerProvider exceptionHandlerProvider, @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { //noinspection unchecked - return new EventNodeImpl<>(serverFacade.getExceptionHandler(), name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); + return new EventNodeImpl<>(exceptionHandlerProvider, name, filter, predicate != null ? (e, o) -> predicate.test(e, (V) o) : null); } /** diff --git a/src/main/java/net/minestom/server/event/EventNodeImpl.java b/src/main/java/net/minestom/server/event/EventNodeImpl.java index 6b02d7b11ed..e4181c6703f 100644 --- a/src/main/java/net/minestom/server/event/EventNodeImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeImpl.java @@ -2,7 +2,7 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.minestom.server.event.trait.RecursiveEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -30,7 +30,7 @@ class EventNodeImpl implements EventNode { final Map> registeredMappedNode = Caffeine.newBuilder() .weakKeys().weakValues().>build().asMap(); - private final ExceptionHandler exceptionHandler; + private final ExceptionHandlerProvider exceptionHandlerProvider; final String name; final EventFilter filter; final BiPredicate predicate; @@ -38,11 +38,11 @@ class EventNodeImpl implements EventNode { volatile int priority; volatile EventNodeImpl parent; - EventNodeImpl(@NotNull ExceptionHandler exceptionHandler, + EventNodeImpl(@NotNull ExceptionHandlerProvider exceptionHandlerProvider, @NotNull String name, @NotNull EventFilter filter, @Nullable BiPredicate predicate) { - this.exceptionHandler = exceptionHandler; + this.exceptionHandlerProvider = exceptionHandlerProvider; this.name = name; this.filter = filter; this.predicate = predicate; @@ -159,7 +159,7 @@ public void removeChildren(@NotNull String name, @NotNull Class eve public @NotNull EventNode map(@NotNull H value, @NotNull EventFilter filter) { EventNodeImpl node; synchronized (GLOBAL_CHILD_LOCK) { - node = new EventNodeLazyImpl<>(exceptionHandler,this, value, filter); + node = new EventNodeLazyImpl<>(exceptionHandlerProvider,this, value, filter); Check.stateCondition(node.parent != null, "Node already has a parent"); Check.stateCondition(Objects.equals(parent, node), "Cannot map to self"); EventNodeImpl previous = this.mappedNodeCache.putIfAbsent(value, (EventNodeImpl) node); @@ -329,7 +329,7 @@ public void call(@NotNull E event) { try { listener.accept(event); } catch (Throwable e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } diff --git a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java index 0d0abfd212f..e4d59917377 100644 --- a/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java +++ b/src/main/java/net/minestom/server/event/EventNodeLazyImpl.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import org.jetbrains.annotations.NotNull; import java.lang.invoke.MethodHandles; @@ -24,9 +24,9 @@ final class EventNodeLazyImpl extends EventNodeImpl { @SuppressWarnings("unused") private boolean mapped; - EventNodeLazyImpl(@NotNull ExceptionHandler exceptionHandler, @NotNull EventNodeImpl holder, + EventNodeLazyImpl(@NotNull ExceptionHandlerProvider exceptionHandlerProvider, @NotNull EventNodeImpl holder, @NotNull Object owner, @NotNull EventFilter filter) { - super(exceptionHandler, owner.toString(), filter, null); + super(exceptionHandlerProvider, owner.toString(), filter, null); this.holder = holder; this.owner = new WeakReference<>(owner); } diff --git a/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java b/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java index d03247bd008..f2856034909 100644 --- a/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java +++ b/src/main/java/net/minestom/server/event/GlobalEventHandlerImpl.java @@ -1,12 +1,12 @@ package net.minestom.server.event; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; /** * Object containing all the global event listeners. */ public final class GlobalEventHandlerImpl extends EventNodeImpl implements GlobalEventHandler { - public GlobalEventHandlerImpl(ExceptionHandler exceptionHandler) { - super(exceptionHandler, "global", EventFilter.ALL, null); + public GlobalEventHandlerImpl(ExceptionHandlerProvider exceptionHandlerProvider) { + super(exceptionHandlerProvider, "global", EventFilter.ALL, null); } } diff --git a/src/main/java/net/minestom/server/instance/AnvilLoader.java b/src/main/java/net/minestom/server/instance/AnvilLoader.java index fdbb8c10d03..f623aac610f 100644 --- a/src/main/java/net/minestom/server/instance/AnvilLoader.java +++ b/src/main/java/net/minestom/server/instance/AnvilLoader.java @@ -3,14 +3,14 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.IntIntImmutablePair; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockHandler; -import net.minestom.server.instance.block.BlockManager; +import net.minestom.server.instance.block.BlockManagerProvider; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.async.AsyncUtils; import net.minestom.server.world.biomes.Biome; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jglrxavpok.hephaistos.mca.*; @@ -42,9 +42,9 @@ public class AnvilLoader implements IChunkLoader { private static final Biome BIOME = Biome.PLAINS; private final Map alreadyLoaded = new ConcurrentHashMap<>(); - private final ExceptionHandler exceptionHandler; - private final BlockManager blockManager; - private final BiomeManager biomeManager; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final BlockManagerProvider blockManagerProvider; + private final BiomeManagerProvider biomeManagerProvider; private final Path path; private final Path levelPath; private final Path regionPath; @@ -60,17 +60,17 @@ private static class RegionCache extends ConcurrentHashMap> blockStateId2ObjectCacheTLS = ThreadLocal.withInitial(Int2ObjectArrayMap::new); - public AnvilLoader(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, @NotNull Path path) { - this.exceptionHandler = exceptionHandler; - this.blockManager = blockManager; - this.biomeManager = biomeManager; + public AnvilLoader(ExceptionHandlerProvider exceptionHandlerProvider, BlockManagerProvider blockManagerProvider, BiomeManagerProvider biomeManagerProvider, @NotNull Path path) { + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.blockManagerProvider = blockManagerProvider; + this.biomeManagerProvider = biomeManagerProvider; this.path = path; this.levelPath = path.resolve("level.dat"); this.regionPath = path.resolve("region"); } - public AnvilLoader(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, @NotNull String path) { - this(exceptionHandler, blockManager, biomeManager, Path.of(path)); + public AnvilLoader(ExceptionHandlerProvider exceptionHandlerProvider, BlockManagerProvider blockManagerProvider, BiomeManagerProvider biomeManagerProvider, @NotNull String path) { + this(exceptionHandlerProvider, blockManagerProvider, biomeManagerProvider, Path.of(path)); } @Override @@ -83,7 +83,7 @@ public void loadInstance(@NotNull Instance instance) { Files.copy(levelPath, path.resolve("level.dat_old"), StandardCopyOption.REPLACE_EXISTING); instance.tagHandler().updateContent(tag); } catch (IOException | NBTException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } @@ -96,7 +96,7 @@ public void loadInstance(@NotNull Instance instance) { try { return loadMCA(instance, chunkX, chunkZ); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } return CompletableFuture.completedFuture(null); } @@ -162,7 +162,7 @@ public void loadInstance(@NotNull Instance instance) { } return new RegionFile(new RandomAccessFile(regionPath.toFile(), "rw"), regionX, regionZ, instance.getDimensionType().getMinY(), instance.getDimensionType().getMaxY() - 1); } catch (IOException | AnvilException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return null; } }); @@ -200,7 +200,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { int finalY = sectionY * Chunk.CHUNK_SECTION_SIZE + y; String biomeName = sectionBiomeInformation.getBaseBiome(); Biome biome = biomeCache.computeIfAbsent(biomeName, n -> - Objects.requireNonNullElse(biomeManager.getByName(NamespaceID.from(n)), BIOME)); + Objects.requireNonNullElse(biomeManagerProvider.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); chunk.setBiome(finalX, finalY, finalZ, biome); } } @@ -216,7 +216,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { int index = x / 4 + (z / 4) * 4 + (y / 4) * 16; String biomeName = sectionBiomeInformation.getBiomes()[index]; Biome biome = biomeCache.computeIfAbsent(biomeName, n -> - Objects.requireNonNullElse(biomeManager.getByName(NamespaceID.from(n)), BIOME)); + Objects.requireNonNullElse(biomeManagerProvider.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); chunk.setBiome(finalX, finalY, finalZ, biome); } } @@ -258,7 +258,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { if (!properties.isEmpty()) block = block.withProperties(properties); // Handler - final BlockHandler handler = blockManager.getHandler(block.name()); + final BlockHandler handler = blockManagerProvider.getBlockManager().getHandler(block.name()); if (handler != null) block = block.withHandler(handler); convertedPalette[i] = block; @@ -275,7 +275,7 @@ private void loadSections(Chunk chunk, ChunkReader chunkReader) { chunk.setBlock(x, y + yOffset, z, block); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } } @@ -297,7 +297,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { final String tileEntityID = te.getString("id"); if (tileEntityID != null) { - final BlockHandler handler = blockManager.getHandlerOrDummy(tileEntityID); + final BlockHandler handler = blockManagerProvider.getBlockManager().getHandlerOrDummy(tileEntityID); block = block.withHandler(handler); } // Remove anvil tags @@ -352,7 +352,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { alreadyLoaded.put(n, mcaFile); } catch (AnvilException | IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return AsyncUtils.VOID_FUTURE; } } @@ -364,7 +364,7 @@ private void loadBlockEntities(Chunk loadedChunk, ChunkReader chunkReader) { mcaFile.writeColumnData(writer.toNBT(), chunk.getChunkX(), chunk.getChunkZ()); } catch (IOException e) { LOGGER.error("Failed to save chunk " + chunkX + ", " + chunkZ, e); - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return AsyncUtils.VOID_FUTURE; } return AsyncUtils.VOID_FUTURE; @@ -471,7 +471,7 @@ public void unloadChunk(Chunk chunk) { try { regionFile.close(); } catch (IOException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } } @@ -493,7 +493,7 @@ public boolean supportsParallelLoading() { parallelSavingThreadPool.shutdown(); parallelSavingThreadPool.awaitTermination(1L, java.util.concurrent.TimeUnit.DAYS); } catch (InterruptedException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } return AsyncUtils.VOID_FUTURE; } else { diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java index 93a3d3403f4..a5853a54f08 100644 --- a/src/main/java/net/minestom/server/instance/DynamicChunk.java +++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java @@ -23,7 +23,7 @@ import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.world.biomes.Biome; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jglrxavpok.hephaistos.nbt.NBT; @@ -42,7 +42,7 @@ */ public class DynamicChunk extends Chunk { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicChunk.class); - protected final BiomeManager biomeManager; + protected final BiomeManagerProvider biomeManagerProvider; protected List

        sections; @@ -53,13 +53,13 @@ public class DynamicChunk extends Chunk { private long lastChange; final CachedPacket chunkCache; - public DynamicChunk(BiomeManager biomeManager, @NotNull Instance instance, int chunkX, int chunkZ) { + public DynamicChunk(BiomeManagerProvider biomeManagerProvider, @NotNull Instance instance, int chunkX, int chunkZ) { super(instance, chunkX, chunkZ, true); - this.biomeManager = biomeManager; + this.biomeManagerProvider = biomeManagerProvider; var sectionsTemp = new Section[maxSection - minSection]; Arrays.setAll(sectionsTemp, value -> new Section()); this.sections = List.of(sectionsTemp); - chunkCache = new CachedPacket(instance.getServerSettings(), this::createChunkPacket); + chunkCache = new CachedPacket(instance.getServerSettingsProvider(), this::createChunkPacket); } @Override @@ -183,7 +183,7 @@ public void tick(long time) { final Section section = getSectionAt(y); final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return biomeManager.getById(id); + return biomeManagerProvider.getBiomeManager().getById(id); } @Override @@ -198,7 +198,7 @@ public long getLastChangeTime() { @Override public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) { - DynamicChunk dynamicChunk = new DynamicChunk(biomeManager, instance, chunkX, chunkZ); + DynamicChunk dynamicChunk = new DynamicChunk(biomeManagerProvider, instance, chunkX, chunkZ); dynamicChunk.sections = sections.stream().map(Section::clone).toList(); dynamicChunk.entries.putAll(entries); return dynamicChunk; @@ -316,7 +316,7 @@ protected LightData createLightData(boolean sendLater) { clonedSections[i] = sections.get(i).clone(); var entities = instance.getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES); final int[] entityIds = ArrayUtils.mapToIntArray(entities, Entity::getEntityId); - return new SnapshotImpl.Chunk(biomeManager, minSection, chunkX, chunkZ, + return new SnapshotImpl.Chunk(biomeManagerProvider, minSection, chunkX, chunkZ, clonedSections, entries.clone(), entityIds, updater.reference(instance), tagHandler().readableCopy()); } diff --git a/src/main/java/net/minestom/server/instance/EntityTracker.java b/src/main/java/net/minestom/server/instance/EntityTracker.java index a66a0cc7efc..41bffafd226 100644 --- a/src/main/java/net/minestom/server/instance/EntityTracker.java +++ b/src/main/java/net/minestom/server/instance/EntityTracker.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Entity; @@ -24,8 +24,8 @@ */ @ApiStatus.Experimental public sealed interface EntityTracker permits EntityTrackerImpl { - static @NotNull EntityTracker newTracker(ServerSettings serverSettings) { - return new EntityTrackerImpl(serverSettings); + static @NotNull EntityTracker newTracker(ServerSettingsProvider serverSettingsProvider) { + return new EntityTrackerImpl(serverSettingsProvider); } /** diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index a17895faf0a..4089fd7df85 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -2,7 +2,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import lombok.RequiredArgsConstructor; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -30,7 +30,7 @@ @RequiredArgsConstructor final class EntityTrackerImpl implements EntityTracker { - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; static final AtomicInteger TARGET_COUNTER = new AtomicInteger(); @@ -55,7 +55,7 @@ public void register(@NotNull Entity entity, @NotNull Point p } if (update != null) { update.referenceUpdate(point, this); - nearbyEntitiesByChunkRange(point, serverSettings.getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverSettingsProvider.getServerSettings().getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.add(newEntity); }); @@ -76,7 +76,7 @@ public void unregister(@NotNull Entity entity, } if (update != null) { update.referenceUpdate(point, null); - nearbyEntitiesByChunkRange(point, serverSettings.getEntityViewDistance(), target, newEntity -> { + nearbyEntitiesByChunkRange(point, serverSettingsProvider.getServerSettings().getEntityViewDistance(), target, newEntity -> { if (newEntity == entity) return; update.remove(newEntity); }); @@ -188,7 +188,7 @@ private void difference(Point oldPoint, Point newPoint, @NotNull Target target, @NotNull Update update) { final TargetEntry entry = entries[target.ordinal()]; forDifferingChunksInRange(newPoint.chunkX(), newPoint.chunkZ(), oldPoint.chunkX(), oldPoint.chunkZ(), - serverSettings.getEntityViewDistance(), (chunkX, chunkZ) -> { + serverSettingsProvider.getServerSettings().getEntityViewDistance(), (chunkX, chunkZ) -> { // Add final List entities = entry.chunkEntities.get(getChunkIndex(chunkX, chunkZ)); if (entities == null || entities.isEmpty()) return; @@ -282,7 +282,7 @@ private Collection references() { } private void collectPlayers(EntityTracker tracker, Int2ObjectOpenHashMap map) { - tracker.nearbyEntitiesByChunkRange(point, serverSettings.getChunkViewDistance(), + tracker.nearbyEntitiesByChunkRange(point, serverSettingsProvider.getServerSettings().getChunkViewDistance(), EntityTracker.Target.PLAYERS, (player) -> map.putIfAbsent(player.getEntityId(), player)); } diff --git a/src/main/java/net/minestom/server/instance/Explosion.java b/src/main/java/net/minestom/server/instance/Explosion.java index 9f389355f56..e1405b12bb9 100644 --- a/src/main/java/net/minestom/server/instance/Explosion.java +++ b/src/main/java/net/minestom/server/instance/Explosion.java @@ -73,7 +73,7 @@ public void apply(@NotNull Instance instance) { ExplosionPacket packet = new ExplosionPacket(centerX, centerY, centerZ, strength, records, 0, 0, 0); postExplosion(instance, blocks, packet); - PacketUtils.sendGroupedPacket(instance.getServerSettings(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance::getServerSettings, instance.getPlayers(), packet); postSend(instance, blocks); } diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index 0e33d3e830d..f05aed5fa09 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -2,9 +2,12 @@ import it.unimi.dsi.fastutil.objects.ObjectArraySet; import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointers; import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Tickable; import net.minestom.server.adventure.audience.PacketGroupingAudience; import net.minestom.server.coordinate.Point; @@ -13,10 +16,7 @@ import net.minestom.server.entity.ExperienceOrb; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.PFInstanceSpace; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventFilter; -import net.minestom.server.event.EventHandler; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.*; import net.minestom.server.event.instance.InstanceTickEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; import net.minestom.server.event.trait.InstanceEvent; @@ -68,46 +68,67 @@ public abstract class Instance implements Block.Getter, Block.Setter, Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { @Getter // FIXME bad shit - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; private final EventNode globalEventHandler; + @Getter + @Setter(lombok.AccessLevel.PROTECTED) private boolean registered; + + @Getter private final DimensionType dimensionType; - private final String dimensionName; + @Getter + private final NamespaceID dimensionName; + @Getter private final WorldBorder worldBorder; + // Tick since the creation of the instance + @Getter private long worldAge; // The time of the instance + @Getter private long time; + @Getter private int timeRate = 1; + @Setter + @Getter private Duration timeUpdate = Duration.of(1, TimeUnit.SECOND); private long lastTimeUpdate; // Field for tick events private long lastTickAge = System.currentTimeMillis(); + @Getter private final EntityTracker entityTracker; private final ChunkCache blockRetriever = new ChunkCache(this, null, null); // the uuid of this instance + @Getter protected UUID uniqueId; // instance custom data + @Getter + @Accessors(fluent = true) protected TagHandler tagHandler = TagHandler.newHandler(); + @Getter private final Scheduler scheduler = Scheduler.newScheduler(); + @Getter private final EventNode eventNode; // the explosion supplier private ExplosionSupplier explosionSupplier; // Pathfinder + @Getter private final PFInstanceSpace instanceSpace = new PFInstanceSpace(this); // Adventure + @Getter + @Accessors(fluent = true) private final Pointers pointers; /** @@ -116,8 +137,13 @@ public abstract class Instance implements Block.Getter, Block.Setter, * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull ServerSettings serverSettings, EventNode globalEventHandler, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(serverSettings, globalEventHandler, uniqueId, dimensionType, dimensionType.getName()); + public Instance( + @NotNull GlobalEventHandler globalEventHandler, + @NotNull ServerSettingsProvider serverSettingsProvider, + @NotNull UUID uniqueId, + @NotNull DimensionType dimensionType + ) { + this(globalEventHandler, serverSettingsProvider, uniqueId, dimensionType, dimensionType.getName()); } /** @@ -126,14 +152,21 @@ public Instance(@NotNull ServerSettings serverSettings, EventNode globalE * @param uniqueId the {@link UUID} of the instance * @param dimensionType the {@link DimensionType} of the instance */ - public Instance(@NotNull ServerSettings serverSettings, EventNode globalEventHandler, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + public Instance( + @NotNull GlobalEventHandler globalEventHandler, + @NotNull ServerSettingsProvider serverSettingsProvider, + + @NotNull UUID uniqueId, + @NotNull DimensionType dimensionType, + @NotNull NamespaceID dimensionName + ) { this.globalEventHandler = globalEventHandler; Check.argCondition(!dimensionType.isRegistered(), "The dimension " + dimensionType.getName() + " is not registered! Please use DimensionTypeManager#addDimension"); - this.serverSettings = serverSettings; + this.serverSettingsProvider = serverSettingsProvider; this.uniqueId = uniqueId; this.dimensionType = dimensionType; - this.dimensionName = dimensionName.asString(); + this.dimensionName = dimensionName; this.worldBorder = new WorldBorder(this); @@ -142,7 +175,7 @@ public Instance(@NotNull ServerSettings serverSettings, EventNode globalE .build(); this.eventNode = globalEventHandler.map(this, EventFilter.INSTANCE); - entityTracker = new EntityTrackerImpl(serverSettings); + entityTracker = new EntityTrackerImpl(serverSettingsProvider); } /** @@ -190,8 +223,8 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, * Does call {@link PlayerBlockBreakEvent} * and send particle packets * - * @param player the {@link Player} who break the block - * @param blockPosition the position of the broken block + * @param player the {@link Player} who break the block + * @param blockPosition the position of the broken block * @param doBlockUpdates true to do block updates, false otherwise * @return true if the block has been broken, false if it has been cancelled */ @@ -327,6 +360,7 @@ public void setChunkGenerator(@Nullable ChunkGenerator chunkGenerator) { /** * Gets the chunk supplier of the instance. + * * @return the chunk supplier of the instance */ public abstract ChunkSupplier getChunkSupplier(); @@ -375,61 +409,6 @@ public void setChunkGenerator(@Nullable ChunkGenerator chunkGenerator) { */ public abstract boolean isInVoid(@NotNull Point point); - /** - * Gets if the instance has been registered in {@link InstanceManagerImpl}. - * - * @return true if the instance has been registered - */ - public boolean isRegistered() { - return registered; - } - - /** - * Changes the registered field. - *

        - * WARNING: should only be used by {@link InstanceManagerImpl}. - * - * @param registered true to mark the instance as registered - */ - protected void setRegistered(boolean registered) { - this.registered = registered; - } - - /** - * Gets the instance {@link DimensionType}. - * - * @return the dimension of the instance - */ - public DimensionType getDimensionType() { - return dimensionType; - } - - /** - * Gets the instance dimension name. - * @return the dimension name of the instance - */ - public @NotNull String getDimensionName() { - return dimensionName; - } - - /** - * Gets the age of this instance in tick. - * - * @return the age of this instance in tick - */ - public long getWorldAge() { - return worldAge; - } - - /** - * Gets the current time in the instance (sun/moon). - * - * @return the time in the instance - */ - public long getTime() { - return time; - } - /** * Changes the current time in the instance, from 0 to 24000. *

        @@ -448,16 +427,7 @@ public long getTime() { */ public void setTime(long time) { this.time = time; - PacketUtils.sendGroupedPacket(serverSettings, getPlayers(), createTimePacket()); - } - - /** - * Gets the rate of the time passing, it is 1 by default - * - * @return the time rate of the instance - */ - public int getTimeRate() { - return timeRate; + PacketUtils.sendGroupedPacket(serverSettingsProvider, getPlayers(), createTimePacket()); } /** @@ -473,27 +443,6 @@ public void setTimeRate(int timeRate) { this.timeRate = timeRate; } - /** - * Gets the rate at which the client is updated with the current instance time - * - * @return the client update rate for time related packet - */ - public @Nullable Duration getTimeUpdate() { - return timeUpdate; - } - - /** - * Changes the rate at which the client is updated about the time - *

        - * Setting it to null means that the client will never know about time change - * (but will still change server-side) - * - * @param timeUpdate the new update rate concerning time - */ - public void setTimeUpdate(@Nullable Duration timeUpdate) { - this.timeUpdate = timeUpdate; - } - /** * Creates a {@link TimeUpdatePacket} with the current age and time of this instance * @@ -510,15 +459,6 @@ public void setTimeUpdate(@Nullable Duration timeUpdate) { return new TimeUpdatePacket(worldAge, time); } - /** - * Gets the instance {@link WorldBorder}; - * - * @return the {@link WorldBorder} linked to the instance - */ - public @NotNull WorldBorder getWorldBorder() { - return worldBorder; - } - /** * Gets the entities in the instance; * @@ -608,7 +548,7 @@ public void sendBlockAction(@NotNull Point blockPosition, byte actionId, byte ac final Block block = getBlock(blockPosition); final Chunk chunk = getChunkAt(blockPosition); Check.notNull(chunk, "The chunk at {0} is not loaded!", blockPosition); - chunk.sendPacketToViewers(serverSettings, new BlockActionPacket(blockPosition, actionId, actionParam, block)); + chunk.sendPacketToViewers(serverSettingsProvider, new BlockActionPacket(blockPosition, actionId, actionParam, block)); } /** @@ -632,20 +572,6 @@ public void sendBlockAction(@NotNull Point blockPosition, byte actionId, byte ac return getChunk(point.chunkX(), point.chunkZ()); } - @ApiStatus.Experimental - public EntityTracker getEntityTracker() { - return entityTracker; - } - - /** - * Gets the instance unique id. - * - * @return the instance unique id - */ - public @NotNull UUID getUniqueId() { - return uniqueId; - } - /** * Performs a single tick in the instance, including scheduled tasks from {@link #scheduleNextTick(Consumer)}. *

        @@ -663,7 +589,7 @@ public void tick(long time) { this.time += timeRate; // time needs to be sent to players if (timeUpdate != null && !Cooldown.hasCooldown(time, lastTimeUpdate, timeUpdate)) { - PacketUtils.sendGroupedPacket(serverSettings, getPlayers(), createTimePacket()); + PacketUtils.sendGroupedPacket(serverSettingsProvider, getPlayers(), createTimePacket()); this.lastTimeUpdate = time; } @@ -678,22 +604,6 @@ public void tick(long time) { this.worldBorder.update(); } - @Override - public @NotNull TagHandler tagHandler() { - return tagHandler; - } - - @Override - public @NotNull Scheduler scheduler() { - return scheduler; - } - - @Override - @ApiStatus.Experimental - public @NotNull EventNode eventNode() { - return eventNode; - } - @Override public @NotNull InstanceSnapshot updateSnapshot(@NotNull SnapshotUpdater updater) { throw new RuntimeException("Not implemented"); // FIXME @@ -754,20 +664,8 @@ public void setExplosionSupplier(@Nullable ExplosionSupplier supplier) { this.explosionSupplier = supplier; } - /** - * Gets the instance space. - *

        - * Used by the pathfinder for entities. - * - * @return the instance space - */ - @ApiStatus.Internal - public @NotNull PFInstanceSpace getInstanceSpace() { - return instanceSpace; - } - @Override - public @NotNull Pointers pointers() { - return this.pointers; + public ServerSettings getServerSettings() { + return serverSettingsProvider.getServerSettings(); } } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index d9dff845c8e..ccbe3fe3e17 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -1,21 +1,21 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.instance.InstanceChunkLoadEvent; import net.minestom.server.event.instance.InstanceChunkUnloadEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; -import net.minestom.server.instance.block.BlockManager; +import net.minestom.server.instance.block.BlockManagerProvider; import net.minestom.server.instance.block.rule.BlockPlacementRule; import net.minestom.server.instance.generator.Generator; import net.minestom.server.instance.palette.Palette; @@ -23,7 +23,7 @@ import net.minestom.server.network.packet.server.play.BlockEntityDataPacket; import net.minestom.server.network.packet.server.play.EffectPacket; import net.minestom.server.network.packet.server.play.UnloadChunkPacket; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.async.AsyncUtils; @@ -32,7 +32,7 @@ import net.minestom.server.utils.chunk.ChunkSupplier; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -64,12 +64,12 @@ public class InstanceContainer extends Instance { // the shared instances assigned to this instance private final List sharedInstances = new CopyOnWriteArrayList<>(); - private final ExceptionHandler exceptionHandler; - private final BlockManager blockManager; - private final ServerSettings serverSettings; - private final EventNode globalEventHandler; - private final ThreadDispatcher dispatcher; - private final BiomeManager biomeManager; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final BlockManagerProvider blockManagerProvider; + private final BiomeManagerProvider biomeManagerProvider; + private final ServerSettingsProvider serverSettingsProvider; + private final GlobalEventHandler globalEventHandler; + private final ChunkDispatcherProvider chunkDispatcherProvider; // the chunk generator used, can be null private volatile Generator generator; @@ -94,30 +94,47 @@ public class InstanceContainer extends Instance { protected InstanceContainer srcInstance; // only present if this instance has been created using a copy private long lastBlockChangeTime; // Time at which the last block change happened (#setBlock) - public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, uniqueId, dimensionType, null, dimensionType.getName()); + public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(serverFacade, uniqueId, dimensionType, null, dimensionType.getName()); } - public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { - this(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, uniqueId, dimensionType, null, dimensionName); + public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + this(serverFacade, uniqueId, dimensionType, null, dimensionName); } @ApiStatus.Experimental - public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - this(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, uniqueId, dimensionType, loader, dimensionType.getName()); + public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + this(serverFacade, uniqueId, dimensionType, loader, dimensionType.getName()); + } + + public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { + this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, uniqueId, dimensionType, loader, dimensionName); } @ApiStatus.Experimental - public InstanceContainer(ExceptionHandler exceptionHandler, BlockManager blockManager, BiomeManager biomeManager, ServerSettings serverSettings, EventNode globalEventHandler, ThreadDispatcher dispatcher, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { - super(serverSettings, globalEventHandler, uniqueId, dimensionType, dimensionName); - this.exceptionHandler = exceptionHandler; - this.blockManager = blockManager; - this.biomeManager = biomeManager; - this.serverSettings = serverSettings; + public InstanceContainer( + @NotNull GlobalEventHandler globalEventHandler, + + @NotNull ExceptionHandlerProvider exceptionHandlerProvider, + @NotNull BlockManagerProvider blockManagerProvider, + @NotNull BiomeManagerProvider biomeManagerProvider, + @NotNull ServerSettingsProvider serverSettingsProvider, + @NotNull ChunkDispatcherProvider chunkDispatcherProvider, + + @NotNull UUID uniqueId, + @NotNull DimensionType dimensionType, + @Nullable IChunkLoader loader, + @NotNull NamespaceID dimensionName + ) { + super(globalEventHandler, serverSettingsProvider, uniqueId, dimensionType, dimensionName); + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.blockManagerProvider = blockManagerProvider; + this.biomeManagerProvider = biomeManagerProvider; + this.serverSettingsProvider = serverSettingsProvider; this.globalEventHandler = globalEventHandler; - this.dispatcher = dispatcher; - setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(biomeManager, instance, chunkX, chunkZ)); - setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(exceptionHandler, blockManager, biomeManager, "world"))); + this.chunkDispatcherProvider = chunkDispatcherProvider; + setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(biomeManagerProvider, instance, chunkX, chunkZ)); + setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(exceptionHandlerProvider, blockManagerProvider, biomeManagerProvider, "world"))); this.chunkLoader.loadInstance(this); } @@ -147,7 +164,7 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in @Nullable BlockHandler.Placement placement, @Nullable BlockHandler.Destroy destroy, boolean doBlockUpdates, int updateDistance) { if (chunk.isReadOnly()) return; - if(y >= getDimensionType().getMaxY() || y < getDimensionType().getMinY()) { + if (y >= getDimensionType().getMaxY() || y < getDimensionType().getMinY()) { LOGGER.warn("tried to set a block outside the world bounds, should be within [{}, {}): {}", getDimensionType().getMinY(), getDimensionType().getMaxY(), y); return; } @@ -164,7 +181,7 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in this.currentlyChangingBlocks.put(blockPosition, block); // Change id based on neighbors - final BlockPlacementRule blockPlacementRule = blockManager.getBlockPlacementRule(block); + final BlockPlacementRule blockPlacementRule = blockManagerProvider.getBlockManager().getBlockPlacementRule(block); if (placement != null && blockPlacementRule != null && doBlockUpdates) { BlockPlacementRule.PlacementState rulePlacement; if (placement instanceof BlockHandler.PlayerPlacement pp) { @@ -197,11 +214,11 @@ private synchronized void UNSAFE_setBlock(@NotNull Chunk chunk, int x, int y, in // Refresh player chunk block { - chunk.sendPacketToViewers(serverSettings, new BlockChangePacket(blockPosition, block.stateId())); + chunk.sendPacketToViewers(serverSettingsProvider, new BlockChangePacket(blockPosition, block.stateId())); var registry = block.registry(); if (registry.isBlockEntity()) { final NBTCompound data = BlockUtils.extractClientNbt(block); - chunk.sendPacketToViewers(serverSettings, new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); + chunk.sendPacketToViewers(serverSettingsProvider, new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); } } } @@ -242,7 +259,7 @@ public boolean breakBlock(@NotNull Player player, @NotNull Point blockPosition, UNSAFE_setBlock(chunk, x, y, z, resultBlock, null, new BlockHandler.PlayerDestroy(block, this, blockPosition, player), doBlockUpdates, 0); // Send the block break effect packet - PacketUtils.sendGroupedPacket(serverSettings, chunk.getViewers(), + PacketUtils.sendGroupedPacket(serverSettingsProvider, chunk.getViewers(), new EffectPacket(2001 /*Block break + block break sound*/, blockPosition, block.stateId(), false), // Prevent the block breaker to play the particles and sound two times (viewer) -> !viewer.equals(player)); @@ -265,7 +282,7 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { if (!isLoaded(chunk)) return; final int chunkX = chunk.getChunkX(); final int chunkZ = chunk.getChunkZ(); - chunk.sendPacketToViewers(serverSettings, new UnloadChunkPacket(chunkX, chunkZ)); + chunk.sendPacketToViewers(serverSettingsProvider, new UnloadChunkPacket(chunkX, chunkZ)); globalEventHandler.call(new InstanceChunkUnloadEvent(this, chunk)); // Remove all entities in chunk getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES).forEach(Entity::remove); @@ -275,7 +292,7 @@ public synchronized void unloadChunk(@NotNull Chunk chunk) { if (chunkLoader != null) { chunkLoader.unloadChunk(chunk); } - dispatcher.deletePartition(chunk); + chunkDispatcherProvider.getChunkDispatcher().deletePartition(chunk); } @Override @@ -326,7 +343,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { completableFuture.complete(chunk); }) .exceptionally(throwable -> { - exceptionHandler.handleException(throwable); + exceptionHandlerProvider.getExceptionHandler().handleException(throwable); return null; }); if (loader.supportsParallelLoading()) { @@ -392,7 +409,7 @@ public Chunk getChunk(int chunkX, int chunkZ) { // Apply awaiting forks processFork(chunk); } catch (Throwable e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } finally { // End generation refreshLastBlockChangeTime(); @@ -527,7 +544,14 @@ protected void addSharedInstance(SharedInstance sharedInstance) { * @see #getSrcInstance() to retrieve the "creation source" of the copied instance */ public synchronized InstanceContainer copy() { - InstanceContainer copiedInstance = new InstanceContainer(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, UUID.randomUUID(), getDimensionType()); + InstanceContainer copiedInstance = new InstanceContainer( + globalEventHandler, + exceptionHandlerProvider, + blockManagerProvider, + biomeManagerProvider, + serverSettingsProvider, + chunkDispatcherProvider, + UUID.randomUUID(), getDimensionType(), null, getDimensionName()); copiedInstance.srcInstance = this; copiedInstance.tagHandler = this.tagHandler.copy(); copiedInstance.lastBlockChangeTime = this.lastBlockChangeTime; @@ -651,8 +675,9 @@ private void executeNeighboursBlockPlacementRule(@NotNull Point blockPosition, i final Block neighborBlock = cache.getBlock(neighborX, neighborY, neighborZ, Condition.TYPE); if (neighborBlock == null) continue; - final BlockPlacementRule neighborBlockPlacementRule = blockManager.getBlockPlacementRule(neighborBlock); - if (neighborBlockPlacementRule == null || updateDistance >= neighborBlockPlacementRule.maxUpdateDistance()) continue; + final BlockPlacementRule neighborBlockPlacementRule = blockManagerProvider.getBlockManager().getBlockPlacementRule(neighborBlock); + if (neighborBlockPlacementRule == null || updateDistance >= neighborBlockPlacementRule.maxUpdateDistance()) + continue; final Vec neighborPosition = new Vec(neighborX, neighborY, neighborZ); final Block newNeighborBlock = neighborBlockPlacementRule.blockUpdate(new BlockPlacementRule.UpdateState( @@ -681,6 +706,6 @@ private CompletableFuture loadOrRetrieve(int chunkX, int chunkZ, Supplier private void cacheChunk(@NotNull Chunk chunk) { this.chunks.put(getChunkIndex(chunk), chunk); - dispatcher.createPartition(chunk); + chunkDispatcherProvider.getChunkDispatcher().createPartition(chunk); } } diff --git a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java index 1ec03b9b4e5..52fada4e17e 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java +++ b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java @@ -1,17 +1,17 @@ package net.minestom.server.instance; import lombok.RequiredArgsConstructor; -import net.minestom.server.ServerSettings; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettingsProvider; +import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.instance.InstanceRegisterEvent; import net.minestom.server.event.instance.InstanceUnregisterEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.block.BlockManager; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.exception.ExceptionHandlerProvider; +import net.minestom.server.instance.block.BlockManagerProvider; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -24,12 +24,16 @@ @RequiredArgsConstructor public final class InstanceManagerImpl implements InstanceManager { - private final ThreadDispatcher dispatcher; - private final EventNode globalEventHandler; - private final ServerSettings serverSettings; - private final ExceptionHandler exceptionHandler; - private final BlockManager blockManager; - private final BiomeManager biomeManager; + private final ChunkDispatcherProvider chunkDispatcherProvider; + private final GlobalEventHandlerProvider globalEventHandlerProvider; + private final ServerSettingsProvider serverSettingsProvider; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final BlockManagerProvider blockManagerProvider; + private final BiomeManagerProvider biomeManagerProvider; + + public InstanceManagerImpl(ServerFacade serverFacade) { + this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + } private final Set instances = new CopyOnWriteArraySet<>(); @@ -42,7 +46,7 @@ public void registerInstance(@NotNull Instance instance) { @Override @ApiStatus.Experimental public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - final InstanceContainer instanceContainer = new InstanceContainer(exceptionHandler, blockManager, biomeManager, serverSettings, globalEventHandler, dispatcher, UUID.randomUUID(), dimensionType, loader); + final InstanceContainer instanceContainer = new InstanceContainer(globalEventHandlerProvider.getGlobalEventHandler(), exceptionHandlerProvider, blockManagerProvider, biomeManagerProvider, serverSettingsProvider, chunkDispatcherProvider, UUID.randomUUID(), dimensionType, loader, dimensionType.getName()); registerInstance(instanceContainer); return instanceContainer; } @@ -62,7 +66,7 @@ public void registerInstance(@NotNull Instance instance) { Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); - final SharedInstance sharedInstance = new SharedInstance(serverSettings, globalEventHandler, UUID.randomUUID(), instanceContainer); + final SharedInstance sharedInstance = new SharedInstance(globalEventHandlerProvider.getGlobalEventHandler(), serverSettingsProvider, UUID.randomUUID(), instanceContainer); return registerSharedInstance(sharedInstance); } @@ -71,12 +75,12 @@ public void unregisterInstance(@NotNull Instance instance) { Check.stateCondition(!instance.getPlayers().isEmpty(), "You cannot unregister an instance with players inside."); synchronized (instance) { InstanceUnregisterEvent event = new InstanceUnregisterEvent(instance); - globalEventHandler.call(event); + globalEventHandlerProvider.getGlobalEventHandler().call(event); // Unload all chunks if (instance instanceof InstanceContainer) { instance.getChunks().forEach(instance::unloadChunk); - instance.getChunks().forEach(dispatcher::deletePartition); + instance.getChunks().forEach((partition) -> chunkDispatcherProvider.getChunkDispatcher().deletePartition(partition)); } // Unregister instance.setRegistered(false); @@ -108,8 +112,8 @@ public void unregisterInstance(@NotNull Instance instance) { private void UNSAFE_registerInstance(@NotNull Instance instance) { instance.setRegistered(true); this.instances.add(instance); - instance.getChunks().forEach(dispatcher::createPartition); + instance.getChunks().forEach((partition) -> chunkDispatcherProvider.getChunkDispatcher().createPartition(partition)); InstanceRegisterEvent event = new InstanceRegisterEvent(instance); - globalEventHandler.call(event); + globalEventHandlerProvider.getGlobalEventHandler().call(event); } } diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index d7e5cdae202..1d1e0c305b6 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -2,7 +2,8 @@ import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.collision.Shape; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -14,12 +15,12 @@ import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.play.data.LightData; import net.minestom.server.timer.ExecutionType; -import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.timer.Task; import net.minestom.server.timer.TaskSchedule; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.chunk.ChunkUtils; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -38,11 +39,11 @@ public class LightingChunk extends DynamicChunk { private static final int LIGHTING_CHUNKS_SEND_DELAY = Integer.getInteger("minestom.lighting.chunks-send-delay", 100); private static final ExecutorService pool = Executors.newWorkStealingPool(); - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; + private final SchedulerManagerProvider schedulerManagerProvider; private int[] heightmap; final CachedPacket lightCache; - private final SchedulerManager schedulerManager; boolean sendNeighbours = true; boolean chunkLoaded = false; @@ -81,11 +82,15 @@ private enum QueueType { Block.LAVA.namespace() ); - public LightingChunk(BiomeManager biomeManager, ServerSettings serverSettings, SchedulerManager schedulerManager, @NotNull Instance instance, int chunkX, int chunkZ) { - super(biomeManager, instance, chunkX, chunkZ); - this.serverSettings = serverSettings; - this.lightCache = new CachedPacket(serverSettings, this::createLightPacket); - this.schedulerManager = schedulerManager; + public LightingChunk(ServerFacade serverFacade, @NotNull Instance instance, int chunkX, int chunkZ) { + this(serverFacade, serverFacade, serverFacade, instance, chunkX, chunkZ); + } + + public LightingChunk(BiomeManagerProvider biomeManagerProvider, ServerSettingsProvider serverSettingsProvider, SchedulerManagerProvider schedulerManagerProvider, @NotNull Instance instance, int chunkX, int chunkZ) { + super(biomeManagerProvider, instance, chunkX, chunkZ); + this.serverSettingsProvider = serverSettingsProvider; + this.schedulerManagerProvider = schedulerManagerProvider; + this.lightCache = new CachedPacket(serverSettingsProvider, this::createLightPacket); } private boolean checkSkyOcclusion(Block block) { @@ -136,7 +141,7 @@ public void setBlock(int x, int y, int z, @NotNull Block block, public void sendLighting() { if (!isLoaded()) return; - sendPacketToViewers(serverSettings, lightCache); + sendPacketToViewers(serverSettingsProvider, lightCache); } @Override @@ -264,7 +269,7 @@ static void updateAfterGeneration(LightingChunk chunk) { return; } - sendingTask = chunk.schedulerManager.scheduleTask(() -> { + sendingTask = chunk.schedulerManagerProvider.getSchedulerManager().scheduleTask(() -> { queueLock.lock(); var copy = new ArrayList<>(sendQueue); sendQueue.clear(); @@ -436,7 +441,7 @@ private static void relight(Instance instance, Set queue, LightType type) @Override public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) { - LightingChunk lightingChunk = new LightingChunk(biomeManager, serverSettings, schedulerManager, instance, chunkX, chunkZ); + LightingChunk lightingChunk = new LightingChunk(biomeManagerProvider, serverSettingsProvider, schedulerManagerProvider, instance, chunkX, chunkZ); lightingChunk.sections = sections.stream().map(Section::clone).toList(); lightingChunk.entries.putAll(entries); return lightingChunk; diff --git a/src/main/java/net/minestom/server/instance/SharedInstance.java b/src/main/java/net/minestom/server/instance/SharedInstance.java index 380ca8a9668..667c9d12902 100644 --- a/src/main/java/net/minestom/server/instance/SharedInstance.java +++ b/src/main/java/net/minestom/server/instance/SharedInstance.java @@ -1,10 +1,10 @@ package net.minestom.server.instance; import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.instance.block.Block; import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; @@ -24,8 +24,8 @@ public class SharedInstance extends Instance { private final InstanceContainer instanceContainer; - public SharedInstance(ServerSettings serverSettings, EventNode globalEventHandler, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { - super(serverSettings, globalEventHandler, uniqueId, instanceContainer.getDimensionType()); + public SharedInstance(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { + super(globalEventHandler, serverSettingsProvider, uniqueId, instanceContainer.getDimensionType()); this.instanceContainer = instanceContainer; } @@ -128,4 +128,9 @@ public boolean isInVoid(@NotNull Point point) { public @NotNull InstanceContainer getInstanceContainer() { return instanceContainer; } + + @Override + public ServerSettings getServerSettings() { + return null; + } } diff --git a/src/main/java/net/minestom/server/instance/WorldBorder.java b/src/main/java/net/minestom/server/instance/WorldBorder.java index 07d4aee1c52..1db192c4d68 100644 --- a/src/main/java/net/minestom/server/instance/WorldBorder.java +++ b/src/main/java/net/minestom/server/instance/WorldBorder.java @@ -254,7 +254,7 @@ private void refreshCenter() { } private void sendPacket(@NotNull ServerPacket packet) { - PacketUtils.sendGroupedPacket(instance.getServerSettings(), instance.getPlayers(), packet); + PacketUtils.sendGroupedPacket(instance::getServerSettings, instance.getPlayers(), packet); } public enum CollisionAxis { diff --git a/src/main/java/net/minestom/server/inventory/EquipmentHandler.java b/src/main/java/net/minestom/server/inventory/EquipmentHandler.java index 17c06681f67..f47802a54ab 100644 --- a/src/main/java/net/minestom/server/inventory/EquipmentHandler.java +++ b/src/main/java/net/minestom/server/inventory/EquipmentHandler.java @@ -168,7 +168,7 @@ default void syncEquipment(@NotNull EquipmentSlot slot) { Entity entity = (Entity) this; final ItemStack itemStack = getEquipment(slot); - entity.sendPacketToViewers(getServerSettings(), new EntityEquipmentPacket(entity.getEntityId(), Map.of(slot, itemStack))); + entity.sendPacketToViewers(this::getServerSettings, new EntityEquipmentPacket(entity.getEntityId(), Map.of(slot, itemStack))); } ServerSettings getServerSettings(); diff --git a/src/main/java/net/minestom/server/inventory/Inventory.java b/src/main/java/net/minestom/server/inventory/Inventory.java index 1618f07c021..9f797f58404 100644 --- a/src/main/java/net/minestom/server/inventory/Inventory.java +++ b/src/main/java/net/minestom/server/inventory/Inventory.java @@ -92,7 +92,7 @@ private static byte generateId() { public void setTitle(@NotNull Component title) { this.title = title; // Re-open the inventory - sendPacketToViewers(serverSettings, new OpenWindowPacket(getWindowId(), getInventoryType().getWindowType(), title)); + sendPacketToViewers(() -> serverSettings, new OpenWindowPacket(getWindowId(), getInventoryType().getWindowType(), title)); // Send inventory items update(); } @@ -198,7 +198,7 @@ public void setCursorItem(@NotNull Player player, @NotNull ItemStack cursorItem) @Override protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean sendPacket) { itemStacks[slot] = itemStack; - if (sendPacket) sendPacketToViewers(serverSettings, new SetSlotPacket(getWindowId(), 0, (short) slot, itemStack)); + if (sendPacket) sendPacketToViewers(() -> serverSettings, new SetSlotPacket(getWindowId(), 0, (short) slot, itemStack)); } private @NotNull WindowItemsPacket createNewWindowItemsPacket(Player player) { @@ -213,7 +213,7 @@ protected void UNSAFE_itemInsert(int slot, @NotNull ItemStack itemStack, boolean * @see https://wiki.vg/Protocol#Window_Property */ protected void sendProperty(@NotNull InventoryProperty property, short value) { - sendPacketToViewers(serverSettings, new WindowPropertyPacket(getWindowId(), property.getProperty(), value)); + sendPacketToViewers(() -> serverSettings, new WindowPropertyPacket(getWindowId(), property.getProperty(), value)); } @Override diff --git a/src/main/java/net/minestom/server/inventory/PlayerInventory.java b/src/main/java/net/minestom/server/inventory/PlayerInventory.java index 0aecd565866..eae5cebb77c 100644 --- a/src/main/java/net/minestom/server/inventory/PlayerInventory.java +++ b/src/main/java/net/minestom/server/inventory/PlayerInventory.java @@ -39,7 +39,7 @@ public synchronized void clear() { cursorItem = ItemStack.AIR; super.clear(); // Update equipments - this.player.sendPacketToViewersAndSelf(serverSettings, player.getEquipmentsPacket()); + this.player.sendPacketToViewersAndSelf(() -> serverSettings, player.getEquipmentsPacket()); } @Override diff --git a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java index ac19071cec9..0a18b30821c 100644 --- a/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java +++ b/src/main/java/net/minestom/server/inventory/type/VillagerInventory.java @@ -25,12 +25,12 @@ public class VillagerInventory extends Inventory { public VillagerInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull Component title) { super(globalEventHandler, serverSettings, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(serverSettings, this::createTradePacket); + tradeCache = new CachedPacket(() -> serverSettings, this::createTradePacket); } public VillagerInventory(@NotNull EventNode globalEventHandler, @NotNull ServerSettings serverSettings, @NotNull String title) { super(globalEventHandler, serverSettings, InventoryType.MERCHANT, title); - tradeCache = new CachedPacket(serverSettings, this::createTradePacket); + tradeCache = new CachedPacket(() -> serverSettings, this::createTradePacket); } public List getTrades() { @@ -87,7 +87,7 @@ public void setCanRestock(boolean canRestock) { public void update() { super.update(); this.tradeCache.invalidate(); - sendPacketToViewers(serverSettings, tradeCache); + sendPacketToViewers(() -> serverSettings, tradeCache); } @Override diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index 9801eff6750..61dd5bd7e77 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -51,7 +51,7 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl final Collection recipients = playerChatEvent.getRecipients(); if (!recipients.isEmpty()) { // delegate to the messenger to avoid sending messages we shouldn't be - Messenger.sendMessage(player.getServerSettings(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); + Messenger.sendMessage(player.getServerSettingsProvider(), recipients, textObject, ChatPosition.CHAT, player.getUuid()); } }); } diff --git a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java index 606009d3643..071bbe41a24 100644 --- a/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerDiggingListener.java @@ -58,7 +58,7 @@ public static void playerDiggingListener(ClientPlayerDiggingPacket packet, Playe var registry = diggingResult.block().registry(); if (registry.isBlockEntity()) { final NBTCompound data = BlockUtils.extractClientNbt(diggingResult.block()); - player.sendPacketToViewersAndSelf(player.getServerSettings(), new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); + player.sendPacketToViewersAndSelf(player.getServerSettingsProvider(), new BlockEntityDataPacket(blockPosition, registry.blockEntityId(), data)); } } } diff --git a/src/main/java/net/minestom/server/listener/UseItemListener.java b/src/main/java/net/minestom/server/listener/UseItemListener.java index f16f8547a40..e40c88202f2 100644 --- a/src/main/java/net/minestom/server/listener/UseItemListener.java +++ b/src/main/java/net/minestom/server/listener/UseItemListener.java @@ -67,7 +67,7 @@ public static void useItemListener(ClientUseItemPacket packet, Player player) { PlayerItemAnimationEvent playerItemAnimationEvent = new PlayerItemAnimationEvent(player, itemAnimationType, hand); player.getGlobalEventHandler().callCancellable(playerItemAnimationEvent, () -> { player.refreshActiveHand(true, hand == Player.Hand.OFF, false); - player.sendPacketToViewers(player.getServerSettings(), player.getMetadataPacket()); + player.sendPacketToViewers(player.getServerSettingsProvider(), player.getMetadataPacket()); }); } } diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java index 67e0d7f2c5e..a9397e0d023 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java @@ -1,8 +1,9 @@ package net.minestom.server.listener.manager; -import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.ServerFacade; +import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.player.PlayerPacketEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.extras.MojangAuthProvider; import net.minestom.server.listener.*; import net.minestom.server.listener.common.KeepAliveListener; @@ -41,24 +42,28 @@ public final class PacketListenerManagerImpl implements PacketListenerManager { private final static Logger LOGGER = LoggerFactory.getLogger(PacketListenerManagerImpl.class); private final Map, PacketPrePlayListenerConsumer>[] listeners = new Map[ConnectionState.values().length]; - private final GlobalEventHandler globalEventHandler; - private final ExceptionHandler exceptionHandler; + private final GlobalEventHandlerProvider globalEventHandlerProvider; + private final ExceptionHandlerProvider exceptionHandlerProvider; - public PacketListenerManagerImpl(GlobalEventHandler globalEventHandler, ExceptionHandler exceptionHandler, MojangAuthProvider mojangAuthProvider, ConnectionManagerProvider connectionManagerProvider, SchedulerManagerProvider schedulerManagerProvider, ServerProvider serverProvider) { - this.globalEventHandler = globalEventHandler; - this.exceptionHandler = exceptionHandler; + public PacketListenerManagerImpl(ServerFacade serverFacade) { + this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + } + + public PacketListenerManagerImpl(GlobalEventHandlerProvider globalEventHandlerProvider, ExceptionHandlerProvider exceptionHandlerProvider, MojangAuthProvider mojangAuthProvider, ConnectionManagerProvider connectionManagerProvider, SchedulerManagerProvider schedulerManagerProvider, ServerProvider serverProvider) { + this.globalEventHandlerProvider = globalEventHandlerProvider; + this.exceptionHandlerProvider = exceptionHandlerProvider; for (int i = 0; i < listeners.length; i++) { listeners[i] = new ConcurrentHashMap<>(); } setListener(ConnectionState.HANDSHAKE, ClientHandshakePacket.class, HandshakeListener::listener); - setListener(ConnectionState.STATUS, StatusRequestPacket.class, (packet, connection) -> StatusListener.requestListener(connectionManagerProvider.getConnectionManager(), globalEventHandler, serverProvider.getServer(), packet, connection)); - setListener(ConnectionState.STATUS, PingPacket.class, (packet, connection) -> StatusListener.pingListener(globalEventHandler, schedulerManagerProvider.getSchedulerManager(), packet, connection)); + setListener(ConnectionState.STATUS, StatusRequestPacket.class, (packet, connection) -> StatusListener.requestListener(connectionManagerProvider.getConnectionManager(), globalEventHandlerProvider.getGlobalEventHandler(), serverProvider.getServer(), packet, connection)); + setListener(ConnectionState.STATUS, PingPacket.class, (packet, connection) -> StatusListener.pingListener(globalEventHandlerProvider.getGlobalEventHandler(), schedulerManagerProvider.getSchedulerManager(), packet, connection)); setListener(ConnectionState.LOGIN, ClientLoginStartPacket.class, (packet, connection) -> LoginListener.loginStartListener(mojangAuthProvider.getMojangAuth(), connectionManagerProvider.getConnectionManager(), packet, connection)); - setListener(ConnectionState.LOGIN, ClientEncryptionResponsePacket.class, (packet, connection) -> LoginListener.loginEncryptionResponseListener(mojangAuthProvider.getMojangAuth(), exceptionHandler, connectionManagerProvider.getConnectionManager(), packet, connection)); - setListener(ConnectionState.LOGIN, ClientLoginPluginResponsePacket.class, (packet, connection) -> LoginListener.loginPluginResponseListener(exceptionHandler, connectionManagerProvider.getConnectionManager(), packet, connection)); + setListener(ConnectionState.LOGIN, ClientEncryptionResponsePacket.class, (packet, connection) -> LoginListener.loginEncryptionResponseListener(mojangAuthProvider.getMojangAuth(), exceptionHandlerProvider.getExceptionHandler(), connectionManagerProvider.getConnectionManager(), packet, connection)); + setListener(ConnectionState.LOGIN, ClientLoginPluginResponsePacket.class, (packet, connection) -> LoginListener.loginPluginResponseListener(exceptionHandlerProvider.getExceptionHandler(), connectionManagerProvider.getConnectionManager(), packet, connection)); setListener(ConnectionState.LOGIN, ClientLoginAcknowledgedPacket.class, (packet, connection) -> LoginListener.loginAckListener(connectionManagerProvider.getConnectionManager(), packet, connection)); setConfigurationListener(ClientSettingsPacket.class, SettingsListener::listener); @@ -120,7 +125,7 @@ public void processClientPacket(@NotNull T packet, @Not // Event if (state == ConnectionState.PLAY) { PlayerPacketEvent playerPacketEvent = new PlayerPacketEvent(connection.getPlayer(), packet); - globalEventHandler.call(playerPacketEvent); + globalEventHandlerProvider.getGlobalEventHandler().call(playerPacketEvent); if (playerPacketEvent.isCancelled()) { return; } @@ -131,7 +136,7 @@ public void processClientPacket(@NotNull T packet, @Not packetListenerConsumer.accept(packet, connection); } catch (Exception e) { // Packet is likely invalid - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } diff --git a/src/main/java/net/minestom/server/message/Messenger.java b/src/main/java/net/minestom/server/message/Messenger.java index 7f193fcbe53..c3341fc3881 100644 --- a/src/main/java/net/minestom/server/message/Messenger.java +++ b/src/main/java/net/minestom/server/message/Messenger.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.entity.Player; import net.minestom.server.network.packet.server.play.SystemChatPacket; import net.minestom.server.utils.PacketUtils; @@ -93,9 +93,9 @@ public static boolean sendMessage(@NotNull Player player, @NotNull Component mes * @param position the position * @param uuid the UUID of the sender, if any */ - public static void sendMessage(ServerSettings serverSettings, @NotNull Collection players, @NotNull Component message, + public static void sendMessage(ServerSettingsProvider serverSettingsProvider, @NotNull Collection players, @NotNull Component message, @NotNull ChatPosition position, @Nullable UUID uuid) { - PacketUtils.sendGroupedPacket(serverSettings, players, new SystemChatPacket(message, false), + PacketUtils.sendGroupedPacket(serverSettingsProvider, players, new SystemChatPacket(message, false), player -> getChatMessageType(player).accepts(position)); } diff --git a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java index c8ce9251ab2..0ec3a888d2f 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java +++ b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java @@ -9,11 +9,11 @@ import net.minestom.server.entity.damage.DamageType; import net.minestom.server.event.Event; import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; import net.minestom.server.event.player.AsyncPlayerPreLoginEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.gamedata.tags.TagManager; -import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.BlockManager; import net.minestom.server.listener.manager.PacketListenerManager; @@ -30,7 +30,7 @@ import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.recipe.RecipeManager; import net.minestom.server.scoreboard.TeamManager; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.StringUtils; import net.minestom.server.utils.async.AsyncUtils; @@ -80,7 +80,7 @@ public final class ConnectionManagerImpl implements ConnectionManager { private final Set unmodifiableConfigurationPlayers = Collections.unmodifiableSet(configurationPlayers); private final Set unmodifiablePlayPlayers = Collections.unmodifiableSet(playPlayers); - private final ExceptionHandler exceptionHandler; + private final ExceptionHandlerProvider exceptionHandlerProvider; private final ServerSettings serverSettings; private final BiomeManager biomeManager; private final DimensionTypeManager dimensionTypeManager; @@ -95,9 +95,9 @@ public final class ConnectionManagerImpl implements ConnectionManager { public ConnectionManagerImpl( ServerSettings serverSettings, - EventNode globalEventHandler, - ThreadDispatcher dispatcher, - ExceptionHandler exceptionHandler, + GlobalEventHandler globalEventHandler, + ChunkDispatcherProvider chunkDispatcherProvider, + ExceptionHandlerProvider exceptionHandlerProvider, TeamManager teamManager, RecipeManager recipeManager, CommandManager commandManager, @@ -109,13 +109,13 @@ public ConnectionManagerImpl( TagManager tagManager, BlockManager blockManager ) { - this.exceptionHandler = exceptionHandler; + this.exceptionHandlerProvider = exceptionHandlerProvider; this.serverSettings = serverSettings; this.biomeManager = biomeManager; this.dimensionTypeManager = dimensionTypeManager; this.globalEventHandler = globalEventHandler; - this.defaultTags = new CachedPacket(serverSettings, new TagsPacket(tagManager.getTagMap())); - defaultPlayerProvider = (uuid, username, connection) -> new Player(serverSettings, globalEventHandler, dispatcher, exceptionHandler, this, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, connection); + this.defaultTags = new CachedPacket(() -> serverSettings, new TagsPacket(tagManager.getTagMap())); + defaultPlayerProvider = (uuid, username, connection) -> new Player(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, this, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, connection); playerProvider = defaultPlayerProvider; } @@ -201,7 +201,7 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { @Override @ApiStatus.Internal public @NotNull CompletableFuture transitionLoginToConfig(@NotNull Player player) { - return AsyncUtils.runAsync(exceptionHandler, () -> { + return AsyncUtils.runAsync(exceptionHandlerProvider.getExceptionHandler(), () -> { final PlayerConnection playerConnection = player.getPlayerConnection(); // Compression @@ -250,7 +250,7 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { } player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); - CompletableFuture configFuture = AsyncUtils.runAsync(exceptionHandler, () -> { + CompletableFuture configFuture = AsyncUtils.runAsync(exceptionHandlerProvider.getExceptionHandler(), () -> { player.sendPacket(PluginMessagePacket.getBrandPacket(serverSettings)); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); diff --git a/src/main/java/net/minestom/server/network/PacketProcessorImpl.java b/src/main/java/net/minestom/server/network/PacketProcessorImpl.java index 2404c332317..0acfa8b175d 100644 --- a/src/main/java/net/minestom/server/network/PacketProcessorImpl.java +++ b/src/main/java/net/minestom/server/network/PacketProcessorImpl.java @@ -1,7 +1,7 @@ package net.minestom.server.network; import net.minestom.server.entity.Player; -import net.minestom.server.listener.manager.PacketListenerManager; +import net.minestom.server.listener.manager.PacketListenerManagerProvider; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.ClientPacketsHandler; import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; @@ -17,15 +17,15 @@ public class PacketProcessorImpl implements PacketProcessor { private final ClientPacketsHandler configurationHandler; private final ClientPacketsHandler playHandler; - private final PacketListenerManager packetListenerManager; + private final PacketListenerManagerProvider packetListenerManagerProvider; - public PacketProcessorImpl(@NotNull PacketListenerManager packetListenerManager) { + public PacketProcessorImpl(@NotNull PacketListenerManagerProvider packetListenerManagerProvider) { statusHandler = new ClientPacketsHandler.Status(); loginHandler = new ClientPacketsHandler.Login(); configurationHandler = new ClientPacketsHandler.Configuration(); playHandler = new ClientPacketsHandler.Play(); - this.packetListenerManager = packetListenerManager; + this.packetListenerManagerProvider = packetListenerManagerProvider; } @Override @@ -51,7 +51,7 @@ public ClientPacket process(@NotNull PlayerConnection connection, int packetId, switch (connection.getConnectionState()) { // Process all pre-config packets immediately - case HANDSHAKE, STATUS, LOGIN -> packetListenerManager.processClientPacket(packet, connection); + case HANDSHAKE, STATUS, LOGIN -> packetListenerManagerProvider.getPacketListenerManager().processClientPacket(packet, connection); // Process config and play packets on the next tick case CONFIGURATION, PLAY -> { final Player player = connection.getPlayer(); diff --git a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java index 84eff0ef640..367314857d4 100644 --- a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java @@ -1,6 +1,6 @@ package net.minestom.server.network.packet.server; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.network.ConnectionState; import net.minestom.server.utils.PacketUtils; import org.jetbrains.annotations.ApiStatus; @@ -22,15 +22,15 @@ public final class CachedPacket implements SendablePacket { private final Supplier packetSupplier; private volatile SoftReference packet; - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; - public CachedPacket(ServerSettings serverSettings, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { + public CachedPacket(ServerSettingsProvider serverSettingsProvider, @NotNull Supplier<@NotNull ServerPacket> packetSupplier) { this.packetSupplier = packetSupplier; - this.serverSettings = serverSettings; + this.serverSettingsProvider = serverSettingsProvider; } - public CachedPacket(ServerSettings serverSettings, @NotNull ServerPacket packet) { - this(serverSettings, () -> packet); + public CachedPacket(ServerSettingsProvider serverSettingsProvider, @NotNull ServerPacket packet) { + this(serverSettingsProvider, () -> packet); } public void invalidate() { @@ -53,7 +53,7 @@ public void invalidate() { SoftReference ref = packet; FramedPacket cache; if (ref == null || (cache = ref.get()) == null) { - cache = PacketUtils.allocateTrimmedPacket(serverSettings, state, packetSupplier.get()); + cache = PacketUtils.allocateTrimmedPacket(serverSettingsProvider.getServerSettings(), state, packetSupplier.get()); this.packet = new SoftReference<>(cache); } return cache; diff --git a/src/main/java/net/minestom/server/potion/Potion.java b/src/main/java/net/minestom/server/potion/Potion.java index d3d4a4bd633..d6d9b79851d 100644 --- a/src/main/java/net/minestom/server/potion/Potion.java +++ b/src/main/java/net/minestom/server/potion/Potion.java @@ -114,7 +114,7 @@ public boolean hasIcon() { * @param entity the entity to add the effect to */ public void sendAddPacket(@NotNull Entity entity) { - entity.sendPacketToViewersAndSelf(entity.getServerSettings(), new EntityEffectPacket(entity.getEntityId(), this, null)); + entity.sendPacketToViewersAndSelf(entity.getServerSettingsProvider(), new EntityEffectPacket(entity.getEntityId(), this, null)); } /** @@ -125,7 +125,7 @@ public void sendAddPacket(@NotNull Entity entity) { * @param entity the entity to remove the effect from */ public void sendRemovePacket(@NotNull Entity entity) { - entity.sendPacketToViewersAndSelf(entity.getServerSettings(), new RemoveEntityEffectPacket(entity.getEntityId(), effect)); + entity.sendPacketToViewersAndSelf(entity.getServerSettingsProvider(), new RemoveEntityEffectPacket(entity.getEntityId(), effect)); } @Override diff --git a/src/main/java/net/minestom/server/scoreboard/Sidebar.java b/src/main/java/net/minestom/server/scoreboard/Sidebar.java index 72eff95cec5..1571d74c80d 100644 --- a/src/main/java/net/minestom/server/scoreboard/Sidebar.java +++ b/src/main/java/net/minestom/server/scoreboard/Sidebar.java @@ -98,7 +98,7 @@ public void setTitle(@NotNull String title) { */ public void setTitle(@NotNull Component title) { this.title = title; - sendPacketToViewers(serverSettings, new ScoreboardObjectivePacket(objectiveName, (byte) 2, title, + sendPacketToViewers(() -> serverSettings, new ScoreboardObjectivePacket(objectiveName, (byte) 2, title, ScoreboardObjectivePacket.Type.INTEGER, null)); } @@ -129,7 +129,7 @@ public void createLine(@NotNull ScoreboardLine scoreboardLine) { this.lines.add(scoreboardLine); // Send to current viewers - sendPacketsToViewers(serverSettings, scoreboardLine.sidebarTeam.getCreationPacket(), scoreboardLine.getScoreCreationPacket(objectiveName)); + sendPacketsToViewers(() -> serverSettings, scoreboardLine.sidebarTeam.getCreationPacket(), scoreboardLine.getScoreCreationPacket(objectiveName)); } } @@ -143,7 +143,7 @@ public void updateLineContent(@NotNull String id, @NotNull Component content) { final ScoreboardLine scoreboardLine = getLine(id); if (scoreboardLine != null) { scoreboardLine.refreshContent(content); - sendPacketToViewers(serverSettings, scoreboardLine.sidebarTeam.updatePrefix(content)); + sendPacketToViewers(() -> serverSettings, scoreboardLine.sidebarTeam.updatePrefix(content)); } } @@ -157,7 +157,7 @@ public void updateLineScore(@NotNull String id, int score) { final ScoreboardLine scoreboardLine = getLine(id); if (scoreboardLine != null) { scoreboardLine.line = score; - sendPacketToViewers(serverSettings, scoreboardLine.getLineScoreUpdatePacket(objectiveName, score)); + sendPacketToViewers(() -> serverSettings, scoreboardLine.getLineScoreUpdatePacket(objectiveName, score)); } } @@ -196,7 +196,7 @@ public void removeLine(@NotNull String id) { if (line.id.equals(id)) { // Remove the line for current viewers - sendPacketsToViewers(serverSettings, line.getScoreDestructionPacket(objectiveName), line.sidebarTeam.getDestructionPacket()); + sendPacketsToViewers(() -> serverSettings, line.getScoreDestructionPacket(objectiveName), line.sidebarTeam.getDestructionPacket()); line.returnName(availableColors); return true; diff --git a/src/main/java/net/minestom/server/scoreboard/TabList.java b/src/main/java/net/minestom/server/scoreboard/TabList.java index 929705691bd..32f81dc8790 100644 --- a/src/main/java/net/minestom/server/scoreboard/TabList.java +++ b/src/main/java/net/minestom/server/scoreboard/TabList.java @@ -62,12 +62,12 @@ public void setType(ScoreboardObjectivePacket.Type type) { public void setHeader(@NotNull Component header) { this.header = header; - sendPacketToViewers(serverSettings, new PlayerListHeaderAndFooterPacket(header, footer)); + sendPacketToViewers(() -> serverSettings, new PlayerListHeaderAndFooterPacket(header, footer)); } public void setFooter(@NotNull Component footer) { this.footer = footer; - sendPacketToViewers(serverSettings, new PlayerListHeaderAndFooterPacket(header, footer)); + sendPacketToViewers(() -> serverSettings, new PlayerListHeaderAndFooterPacket(header, footer)); } @Override diff --git a/src/main/java/net/minestom/server/scoreboard/Team.java b/src/main/java/net/minestom/server/scoreboard/Team.java index c8e988d7cf6..7045424b111 100644 --- a/src/main/java/net/minestom/server/scoreboard/Team.java +++ b/src/main/java/net/minestom/server/scoreboard/Team.java @@ -134,7 +134,7 @@ public void addMembers(@NotNull Collection<@NotNull String> toAdd) { final TeamsPacket addPlayerPacket = new TeamsPacket(teamName, new TeamsPacket.AddEntitiesToTeamAction(toAdd)); // Sends to all online players the add player packet - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, addPlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManager, () -> serverSettings, addPlayerPacket); // invalidate player members this.isPlayerMembersUpToDate = false; @@ -165,7 +165,7 @@ public void removeMembers(@NotNull Collection<@NotNull String> toRemove) { final TeamsPacket removePlayerPacket = new TeamsPacket(teamName, new TeamsPacket.RemoveEntitiesToTeamAction(toRemove)); // Sends to all online player the remove player packet - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, removePlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManager, () -> serverSettings, removePlayerPacket); // Removes the member from the team this.members.removeAll(toRemove); @@ -469,7 +469,7 @@ public Component getSuffix() { public void sendUpdatePacket() { final var info = new TeamsPacket.UpdateTeamAction(teamDisplayName, friendlyFlags, nameTagVisibility, collisionRule, teamColor, prefix, suffix); - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, new TeamsPacket(teamName, info)); + PacketUtils.broadcastPlayPacket(connectionManager, () -> serverSettings, new TeamsPacket(teamName, info)); } @Override diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java b/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java index bfa19523dc2..10732012286 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java @@ -29,13 +29,13 @@ public final class TeamManagerImpl implements TeamManager { */ void registerNewTeam(@NotNull Team team, ConnectionManager connectionManager) { this.teams.add(team); - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, team.createTeamsCreationPacket()); + PacketUtils.broadcastPlayPacket(connectionManager, () -> serverSettings, team.createTeamsCreationPacket()); } @Override public boolean deleteTeam(@NotNull Team team, ConnectionManager connectionManager) { // Sends to all online players a team destroy packet - PacketUtils.broadcastPlayPacket(connectionManager, serverSettings, team.createTeamDestructionPacket()); + PacketUtils.broadcastPlayPacket(connectionManager, () -> serverSettings, team.createTeamDestructionPacket()); return this.teams.remove(team); } diff --git a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java index baf7a1fcbbd..8729a632488 100644 --- a/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java +++ b/src/main/java/net/minestom/server/snapshot/SnapshotImpl.java @@ -13,7 +13,7 @@ import net.minestom.server.utils.collection.MappedCollection; import net.minestom.server.world.DimensionType; import net.minestom.server.world.biomes.Biome; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -75,7 +75,7 @@ public record Instance(AtomicReference serverRef, } } - public record Chunk(BiomeManager biomeManager, + public record Chunk(BiomeManagerProvider biomeManagerProvider, int minSection, int chunkX, int chunkZ, Section[] sections, Int2ObjectOpenHashMap blockEntries, @@ -104,7 +104,7 @@ public record Chunk(BiomeManager biomeManager, final Section section = sections[getChunkCoordinate(y) - minSection]; final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return biomeManager.getById(id); + return biomeManagerProvider.getBiomeManager().getById(id); } @Override diff --git a/src/main/java/net/minestom/server/thread/ChunkDispatcher.java b/src/main/java/net/minestom/server/thread/ChunkDispatcher.java index 58da8d4289a..03a79f260c7 100644 --- a/src/main/java/net/minestom/server/thread/ChunkDispatcher.java +++ b/src/main/java/net/minestom/server/thread/ChunkDispatcher.java @@ -1,15 +1,15 @@ package net.minestom.server.thread; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Chunk; import org.jetbrains.annotations.NotNull; public interface ChunkDispatcher extends ThreadDispatcher{ - static @NotNull ChunkDispatcher of(ExceptionHandler exceptionHandler, @NotNull ThreadProvider provider, int threadCount) { - return new ChunkDispatcherImpl(exceptionHandler, provider, threadCount); + static @NotNull ChunkDispatcher of(ExceptionHandlerProvider exceptionHandlerProvider, @NotNull ThreadProvider provider, int threadCount) { + return new ChunkDispatcherImpl(exceptionHandlerProvider, provider, threadCount); } - static @NotNull ChunkDispatcher singleThread(ExceptionHandler exceptionHandler) { - return of(exceptionHandler, ThreadProvider.counter(), 1); + static @NotNull ChunkDispatcher singleThread(ExceptionHandlerProvider exceptionHandlerProvider) { + return of(exceptionHandlerProvider, ThreadProvider.counter(), 1); } } diff --git a/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java b/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java index 52561a704c4..1a74430ec43 100644 --- a/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java +++ b/src/main/java/net/minestom/server/thread/ChunkDispatcherImpl.java @@ -1,10 +1,10 @@ package net.minestom.server.thread; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Chunk; public class ChunkDispatcherImpl extends ThreadDispatcherImpl implements ChunkDispatcher{ - ChunkDispatcherImpl(ExceptionHandler exceptionHandler, ThreadProvider provider, int threadCount) { - super(exceptionHandler, provider, threadCount); + ChunkDispatcherImpl(ExceptionHandlerProvider exceptionHandlerProvider, ThreadProvider provider, int threadCount) { + super(exceptionHandlerProvider, provider, threadCount); } } diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java index b081f91701d..e045d0c8f5a 100644 --- a/src/main/java/net/minestom/server/thread/ThreadDispatcher.java +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcher.java @@ -1,19 +1,19 @@ package net.minestom.server.thread; import net.minestom.server.Tickable; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; import java.util.List; public interface ThreadDispatcher

        { - static

        @NotNull ThreadDispatcher

        of(ExceptionHandler exceptionHandler, @NotNull ThreadProvider

        provider, int threadCount) { - return new ThreadDispatcherImpl<>(exceptionHandler, provider, threadCount); + static

        @NotNull ThreadDispatcher

        of(ExceptionHandlerProvider exceptionHandlerProvider, @NotNull ThreadProvider

        provider, int threadCount) { + return new ThreadDispatcherImpl<>(exceptionHandlerProvider, provider, threadCount); } - static

        @NotNull ThreadDispatcher

        singleThread(ExceptionHandler exceptionHandler) { - return of(exceptionHandler, ThreadProvider.counter(), 1); + static

        @NotNull ThreadDispatcher

        singleThread(ExceptionHandlerProvider exceptionHandlerProvider) { + return of(exceptionHandlerProvider, ThreadProvider.counter(), 1); } @Unmodifiable diff --git a/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java b/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java index b40f0b8d95c..d4cba1e923a 100644 --- a/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java +++ b/src/main/java/net/minestom/server/thread/ThreadDispatcherImpl.java @@ -2,7 +2,7 @@ import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import org.jctools.queues.MessagePassingQueue; import org.jctools.queues.MpscUnboundedArrayQueue; import org.jetbrains.annotations.ApiStatus; @@ -31,10 +31,10 @@ public class ThreadDispatcherImpl

        implements ThreadDispatcher

        { // Requests consumed at the end of each tick private final MessagePassingQueue> updates = new MpscUnboundedArrayQueue<>(1024); - ThreadDispatcherImpl(ExceptionHandler exceptionHandler, ThreadProvider

        provider, int threadCount) { + ThreadDispatcherImpl(ExceptionHandlerProvider exceptionHandlerProvider, ThreadProvider

        provider, int threadCount) { this.provider = provider; TickThread[] threads = new TickThread[threadCount]; - Arrays.setAll(threads, (i) -> new TickThread(exceptionHandler, i)); + Arrays.setAll(threads, (i) -> new TickThread(exceptionHandlerProvider, i)); this.threads = List.of(threads); this.threads.forEach(Thread::start); } diff --git a/src/main/java/net/minestom/server/thread/TickThread.java b/src/main/java/net/minestom/server/thread/TickThread.java index 71a512ba1bd..189fa216cc5 100644 --- a/src/main/java/net/minestom/server/thread/TickThread.java +++ b/src/main/java/net/minestom/server/thread/TickThread.java @@ -3,7 +3,7 @@ import net.minestom.server.ServerConsts; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Chunk; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -24,7 +24,7 @@ @ApiStatus.Internal public final class TickThread extends MinestomThread { private final ReentrantLock lock = new ReentrantLock(); - private final ExceptionHandler exceptionHandler; + private final ExceptionHandlerProvider exceptionHandlerProvider; private volatile boolean stop; private CountDownLatch latch; @@ -32,9 +32,9 @@ public final class TickThread extends MinestomThread { private long tickNum = 0; private final List entries = new ArrayList<>(); - public TickThread(ExceptionHandler exceptionHandler, int number) { + public TickThread(ExceptionHandlerProvider exceptionHandlerProvider, int number) { super(ServerConsts.THREAD_NAME_TICK + "-" + number); - this.exceptionHandler = exceptionHandler; + this.exceptionHandlerProvider = exceptionHandlerProvider; } public static @Nullable TickThread current() { @@ -51,7 +51,7 @@ public void run() { try { tick(); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } this.lock.unlock(); // #acquire() callbacks @@ -76,7 +76,7 @@ private void tick() { try { element.tick(tickTime); } catch (Throwable e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } } diff --git a/src/main/java/net/minestom/server/timer/Schedulable.java b/src/main/java/net/minestom/server/timer/Schedulable.java index 998d5703b06..04dae8bd0d6 100644 --- a/src/main/java/net/minestom/server/timer/Schedulable.java +++ b/src/main/java/net/minestom/server/timer/Schedulable.java @@ -3,5 +3,5 @@ import org.jetbrains.annotations.NotNull; public interface Schedulable { - @NotNull Scheduler scheduler(); + @NotNull Scheduler getScheduler(); } diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index fe04a5cf27f..6d36e86f4d3 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -12,6 +12,7 @@ import net.kyori.adventure.text.TranslatableComponent; import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Viewable; import net.minestom.server.adventure.ComponentHolder; import net.minestom.server.adventure.MinestomAdventure; @@ -69,7 +70,7 @@ private PacketUtils() { *

          *
        1. If {@code audience} is a {@link Player}, send the packet to them.
        2. *
        3. Otherwise, if {@code audience} is a {@link PacketGroupingAudience}, call - * {@link #sendGroupedPacket(ServerSettings, Collection, ServerPacket)} on the players that the + * {@link #sendGroupedPacket(ServerSettingsProvider, Collection, ServerPacket)} on the players that the * grouping audience contains.
        4. *
        5. Otherwise, if {@code audience} is a {@link ForwardingAudience.Single}, * call this method on the single audience inside the forwarding audience.
        6. @@ -86,7 +87,7 @@ public static void sendPacket(ServerFacade serverFacade, @NotNull Audience audie if (audience instanceof Player player) { player.sendPacket(packet); } else if (audience instanceof PacketGroupingAudience groupingAudience) { - PacketUtils.sendGroupedPacket(serverFacade.getServerSettings(), groupingAudience.getPlayers(), packet); + PacketUtils.sendGroupedPacket(serverFacade, groupingAudience.getPlayers(), packet); } else if (audience instanceof ForwardingAudience.Single singleAudience) { PacketUtils.sendPacket(serverFacade, singleAudience.audience(), packet); } else if (audience instanceof ForwardingAudience forwardingAudience) { @@ -105,9 +106,9 @@ public static void sendPacket(ServerFacade serverFacade, @NotNull Audience audie * @param packet the packet to send to the players * @param predicate predicate to ignore specific players */ - public static void sendGroupedPacket(ServerSettings serverSettings, @NotNull Collection players, @NotNull ServerPacket packet, + public static void sendGroupedPacket(ServerSettingsProvider serverSettingsProvider, @NotNull Collection players, @NotNull ServerPacket packet, @NotNull Predicate predicate) { - final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(serverSettings, packet) : packet; + final var sendablePacket = shouldUseCachePacket(packet) ? new CachedPacket(serverSettingsProvider, packet) : packet; players.forEach(player -> { if (predicate.test(player)) player.sendPacket(sendablePacket); @@ -148,17 +149,17 @@ private static boolean isTranslatable(final @NotNull Component component) { } /** - * Same as {@link #sendGroupedPacket(ServerSettings, Collection, ServerPacket, Predicate)} + * Same as {@link #sendGroupedPacket(ServerSettingsProvider, Collection, ServerPacket, Predicate)} * but with the player validator sets to null. * - * @see #sendGroupedPacket(ServerSettings, Collection, ServerPacket, Predicate) + * @see #sendGroupedPacket(ServerSettingsProvider, Collection, ServerPacket, Predicate) */ - public static void sendGroupedPacket(ServerSettings serverSettings, @NotNull Collection players, @NotNull ServerPacket packet) { - sendGroupedPacket(serverSettings, players, packet, player -> true); + public static void sendGroupedPacket(ServerSettingsProvider serverSettingsProvider, @NotNull Collection players, @NotNull ServerPacket packet) { + sendGroupedPacket(serverSettingsProvider, players, packet, player -> true); } - public static void broadcastPlayPacket(ConnectionManager connectionManager, ServerSettings serverSettings, @NotNull ServerPacket packet) { - sendGroupedPacket(serverSettings, connectionManager.getOnlinePlayers(), packet); + public static void broadcastPlayPacket(ConnectionManager connectionManager, ServerSettingsProvider serverSettingsProvider, @NotNull ServerPacket packet) { + sendGroupedPacket(serverSettingsProvider, connectionManager.getOnlinePlayers(), packet); } @ApiStatus.Experimental @@ -166,11 +167,11 @@ public static void prepareViewablePacket(ServerSettings serverSettings, @NotNull @Nullable Entity entity) { if (entity != null && !entity.hasPredictableViewers()) { // Operation cannot be optimized - entity.sendPacketToViewers(serverSettings, serverPacket); + entity.sendPacketToViewers(() -> serverSettings, serverPacket); return; } if (!VIEWABLE_PACKET) { - sendGroupedPacket(serverSettings, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); + sendGroupedPacket(() -> serverSettings, viewable.getViewers(), serverPacket, value -> !Objects.equals(value, entity)); return; } final Player exception = entity instanceof Player ? (Player) entity : null; diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index 5cf943b0b16..e9edb7f2523 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -85,7 +85,7 @@ public void entityNodeGC(Env env) { // Ensure that the entities GCed when a local listener is present var node = env.process().getGlobalEventHandler(); var entity = new Entity(env.process(), EntityType.ZOMBIE); - entity.eventNode().addListener(EntityTickEvent.class, event -> { + entity.getEventNode().addListener(EntityTickEvent.class, event -> { }); node.call(new EntityTickEvent(entity)); diff --git a/src/test/java/net/minestom/server/event/EventNodeMapTest.java b/src/test/java/net/minestom/server/event/EventNodeMapTest.java index d7c9c52e058..7be2f5f36c8 100644 --- a/src/test/java/net/minestom/server/event/EventNodeMapTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeMapTest.java @@ -91,7 +91,7 @@ public void entityLocal() { var handle = node.getHandle(EventNodeTest.EntityTestEvent.class); assertFalse(handle.hasListener()); - entity.eventNode().addListener(listener); + entity.getEventNode().addListener(listener); assertTrue(handle.hasListener()); assertFalse(result.get()); @@ -100,7 +100,7 @@ public void entityLocal() { assertTrue(result.get()); result.set(false); - entity.eventNode().removeListener(listener); + entity.getEventNode().removeListener(listener); handle.call(new EventNodeTest.EntityTestEvent(entity)); assertFalse(result.get()); diff --git a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java index 9d6404e31b7..2c8720a166f 100644 --- a/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceUnregisterIntegrationTest.java @@ -57,7 +57,7 @@ final class Game { Game(Env env) { instance = env.process().getInstanceManager().createInstanceContainer(env.process()); - instance.eventNode().addListener(PlayerMoveEvent.class, e -> System.out.println(instance)); + instance.getEventNode().addListener(PlayerMoveEvent.class, e -> System.out.println(instance)); } } var game = new Game(env); @@ -98,7 +98,7 @@ public void testGCWithEventsLambda(Env env) { } private void tmp(InstanceContainer instanceContainer) { - instanceContainer.eventNode().addListener(InstanceTickEvent.class, (e) -> { + instanceContainer.getEventNode().addListener(InstanceTickEvent.class, (e) -> { var uuid = instanceContainer.getUniqueId(); }); } diff --git a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java index dc5744b9cc5..3422a2d7910 100644 --- a/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java +++ b/testing/src/main/java/net/minestom/testing/TestConnectionImpl.java @@ -42,7 +42,7 @@ final class TestConnectionImpl implements TestConnection { playerConnection.setConnectionState(ConnectionState.LOGIN); var player = process.getConnectionManager().createPlayer(playerConnection, UUID.randomUUID(), "RandName"); - player.eventNode().addListener(AsyncPlayerConfigurationEvent.class, event -> { + player.getEventNode().addListener(AsyncPlayerConfigurationEvent.class, event -> { event.setSpawningInstance(instance); event.getPlayer().setRespawnPoint(pos); }); From a700e6b8234288ec50c3db31b1d187127363ec04 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Wed, 31 Jan 2024 21:50:20 +0300 Subject: [PATCH 11/16] more little improvements --- .../net/minestom/server/ServerFacadeImpl.java | 16 +- .../net/minestom/server/ServerStarter.java | 61 ++--- .../java/net/minestom/server/TickerImpl.java | 54 ++-- .../java/net/minestom/server/Viewable.java | 2 +- .../audience/AudienceManagerImpl.java | 18 +- .../audience/IterableAudienceProvider.java | 15 +- .../audience/PacketGroupingAudience.java | 20 +- .../audience/SingleAudienceProvider.java | 22 +- .../server/command/CommandManagerImpl.java | 15 +- .../command/builder/CommandDispatcher.java | 15 +- .../server/crypto/SignatureValidator.java | 4 +- .../net/minestom/server/entity/Player.java | 236 ++++++------------ .../server/entity/fakeplayer/FakePlayer.java | 60 ++--- .../minestom/server/extras/MojangAuth.java | 31 +-- .../server/extras/mojangAuth/MojangCrypt.java | 18 +- .../listener/BlockPlacementListener.java | 4 +- .../server/listener/ChatMessageListener.java | 4 +- .../server/listener/PlayConfigListener.java | 2 +- .../listener/PlayerPositionListener.java | 2 +- .../server/listener/TabCompleteListener.java | 2 +- .../listener/preplay/ConfigListener.java | 2 +- .../listener/preplay/LoginListener.java | 2 +- .../monitoring/BenchmarkManagerImpl.java | 18 +- .../server/network/ConnectionManagerImpl.java | 85 ++++--- .../network/player/FakePlayerConnection.java | 8 +- .../network/player/PlayerConnection.java | 79 ++---- .../player/PlayerSocketConnection.java | 40 +-- .../server/network/socket/ServerImpl.java | 33 +-- .../server/network/socket/Worker.java | 42 ++-- 29 files changed, 393 insertions(+), 517 deletions(-) diff --git a/src/main/java/net/minestom/server/ServerFacadeImpl.java b/src/main/java/net/minestom/server/ServerFacadeImpl.java index 7b6658ce506..a8b2863fdd9 100644 --- a/src/main/java/net/minestom/server/ServerFacadeImpl.java +++ b/src/main/java/net/minestom/server/ServerFacadeImpl.java @@ -85,20 +85,20 @@ public ServerFacadeImpl(ServerSettings serverSettings) { this.biomeManager = new BiomeManagerImpl(); this.instanceManager = new InstanceManagerImpl(this); - this.commandManager = new CommandManagerImpl(exceptionHandler, globalEventHandler); + this.commandManager = new CommandManagerImpl(this, this); this.recipeManager = new RecipeManagerImpl(); this.schedulerManager = new SchedulerManagerImpl(); - this.benchmarkManager = new BenchmarkManagerImpl(exceptionHandler); + this.benchmarkManager = new BenchmarkManagerImpl(this); this.dimensionTypeManager = new DimensionTypeManagerImpl(); this.advancementManager = new AdvancementManagerImpl(serverSettings); this.tagManager = new TagManagerImpl(); this.teamManager = new TeamManagerImpl(serverSettings); - this.connectionManager = new ConnectionManagerImpl(serverSettings, globalEventHandler, this, this, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, biomeManager, dimensionTypeManager, tagManager, blockManager); - this.server = new ServerImpl(connectionManager, globalEventHandler, exceptionHandler, serverSettings, packetProcessor); - this.audienceManager = new AudienceManagerImpl(connectionManager, commandManager, serverSettings); - this.ticker = new TickerImpl(connectionManager, schedulerManager, server, globalEventHandler, exceptionHandler, instanceManager, chunkDispatcher); - this.serverStarter = new ServerStarter(serverSettings, server, exceptionHandler, schedulerManager, connectionManager, benchmarkManager, chunkDispatcher, ticker); - this.mojangAuth = new MojangAuth(serverStarter, exceptionHandler); + this.connectionManager = new ConnectionManagerImpl(tagManager, this); + this.server = new ServerImpl(serverSettings, this); + this.audienceManager = new AudienceManagerImpl(commandManager, this, this); + this.ticker = new TickerImpl(this); + this.serverStarter = new ServerStarter(this); + this.mojangAuth = new MojangAuth(this, this); } } diff --git a/src/main/java/net/minestom/server/ServerStarter.java b/src/main/java/net/minestom/server/ServerStarter.java index 06cb5907017..eaf742863e1 100644 --- a/src/main/java/net/minestom/server/ServerStarter.java +++ b/src/main/java/net/minestom/server/ServerStarter.java @@ -1,14 +1,13 @@ package net.minestom.server; import lombok.RequiredArgsConstructor; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; -import net.minestom.server.monitoring.BenchmarkManager; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.socket.Server; -import net.minestom.server.thread.ThreadDispatcher; +import net.minestom.server.exception.ExceptionHandlerProvider; +import net.minestom.server.monitoring.BenchmarkManagerProvider; +import net.minestom.server.network.ConnectionManagerProvider; +import net.minestom.server.network.socket.ServerProvider; +import net.minestom.server.thread.ChunkDispatcherProvider; import net.minestom.server.thread.TickSchedulerThread; -import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerProvider; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,14 +21,18 @@ public class ServerStarter { private static final Logger LOGGER = LoggerFactory.getLogger(ServerStarter.class); - private final ServerSettings serverSettings; - private final Server server; - private final ExceptionHandler exceptionHandler; - private final SchedulerManager schedulerManager; - private final ConnectionManager connectionManager; - private final BenchmarkManager benchmarkManager; - private final ThreadDispatcher dispatcher; - private final Ticker ticker; + private final ServerSettingsProvider serverSettingsProvider; + private final ServerProvider serverProvider; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final SchedulerManagerProvider schedulerManagerProvider; + private final ConnectionManagerProvider connectionManagerProvider; + private final BenchmarkManagerProvider benchmarkManagerProvider; + private final ChunkDispatcherProvider chunkDispatcherProvider; + private final TickerProvider tickerProvider; + + public ServerStarter(ServerFacade serverFacade) { + this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + } private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); @@ -38,25 +41,25 @@ public void start(@NotNull SocketAddress socketAddress) { throw new IllegalStateException("Server already started"); } - LOGGER.info("Starting " + serverSettings.getBrandName() + " server."); + LOGGER.info("Starting " + serverSettingsProvider.getServerSettings().getBrandName() + " server."); // Init server try { - server.init(socketAddress); + serverProvider.getServer().init(socketAddress); } catch (IOException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); throw new RuntimeException(e); } // Start server - server.start(); + serverProvider.getServer().start(); - LOGGER.info(serverSettings.getBrandName() + " server started successfully."); + LOGGER.info(serverSettingsProvider.getServerSettings().getBrandName() + " server started successfully."); // Stop the server on SIGINT - if (serverSettings.isShutdownOnSignal()) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); + if (serverSettingsProvider.getServerSettings().isShutdownOnSignal()) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); - new TickSchedulerThread(serverSettings, ticker, this, exceptionHandler).start(); + new TickSchedulerThread(serverSettingsProvider.getServerSettings(), tickerProvider.getTicker(), this, exceptionHandlerProvider.getExceptionHandler()).start(); } public void start(@NotNull String hostname, int port) { @@ -66,14 +69,14 @@ public void start(@NotNull String hostname, int port) { public void stop() { if (!stopped.compareAndSet(false, true)) return; - LOGGER.info("Stopping " + serverSettings.getBrandName() + " server."); - schedulerManager.shutdown(); - connectionManager.shutdown(); - server.stop(); + LOGGER.info("Stopping " + serverSettingsProvider.getServerSettings().getBrandName() + " server."); + schedulerManagerProvider.getSchedulerManager().shutdown(); + connectionManagerProvider.getConnectionManager().shutdown(); + serverProvider.getServer().stop(); LOGGER.info("Shutting down all thread pools."); - benchmarkManager.disable(); - dispatcher.shutdown(); - LOGGER.info(serverSettings.getBrandName() + " server stopped successfully."); + benchmarkManagerProvider.getBenchmarkManager().disable(); + chunkDispatcherProvider.getChunkDispatcher().shutdown(); + LOGGER.info(serverSettingsProvider.getServerSettings().getBrandName() + " server stopped successfully."); } public boolean isAlive() { diff --git a/src/main/java/net/minestom/server/TickerImpl.java b/src/main/java/net/minestom/server/TickerImpl.java index 8a8515d135d..d9fdb0e4835 100644 --- a/src/main/java/net/minestom/server/TickerImpl.java +++ b/src/main/java/net/minestom/server/TickerImpl.java @@ -1,41 +1,41 @@ package net.minestom.server; -import lombok.Getter; import lombok.RequiredArgsConstructor; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.server.ServerTickMonitorEvent; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.instance.Chunk; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Instance; -import net.minestom.server.instance.InstanceManager; +import net.minestom.server.instance.InstanceManagerProvider; import net.minestom.server.monitoring.TickMonitor; -import net.minestom.server.network.ConnectionManager; -import net.minestom.server.network.socket.Server; +import net.minestom.server.network.ConnectionManagerProvider; +import net.minestom.server.network.socket.ServerProvider; import net.minestom.server.thread.Acquirable; -import net.minestom.server.thread.ThreadDispatcher; -import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.thread.ChunkDispatcherProvider; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.PacketUtils; -@Getter @RequiredArgsConstructor -final class TickerImpl implements Ticker { - private final ConnectionManager connectionManager; - private final SchedulerManager schedulerManager; - private final Server server; - private final EventNode globalEventHandler; - private final ExceptionHandler exceptionHandler; - private final InstanceManager instanceManager; - private final ThreadDispatcher dispatcher; +public final class TickerImpl implements Ticker { + private final ConnectionManagerProvider connectionManagerProvider; + private final SchedulerManagerProvider schedulerManagerProvider; + private final ServerProvider serverProvider; + private final GlobalEventHandlerProvider globalEventHandlerProvider; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final InstanceManagerProvider instanceManagerProvider; + private final ChunkDispatcherProvider chunkDispatcherProvider; + + public TickerImpl(ServerFacade serverFacade) { + this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + } @Override public void tick(long nanoTime) { final long msTime = System.currentTimeMillis(); - getSchedulerManager().processTick(); + schedulerManagerProvider.getSchedulerManager().processTick(); // Connection tick (let waiting clients in, send keep alives, handle configuration players packets) - getConnectionManager().tick(msTime); + connectionManagerProvider.getConnectionManager().tick(msTime); // Server tick (chunks/entities) serverTick(msTime); @@ -44,31 +44,31 @@ public void tick(long nanoTime) { PacketUtils.flush(); // Server connection tick - getServer().tick(); + serverProvider.getServer().tick(); // Monitoring { final double acquisitionTimeMs = Acquirable.resetAcquiringTime() / 1e6D; final double tickTimeMs = (System.nanoTime() - nanoTime) / 1e6D; final TickMonitor tickMonitor = new TickMonitor(tickTimeMs, acquisitionTimeMs); - getGlobalEventHandler().call(new ServerTickMonitorEvent(tickMonitor)); + globalEventHandlerProvider.getGlobalEventHandler().call(new ServerTickMonitorEvent(tickMonitor)); } } private void serverTick(long tickStart) { // Tick all instances - for (Instance instance : getInstanceManager().getInstances()) { + for (Instance instance : instanceManagerProvider.getInstanceManager().getInstances()) { try { instance.tick(tickStart); } catch (Exception e) { - getExceptionHandler().handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } // Tick all chunks (and entities inside) - getDispatcher().updateAndAwait(tickStart); + chunkDispatcherProvider.getChunkDispatcher().updateAndAwait(tickStart); // Clear removed entities & update threads final long tickTime = System.currentTimeMillis() - tickStart; - getDispatcher().refreshThreads(tickTime); + chunkDispatcherProvider.getChunkDispatcher().refreshThreads(tickTime); } } diff --git a/src/main/java/net/minestom/server/Viewable.java b/src/main/java/net/minestom/server/Viewable.java index 8f3e32ecbb7..ee56f17298a 100644 --- a/src/main/java/net/minestom/server/Viewable.java +++ b/src/main/java/net/minestom/server/Viewable.java @@ -93,7 +93,7 @@ default void sendPacketToViewersAndSelf(ServerSettingsProvider serverSettingsPro * @return the audience */ default @NotNull Audience getViewersAsAudience(ServerSettings serverSettings) { - return PacketGroupingAudience.of(serverSettings, this.getViewers()); + return PacketGroupingAudience.of(() -> serverSettings, this.getViewers()); } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java b/src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java index 9cc4fdb7e9e..680153320d9 100644 --- a/src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java +++ b/src/main/java/net/minestom/server/adventure/audience/AudienceManagerImpl.java @@ -3,10 +3,10 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Keyed; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerProvider; import org.jetbrains.annotations.NotNull; import java.util.function.Predicate; @@ -17,15 +17,15 @@ public class AudienceManagerImpl implements AudienceManager { private final SingleAudienceProvider audience; - private final ConnectionManager connectionManager; private final CommandManager commandManager; - private final ServerSettings serverSettings; + private final ServerSettingsProvider serverSettingsProvider; + private final ConnectionManagerProvider connectionManagerProvider; - public AudienceManagerImpl(ConnectionManager connectionManager, CommandManager commandManager, ServerSettings serverSettings) { - this.connectionManager = connectionManager; + public AudienceManagerImpl(CommandManager commandManager, ServerSettingsProvider serverSettingsProvider, ConnectionManagerProvider connectionManagerProvider) { this.commandManager = commandManager; - this.serverSettings = serverSettings; - audience = new SingleAudienceProvider(serverSettings, connectionManager, commandManager); + this.serverSettingsProvider = serverSettingsProvider; + this.connectionManagerProvider = connectionManagerProvider; + this.audience = new SingleAudienceProvider(commandManager, serverSettingsProvider, connectionManagerProvider); } /** @@ -78,7 +78,7 @@ public AudienceManagerImpl(ConnectionManager connectionManager, CommandManager c */ @Override public @NotNull Audience players(@NotNull Predicate filter) { - return PacketGroupingAudience.of(serverSettings, connectionManager.getOnlinePlayers().stream().filter(filter).toList()); + return PacketGroupingAudience.of(serverSettingsProvider, connectionManagerProvider.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); } /** diff --git a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java index 2b2183d4da5..7662c11178b 100644 --- a/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/IterableAudienceProvider.java @@ -5,10 +5,11 @@ import net.minestom.server.command.CommandManager; import net.minestom.server.command.ConsoleSender; import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerProvider; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -19,13 +20,13 @@ * A provider of iterable audiences. */ class IterableAudienceProvider implements AudienceProvider> { - private final ConnectionManager connectionManager; + private final ConnectionManagerProvider connectionManagerProvider; private final List console; private final AudienceRegistry registry = new AudienceRegistry(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new); - protected IterableAudienceProvider(ConnectionManager connectionManager, CommandManager commandManager) { - this.connectionManager = connectionManager; - this.console = List.of(commandManager.getConsoleSender()); + protected IterableAudienceProvider(ConnectionManagerProvider connectionManagerProvider, CommandManager commandManager) { + this.connectionManagerProvider = connectionManagerProvider; + this.console = Collections.singletonList(commandManager.getConsoleSender()); } @Override @@ -39,12 +40,12 @@ protected IterableAudienceProvider(ConnectionManager connectionManager, CommandM @Override public @NotNull Iterable players() { - return connectionManager.getOnlinePlayers(); + return connectionManagerProvider.getConnectionManager().getOnlinePlayers(); } @Override public @NotNull Iterable players(@NotNull Predicate filter) { - return connectionManager.getOnlinePlayers().stream().filter(filter).toList(); + return connectionManagerProvider.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList(); } @Override diff --git a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java index 9b74ade4e43..9076a47aeb9 100644 --- a/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java +++ b/src/main/java/net/minestom/server/adventure/audience/PacketGroupingAudience.java @@ -10,6 +10,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.title.TitlePart; import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.coordinate.Point; import net.minestom.server.entity.Player; @@ -23,6 +24,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Collection; +import java.util.function.Supplier; /** * An audience implementation that sends grouped packets if possible. @@ -37,11 +39,11 @@ public interface PacketGroupingAudience extends ForwardingAudience { * @param players the players * @return the audience */ - static @NotNull PacketGroupingAudience of(ServerSettings serverSettings, @NotNull Collection players) { + static @NotNull PacketGroupingAudience of(ServerSettingsProvider serverSettingsProvider, @NotNull Collection players) { return new PacketGroupingAudience() { @Override public ServerSettings getServerSettings() { - return serverSettings; + return serverSettingsProvider.getServerSettings(); } @Override @@ -51,6 +53,20 @@ public ServerSettings getServerSettings() { }; } + static @NotNull PacketGroupingAudience of(ServerSettingsProvider serverSettingsProvider, @NotNull Supplier> playersSupplier) { + return new PacketGroupingAudience() { + @Override + public ServerSettings getServerSettings() { + return serverSettingsProvider.getServerSettings(); + } + + @Override + public @NotNull Collection<@NotNull Player> getPlayers() { + return playersSupplier.get(); + } + }; + } + ServerSettings getServerSettings(); /** diff --git a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java index a77410af0d4..5ad12355c98 100644 --- a/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java +++ b/src/main/java/net/minestom/server/adventure/audience/SingleAudienceProvider.java @@ -2,10 +2,10 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerProvider; import org.jetbrains.annotations.NotNull; import java.util.function.Predicate; @@ -19,16 +19,18 @@ class SingleAudienceProvider implements AudienceProvider { protected final IterableAudienceProvider collection; protected final Audience players; protected final Audience server; - private final ServerSettings serverSettings; - private final ConnectionManager connectionManager; private final CommandManager commandManager; + private final ServerSettingsProvider serverSettingsProvider; + private final ConnectionManagerProvider connectionManagerProvider; - protected SingleAudienceProvider(ServerSettings serverSettings, ConnectionManager connectionManager, CommandManager commandManager) { - this.serverSettings = serverSettings; - this.connectionManager = connectionManager; + + protected SingleAudienceProvider(CommandManager commandManager, ServerSettingsProvider serverSettingsProvider, ConnectionManagerProvider connectionManagerProvider) { this.commandManager = commandManager; - this.collection = new IterableAudienceProvider(connectionManager, commandManager); - this.players = PacketGroupingAudience.of(serverSettings, connectionManager.getOnlinePlayers()); + this.serverSettingsProvider = serverSettingsProvider; + this.connectionManagerProvider = connectionManagerProvider; + + this.collection = new IterableAudienceProvider(connectionManagerProvider, commandManager); + this.players = PacketGroupingAudience.of(serverSettingsProvider, () -> connectionManagerProvider.getConnectionManager().getOnlinePlayers()); this.server = Audience.audience(this.players, commandManager.getConsoleSender()); } @@ -53,7 +55,7 @@ protected SingleAudienceProvider(ServerSettings serverSettings, ConnectionManage @Override public @NotNull Audience players(@NotNull Predicate filter) { - return PacketGroupingAudience.of(serverSettings, connectionManager.getOnlinePlayers().stream().filter(filter).toList()); + return PacketGroupingAudience.of(serverSettingsProvider, connectionManagerProvider.getConnectionManager().getOnlinePlayers().stream().filter(filter).toList()); } @Override diff --git a/src/main/java/net/minestom/server/command/CommandManagerImpl.java b/src/main/java/net/minestom/server/command/CommandManagerImpl.java index c5485742395..d6d0cf77d8a 100644 --- a/src/main/java/net/minestom/server/command/CommandManagerImpl.java +++ b/src/main/java/net/minestom/server/command/CommandManagerImpl.java @@ -6,10 +6,9 @@ import net.minestom.server.command.builder.CommandResult; import net.minestom.server.command.builder.ParsedCommand; import net.minestom.server.entity.Player; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.player.PlayerCommandEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.network.packet.server.play.DeclareCommandsPacket; import net.minestom.server.utils.callback.CommandCallback; import net.minestom.server.utils.validate.Check; @@ -23,8 +22,8 @@ @RequiredArgsConstructor public final class CommandManagerImpl implements CommandManager { - private final ExceptionHandler exceptionHandler; - private final EventNode globalEventHandler; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final GlobalEventHandlerProvider globalEventHandlerProvider; private static final boolean ASYNC_VIRTUAL = Boolean.getBoolean("minestom.command.async-virtual"); @@ -73,7 +72,7 @@ public void unregister(@NotNull Command command) { // Command event if (sender instanceof Player player) { PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, command); - globalEventHandler.call(playerCommandEvent); + globalEventHandlerProvider.getGlobalEventHandler().call(playerCommandEvent); if (playerCommandEvent.isCancelled()) return CommandResult.of(CommandResult.Type.CANCELLED, command); command = playerCommandEvent.getCommand(); @@ -106,7 +105,7 @@ class Reflection { try { callable.call(); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } }); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); @@ -114,7 +113,7 @@ class Reflection { return callable.call(); } } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return CommandResult.of(CommandResult.Type.UNKNOWN, rawCommand); } } diff --git a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java index 10b66447279..bdad9918af6 100644 --- a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java +++ b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java @@ -2,13 +2,13 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; +import lombok.RequiredArgsConstructor; import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandManagerImpl; import net.minestom.server.command.CommandParser; import net.minestom.server.command.CommandSender; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.event.GlobalEventHandlerProvider; +import net.minestom.server.exception.ExceptionHandlerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -18,6 +18,7 @@ /** * Class responsible for parsing {@link Command}. */ +@RequiredArgsConstructor public class CommandDispatcher { private final CommandManager manager; @@ -25,12 +26,8 @@ public class CommandDispatcher { .expireAfterWrite(30, TimeUnit.SECONDS) .build(); - public CommandDispatcher(CommandManager manager) { - this.manager = manager; - } - - public CommandDispatcher(ExceptionHandler exceptionHandler, EventNode globalEventHandler) { - this(new CommandManagerImpl(exceptionHandler, globalEventHandler)); + public CommandDispatcher(ExceptionHandlerProvider exceptionHandlerProvider, GlobalEventHandlerProvider globalEventHandlerProvider) { + this(new CommandManagerImpl(exceptionHandlerProvider, globalEventHandlerProvider)); } /** diff --git a/src/main/java/net/minestom/server/crypto/SignatureValidator.java b/src/main/java/net/minestom/server/crypto/SignatureValidator.java index 734aa69bb49..2ec63daa9a6 100644 --- a/src/main/java/net/minestom/server/crypto/SignatureValidator.java +++ b/src/main/java/net/minestom/server/crypto/SignatureValidator.java @@ -60,8 +60,8 @@ static SignatureValidator from(PublicKey publicKey, KeyUtils.SignatureAlgorithm * @return null if the player didn't send a public key */ static @Nullable SignatureValidator from(Player player) { - if (player.getPlayerConnection().playerPublicKey() == null) return null; - return from(player.getPlayerConnection().playerPublicKey().publicKey(), KeyUtils.SignatureAlgorithm.SHA256withRSA); + if (player.getPlayerConnection().getPlayerPublicKey() == null) return null; + return from(player.getPlayerConnection().getPlayerPublicKey().publicKey(), KeyUtils.SignatureAlgorithm.SHA256withRSA); } private static SignatureValidator createYggdrasilValidator() { diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 4fcbc2c26d8..9c3085a673d 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -26,10 +26,10 @@ import net.minestom.server.advancements.AdvancementTab; import net.minestom.server.adventure.AdventurePacketConvertor; import net.minestom.server.adventure.Localizable; -import net.minestom.server.adventure.bossbar.BossBarManager; +import net.minestom.server.adventure.bossbar.BossBarManagerProvider; import net.minestom.server.attribute.Attribute; import net.minestom.server.collision.BoundingBox; -import net.minestom.server.command.CommandManager; +import net.minestom.server.command.CommandManagerProvider; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.condition.CommandCondition; import net.minestom.server.coordinate.Point; @@ -52,24 +52,27 @@ import net.minestom.server.instance.EntityTracker; import net.minestom.server.instance.Instance; import net.minestom.server.instance.block.Block; -import net.minestom.server.instance.block.BlockManager; +import net.minestom.server.instance.block.BlockManagerProvider; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.PlayerInventory; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.minestom.server.item.metadata.WrittenBookMeta; -import net.minestom.server.listener.manager.PacketListenerManager; +import net.minestom.server.listener.manager.PacketListenerManagerProvider; import net.minestom.server.message.ChatMessageType; import net.minestom.server.message.ChatPosition; import net.minestom.server.message.Messenger; -import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.ConnectionManagerImpl; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.PlayerProvider; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.server.SendablePacket; import net.minestom.server.network.packet.server.ServerPacket; -import net.minestom.server.network.packet.server.common.*; +import net.minestom.server.network.packet.server.common.DisconnectPacket; +import net.minestom.server.network.packet.server.common.PluginMessagePacket; +import net.minestom.server.network.packet.server.common.ResourcePackPopPacket; +import net.minestom.server.network.packet.server.common.ResourcePackPushPacket; import net.minestom.server.network.packet.server.login.LoginDisconnectPacket; import net.minestom.server.network.packet.server.play.*; import net.minestom.server.network.packet.server.play.data.DeathLocation; @@ -77,17 +80,17 @@ import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.recipe.Recipe; -import net.minestom.server.recipe.RecipeManager; +import net.minestom.server.recipe.RecipeManagerProvider; import net.minestom.server.scoreboard.BelowNameTag; import net.minestom.server.scoreboard.Team; -import net.minestom.server.scoreboard.TeamManager; +import net.minestom.server.scoreboard.TeamManagerProvider; import net.minestom.server.snapshot.EntitySnapshot; import net.minestom.server.snapshot.PlayerSnapshot; import net.minestom.server.snapshot.SnapshotImpl; import net.minestom.server.snapshot.SnapshotUpdater; import net.minestom.server.statistic.PlayerStatistic; import net.minestom.server.thread.ChunkDispatcherProvider; -import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.MathUtils; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.PropertyUtils; @@ -139,30 +142,36 @@ public class Player extends LivingEntity implements CommandSender, Localizable, public static final boolean EXPERIMENT_PERFORM_POSE_UPDATES = Boolean.getBoolean("minestom.experiment.pose-updates"); + @Getter private long lastKeepAlive; private boolean answerKeepAlive; @Getter // FIXME bad shit - protected final ConnectionManager connectionManager; - protected final TeamManager teamManager; - protected final RecipeManager recipeManager; + protected final ConnectionManagerProvider connectionManagerProvider; + protected final TeamManagerProvider teamManagerProvider; + protected final RecipeManagerProvider recipeManagerProvider; @Getter // FIXME bad shit - private final CommandManager commandManager; - private final BossBarManager bossBarManager; - private final SchedulerManager schedulerManager; - private final PacketListenerManager packetListenerManager; + private final CommandManagerProvider commandManagerProvider; + private final BossBarManagerProvider bossBarManagerProvider; + private final SchedulerManagerProvider schedulerManagerProvider; + private final PacketListenerManagerProvider packetListenerManagerProvider; @Getter // FIXME bad shit - private final BlockManager blockManager; + private final BlockManagerProvider blockManagerProvider; private String username; private Component usernameComponent; + @Getter protected final PlayerConnection playerConnection; + @Getter private int latency; private Component displayName; + @Getter private PlayerSkin skin; private Instance pendingInstance = null; + @Getter private DimensionType dimensionType; + @Getter private GameMode gameMode; private DeathLocation deathLocation; @@ -185,20 +194,27 @@ public class Player extends LivingEntity implements CommandSender, Localizable, final IntegerBiConsumer chunkRemover; private final AtomicInteger teleportId = new AtomicInteger(); - private int receivedTeleportId; + @lombok.Setter + @Getter + private int lastReceivedTeleportId; private final MessagePassingQueue packets = new MpscUnboundedXaddArrayQueue<>(32); private final boolean levelFlat; + @Getter private final PlayerSettings settings; private float exp; private int level; + @Getter + @lombok.Setter private int portalCooldown = 0; + @Getter protected PlayerInventory inventory; private Inventory openInventory; // Used internally to allow the closing of inventory within the inventory listener private boolean didCloseInventory; + @Getter private byte heldSlot; private Pos respawnPoint; @@ -219,6 +235,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable, private BelowNameTag belowNameTag; + @Getter private int permissionLevel; private boolean reducedDebugScreenInformation; @@ -247,7 +264,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable, private CompletableFuture resourcePackFuture = null; public Player(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, serverFacade.getConnectionManager(), serverFacade.getTeamManager(), serverFacade.getRecipeManager(), serverFacade.getCommandManager(), serverFacade.getBossBarManager(), serverFacade.getSchedulerManager(), serverFacade.getPacketListenerManager(), serverFacade.getBlockManager(), uuid, username, playerConnection); + this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, uuid, username, playerConnection); } public Player( @@ -257,28 +274,28 @@ public Player( ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, - ConnectionManager connectionManager, - TeamManager teamManager, - RecipeManager recipeManager, - CommandManager commandManager, - BossBarManager bossBarManager, - SchedulerManager schedulerManager, - PacketListenerManager packetListenerManager, - BlockManager blockManager, + ConnectionManagerProvider connectionManagerProvider, + TeamManagerProvider teamManagerProvider, + RecipeManagerProvider recipeManagerProvider, + CommandManagerProvider commandManagerProvider, + BossBarManagerProvider bossBarManagerProvider, + SchedulerManagerProvider schedulerManagerProvider, + PacketListenerManagerProvider packetListenerManagerProvider, + BlockManagerProvider blockManagerProvider, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection ) { super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, EntityType.PLAYER, uuid); - this.connectionManager = connectionManager; - this.teamManager = teamManager; - this.recipeManager = recipeManager; - this.commandManager = commandManager; - this.bossBarManager = bossBarManager; - this.schedulerManager = schedulerManager; - this.packetListenerManager = packetListenerManager; - this.blockManager = blockManager; + this.connectionManagerProvider = connectionManagerProvider; + this.teamManagerProvider = teamManagerProvider; + this.recipeManagerProvider = recipeManagerProvider; + this.commandManagerProvider = commandManagerProvider; + this.bossBarManagerProvider = bossBarManagerProvider; + this.schedulerManagerProvider = schedulerManagerProvider; + this.packetListenerManagerProvider = packetListenerManagerProvider; + this.blockManagerProvider = blockManagerProvider; this.username = username; this.usernameComponent = Component.text(username); this.playerConnection = playerConnection; @@ -286,7 +303,7 @@ public Player( setRespawnPoint(Pos.ZERO); this.settings = new PlayerSettings(); - this.inventory = new PlayerInventory(serverSettingsProvider.getServerSettings(), globalEventHandler, this); + this.inventory = new PlayerInventory(serverSettings, globalEventHandler, this); setCanPickupItem(true); // By default @@ -315,7 +332,7 @@ public Player( sendPacket(new UnloadChunkPacket(chunkX, chunkZ)); globalEventHandler.call(new PlayerChunkUnloadEvent(this, chunkX, chunkZ)); }; - experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(serverSettingsProvider.getServerSettings()))); + experiencePickupCooldown = new Cooldown(Duration.of(10, TimeUnit.getServerTick(serverSettings))); } @ApiStatus.Internal @@ -374,9 +391,9 @@ public CompletableFuture UNSAFE_init() { globalEventHandler.call(skinInitEvent); this.skin = skinInitEvent.getSkin(); // FIXME: when using Geyser, this line remove the skin of the client - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, getAddPlayerToList()); + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, getAddPlayerToList()); - for (var player : connectionManager.getOnlinePlayers()) { + for (var player : connectionManagerProvider.getConnectionManager().getOnlinePlayers()) { if (player != this) { sendPacket(player.getAddPlayerToList()); if (player.displayName != null) { @@ -386,7 +403,7 @@ public CompletableFuture UNSAFE_init() { } //Teams - for (Team team : teamManager.getTeams()) { + for (Team team : teamManagerProvider.getTeamManager().getTeams()) { sendPacket(team.createTeamsCreationPacket()); } @@ -395,10 +412,10 @@ public CompletableFuture UNSAFE_init() { // Recipes start { - sendPacket(recipeManager.getDeclareRecipesPacket()); + sendPacket(recipeManagerProvider.getRecipeManager().getDeclareRecipesPacket()); List recipesIdentifier = new ArrayList<>(); - for (Recipe recipe : recipeManager.getRecipes()) { + for (Recipe recipe : recipeManagerProvider.getRecipeManager().getRecipes()) { if (!recipe.shouldShow(this)) continue; recipesIdentifier.add(recipe.getRecipeId()); @@ -438,7 +455,7 @@ public void startConfigurationPhase() { // Remove the player, then send them back to configuration remove(false); - connectionManager.transitionPlayToConfig(this); + connectionManagerProvider.getConnectionManager().transitionPlayToConfig(this); } @@ -547,7 +564,7 @@ public void kill() { // #buildDeathMessage can return null, check here if (chatMessage != null) { - for (Player player : connectionManager.getOnlinePlayers()) { + for (Player player : connectionManagerProvider.getConnectionManager().getOnlinePlayers()) { player.sendMessage(chatMessage); } } @@ -614,7 +631,7 @@ private void refreshClientStateAfterRespawn() { * again, and any changes will be visible to the player. */ public void refreshCommands() { - sendPacket(commandManager.createDeclareCommandsPacket(this)); + sendPacket(commandManagerProvider.getCommandManager().createDeclareCommandsPacket(this)); } @Override @@ -635,7 +652,7 @@ public void remove(boolean permanent) { final Inventory currentInventory = getOpenInventory(); if (currentInventory != null) currentInventory.removeViewer(this); - bossBarManager.removeAllBossBars(this); + bossBarManagerProvider.getBossBarManager().removeAllBossBars(this); // Advancement tabs cache { Set advancementTabs = AdvancementTab.getTabs(this); @@ -651,7 +668,7 @@ public void remove(boolean permanent) { // Clear all viewable chunks ChunkUtils.forChunksInRange(chunkX, chunkZ, serverSettingsProvider.getServerSettings().getChunkViewDistance(), chunkRemover); // Remove from the tab-list - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, getRemovePlayerToList()); + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, getRemovePlayerToList()); // Prevent the player from being stuck in loading screen, or just unable to interact with the server // This should be considered as a bug, since the player will ultimately time out anyway. @@ -724,7 +741,7 @@ public Void join() { } catch (InterruptedException e) { throw new RuntimeException(e); } - schedulerManager.process(); + schedulerManagerProvider.getSchedulerManager().process(); assert isDone(); } return super.join(); @@ -733,7 +750,7 @@ public Void join() { CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)) .thenRun(() -> { - schedulerManager.scheduleNextProcess(() -> { + schedulerManagerProvider.getSchedulerManager().scheduleNextProcess(() -> { runnable.accept(instance); future.complete(null); }); @@ -1029,12 +1046,12 @@ public void clearTitle() { @Override public void showBossBar(@NotNull BossBar bar) { - bossBarManager.addBossBar(this, bar); + bossBarManagerProvider.getBossBarManager().addBossBar(this, bar); } @Override public void hideBossBar(@NotNull BossBar bar) { - bossBarManager.removeBossBar(this, bar); + bossBarManagerProvider.getBossBarManager().removeBossBar(this, bar); } @Override @@ -1206,17 +1223,7 @@ public double getEyeHeight() { */ public void setDisplayName(@Nullable Component displayName) { this.displayName = displayName; - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); - } - - /** - * Gets the player skin. - * - * @return the player skin object, - * null means that the player has his {@link #getUuid()} default skin - */ - public @Nullable PlayerSkin getSkin() { - return skin; + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); } /** @@ -1248,11 +1255,11 @@ public synchronized void setSkin(@Nullable PlayerSkin skin) { { // Remove player - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, removePlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, removePlayerPacket); sendPacketToViewers(serverSettingsProvider, destroyEntitiesPacket); // Show player again - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, addPlayerPacket); + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, addPlayerPacket); getViewers().forEach(player -> showPlayer(player.getPlayerConnection())); } @@ -1521,25 +1528,6 @@ public void setLevel(int level) { sendPacket(new SetExperiencePacket(exp, level, 0)); } - public int getPortalCooldown() { - return portalCooldown; - } - - public void setPortalCooldown(int portalCooldown) { - this.portalCooldown = portalCooldown; - } - - /** - * Gets the player connection. - *

          - * Used to send packets and get stuff related to the connection. - * - * @return the player connection - */ - public @NotNull PlayerConnection getPlayerConnection() { - return playerConnection; - } - /** * Shortcut for {@link PlayerConnection#sendPacket(SendablePacket)}. * @@ -1569,47 +1557,6 @@ public boolean isOnline() { return playerConnection.isOnline(); } - /** - * Gets the player settings. - * - * @return the player settings - */ - public @NotNull PlayerSettings getSettings() { - return settings; - } - - /** - * Gets the player dimension. - * - * @return the player current dimension - */ - public DimensionType getDimensionType() { - return dimensionType; - } - - public @NotNull PlayerInventory getInventory() { - return inventory; - } - - /** - * Used to get the player latency, - * computed by seeing how long it takes the client to answer the {@link KeepAlivePacket} packet. - * - * @return the player latency - */ - public int getLatency() { - return latency; - } - - /** - * Gets the player {@link GameMode}. - * - * @return the player current gamemode - */ - public GameMode getGameMode() { - return gameMode; - } - /** * Changes the player {@link GameMode} * @@ -1630,7 +1577,7 @@ public boolean setGameMode(@NotNull GameMode gameMode) { // Condition to prevent sending the packets before spawning the player if (isActive()) { sendPacket(new ChangeGameStatePacket(ChangeGameStatePacket.Reason.CHANGE_GAMEMODE, gameMode.id())); - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, infoEntry())); } // The client updates their abilities based on the GameMode as follows @@ -1724,15 +1671,6 @@ public void setHeldItemSlot(byte slot) { sendPacket(new HeldItemChangePacket(slot)); } - /** - * Gets the player held slot (0-8). - * - * @return the current held slot for the player - */ - public byte getHeldSlot() { - return heldSlot; - } - /** * Changes the tag below the name. * @@ -1860,14 +1798,6 @@ public int getLastSentTeleportId() { return teleportId.get(); } - public int getLastReceivedTeleportId() { - return receivedTeleportId; - } - - public void refreshReceivedTeleportId(int receivedTeleportId) { - this.receivedTeleportId = receivedTeleportId; - } - /** * @see Entity#synchronizePosition(boolean) */ @@ -1880,15 +1810,6 @@ protected void synchronizePosition(boolean includeSelf) { super.synchronizePosition(includeSelf); } - /** - * Gets the player permission level. - * - * @return the player permission level - */ - public int getPermissionLevel() { - return permissionLevel; - } - /** * Changes the player permission level. * @@ -2119,7 +2040,7 @@ public void interpretPacketQueue() { return; } // This method is NOT thread-safe - this.packets.drain(packet -> packetListenerManager.processClientPacket(packet, playerConnection), PACKET_PER_TICK); + this.packets.drain(packet -> packetListenerManagerProvider.getPacketListenerManager().processClientPacket(packet, playerConnection), PACKET_PER_TICK); } /** @@ -2130,7 +2051,7 @@ public void interpretPacketQueue() { public void refreshLatency(int latency) { this.latency = latency; if (getPlayerConnection().getConnectionState() == ConnectionState.PLAY) { - PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); + PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_LATENCY, infoEntry())); } } @@ -2232,15 +2153,6 @@ public void refreshVehicleSteer(float sideways, float forward, boolean jump, boo this.vehicleInformation.refresh(sideways, forward, jump, unmount); } - /** - * Gets the last sent keep alive id. - * - * @return the last keep alive id sent to the player - */ - public long getLastKeepAlive() { - return lastKeepAlive; - } - @Override public @NotNull HoverEvent asHoverEvent(@NotNull UnaryOperator op) { return HoverEvent.showEntity(ShowEntity.showEntity(EntityType.PLAYER, this.uuid, this.displayName)); diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index 197c2e03039..33c0646ef21 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -3,8 +3,8 @@ import com.extollit.gaming.ai.path.HydrazinePathFinder; import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; -import net.minestom.server.adventure.bossbar.BossBarManager; -import net.minestom.server.command.CommandManager; +import net.minestom.server.adventure.bossbar.BossBarManagerProvider; +import net.minestom.server.command.CommandManagerProvider; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.NavigableEntity; @@ -14,18 +14,18 @@ import net.minestom.server.event.player.PlayerSpawnEvent; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.Instance; -import net.minestom.server.instance.block.BlockManager; -import net.minestom.server.listener.manager.PacketListenerManager; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.instance.block.BlockManagerProvider; +import net.minestom.server.listener.manager.PacketListenerManagerProvider; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.login.ClientLoginAcknowledgedPacket; import net.minestom.server.network.player.FakePlayerConnection; import net.minestom.server.network.player.PlayerConnection; -import net.minestom.server.network.socket.Server; -import net.minestom.server.recipe.RecipeManager; -import net.minestom.server.scoreboard.TeamManager; +import net.minestom.server.network.socket.ServerProvider; +import net.minestom.server.recipe.RecipeManagerProvider; +import net.minestom.server.scoreboard.TeamManagerProvider; import net.minestom.server.thread.ChunkDispatcherProvider; -import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.time.TimeUnit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -50,23 +50,13 @@ public class FakePlayer extends Player implements NavigableEntity { private final Navigator navigator = new Navigator(this); private EventListener spawnListener; - private final SchedulerManager scheduleManager; + private final SchedulerManagerProvider schedulerManagerProvider; public FakePlayer(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { this( serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), - serverFacade, - serverFacade, - serverFacade.getConnectionManager(), - serverFacade.getTeamManager(), - serverFacade.getRecipeManager(), - serverFacade.getCommandManager(), - serverFacade.getBossBarManager(), - serverFacade.getSchedulerManager(), - serverFacade.getPacketListenerManager(), - serverFacade.getBlockManager(), - serverFacade.getServer(), + serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, uuid, username, option, spawnCallback ); } @@ -85,21 +75,21 @@ public FakePlayer( ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, - ConnectionManager connectionManager, - TeamManager teamManager, - RecipeManager recipeManager, - CommandManager commandManager, - BossBarManager bossBarManager, - SchedulerManager schedulerManager, - PacketListenerManager packetListenerManager, - BlockManager blockManager, - Server server, + ConnectionManagerProvider connectionManagerProvider, + TeamManagerProvider teamManagerProvider, + RecipeManagerProvider recipeManagerProvider, + CommandManagerProvider commandManagerProvider, + BossBarManagerProvider bossBarManagerProvider, + SchedulerManagerProvider schedulerManagerProvider, + PacketListenerManagerProvider packetListenerManagerProvider, + BlockManagerProvider blockManagerProvider, + ServerProvider serverProvider, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { - super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, connectionManager, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, new FakePlayerConnection(server, connectionManager)); - this.scheduleManager = schedulerManager; + super(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, connectionManagerProvider, teamManagerProvider, recipeManagerProvider, commandManagerProvider, bossBarManagerProvider, schedulerManagerProvider, packetListenerManagerProvider, blockManagerProvider, uuid, username, new FakePlayerConnection(serverProvider, connectionManagerProvider)); + this.schedulerManagerProvider = schedulerManagerProvider; this.option = option; @@ -119,9 +109,9 @@ public FakePlayer( } playerConnection.setConnectionState(ConnectionState.LOGIN); - connectionManager.transitionLoginToConfig(this).thenRun(() -> { + connectionManagerProvider.getConnectionManager().transitionLoginToConfig(this).thenRun(() -> { // Need to immediately reply with login acknowledged for the player to enter config. - packetListenerManager.processClientPacket(new ClientLoginAcknowledgedPacket(), getPlayerConnection()); + packetListenerManagerProvider.getPacketListenerManager().processClientPacket(new ClientLoginAcknowledgedPacket(), getPlayerConnection()); }); } @@ -210,7 +200,7 @@ public Navigator getNavigator() { private void handleTabList(PlayerConnection connection) { if (!option.isInTabList()) { // Remove from tab-list - scheduleManager.buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(serverSettingsProvider.getServerSettings())).schedule(); + schedulerManagerProvider.getSchedulerManager().buildTask(() -> connection.sendPacket(getRemovePlayerToList())).delay(20, TimeUnit.getServerTick(serverSettingsProvider.getServerSettings())).schedule(); } } } diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index c15f75e6e3a..5b023c248a6 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -1,23 +1,26 @@ package net.minestom.server.extras; -import net.minestom.server.ServerStarter; -import net.minestom.server.exception.ExceptionHandler; +import lombok.Getter; +import net.minestom.server.ServerStarterProvider; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.utils.validate.Check; -import org.jetbrains.annotations.Nullable; import java.security.KeyPair; public final class MojangAuth { public final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); + @Getter private volatile boolean enabled = false; + @Getter private volatile KeyPair keyPair; - private final ServerStarter serverStarter; + private final ServerStarterProvider serverStarterProvider; + @Getter private final MojangCrypt mojangCrypt; - public MojangAuth(ServerStarter serverStarter, ExceptionHandler exceptionHandler) { - this.serverStarter = serverStarter; - this.mojangCrypt = new MojangCrypt(exceptionHandler); + public MojangAuth(ServerStarterProvider serverStarterProvider, ExceptionHandlerProvider exceptionHandlerProvider) { + this.serverStarterProvider = serverStarterProvider; + this.mojangCrypt = new MojangCrypt(exceptionHandlerProvider); } /** @@ -27,21 +30,9 @@ public MojangAuth(ServerStarter serverStarter, ExceptionHandler exceptionHandler */ public void init() { Check.stateCondition(enabled, "Mojang auth is already enabled!"); - Check.stateCondition(serverStarter.isAlive(), "The server has already been started!"); + Check.stateCondition(serverStarterProvider.getServerStarter().isAlive(), "The server has already been started!"); enabled = true; // Generate necessary fields... keyPair = mojangCrypt.generateKeyPair(); } - - public boolean isEnabled() { - return enabled; - } - - public @Nullable KeyPair getKeyPair() { - return keyPair; - } - - public MojangCrypt getMojangCrypt() { - return mojangCrypt; - } } diff --git a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java index d96ec9c8d70..8a7531546a9 100644 --- a/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java +++ b/src/main/java/net/minestom/server/extras/mojangAuth/MojangCrypt.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.mojangAuth; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,10 +13,10 @@ public final class MojangCrypt { private final Logger LOGGER = LoggerFactory.getLogger(MojangCrypt.class); - private final ExceptionHandler exceptionHandler; + private final ExceptionHandlerProvider exceptionHandlerProvider; - public MojangCrypt(ExceptionHandler exceptionHandler) { - this.exceptionHandler = exceptionHandler; + public MojangCrypt(ExceptionHandlerProvider exceptionHandlerProvider) { + this.exceptionHandlerProvider = exceptionHandlerProvider; } public @Nullable KeyPair generateKeyPair() { @@ -25,7 +25,7 @@ public MojangCrypt(ExceptionHandler exceptionHandler) { keyGen.initialize(1024); return keyGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); LOGGER.error("Key pair generation failed!"); return null; } @@ -35,7 +35,7 @@ public MojangCrypt(ExceptionHandler exceptionHandler) { try { return digestData("SHA-1", data.getBytes("ISO_8859_1"), secretKey.getEncoded(), publicKey.getEncoded()); } catch (UnsupportedEncodingException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return null; } } @@ -48,7 +48,7 @@ public MojangCrypt(ExceptionHandler exceptionHandler) { } return digest.digest(); } catch (NoSuchAlgorithmException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return null; } } @@ -65,7 +65,7 @@ private byte[] cipherData(int mode, Key key, byte[] data) { try { return setupCipher(mode, key.getAlgorithm(), key).doFinal(data); } catch (IllegalBlockSizeException | BadPaddingException var4) { - exceptionHandler.handleException(var4); + exceptionHandlerProvider.getExceptionHandler().handleException(var4); } LOGGER.error("Cipher data failed!"); return null; @@ -77,7 +77,7 @@ private Cipher setupCipher(int mode, String transformation, Key key) { cipher4.init(mode, key); return cipher4; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException var4) { - exceptionHandler.handleException(var4); + exceptionHandlerProvider.getExceptionHandler().handleException(var4); } LOGGER.error("Cipher creation failed!"); return null; diff --git a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java index 6681cf93be7..3e4fa8968ae 100644 --- a/src/main/java/net/minestom/server/listener/BlockPlacementListener.java +++ b/src/main/java/net/minestom/server/listener/BlockPlacementListener.java @@ -90,7 +90,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play // Get the newly placed block position //todo it feels like it should be possible to have better replacement rules than this, feels pretty scuffed. Point placementPosition = blockPosition; - var interactedPlacementRule = player.getBlockManager().getBlockPlacementRule(interactedBlock); + var interactedPlacementRule = player.getBlockManagerProvider().getBlockManager().getBlockPlacementRule(interactedBlock); if (!interactedBlock.isAir() && (interactedPlacementRule == null || !interactedPlacementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(interactedBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is not replaceable, try to place next to it. @@ -100,7 +100,7 @@ public static void listener(ClientPlayerBlockPlacementPacket packet, Player play placementPosition = blockPosition.add(offsetX, offsetY, offsetZ); var placementBlock = instance.getBlock(placementPosition); - var placementRule = player.getBlockManager().getBlockPlacementRule(placementBlock); + var placementRule = player.getBlockManagerProvider().getBlockManager().getBlockPlacementRule(placementBlock); if (!placementBlock.registry().isReplaceable() && !(placementRule != null && placementRule.isSelfReplaceable( new BlockPlacementRule.Replacement(placementBlock, blockFace, cursorPosition, useMaterial)))) { // If the block is still not replaceable, cancel the placement diff --git a/src/main/java/net/minestom/server/listener/ChatMessageListener.java b/src/main/java/net/minestom/server/listener/ChatMessageListener.java index 61dd5bd7e77..b6651f2bbee 100644 --- a/src/main/java/net/minestom/server/listener/ChatMessageListener.java +++ b/src/main/java/net/minestom/server/listener/ChatMessageListener.java @@ -18,7 +18,7 @@ public class ChatMessageListener { public static void commandChatListener(ClientCommandChatPacket packet, Player player) { final String command = packet.message(); if (Messenger.canReceiveCommand(player)) { - player.getCommandManager().execute(player, command); + player.getCommandManagerProvider().getCommandManager().execute(player, command); } else { Messenger.sendRejectionMessage(player); } @@ -31,7 +31,7 @@ public static void chatMessageListener(ClientChatMessagePacket packet, Player pl return; } - final Collection players = player.getConnectionManager().getOnlinePlayers(); + final Collection players = player.getConnectionManagerProvider().getConnectionManager().getOnlinePlayers(); PlayerChatEvent playerChatEvent = new PlayerChatEvent(player, players, () -> buildDefaultChatMessage(player, message), message); // Call the event diff --git a/src/main/java/net/minestom/server/listener/PlayConfigListener.java b/src/main/java/net/minestom/server/listener/PlayConfigListener.java index fd615224d17..b4e9c095cfd 100644 --- a/src/main/java/net/minestom/server/listener/PlayConfigListener.java +++ b/src/main/java/net/minestom/server/listener/PlayConfigListener.java @@ -6,6 +6,6 @@ public class PlayConfigListener { public static void configAckListener(@NotNull ClientConfigurationAckPacket packet, @NotNull Player player) { - player.getConnectionManager().doConfiguration(player, false); + player.getConnectionManagerProvider().getConnectionManager().doConfiguration(player, false); } } diff --git a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java index 98bdbfd4ff4..c817f89f150 100644 --- a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java @@ -28,7 +28,7 @@ public static void playerPositionAndLookListener(ClientPlayerPositionAndRotation } public static void teleportConfirmListener(ClientTeleportConfirmPacket packet, Player player) { - player.refreshReceivedTeleportId(packet.teleportId()); + player.setLastReceivedTeleportId(packet.teleportId()); } private static void processMovement(@NotNull Player player, @NotNull Pos packetPosition, boolean onGround) { diff --git a/src/main/java/net/minestom/server/listener/TabCompleteListener.java b/src/main/java/net/minestom/server/listener/TabCompleteListener.java index 4215b75795a..b97a1fd4ae5 100644 --- a/src/main/java/net/minestom/server/listener/TabCompleteListener.java +++ b/src/main/java/net/minestom/server/listener/TabCompleteListener.java @@ -12,7 +12,7 @@ public class TabCompleteListener { public static void listener(ClientTabCompletePacket packet, Player player) { final String text = packet.text(); - final Suggestion suggestion = getSuggestion(player.getCommandManager(), player, text); + final Suggestion suggestion = getSuggestion(player.getCommandManagerProvider().getCommandManager(), player, text); if (suggestion != null) { player.sendPacket(new TabCompletePacket( packet.transactionId(), diff --git a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java index 3156dfb3426..d7374bce3ee 100644 --- a/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/ConfigListener.java @@ -7,6 +7,6 @@ public final class ConfigListener { public static void finishConfigListener(@NotNull ClientFinishConfigurationPacket packet, @NotNull Player player) { - player.getConnectionManager().transitionConfigToPlay(player); + player.getConnectionManagerProvider().getConnectionManager().transitionConfigToPlay(player); } } diff --git a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java index f128bacf175..37c1e24114d 100644 --- a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java @@ -96,7 +96,7 @@ public static void loginEncryptionResponseListener(MojangAuth mojangAuth, Except return; } - final boolean hasPublicKey = connection.playerPublicKey() != null; + final boolean hasPublicKey = connection.getPlayerPublicKey() != null; final boolean verificationFailed = hasPublicKey || !Arrays.equals(socketConnection.getNonce(), mojangAuth.getMojangCrypt().decryptUsingKey(mojangAuth.getKeyPair().getPrivate(), packet.encryptedVerifyToken())); diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java index 499d7faa4c5..c72755c4ed4 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java @@ -2,8 +2,9 @@ import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import lombok.RequiredArgsConstructor; import net.minestom.server.ServerConsts; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; @@ -19,6 +20,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +@RequiredArgsConstructor public final class BenchmarkManagerImpl implements BenchmarkManager { private final static Logger LOGGER = LoggerFactory.getLogger(BenchmarkManagerImpl.class); private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); @@ -35,19 +37,11 @@ public final class BenchmarkManagerImpl implements BenchmarkManager { private final Long2LongMap lastBlockedMap = new Long2LongOpenHashMap(); private final Map resultMap = new ConcurrentHashMap<>(); + @lombok.Getter private boolean enabled = false; private volatile boolean stop = false; private long time; - private final ExceptionHandler exceptionHandler; - - public BenchmarkManagerImpl(ExceptionHandler exceptionHandler) { - this.exceptionHandler = exceptionHandler; - } - - @Override - public boolean isEnabled() { - return enabled; - } + private final ExceptionHandlerProvider exceptionHandlerProvider; @Override public void enable(@NotNull Duration duration) { @@ -69,7 +63,7 @@ public void enable(@NotNull Duration duration) { try { Thread.sleep(time); } catch (InterruptedException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } stop = false; diff --git a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java index 0ec3a888d2f..a0565edd8e5 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java +++ b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java @@ -2,21 +2,20 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerSettings; -import net.minestom.server.adventure.bossbar.BossBarManager; -import net.minestom.server.command.CommandManager; +import net.minestom.server.ServerFacade; +import net.minestom.server.ServerSettingsProvider; +import net.minestom.server.adventure.bossbar.BossBarManagerProvider; +import net.minestom.server.command.CommandManagerProvider; import net.minestom.server.entity.Player; import net.minestom.server.entity.damage.DamageType; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; -import net.minestom.server.event.GlobalEventHandler; +import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.player.AsyncPlayerConfigurationEvent; import net.minestom.server.event.player.AsyncPlayerPreLoginEvent; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.gamedata.tags.TagManager; import net.minestom.server.instance.Instance; -import net.minestom.server.instance.block.BlockManager; -import net.minestom.server.listener.manager.PacketListenerManager; +import net.minestom.server.instance.block.BlockManagerProvider; +import net.minestom.server.listener.manager.PacketListenerManagerProvider; import net.minestom.server.message.Messenger; import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.common.KeepAlivePacket; @@ -28,16 +27,16 @@ import net.minestom.server.network.packet.server.play.StartConfigurationPacket; import net.minestom.server.network.player.PlayerConnection; import net.minestom.server.network.player.PlayerSocketConnection; -import net.minestom.server.recipe.RecipeManager; -import net.minestom.server.scoreboard.TeamManager; +import net.minestom.server.recipe.RecipeManagerProvider; +import net.minestom.server.scoreboard.TeamManagerProvider; import net.minestom.server.thread.ChunkDispatcherProvider; -import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.StringUtils; import net.minestom.server.utils.async.AsyncUtils; import net.minestom.server.utils.debug.DebugUtils; import net.minestom.server.utils.validate.Check; -import net.minestom.server.world.DimensionTypeManager; -import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.DimensionTypeManagerProvider; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jctools.queues.MessagePassingQueue; import org.jctools.queues.MpscUnboundedArrayQueue; import org.jetbrains.annotations.ApiStatus; @@ -81,10 +80,10 @@ public final class ConnectionManagerImpl implements ConnectionManager { private final Set unmodifiableConfigurationPlayers = Collections.unmodifiableSet(configurationPlayers); private final Set unmodifiablePlayPlayers = Collections.unmodifiableSet(playPlayers); private final ExceptionHandlerProvider exceptionHandlerProvider; - private final ServerSettings serverSettings; - private final BiomeManager biomeManager; - private final DimensionTypeManager dimensionTypeManager; - private final EventNode globalEventHandler; + private final ServerSettingsProvider serverSettingsProvider; + private final BiomeManagerProvider biomeManagerProvider; + private final DimensionTypeManagerProvider dimensionTypeManagerProvider; + private final GlobalEventHandlerProvider globalEventHandlerProvider; // The uuid provider once a player login @@ -93,29 +92,33 @@ public final class ConnectionManagerImpl implements ConnectionManager { private final PlayerProvider defaultPlayerProvider; private volatile PlayerProvider playerProvider; + public ConnectionManagerImpl(TagManager tagManager, ServerFacade serverFacade) { + this(tagManager, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + } + public ConnectionManagerImpl( - ServerSettings serverSettings, - GlobalEventHandler globalEventHandler, + TagManager tagManager, + ServerSettingsProvider serverSettingsProvider, + GlobalEventHandlerProvider globalEventHandlerProvider, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, - TeamManager teamManager, - RecipeManager recipeManager, - CommandManager commandManager, - BossBarManager bossBarManager, - SchedulerManager schedulerManager, - PacketListenerManager packetListenerManager, - BiomeManager biomeManager, - DimensionTypeManager dimensionTypeManager, - TagManager tagManager, - BlockManager blockManager + TeamManagerProvider teamManagerProvider, + RecipeManagerProvider recipeManagerProvider, + CommandManagerProvider commandManagerProvider, + BossBarManagerProvider bossBarManagerProvider, + SchedulerManagerProvider schedulerManagerProvider, + PacketListenerManagerProvider packetListenerManagerProvider, + BiomeManagerProvider biomeManagerProvider, + DimensionTypeManagerProvider dimensionTypeManagerProvider, + BlockManagerProvider blockManagerProvider ) { this.exceptionHandlerProvider = exceptionHandlerProvider; - this.serverSettings = serverSettings; - this.biomeManager = biomeManager; - this.dimensionTypeManager = dimensionTypeManager; - this.globalEventHandler = globalEventHandler; - this.defaultTags = new CachedPacket(() -> serverSettings, new TagsPacket(tagManager.getTagMap())); - defaultPlayerProvider = (uuid, username, connection) -> new Player(globalEventHandler, serverSettings, chunkDispatcherProvider, exceptionHandlerProvider, this, teamManager, recipeManager, commandManager, bossBarManager, schedulerManager, packetListenerManager, blockManager, uuid, username, connection); + this.serverSettingsProvider = serverSettingsProvider; + this.biomeManagerProvider = biomeManagerProvider; + this.dimensionTypeManagerProvider = dimensionTypeManagerProvider; + this.globalEventHandlerProvider = globalEventHandlerProvider; + this.defaultTags = new CachedPacket(serverSettingsProvider, new TagsPacket(tagManager.getTagMap())); + defaultPlayerProvider = (uuid, username, connection) -> new Player(globalEventHandlerProvider.getGlobalEventHandler(), serverSettingsProvider.getServerSettings(), chunkDispatcherProvider, exceptionHandlerProvider, () -> this, teamManagerProvider, recipeManagerProvider, commandManagerProvider, bossBarManagerProvider, schedulerManagerProvider, packetListenerManagerProvider, blockManagerProvider, uuid, username, connection); playerProvider = defaultPlayerProvider; } @@ -206,13 +209,13 @@ public void setPlayerProvider(@Nullable PlayerProvider playerProvider) { // Compression if (playerConnection instanceof PlayerSocketConnection socketConnection) { - final int threshold = serverSettings.getCompressionThreshold(); + final int threshold = serverSettingsProvider.getServerSettings().getCompressionThreshold(); if (threshold > 0) socketConnection.startCompression(); } // Call pre login event AsyncPlayerPreLoginEvent asyncPlayerPreLoginEvent = new AsyncPlayerPreLoginEvent(player); - globalEventHandler.call(asyncPlayerPreLoginEvent); + globalEventHandlerProvider.getGlobalEventHandler().call(asyncPlayerPreLoginEvent); if (!player.isOnline()) return; // Player has been kicked @@ -251,10 +254,10 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { player.getPlayerConnection().setConnectionState(ConnectionState.CONFIGURATION); CompletableFuture configFuture = AsyncUtils.runAsync(exceptionHandlerProvider.getExceptionHandler(), () -> { - player.sendPacket(PluginMessagePacket.getBrandPacket(serverSettings)); + player.sendPacket(PluginMessagePacket.getBrandPacket(serverSettingsProvider.getServerSettings())); var event = new AsyncPlayerConfigurationEvent(player, isFirstConfig); - globalEventHandler.call(event); + globalEventHandlerProvider.getGlobalEventHandler().call(event); final Instance spawningInstance = event.getSpawningInstance(); Check.notNull(spawningInstance, "You need to specify a spawning instance in the AsyncPlayerConfigurationEvent"); @@ -263,8 +266,8 @@ public void doConfiguration(@NotNull Player player, boolean isFirstConfig) { if (event.willSendRegistryData()) { var registry = new HashMap(); registry.put("minecraft:chat_type", Messenger.chatRegistry()); - registry.put("minecraft:dimension_type", dimensionTypeManager.toNBT()); - registry.put("minecraft:worldgen/biome", biomeManager.toNBT()); + registry.put("minecraft:dimension_type", dimensionTypeManagerProvider.getDimensionTypeManager().toNBT()); + registry.put("minecraft:worldgen/biome", biomeManagerProvider.getBiomeManager().toNBT()); registry.put("minecraft:damage_type", DamageType.getNBT()); player.sendPacket(new RegistryDataPacket(NBT.Compound(registry))); diff --git a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java index 66a1eb9a999..9b9f8d1ba34 100644 --- a/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/FakePlayerConnection.java @@ -3,10 +3,10 @@ import net.minestom.server.entity.Player; import net.minestom.server.entity.fakeplayer.FakePlayer; import net.minestom.server.entity.fakeplayer.FakePlayerController; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.packet.server.SendablePacket; import net.minestom.server.network.packet.server.ServerPacket; -import net.minestom.server.network.socket.Server; +import net.minestom.server.network.socket.ServerProvider; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -15,8 +15,8 @@ public class FakePlayerConnection extends PlayerConnection { - public FakePlayerConnection(Server server, ConnectionManager connectionManager) { - super(server, connectionManager); + public FakePlayerConnection(ServerProvider serverProvider, ConnectionManagerProvider connectionManagerProvider) { + super(serverProvider, connectionManagerProvider); } @Override diff --git a/src/main/java/net/minestom/server/network/player/PlayerConnection.java b/src/main/java/net/minestom/server/network/player/PlayerConnection.java index ab11602dfe3..ec414a923ad 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerConnection.java @@ -1,13 +1,15 @@ package net.minestom.server.network.player; +import lombok.Getter; +import lombok.Setter; import net.minestom.server.ServerConsts; import net.minestom.server.crypto.PlayerPublicKey; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.server.SendablePacket; -import net.minestom.server.network.socket.Server; +import net.minestom.server.network.socket.ServerProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -21,16 +23,23 @@ * It can be extended to create a new kind of player (NPC for instance). */ public abstract class PlayerConnection { - private final Server server; - private final ConnectionManager connectionManager; + private final ServerProvider serverProvider; + private final ConnectionManagerProvider connectionManagerProvider; + @Setter + @Getter private Player player; + @Setter + @Getter private volatile ConnectionState connectionState; + @Getter + @Setter private PlayerPublicKey playerPublicKey; + @Getter volatile boolean online; - public PlayerConnection(Server server, ConnectionManager connectionManager) { - this.server = server; - this.connectionManager = connectionManager; + public PlayerConnection(ServerProvider serverProvider, ConnectionManagerProvider connectionManagerProvider) { + this.serverProvider = serverProvider; + this.connectionManagerProvider = connectionManagerProvider; this.online = true; this.connectionState = ConnectionState.HANDSHAKE; } @@ -89,7 +98,7 @@ public int getProtocolVersion() { * @return the server address used */ public @Nullable String getServerAddress() { - return server.getAddress(); + return serverProvider.getServer().getAddress(); } @@ -101,7 +110,7 @@ public int getProtocolVersion() { * @return the server port used */ public int getServerPort() { - return server.getPort(); + return serverProvider.getServer().getPort(); } /** @@ -109,63 +118,13 @@ public int getServerPort() { */ public void disconnect() { this.online = false; - connectionManager.removePlayer(this); + connectionManagerProvider.getConnectionManager().removePlayer(this); final Player player = getPlayer(); if (player != null && !player.isRemoved()) { player.scheduleNextTick(Entity::remove); } } - /** - * Gets the player linked to this connection. - * - * @return the player, can be null if not initialized yet - */ - public @Nullable Player getPlayer() { - return player; - } - - /** - * Changes the player linked to this connection. - *

          - * WARNING: unsafe. - * - * @param player the player - */ - public void setPlayer(Player player) { - this.player = player; - } - - /** - * Gets if the client is still connected to the server. - * - * @return true if the player is online, false otherwise - */ - public boolean isOnline() { - return online; - } - - public void setConnectionState(@NotNull ConnectionState connectionState) { - this.connectionState = connectionState; - } - - /** - * Gets the client connection state. - * - * @return the client connection state - */ - public @NotNull ConnectionState getConnectionState() { - return connectionState; - } - - public PlayerPublicKey playerPublicKey() { - return playerPublicKey; - } - - public void setPlayerPublicKey(PlayerPublicKey playerPublicKey) { - this.playerPublicKey = playerPublicKey; - } - @Override public String toString() { return "PlayerConnection{" + diff --git a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java index 889fbf99f44..aaf25073c69 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerSocketConnection.java @@ -1,22 +1,21 @@ package net.minestom.server.network.player; -import net.minestom.server.ServerSettings; +import net.minestom.server.ServerSettingsProvider; import net.minestom.server.adventure.MinestomAdventure; import net.minestom.server.entity.Player; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.ListenerHandle; import net.minestom.server.event.player.PlayerPacketOutEvent; -import net.minestom.server.exception.ExceptionHandler; +import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.extras.mojangAuth.MojangCrypt; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.PacketProcessor; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; import net.minestom.server.network.packet.server.*; import net.minestom.server.network.packet.server.login.SetCompressionPacket; -import net.minestom.server.network.socket.Server; +import net.minestom.server.network.socket.ServerProvider; import net.minestom.server.network.socket.Worker; import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.PacketUtils; @@ -52,8 +51,8 @@ public class PlayerSocketConnection extends PlayerConnection { private final static Logger LOGGER = LoggerFactory.getLogger(PlayerSocketConnection.class); private static final ObjectPool POOL = ObjectPool.BUFFER_POOL; - private final ExceptionHandler exceptionHandler; - private final ServerSettings serverSettings; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final ServerSettingsProvider serverSettingsProvider; private final Worker worker; private final MessagePassingQueue workerQueue; private final SocketChannel channel; @@ -82,10 +81,15 @@ public class PlayerSocketConnection extends PlayerConnection { private final ListenerHandle outgoing; - public PlayerSocketConnection(Server server, ConnectionManager connectionManager, EventNode globalEventHandler, ExceptionHandler exceptionHandler, ServerSettings serverSettings, @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { - super(server, connectionManager); - this.exceptionHandler = exceptionHandler; - this.serverSettings = serverSettings; + public PlayerSocketConnection(GlobalEventHandler globalEventHandler, + ServerProvider serverProvider, + ConnectionManagerProvider connectionManagerProvider, + ExceptionHandlerProvider exceptionHandlerProvider, + ServerSettingsProvider serverSettingsProvider, + @NotNull Worker worker, @NotNull SocketChannel channel, SocketAddress remoteAddress) { + super(serverProvider, connectionManagerProvider); + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.serverSettingsProvider = serverSettingsProvider; this.worker = worker; this.workerQueue = worker.queue(); this.channel = channel; @@ -102,7 +106,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces try { encryptionContext.decrypt().update(input, input.duplicate()); } catch (ShortBufferException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); return; } } @@ -118,7 +122,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces packet = packetProcessor.process(this, id, payload); } catch (Exception e) { // Error while reading the packet - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } finally { if (payload.position() != payload.limit()) { LOGGER.warn("WARNING: Packet ({}) 0x{} not fully read ({}) {}", getConnectionState(), Integer.toHexString(id), payload, packet); @@ -126,7 +130,7 @@ public void processPackets(BinaryBuffer readBuffer, PacketProcessor packetProces } }); } catch (DataFormatException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); disconnect(); } } @@ -157,7 +161,7 @@ public void setEncryptionKey(@NotNull SecretKey secretKey) { */ public void startCompression() { Check.stateCondition(compressed, "Compression is already enabled!"); - final int threshold = serverSettings.getCompressionThreshold(); + final int threshold = serverSettingsProvider.getServerSettings().getCompressionThreshold(); Check.stateCondition(threshold == 0, "Compression cannot be enabled because the threshold is equal to 0"); sendPacket(new SetCompressionPacket(threshold)); this.compressed = true; @@ -378,7 +382,7 @@ private void writeServerPacketSync(ServerPacket serverPacket, boolean compressed } } try (var hold = ObjectPool.PACKET_POOL.hold()) { - var buffer = PacketUtils.createFramedPacket(serverSettings, getConnectionState(), hold.get(), serverPacket, compressed); + var buffer = PacketUtils.createFramedPacket(serverSettingsProvider.getServerSettings(), getConnectionState(), hold.get(), serverPacket, compressed); writeBufferSync(buffer, 0, buffer.limit()); } } @@ -393,7 +397,7 @@ private void writeBufferSync(@NotNull ByteBuffer buffer, int index, int length) length = encryptionContext.encrypt().update(buffer.slice(index, length), output); writeBufferSync0(output, 0, length); } catch (ShortBufferException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } return; } diff --git a/src/main/java/net/minestom/server/network/socket/ServerImpl.java b/src/main/java/net/minestom/server/network/socket/ServerImpl.java index f5d1c0ce313..1cd89e6d995 100644 --- a/src/main/java/net/minestom/server/network/socket/ServerImpl.java +++ b/src/main/java/net/minestom/server/network/socket/ServerImpl.java @@ -1,11 +1,12 @@ package net.minestom.server.network.socket; +import net.minestom.server.ServerFacade; import net.minestom.server.ServerSettings; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.event.GlobalEventHandlerProvider; +import net.minestom.server.exception.ExceptionHandlerProvider; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.PacketProcessor; +import net.minestom.server.network.PacketProcessorProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -21,12 +22,12 @@ public final class ServerImpl implements Server { + private final ServerSettings serverSettings; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final PacketProcessorProvider packetProcessorProvider; private volatile boolean stop; private final Selector selector; - private final ServerSettings serverSettings; - private final ExceptionHandler exceptionHandler; - private final PacketProcessor packetProcessor; private final List workers; private int index; @@ -35,12 +36,16 @@ public final class ServerImpl implements Server { private String address; private int port; - public ServerImpl(ConnectionManager connectionManager, EventNode globalEventHandler, ExceptionHandler exceptionHandler, ServerSettings serverSettings, PacketProcessor packetProcessor) { + public ServerImpl(ServerSettings serverSettings, ServerFacade serverFacade) { + this(serverSettings, serverFacade, serverFacade, serverFacade, serverFacade); + } + + public ServerImpl(ServerSettings serverSettings, ConnectionManagerProvider connectionManagerProvider, GlobalEventHandlerProvider globalEventHandlerProvider, ExceptionHandlerProvider exceptionHandlerProvider, PacketProcessorProvider packetProcessorProvider) { this.serverSettings = serverSettings; - this.exceptionHandler = exceptionHandler; - this.packetProcessor = packetProcessor; + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.packetProcessorProvider = packetProcessorProvider; Worker[] workers = new Worker[serverSettings.getWorkers()]; - Arrays.setAll(workers, value -> new Worker(this, connectionManager, globalEventHandler, exceptionHandler, serverSettings)); + Arrays.setAll(workers, value -> new Worker(this, connectionManagerProvider, globalEventHandlerProvider, exceptionHandlerProvider, () -> serverSettings)); this.workers = List.of(workers); try { this.selector = Selector.open(); @@ -97,7 +102,7 @@ public void start() { } }); } catch (IOException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } }, "Ms-entrypoint").start(); @@ -125,7 +130,7 @@ public void stop() { Files.deleteIfExists(unixDomainSocketAddress.getPath()); } } catch (IOException e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } this.selector.wakeup(); this.workers.forEach(worker -> worker.selector.wakeup()); @@ -134,7 +139,7 @@ public void stop() { @Override @ApiStatus.Internal public @NotNull PacketProcessor packetProcessor() { - return packetProcessor; + return packetProcessorProvider.getPacketProcessor(); } @Override diff --git a/src/main/java/net/minestom/server/network/socket/Worker.java b/src/main/java/net/minestom/server/network/socket/Worker.java index 8ec2c1f3b53..eb41309497e 100644 --- a/src/main/java/net/minestom/server/network/socket/Worker.java +++ b/src/main/java/net/minestom/server/network/socket/Worker.java @@ -1,10 +1,9 @@ package net.minestom.server.network.socket; -import net.minestom.server.ServerSettings; -import net.minestom.server.event.Event; -import net.minestom.server.event.EventNode; -import net.minestom.server.exception.ExceptionHandler; -import net.minestom.server.network.ConnectionManager; +import net.minestom.server.ServerSettingsProvider; +import net.minestom.server.event.GlobalEventHandlerProvider; +import net.minestom.server.exception.ExceptionHandlerProvider; +import net.minestom.server.network.ConnectionManagerProvider; import net.minestom.server.network.player.PlayerSocketConnection; import net.minestom.server.thread.MinestomThread; import net.minestom.server.utils.ObjectPool; @@ -30,20 +29,21 @@ public final class Worker extends MinestomThread { final Selector selector; private final Map connectionMap = new ConcurrentHashMap<>(); - private final ConnectionManager connectionManager; - private final EventNode globalEventHandler; - private final ExceptionHandler exceptionHandler; - private final ServerSettings serverSettings; + private final Server server; + private final ConnectionManagerProvider connectionManagerProvider; + private final GlobalEventHandlerProvider globalEventHandlerProvider; + private final ExceptionHandlerProvider exceptionHandlerProvider; + private final ServerSettingsProvider serverSettingsProvider; private final MpscUnboundedXaddArrayQueue queue = new MpscUnboundedXaddArrayQueue<>(1024); - Worker(Server server, ConnectionManager connectionManager, EventNode globalEventHandler, ExceptionHandler exceptionHandler, ServerSettings serverSettings) { + Worker(Server server, ConnectionManagerProvider connectionManagerProvider, GlobalEventHandlerProvider globalEventHandlerProvider, ExceptionHandlerProvider exceptionHandlerProvider, ServerSettingsProvider serverSettingsProvider) { super("Ms-worker-" + COUNTER.getAndIncrement()); - this.connectionManager = connectionManager; - this.globalEventHandler = globalEventHandler; - this.exceptionHandler = exceptionHandler; - this.serverSettings = serverSettings; this.server = server; + this.connectionManagerProvider = connectionManagerProvider; + this.globalEventHandlerProvider = globalEventHandlerProvider; + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.serverSettingsProvider = serverSettingsProvider; try { this.selector = Selector.open(); } catch (IOException e) { @@ -62,7 +62,7 @@ public void run() { try { this.queue.drain(Runnable::run); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } // Flush all connections if needed for (PlayerSocketConnection connection : connectionMap.values()) { @@ -99,12 +99,12 @@ public void run() { // TODO print exception? (should ignore disconnection) connection.disconnect(); } catch (Throwable t) { - exceptionHandler.handleException(t); + exceptionHandlerProvider.getExceptionHandler().handleException(t); connection.disconnect(); } }); } catch (Exception e) { - exceptionHandler.handleException(e); + exceptionHandlerProvider.getExceptionHandler().handleException(e); } } } @@ -124,15 +124,15 @@ public void disconnect(PlayerSocketConnection connection, SocketChannel channel) } void receiveConnection(SocketChannel channel) throws IOException { - this.connectionMap.put(channel, new PlayerSocketConnection(server, connectionManager, globalEventHandler, exceptionHandler, serverSettings, this, channel, channel.getRemoteAddress())); + this.connectionMap.put(channel, new PlayerSocketConnection(globalEventHandlerProvider.getGlobalEventHandler(), () -> server, connectionManagerProvider, exceptionHandlerProvider, serverSettingsProvider, this, channel, channel.getRemoteAddress())); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); if (channel.getLocalAddress() instanceof InetSocketAddress) { Socket socket = channel.socket(); - socket.setSendBufferSize(serverSettings.getSendBufferSize()); - socket.setReceiveBufferSize(serverSettings.getReceiveBufferSize()); - socket.setTcpNoDelay(serverSettings.isTcpNoDelay()); + socket.setSendBufferSize(serverSettingsProvider.getServerSettings().getSendBufferSize()); + socket.setReceiveBufferSize(serverSettingsProvider.getServerSettings().getReceiveBufferSize()); + socket.setTcpNoDelay(serverSettingsProvider.getServerSettings().isTcpNoDelay()); socket.setSoTimeout(30 * 1000); // 30 seconds } } From d5fd344f9c6768c8d5a3fba851a4610ab10d300c Mon Sep 17 00:00:00 2001 From: MelonHell Date: Thu, 1 Feb 2024 10:08:37 +0300 Subject: [PATCH 12/16] renamed ServerFacade to MinecraftServer --- .../src/main/java/net/minestom/demo/Main.java | 52 +++++++++---------- .../java/net/minestom/demo/PlayerInit.java | 34 ++++++------ .../demo/commands/AutoViewCommand.java | 8 +-- .../demo/commands/DimensionCommand.java | 6 +-- .../demo/commands/DisplayCommand.java | 18 +++---- .../demo/commands/EntitySelectorCommand.java | 6 +-- .../demo/commands/ExecuteCommand.java | 6 +-- .../demo/commands/GamemodeCommand.java | 6 +-- .../minestom/demo/commands/GiveCommand.java | 6 +-- .../minestom/demo/commands/HorseCommand.java | 10 ++-- .../demo/commands/PlayersCommand.java | 10 ++-- .../minestom/demo/commands/RemoveCommand.java | 10 ++-- .../minestom/demo/commands/SaveCommand.java | 12 ++--- .../demo/commands/ShutdownCommand.java | 10 ++-- .../demo/commands/SidebarCommand.java | 6 +-- .../minestom/demo/commands/SummonCommand.java | 16 +++--- .../demo/commands/TeleportCommand.java | 10 ++-- .../minestom/demo/entity/ChickenCreature.java | 6 +-- .../minestom/demo/entity/ZombieCreature.java | 6 +-- ...ServerFacade.java => MinecraftServer.java} | 16 ++++-- ...cadeImpl.java => MinecraftServerImpl.java} | 4 +- .../net/minestom/server/ServerConsts.java | 12 ----- .../net/minestom/server/ServerStarter.java | 4 +- .../java/net/minestom/server/TickerImpl.java | 4 +- .../server/crypto/SignatureValidator.java | 6 +-- .../net/minestom/server/entity/Entity.java | 10 ++-- .../server/entity/EntityCreature.java | 10 ++-- .../server/entity/EntityProjectile.java | 6 +-- .../minestom/server/entity/ExperienceOrb.java | 6 +-- .../minestom/server/entity/ItemEntity.java | 6 +-- .../minestom/server/entity/LivingEntity.java | 10 ++-- .../net/minestom/server/entity/Player.java | 6 +-- .../server/entity/fakeplayer/FakePlayer.java | 10 ++-- .../net/minestom/server/event/EventNode.java | 26 +++++----- .../minestom/server/extras/query/Query.java | 18 +++---- .../extras/query/event/BasicQueryEvent.java | 6 +-- .../extras/query/event/FullQueryEvent.java | 8 +-- .../query/response/BasicQueryResponse.java | 14 ++--- .../query/response/FullQueryResponse.java | 19 ++++--- .../extras/query/response/QueryKey.java | 15 +++--- .../server/instance/InstanceContainer.java | 18 +++---- .../server/instance/InstanceManagerImpl.java | 6 +-- .../server/instance/LightingChunk.java | 6 +-- .../manager/PacketListenerManagerImpl.java | 6 +-- .../listener/preplay/HandshakeListener.java | 6 +-- .../listener/preplay/LoginListener.java | 8 +-- .../monitoring/BenchmarkManagerImpl.java | 8 +-- .../server/network/ConnectionManagerImpl.java | 6 +-- .../network/player/PlayerConnection.java | 4 +- .../server/network/socket/ServerImpl.java | 6 +-- .../minestom/server/ping/ResponseData.java | 6 +-- .../server/thread/TickSchedulerThread.java | 4 +- .../minestom/server/thread/TickThread.java | 4 +- .../minestom/server/utils/PacketUtils.java | 10 ++-- .../minestom/server/ServerProcessTest.java | 6 +-- .../minestom/server/command/ArgumentTest.java | 16 +++--- .../server/command/ArgumentTypeTest.java | 28 +++++----- .../server/command/CommandConditionTest.java | 16 +++--- .../server/command/CommandManagerTest.java | 18 +++---- .../command/CommandPacketFilteringTest.java | 4 +- .../server/command/CommandParseTest.java | 6 +-- .../server/command/CommandSenderTest.java | 4 +- .../command/CommandSyntaxMultiTest.java | 6 +-- .../command/CommandSyntaxSingleTest.java | 6 +-- .../minestom/server/command/CommandTest.java | 6 +-- .../server/command/SubcommandTest.java | 10 ++-- .../entity/EntityRemovalIntegrationTest.java | 6 +-- .../server/event/EventNodeGraphTest.java | 26 +++++----- .../server/event/EventNodeMapTest.java | 28 +++++----- .../server/event/EventNodeQueryTest.java | 36 ++++++------- .../minestom/server/event/EventNodeTest.java | 48 ++++++++--------- .../EntityTrackerIntegrationTest.java | 6 +-- .../server/instance/EntityTrackerTest.java | 52 +++++++++---------- .../instance/InstanceContainerTest.java | 6 +-- .../server/instance/light/BlockLightTest.java | 42 +++++++-------- .../light/LightParityIntegrationTest.java | 10 ++-- .../light/WorldRelightIntegrationTest.java | 4 +- .../palette/PaletteOptimizationTest.java | 22 ++++---- .../server/instance/palette/PaletteTest.java | 52 +++++++++---------- .../server/inventory/InventoryTest.java | 14 ++--- .../network/socket/ServerAddressTest.java | 18 +++---- .../server/permission/TestPermissions.java | 8 +-- .../server/thread/AcquirableTest.java | 8 +-- .../server/thread/ThreadDispatcherTest.java | 20 +++---- 84 files changed, 539 insertions(+), 545 deletions(-) rename src/main/java/net/minestom/server/{ServerFacade.java => MinecraftServer.java} (82%) rename src/main/java/net/minestom/server/{ServerFacadeImpl.java => MinecraftServerImpl.java} (97%) delete mode 100644 src/main/java/net/minestom/server/ServerConsts.java diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index 6b432def883..f2c0c7c2ee0 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -8,7 +8,7 @@ import net.minestom.demo.block.TestBlockHandler; import net.minestom.demo.block.placement.DripstonePlacementRule; import net.minestom.demo.commands.*; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; @@ -36,51 +36,51 @@ public static void main(String[] args) { ServerSettings serverSettings = ServerSettings.builder().compressionThreshold(0).build(); - ServerFacade serverFacade = ServerFacade.of(serverSettings); + MinecraftServer minecraftServer = MinecraftServer.of(serverSettings); - BlockManager blockManager = serverFacade.getBlockManager(); + BlockManager blockManager = minecraftServer.getBlockManager(); blockManager.registerBlockPlacementRule(new DripstonePlacementRule()); blockManager.registerHandler(TestBlockHandler.INSTANCE.getNamespaceId(), () -> TestBlockHandler.INSTANCE); - CommandManager commandManager = serverFacade.getCommandManager(); + CommandManager commandManager = minecraftServer.getCommandManager(); commandManager.register(new TestCommand()); - commandManager.register(new EntitySelectorCommand(serverFacade)); + commandManager.register(new EntitySelectorCommand(minecraftServer)); commandManager.register(new HealthCommand()); commandManager.register(new LegacyCommand()); - commandManager.register(new DimensionCommand(serverFacade)); - commandManager.register(new ShutdownCommand(serverFacade)); - commandManager.register(new TeleportCommand(serverFacade)); - commandManager.register(new PlayersCommand(serverFacade)); + commandManager.register(new DimensionCommand(minecraftServer)); + commandManager.register(new ShutdownCommand(minecraftServer)); + commandManager.register(new TeleportCommand(minecraftServer)); + commandManager.register(new PlayersCommand(minecraftServer)); commandManager.register(new FindCommand()); commandManager.register(new TitleCommand()); commandManager.register(new BookCommand()); commandManager.register(new ShootCommand()); - commandManager.register(new HorseCommand(serverFacade)); + commandManager.register(new HorseCommand(minecraftServer)); commandManager.register(new EchoCommand()); - commandManager.register(new SummonCommand(serverFacade)); - commandManager.register(new RemoveCommand(serverFacade)); - commandManager.register(new GiveCommand(serverFacade)); + commandManager.register(new SummonCommand(minecraftServer)); + commandManager.register(new RemoveCommand(minecraftServer)); + commandManager.register(new GiveCommand(minecraftServer)); commandManager.register(new SetBlockCommand()); - commandManager.register(new AutoViewCommand(serverFacade)); - commandManager.register(new SaveCommand(serverFacade)); - commandManager.register(new GamemodeCommand(serverFacade)); - commandManager.register(new ExecuteCommand(serverFacade)); + commandManager.register(new AutoViewCommand(minecraftServer)); + commandManager.register(new SaveCommand(minecraftServer)); + commandManager.register(new GamemodeCommand(minecraftServer)); + commandManager.register(new ExecuteCommand(minecraftServer)); commandManager.register(new RedirectTestCommand()); - commandManager.register(new DisplayCommand(serverFacade)); + commandManager.register(new DisplayCommand(minecraftServer)); commandManager.register(new NotificationCommand()); commandManager.register(new TestCommand2()); commandManager.register(new ConfigCommand()); - commandManager.register(new SidebarCommand(serverFacade)); + commandManager.register(new SidebarCommand(minecraftServer)); commandManager.register(new SetEntityType()); commandManager.setUnknownCommandCallback((sender, command) -> sender.sendMessage(Component.text("Unknown command", NamedTextColor.RED))); - serverFacade.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); + minecraftServer.getBenchmarkManager().enable(Duration.of(10, TimeUnit.SECOND)); - serverFacade.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); + minecraftServer.getSchedulerManager().buildShutdownTask(() -> System.out.println("Good night")); - serverFacade.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { + minecraftServer.getGlobalEventHandler().addListener(ServerListPingEvent.class, event -> { ResponseData responseData = event.getResponseData(); responseData.addEntry(NamedAndIdentified.named("The first line is separated from the others")); responseData.addEntry(NamedAndIdentified.named("Could be a name, or a message")); @@ -128,9 +128,9 @@ public boolean shouldShow(@NotNull Player player) { return true; } }; - serverFacade.getRecipeManager().addRecipe(ironBlockRecipe); + minecraftServer.getRecipeManager().addRecipe(ironBlockRecipe); - new PlayerInit(serverFacade).init(); + new PlayerInit(minecraftServer).init(); // VelocityProxy.enable("abcdef"); //BungeeCordProxy.enable(); @@ -138,9 +138,9 @@ public boolean shouldShow(@NotNull Player player) { //MojangAuth.init(); // useful for testing - we don't need to worry about event calls so just set this to a long time - new OpenToLAN(serverFacade.getConnectionManager(), serverFacade.getServer(), serverFacade.getSchedulerManager(), serverFacade.getGlobalEventHandler()).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); + new OpenToLAN(minecraftServer.getConnectionManager(), minecraftServer.getServer(), minecraftServer.getSchedulerManager(), minecraftServer.getGlobalEventHandler()).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); - serverFacade.getServerStarter().start("0.0.0.0", 25565); + minecraftServer.getServerStarter().start("0.0.0.0", 25565); // minecraftServer.start(java.net.UnixDomainSocketAddress.of("minestom-demo.sock")); //Runtime.getRuntime().addShutdownHook(new Thread(MinecraftServer::stopCleanly)); } diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index 7752170383a..5d67f56e2ff 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -1,7 +1,7 @@ package net.minestom.demo; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.advancements.FrameType; import net.minestom.server.advancements.notifications.Notification; import net.minestom.server.advancements.notifications.NotificationCenter; @@ -47,15 +47,15 @@ public class PlayerInit { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public PlayerInit(ServerFacade serverFacade) { - this.serverFacade = serverFacade; - InstanceManager instanceManager = serverFacade.getInstanceManager(); + public PlayerInit(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; + InstanceManager instanceManager = minecraftServer.getInstanceManager(); InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); instanceContainer.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); - instanceContainer.setChunkSupplier((instance, chunkX, chunkZ) -> new LightingChunk(serverFacade, instance, chunkX, chunkZ)); + instanceContainer.setChunkSupplier((instance, chunkX, chunkZ) -> new LightingChunk(minecraftServer, instance, chunkX, chunkZ)); // var i2 = new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD, null, NamespaceID.from("minestom:demo")); // instanceManager.registerInstance(i2); @@ -71,10 +71,10 @@ public PlayerInit(ServerFacade serverFacade) { // System.out.println("load end"); // }); - inventory = new Inventory(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), InventoryType.CHEST_1_ROW, Component.text("Test inventory")); + inventory = new Inventory(minecraftServer.getGlobalEventHandler(), minecraftServer.getServerSettings(), InventoryType.CHEST_1_ROW, Component.text("Test inventory")); inventory.setItemStack(3, ItemStack.of(Material.DIAMOND, 34)); - DEMO_NODE = EventNode.all(serverFacade, "demo") + DEMO_NODE = EventNode.all(minecraftServer, "demo") .addListener(EntityAttackEvent.class, event -> { final Entity source = event.getEntity(); final Entity entity = event.getTarget(); @@ -104,13 +104,13 @@ public PlayerInit(ServerFacade serverFacade) { ItemStack droppedItem = event.getItemStack(); Pos playerPos = player.getPosition(); - ItemEntity itemEntity = new ItemEntity(serverFacade, droppedItem); + ItemEntity itemEntity = new ItemEntity(minecraftServer, droppedItem); itemEntity.setPickupDelay(Duration.of(500, TimeUnit.MILLISECOND)); itemEntity.setInstance(player.getInstance(), playerPos.withY(y -> y + 1.5)); Vec velocity = playerPos.direction().mul(6); itemEntity.setVelocity(velocity); - new FakePlayer(serverFacade, UUID.randomUUID(), "fake123", new FakePlayerOption(), fp -> { + new FakePlayer(minecraftServer, UUID.randomUUID(), "fake123", new FakePlayerOption(), fp -> { System.out.println("fp = " + fp); }); }) @@ -118,7 +118,7 @@ public PlayerInit(ServerFacade serverFacade) { .addListener(AsyncPlayerConfigurationEvent.class, event -> { final Player player = event.getPlayer(); - var instances = serverFacade.getInstanceManager().getInstances(); + var instances = minecraftServer.getInstanceManager().getInstances(); Instance instance = instances.stream().skip(new Random().nextInt(instances.size())).findFirst().orElse(null); event.setSpawningInstance(instance); int x = Math.abs(ThreadLocalRandom.current().nextInt()) % 500 - 250; @@ -199,7 +199,7 @@ public PlayerInit(ServerFacade serverFacade) { private final AtomicReference LAST_TICK = new AtomicReference<>(); public void init() { - var eventHandler = serverFacade.getGlobalEventHandler(); + var eventHandler = minecraftServer.getGlobalEventHandler(); eventHandler.addChild(DEMO_NODE); MinestomAdventure.AUTOMATIC_COMPONENT_TRANSLATION = true; @@ -207,9 +207,9 @@ public void init() { eventHandler.addListener(ServerTickMonitorEvent.class, event -> LAST_TICK.set(event.getTickMonitor())); - BenchmarkManager benchmarkManager = serverFacade.getBenchmarkManager(); - serverFacade.getSchedulerManager().buildTask(() -> { - if (serverFacade.getConnectionManager().getOnlinePlayerCount() != 0) + BenchmarkManager benchmarkManager = minecraftServer.getBenchmarkManager(); + minecraftServer.getSchedulerManager().buildTask(() -> { + if (minecraftServer.getConnectionManager().getOnlinePlayerCount() != 0) return; long ramUsage = benchmarkManager.getUsedMemory(); @@ -222,7 +222,7 @@ public void init() { .append(Component.newline()) .append(Component.text("ACQ TIME: " + MathUtils.round(tickMonitor.getAcquisitionTime(), 2) + "ms")); final Component footer = BenchmarkManager.getCpuMonitoringMessage(benchmarkManager); - serverFacade.getAudienceManager().players().sendPlayerListHeaderAndFooter(header, footer); - }).repeat(10, TimeUnit.getServerTick(serverFacade.getServerSettings())); //.schedule(); + minecraftServer.getAudienceManager().players().sendPlayerListHeaderAndFooter(header, footer); + }).repeat(10, TimeUnit.getServerTick(minecraftServer.getServerSettings())); //.schedule(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java b/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java index e732b73c0b3..a90ce1f3003 100644 --- a/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/AutoViewCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; @@ -11,7 +11,7 @@ import static net.minestom.server.command.builder.arguments.ArgumentType.*; public class AutoViewCommand extends Command { - public AutoViewCommand(ServerFacade serverFacade) { + public AutoViewCommand(MinecraftServer minecraftServer) { super("autoview"); // Modify viewable @@ -37,7 +37,7 @@ public AutoViewCommand(ServerFacade serverFacade) { final List entities = finder.find(sender); player.updateViewableRule(entities::contains); player.sendMessage("Viewable rule updated to see " + entities.size() + " players"); - }, Literal("rule-viewable"), Entity("targets", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true)); + }, Literal("rule-viewable"), Entity("targets", minecraftServer.getInstanceManager(), minecraftServer.getConnectionManager()).onlyPlayers(true)); // Modify viewer rule addSyntax((sender, context) -> { @@ -46,7 +46,7 @@ public AutoViewCommand(ServerFacade serverFacade) { final List entities = finder.find(sender); player.updateViewerRule(entities::contains); player.sendMessage("Viewer rule updated to see " + entities.size() + " entities"); - }, Literal("rule-viewer"), Entity("targets", serverFacade.getInstanceManager(), serverFacade.getConnectionManager())); + }, Literal("rule-viewer"), Entity("targets", minecraftServer.getInstanceManager(), minecraftServer.getConnectionManager())); // Remove viewable rule addSyntax((sender, context) -> { diff --git a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java index 48570555d31..2ca66f60cd7 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DimensionCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.condition.Conditions; import net.minestom.server.entity.Player; @@ -10,14 +10,14 @@ public class DimensionCommand extends Command { - public DimensionCommand(ServerFacade serverFacade) { + public DimensionCommand(MinecraftServer minecraftServer) { super("dimensiontest"); setCondition(Conditions::playerOnly); addSyntax((sender, context) -> { final Player player = (Player) sender; final Instance instance = player.getInstance(); - final var instances = serverFacade.getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); + final var instances = minecraftServer.getInstanceManager().getInstances().stream().filter(instance1 -> !instance1.equals(instance)).toList(); if (instances.isEmpty()) { player.sendMessage("No instance available"); return; diff --git a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java index 45059ef2ef8..60f38985823 100644 --- a/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/DisplayCommand.java @@ -1,7 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -23,11 +23,11 @@ public class DisplayCommand extends Command { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public DisplayCommand(ServerFacade serverFacade) { + public DisplayCommand(MinecraftServer minecraftServer) { super("display"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; var follow = ArgumentType.Literal("follow"); @@ -44,7 +44,7 @@ public void spawnItem(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(serverFacade, EntityType.ITEM_DISPLAY); + var entity = new Entity(minecraftServer, EntityType.ITEM_DISPLAY); var meta = (ItemDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setItemStack(ItemStack.of(Material.STICK)); @@ -59,7 +59,7 @@ public void spawnBlock(@NotNull CommandSender sender, @NotNull CommandContext co if (!(sender instanceof Player player)) return; - var entity = new Entity(serverFacade, EntityType.BLOCK_DISPLAY); + var entity = new Entity(minecraftServer, EntityType.BLOCK_DISPLAY); var meta = (BlockDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBlockState(Block.ORANGE_CANDLE_CAKE.stateId()); @@ -74,7 +74,7 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con if (!(sender instanceof Player player)) return; - var entity = new Entity(serverFacade, EntityType.TEXT_DISPLAY); + var entity = new Entity(minecraftServer, EntityType.TEXT_DISPLAY); var meta = (TextDisplayMeta) entity.getEntityMeta(); meta.setTransformationInterpolationDuration(20); meta.setBillboardRenderConstraints(AbstractDisplayMeta.BillboardConstraints.CENTER); @@ -89,8 +89,8 @@ public void spawnText(@NotNull CommandSender sender, @NotNull CommandContext con private void startSmoothFollow(@NotNull Entity entity, @NotNull Player player) { // entity.setCustomName(Component.text("MY CUSTOM NAME")); // entity.setCustomNameVisible(true); - TemporalUnit serverTick = TimeUnit.getServerTick(serverFacade.getServerSettings()); - serverFacade.getSchedulerManager().buildTask(() -> { + TemporalUnit serverTick = TimeUnit.getServerTick(minecraftServer.getServerSettings()); + minecraftServer.getSchedulerManager().buildTask(() -> { var meta = (AbstractDisplayMeta) entity.getEntityMeta(); meta.setNotifyAboutChanges(false); meta.setTransformationInterpolationStartDelta(1); diff --git a/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java b/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java index 1dfe7047511..6e5a7c13450 100644 --- a/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/EntitySelectorCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -13,12 +13,12 @@ public class EntitySelectorCommand extends Command { - public EntitySelectorCommand(ServerFacade serverFacade) { + public EntitySelectorCommand(MinecraftServer minecraftServer) { super("ent"); setDefaultExecutor((sender, context) -> System.out.println("DEFAULT")); - ArgumentEntity argumentEntity = ArgumentType.Entity("entities", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true); + ArgumentEntity argumentEntity = ArgumentType.Entity("entities", minecraftServer.getInstanceManager(), minecraftServer.getConnectionManager()).onlyPlayers(true); setArgumentCallback((sender, exception) -> exception.printStackTrace(), argumentEntity); diff --git a/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java b/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java index de9229c57d8..6b601a96e41 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ExecuteCommand.java @@ -1,14 +1,14 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentCommand; public class ExecuteCommand extends Command { - public ExecuteCommand(ServerFacade serverFacade) { + public ExecuteCommand(MinecraftServer minecraftServer) { super("execute"); - ArgumentCommand run = new ArgumentCommand(serverFacade.getCommandManager(), "run"); + ArgumentCommand run = new ArgumentCommand(minecraftServer.getCommandManager(), "run"); addSyntax(((sender, context) -> {}), run); } diff --git a/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java b/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java index f8c1c9f4ce6..d36d16ac11b 100644 --- a/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/GamemodeCommand.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentEnum; @@ -24,7 +24,7 @@ */ public class GamemodeCommand extends Command { - public GamemodeCommand(ServerFacade serverFacade) { + public GamemodeCommand(MinecraftServer minecraftServer) { super("gamemode", "gm"); //GameMode parameter @@ -36,7 +36,7 @@ public GamemodeCommand(ServerFacade serverFacade) { .append(Component.text("!"))); }); - ArgumentEntity player = ArgumentType.Entity("targets", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true); + ArgumentEntity player = ArgumentType.Entity("targets", minecraftServer.getInstanceManager(), minecraftServer.getConnectionManager()).onlyPlayers(true); //Upon invalid usage, print the correct usage of the command to the sender setDefaultExecutor((sender, context) -> { diff --git a/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java b/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java index fea1c907eef..cdc2c246985 100644 --- a/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/GiveCommand.java @@ -1,7 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; @@ -16,7 +16,7 @@ import static net.minestom.server.command.builder.arguments.ArgumentType.*; public class GiveCommand extends Command { - public GiveCommand(ServerFacade serverFacade) { + public GiveCommand(MinecraftServer minecraftServer) { super("give"); setDefaultExecutor((sender, context) -> @@ -51,7 +51,7 @@ public GiveCommand(ServerFacade serverFacade) { sender.sendMessage(Component.text("Items have been given successfully!")); - }, Entity("target", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()).onlyPlayers(true), ItemStack("item"), Integer("count").setDefaultValue(() -> 1)); + }, Entity("target", minecraftServer.getInstanceManager(), minecraftServer.getConnectionManager()).onlyPlayers(true), ItemStack("item"), Integer("count").setDefaultValue(() -> 1)); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java index 60c79aa035e..d8490e832db 100644 --- a/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/HorseCommand.java @@ -1,7 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -19,11 +19,11 @@ public class HorseCommand extends Command { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public HorseCommand(ServerFacade serverFacade) { + public HorseCommand(MinecraftServer minecraftServer) { super("horse"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; setCondition(Conditions::playerOnly); setDefaultExecutor(this::defaultExecutor); var babyArg = ArgumentType.Boolean("baby"); @@ -63,7 +63,7 @@ private void onHorseCommand(CommandSender sender, CommandContext context) { boolean baby = context.get("baby"); HorseMeta.Marking marking = context.get("marking"); HorseMeta.Color color = context.get("color"); - var horse = new EntityCreature(serverFacade, EntityType.HORSE); + var horse = new EntityCreature(minecraftServer, EntityType.HORSE); var meta = (HorseMeta) horse.getEntityMeta(); meta.setBaby(baby); meta.setVariant(new HorseMeta.Variant(marking, color)); diff --git a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java index a1cc3fb20c5..705f70998db 100644 --- a/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/PlayersCommand.java @@ -1,7 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -10,16 +10,16 @@ public class PlayersCommand extends Command { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public PlayersCommand(ServerFacade serverFacade) { + public PlayersCommand(MinecraftServer minecraftServer) { super("players"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; setDefaultExecutor(this::usage); } private void usage(CommandSender sender, CommandContext context) { - final var players = List.copyOf(serverFacade.getConnectionManager().getOnlinePlayers()); + final var players = List.copyOf(minecraftServer.getConnectionManager().getOnlinePlayers()); final int playerCount = players.size(); sender.sendMessage(Component.text("Total players: " + playerCount)); diff --git a/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java b/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java index 911bd0e13b6..0c19a812138 100644 --- a/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/RemoveCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -13,18 +13,18 @@ public class RemoveCommand extends Command { - public RemoveCommand(ServerFacade serverFacade) { + public RemoveCommand(MinecraftServer minecraftServer) { super("remove"); - addSubcommand(new RemoveEntities(serverFacade)); + addSubcommand(new RemoveEntities(minecraftServer)); } static class RemoveEntities extends Command { private final ArgumentEntity entity; - public RemoveEntities(ServerFacade serverFacade) { + public RemoveEntities(MinecraftServer minecraftServer) { super("entities"); setCondition(Conditions::playerOnly); - entity = ArgumentType.Entity("entity", serverFacade.getInstanceManager(), serverFacade.getConnectionManager()); + entity = ArgumentType.Entity("entity", minecraftServer.getInstanceManager(), minecraftServer.getConnectionManager()); addSyntax(this::remove, entity); } diff --git a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java index a8483370eb0..f8cba801ee1 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SaveCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -14,21 +14,21 @@ */ public class SaveCommand extends Command { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public SaveCommand(ServerFacade serverFacade) { + public SaveCommand(MinecraftServer minecraftServer) { super("save"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; addSyntax(this::execute); } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - for(var instance : serverFacade.getInstanceManager().getInstances()) { + for(var instance : minecraftServer.getInstanceManager().getInstances()) { CompletableFuture instanceSave = instance.saveInstance().thenCompose(v -> instance.saveChunksToStorage()); try { instanceSave.get(); } catch (InterruptedException | ExecutionException e) { - serverFacade.getExceptionHandler().handleException(e); + minecraftServer.getExceptionHandler().handleException(e); } } commandSender.sendMessage("Saving done!"); diff --git a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java index 8aeeb729730..16c43721d48 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -11,15 +11,15 @@ */ public class ShutdownCommand extends Command { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public ShutdownCommand(ServerFacade serverFacade) { + public ShutdownCommand(MinecraftServer minecraftServer) { super("shutdown"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; addSyntax(this::execute); } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - serverFacade.getServerStarter().stop(); + minecraftServer.getServerStarter().stop(); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java index cc99abc4de5..c309c7cc212 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SidebarCommand.java @@ -3,7 +3,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -18,10 +18,10 @@ public class SidebarCommand extends Command { private final Sidebar sidebar; private int currentLine = 0; - public SidebarCommand(ServerFacade serverFacade) { + public SidebarCommand(MinecraftServer minecraftServer) { super("sidebar"); - sidebar = new Sidebar(serverFacade.getServerSettings(), Component.text("DEMO").decorate(TextDecoration.BOLD)); + sidebar = new Sidebar(minecraftServer.getServerSettings(), Component.text("DEMO").decorate(TextDecoration.BOLD)); addLine("BLANK ", Sidebar.NumberFormat.blank()); addLine("STYLE ", Sidebar.NumberFormat.styled(Component.empty().decorate(TextDecoration.STRIKETHROUGH).color(NamedTextColor.GRAY))); diff --git a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java index b28ca7911b1..f721fbd0a32 100644 --- a/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/SummonCommand.java @@ -1,6 +1,6 @@ package net.minestom.demo.commands; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -19,11 +19,11 @@ public class SummonCommand extends Command { private final ArgumentEntityType entity; private final Argument pos; private final Argument entityClass; - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public SummonCommand(ServerFacade serverFacade) { + public SummonCommand(MinecraftServer minecraftServer) { super("summon"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; setCondition(Conditions::playerOnly); entity = ArgumentType.EntityType("entity type"); @@ -40,7 +40,7 @@ public SummonCommand(ServerFacade serverFacade) { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - final Entity entity = commandContext.get(entityClass).instantiate(serverFacade, commandContext.get(this.entity)); + final Entity entity = commandContext.get(entityClass).instantiate(minecraftServer, commandContext.get(this.entity)); //noinspection ConstantConditions - One couldn't possibly execute a command without being in an instance entity.setInstance(((Player) commandSender).getInstance(), commandContext.get(pos).fromSender(commandSender)); } @@ -56,12 +56,12 @@ enum EntityClass { this.factory = factory; } - public Entity instantiate(ServerFacade serverFacade, EntityType type) { - return factory.newInstance(serverFacade, type); + public Entity instantiate(MinecraftServer minecraftServer, EntityType type) { + return factory.newInstance(minecraftServer, type); } } interface EntityFactory { - Entity newInstance(ServerFacade serverFacade, EntityType type); + Entity newInstance(MinecraftServer minecraftServer, EntityType type); } } diff --git a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java index c760f21e998..4b089d3fa6b 100644 --- a/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/TeleportCommand.java @@ -1,7 +1,7 @@ package net.minestom.demo.commands; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.command.CommandSender; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -12,11 +12,11 @@ public class TeleportCommand extends Command { - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public TeleportCommand(ServerFacade serverFacade) { + public TeleportCommand(MinecraftServer minecraftServer) { super("tp"); - this.serverFacade = serverFacade; + this.minecraftServer = minecraftServer; setDefaultExecutor((source, context) -> source.sendMessage(Component.text("Usage: /tp x y z"))); @@ -29,7 +29,7 @@ public TeleportCommand(ServerFacade serverFacade) { private void onPlayerTeleport(CommandSender sender, CommandContext context) { final String playerName = context.get("player"); - Player pl = serverFacade.getConnectionManager().getOnlinePlayerByUsername(playerName); + Player pl = minecraftServer.getConnectionManager().getOnlinePlayerByUsername(playerName); if (sender instanceof Player player) { player.teleport(pl.getPosition()); } diff --git a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java index eee3e5d9db4..a6aaee53ef8 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ChickenCreature.java @@ -1,6 +1,6 @@ package net.minestom.demo.entity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.attribute.Attribute; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; @@ -10,8 +10,8 @@ public class ChickenCreature extends EntityCreature { - public ChickenCreature(ServerFacade serverFacade) { - super(serverFacade, EntityType.CHICKEN); + public ChickenCreature(MinecraftServer minecraftServer) { + super(minecraftServer, EntityType.CHICKEN); addAIGroup( List.of( diff --git a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java index 3488cc3e71c..e9b89f58fe5 100644 --- a/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java +++ b/demo/src/main/java/net/minestom/demo/entity/ZombieCreature.java @@ -1,6 +1,6 @@ package net.minestom.demo.entity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.ai.EntityAIGroupBuilder; @@ -8,8 +8,8 @@ public class ZombieCreature extends EntityCreature { - public ZombieCreature(ServerFacade serverFacade) { - super(serverFacade, EntityType.ZOMBIE); + public ZombieCreature(MinecraftServer minecraftServer) { + super(minecraftServer, EntityType.ZOMBIE); addAIGroup( new EntityAIGroupBuilder() .addGoalSelector(new RandomLookAroundGoal(this, 20)) diff --git a/src/main/java/net/minestom/server/ServerFacade.java b/src/main/java/net/minestom/server/MinecraftServer.java similarity index 82% rename from src/main/java/net/minestom/server/ServerFacade.java rename to src/main/java/net/minestom/server/MinecraftServer.java index 57361ef3f73..8879f9125e6 100644 --- a/src/main/java/net/minestom/server/ServerFacade.java +++ b/src/main/java/net/minestom/server/MinecraftServer.java @@ -23,7 +23,7 @@ import net.minestom.server.world.DimensionTypeManagerProvider; import net.minestom.server.world.biomes.BiomeManagerProvider; -public interface ServerFacade extends +public interface MinecraftServer extends ExceptionHandlerProvider, ConnectionManagerProvider, PacketListenerManagerProvider, @@ -49,8 +49,16 @@ public interface ServerFacade extends MojangAuthProvider, ServerStarterProvider { - ComponentLogger LOGGER = ComponentLogger.logger(ServerFacade.class); - static ServerFacade of(ServerSettings serverSettings) { - return new ServerFacadeImpl(serverSettings); + ComponentLogger LOGGER = ComponentLogger.logger(MinecraftServer.class); + String VERSION_NAME = "1.20.4"; + int PROTOCOL_VERSION = 765; + + // Threads + String THREAD_NAME_BENCHMARK = "Ms-Benchmark"; + + String THREAD_NAME_TICK_SCHEDULER = "Ms-TickScheduler"; + String THREAD_NAME_TICK = "Ms-Tick"; + static MinecraftServer of(ServerSettings serverSettings) { + return new MinecraftServerImpl(serverSettings); } } diff --git a/src/main/java/net/minestom/server/ServerFacadeImpl.java b/src/main/java/net/minestom/server/MinecraftServerImpl.java similarity index 97% rename from src/main/java/net/minestom/server/ServerFacadeImpl.java rename to src/main/java/net/minestom/server/MinecraftServerImpl.java index a8b2863fdd9..f1759bec205 100644 --- a/src/main/java/net/minestom/server/ServerFacadeImpl.java +++ b/src/main/java/net/minestom/server/MinecraftServerImpl.java @@ -43,7 +43,7 @@ import net.minestom.server.world.biomes.BiomeManagerImpl; @Getter -final class ServerFacadeImpl implements ServerFacade { +final class MinecraftServerImpl implements MinecraftServer { private final ExceptionHandler exceptionHandler; private final ConnectionManager connectionManager; @@ -73,7 +73,7 @@ final class ServerFacadeImpl implements ServerFacade { private final ServerStarter serverStarter; - public ServerFacadeImpl(ServerSettings serverSettings) { + public MinecraftServerImpl(ServerSettings serverSettings) { this.serverSettings = serverSettings; this.exceptionHandler = new ExceptionHandlerImpl(); this.globalEventHandler = new GlobalEventHandlerImpl(this); diff --git a/src/main/java/net/minestom/server/ServerConsts.java b/src/main/java/net/minestom/server/ServerConsts.java deleted file mode 100644 index b2841664077..00000000000 --- a/src/main/java/net/minestom/server/ServerConsts.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.minestom.server; - -public interface ServerConsts { - String VERSION_NAME = "1.20.4"; - int PROTOCOL_VERSION = 765; - - // Threads - String THREAD_NAME_BENCHMARK = "Ms-Benchmark"; - - String THREAD_NAME_TICK_SCHEDULER = "Ms-TickScheduler"; - String THREAD_NAME_TICK = "Ms-Tick"; -} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/ServerStarter.java b/src/main/java/net/minestom/server/ServerStarter.java index eaf742863e1..c2cf13b41b3 100644 --- a/src/main/java/net/minestom/server/ServerStarter.java +++ b/src/main/java/net/minestom/server/ServerStarter.java @@ -30,8 +30,8 @@ public class ServerStarter { private final ChunkDispatcherProvider chunkDispatcherProvider; private final TickerProvider tickerProvider; - public ServerStarter(ServerFacade serverFacade) { - this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + public ServerStarter(MinecraftServer minecraftServer) { + this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } private final AtomicBoolean started = new AtomicBoolean(); diff --git a/src/main/java/net/minestom/server/TickerImpl.java b/src/main/java/net/minestom/server/TickerImpl.java index d9fdb0e4835..4e7478b0d77 100644 --- a/src/main/java/net/minestom/server/TickerImpl.java +++ b/src/main/java/net/minestom/server/TickerImpl.java @@ -24,8 +24,8 @@ public final class TickerImpl implements Ticker { private final InstanceManagerProvider instanceManagerProvider; private final ChunkDispatcherProvider chunkDispatcherProvider; - public TickerImpl(ServerFacade serverFacade) { - this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + public TickerImpl(MinecraftServer minecraftServer) { + this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } @Override diff --git a/src/main/java/net/minestom/server/crypto/SignatureValidator.java b/src/main/java/net/minestom/server/crypto/SignatureValidator.java index 2ec63daa9a6..3398fd21a0b 100644 --- a/src/main/java/net/minestom/server/crypto/SignatureValidator.java +++ b/src/main/java/net/minestom/server/crypto/SignatureValidator.java @@ -1,6 +1,6 @@ package net.minestom.server.crypto; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.network.NetworkBuffer; import net.minestom.server.utils.crypto.KeyUtils; @@ -67,12 +67,12 @@ static SignatureValidator from(PublicKey publicKey, KeyUtils.SignatureAlgorithm private static SignatureValidator createYggdrasilValidator() { try (var stream = SignatureValidator.class.getResourceAsStream("/yggdrasil_session_pubkey.der")) { if (stream == null) { - ServerFacade.LOGGER.error("Couldn't find Yggdrasil public key, falling back to prohibiting validator!"); + MinecraftServer.LOGGER.error("Couldn't find Yggdrasil public key, falling back to prohibiting validator!"); return FAIL; } return from(KeyUtils.publicRSAKeyFrom(stream.readAllBytes()), KeyUtils.SignatureAlgorithm.SHA1withRSA); } catch (Exception e) { - ServerFacade.LOGGER.error("Exception while reading Yggdrasil public key, falling back to prohibiting validator!", e); + MinecraftServer.LOGGER.error("Exception while reading Yggdrasil public key, falling back to prohibiting validator!", e); return FAIL; } } diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index dfb8814c85a..099bd631fab 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -6,7 +6,7 @@ import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEvent.ShowEntity; import net.kyori.adventure.text.event.HoverEventSource; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Tickable; import net.minestom.server.Viewable; @@ -189,12 +189,12 @@ public void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracke private final Acquirable acquirable = Acquirable.of(this); - public Entity(@NotNull ServerFacade serverFacade, @NotNull EntityType entityType) { - this(serverFacade, entityType, UUID.randomUUID()); + public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType) { + this(minecraftServer, entityType, UUID.randomUUID()); } - public Entity(@NotNull ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { - this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, entityType, uuid); + public Entity(@NotNull MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer, minecraftServer, minecraftServer, entityType, uuid); } public Entity( diff --git a/src/main/java/net/minestom/server/entity/EntityCreature.java b/src/main/java/net/minestom/server/entity/EntityCreature.java index 766355d38fc..c8b00af18cd 100644 --- a/src/main/java/net/minestom/server/entity/EntityCreature.java +++ b/src/main/java/net/minestom/server/entity/EntityCreature.java @@ -1,7 +1,7 @@ package net.minestom.server.entity; import com.extollit.gaming.ai.path.HydrazinePathFinder; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.ai.EntityAI; @@ -34,12 +34,12 @@ public class EntityCreature extends LivingEntity implements NavigableEntity, Ent private Entity target; - public EntityCreature(ServerFacade serverFacade, @NotNull EntityType entityType) { - this(serverFacade, entityType, UUID.randomUUID()); + public EntityCreature(MinecraftServer minecraftServer, @NotNull EntityType entityType) { + this(minecraftServer, entityType, UUID.randomUUID()); } - public EntityCreature(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { - this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, entityType, uuid); + public EntityCreature(MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer.getServerSettings(), minecraftServer, minecraftServer, entityType, uuid); } /** diff --git a/src/main/java/net/minestom/server/entity/EntityProjectile.java b/src/main/java/net/minestom/server/entity/EntityProjectile.java index 408873af123..526f0d76d48 100644 --- a/src/main/java/net/minestom/server/entity/EntityProjectile.java +++ b/src/main/java/net/minestom/server/entity/EntityProjectile.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.collision.BoundingBox; import net.minestom.server.coordinate.Point; @@ -39,8 +39,8 @@ public EntityProjectile(@NotNull Entity shooter, @NotNull EntityType entityType) this(shooter.globalEventHandler, shooter.serverSettingsProvider, shooter.chunkDispatcherProvider, shooter.exceptionHandlerProvider, shooter, entityType); } - public EntityProjectile(ServerFacade serverFacade, @Nullable Entity shooter, @NotNull EntityType entityType) { - this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, shooter, entityType); + public EntityProjectile(MinecraftServer minecraftServer, @Nullable Entity shooter, @NotNull EntityType entityType) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer, minecraftServer, minecraftServer, shooter, entityType); } public EntityProjectile(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, @Nullable Entity shooter, @NotNull EntityType entityType) { diff --git a/src/main/java/net/minestom/server/entity/ExperienceOrb.java b/src/main/java/net/minestom/server/entity/ExperienceOrb.java index 700713e0f53..224e0d26ecc 100644 --- a/src/main/java/net/minestom/server/entity/ExperienceOrb.java +++ b/src/main/java/net/minestom/server/entity/ExperienceOrb.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.coordinate.Vec; import net.minestom.server.event.GlobalEventHandler; @@ -16,8 +16,8 @@ public class ExperienceOrb extends Entity { private Player target; private long lastTargetUpdateTick; - public ExperienceOrb(ServerFacade serverFacade, short experienceCount) { - this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, experienceCount); + public ExperienceOrb(MinecraftServer minecraftServer, short experienceCount) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer, minecraftServer, minecraftServer, experienceCount); } public ExperienceOrb(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, short experienceCount) { super(globalEventHandler, serverSettingsProvider, chunkDispatcherProvider, exceptionHandlerProvider, EntityType.EXPERIENCE_ORB, UUID.randomUUID()); diff --git a/src/main/java/net/minestom/server/entity/ItemEntity.java b/src/main/java/net/minestom/server/entity/ItemEntity.java index ab3e9e92571..e4b1b45688c 100644 --- a/src/main/java/net/minestom/server/entity/ItemEntity.java +++ b/src/main/java/net/minestom/server/entity/ItemEntity.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.entity.metadata.item.ItemEntityMeta; import net.minestom.server.event.GlobalEventHandler; @@ -43,8 +43,8 @@ public class ItemEntity extends Entity { private long spawnTime; private long pickupDelay; - public ItemEntity(ServerFacade serverFacade, @NotNull ItemStack itemStack) { - this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, itemStack); + public ItemEntity(MinecraftServer minecraftServer, @NotNull ItemStack itemStack) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer.getServerSettings(), minecraftServer, minecraftServer, itemStack); } public ItemEntity(GlobalEventHandler globalEventHandler, ServerSettings serverSettings, ChunkDispatcherProvider chunkDispatcherProvider, ExceptionHandlerProvider exceptionHandlerProvider, @NotNull ItemStack itemStack) { diff --git a/src/main/java/net/minestom/server/entity/LivingEntity.java b/src/main/java/net/minestom/server/entity/LivingEntity.java index 38c6e8f3873..999d72aebfc 100644 --- a/src/main/java/net/minestom/server/entity/LivingEntity.java +++ b/src/main/java/net/minestom/server/entity/LivingEntity.java @@ -1,7 +1,7 @@ package net.minestom.server.entity; import net.kyori.adventure.sound.Sound.Source; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.attribute.Attribute; import net.minestom.server.attribute.AttributeInstance; @@ -87,12 +87,12 @@ public class LivingEntity extends Entity implements EquipmentHandler { private ItemStack leggings; private ItemStack boots; - public LivingEntity(ServerFacade serverFacade, @NotNull EntityType entityType) { - this(serverFacade, entityType, UUID.randomUUID()); + public LivingEntity(MinecraftServer minecraftServer, @NotNull EntityType entityType) { + this(minecraftServer, entityType, UUID.randomUUID()); } - public LivingEntity(ServerFacade serverFacade, @NotNull EntityType entityType, @NotNull UUID uuid) { - this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, entityType, uuid); + public LivingEntity(MinecraftServer minecraftServer, @NotNull EntityType entityType, @NotNull UUID uuid) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer.getServerSettings(), minecraftServer, minecraftServer, entityType, uuid); } /** diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 9c3085a673d..0f53c160e8c 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -20,7 +20,7 @@ import net.kyori.adventure.text.event.HoverEventSource; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.title.TitlePart; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.advancements.AdvancementTab; @@ -263,8 +263,8 @@ public class Player extends LivingEntity implements CommandSender, Localizable, // The future is non-null when a resource pack is in-flight, and completed when all statuses have been received. private CompletableFuture resourcePackFuture = null; - public Player(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { - this(serverFacade.getGlobalEventHandler(), serverFacade.getServerSettings(), serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, uuid, username, playerConnection); + public Player(MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer.getServerSettings(), minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, uuid, username, playerConnection); } public Player( diff --git a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java index 33c0646ef21..329aeb174d6 100644 --- a/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java +++ b/src/main/java/net/minestom/server/entity/fakeplayer/FakePlayer.java @@ -1,7 +1,7 @@ package net.minestom.server.entity.fakeplayer; import com.extollit.gaming.ai.path.HydrazinePathFinder; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.adventure.bossbar.BossBarManagerProvider; import net.minestom.server.command.CommandManagerProvider; @@ -52,11 +52,11 @@ public class FakePlayer extends Player implements NavigableEntity { private EventListener spawnListener; private final SchedulerManagerProvider schedulerManagerProvider; - public FakePlayer(ServerFacade serverFacade, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { + public FakePlayer(MinecraftServer minecraftServer, @NotNull UUID uuid, @NotNull String username, @NotNull FakePlayerOption option, @Nullable Consumer spawnCallback) { this( - serverFacade.getGlobalEventHandler(), - serverFacade.getServerSettings(), - serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, + minecraftServer.getGlobalEventHandler(), + minecraftServer.getServerSettings(), + minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, uuid, username, option, spawnCallback ); } diff --git a/src/main/java/net/minestom/server/event/EventNode.java b/src/main/java/net/minestom/server/event/EventNode.java index d89ac1a0758..632cdf4e633 100644 --- a/src/main/java/net/minestom/server/event/EventNode.java +++ b/src/main/java/net/minestom/server/event/EventNode.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.tag.Tag; @@ -34,9 +34,9 @@ public interface EventNode { * @return An event node with no filtering */ @Contract(value = "_, _ -> new", pure = true) - static @NotNull EventNode all(@NotNull ServerFacade serverFacade, + static @NotNull EventNode all(@NotNull MinecraftServer minecraftServer, @NotNull String name) { - return type(serverFacade, name, EventFilter.ALL); + return type(minecraftServer, name, EventFilter.ALL); } /** @@ -54,10 +54,10 @@ public interface EventNode { * @return A node with just an event type filter */ @Contract(value = "_, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull ServerFacade serverFacade, + static @NotNull EventNode type(@NotNull MinecraftServer minecraftServer, @NotNull String name, @NotNull EventFilter filter) { - return create(serverFacade, name, filter, null); + return create(minecraftServer, name, filter, null); } /** @@ -80,11 +80,11 @@ public interface EventNode { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode event(@NotNull ServerFacade serverFacade, + static @NotNull EventNode event(@NotNull MinecraftServer minecraftServer, @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(serverFacade, name, filter, (e, h) -> predicate.test(e)); + return create(minecraftServer, name, filter, (e, h) -> predicate.test(e)); } /** @@ -109,11 +109,11 @@ public interface EventNode { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode type(@NotNull ServerFacade serverFacade, + static @NotNull EventNode type(@NotNull MinecraftServer minecraftServer, @NotNull String name, @NotNull EventFilter filter, @NotNull BiPredicate predicate) { - return create(serverFacade, name, filter, predicate); + return create(minecraftServer, name, filter, predicate); } /** @@ -135,11 +135,11 @@ public interface EventNode { * @return A node with an event type filter as well as a condition on the event. */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode value(@NotNull ServerFacade serverFacade, + static @NotNull EventNode value(@NotNull MinecraftServer minecraftServer, @NotNull String name, @NotNull EventFilter filter, @NotNull Predicate predicate) { - return create(serverFacade, name, filter, (e, h) -> predicate.test(h)); + return create(minecraftServer, name, filter, (e, h) -> predicate.test(h)); } /** @@ -155,11 +155,11 @@ public interface EventNode { * @return A node with an event type filter as well as a handler with the provided tag */ @Contract(value = "_, _, _, _ -> new", pure = true) - static @NotNull EventNode tag(@NotNull ServerFacade serverFacade, + static @NotNull EventNode tag(@NotNull MinecraftServer minecraftServer, @NotNull String name, @NotNull EventFilter filter, @NotNull Tag tag) { - return create(serverFacade, name, filter, (e, h) -> h.hasTag(tag)); + return create(minecraftServer, name, filter, (e, h) -> h.hasTag(tag)); } /** diff --git a/src/main/java/net/minestom/server/extras/query/Query.java b/src/main/java/net/minestom/server/extras/query/Query.java index 10d921f76a9..31c808b0994 100644 --- a/src/main/java/net/minestom/server/extras/query/Query.java +++ b/src/main/java/net/minestom/server/extras/query/Query.java @@ -3,7 +3,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.event.BasicQueryEvent; import net.minestom.server.extras.query.event.FullQueryEvent; import net.minestom.server.timer.Task; @@ -39,10 +39,10 @@ public class Query { private volatile DatagramSocket socket; private volatile Thread thread; private volatile Task task; - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; - public Query(ServerFacade serverFacade) { - this.serverFacade = serverFacade; + public Query(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; } /** @@ -82,7 +82,7 @@ public boolean start(int port) { thread.start(); started = true; - task = serverFacade.getSchedulerManager() + task = minecraftServer.getSchedulerManager() .buildTask(CHALLENGE_TOKENS::clear) .repeat(30, TimeUnit.SECOND) .schedule(); @@ -183,12 +183,12 @@ private void run() { int remaining = data.remaining(); if (remaining == 0) { // basic - BasicQueryEvent event = new BasicQueryEvent(serverFacade, sender, sessionID); - serverFacade.getGlobalEventHandler().callCancellable(event, () -> + BasicQueryEvent event = new BasicQueryEvent(minecraftServer, sender, sessionID); + minecraftServer.getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } else if (remaining == 5) { // full - FullQueryEvent event = new FullQueryEvent(serverFacade, sender, sessionID); - serverFacade.getGlobalEventHandler().callCancellable(event, () -> + FullQueryEvent event = new FullQueryEvent(minecraftServer, sender, sessionID); + minecraftServer.getGlobalEventHandler().callCancellable(event, () -> sendResponse(event.getQueryResponse(), sessionID, sender)); } } diff --git a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java index c14e950f17a..c0fd8cb172d 100644 --- a/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/BasicQueryEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.response.BasicQueryResponse; import org.jetbrains.annotations.NotNull; @@ -17,7 +17,7 @@ public class BasicQueryEvent extends QueryEvent { * @param sessionID the session ID * @param sender the sender */ - public BasicQueryEvent(ServerFacade serverFacade, @NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new BasicQueryResponse(serverFacade)); + public BasicQueryEvent(MinecraftServer minecraftServer, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new BasicQueryResponse(minecraftServer)); } } diff --git a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java index 7008f02d7fe..80f82d32264 100644 --- a/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java +++ b/src/main/java/net/minestom/server/extras/query/event/FullQueryEvent.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.response.FullQueryResponse; import org.jetbrains.annotations.NotNull; @@ -14,11 +14,11 @@ public class FullQueryEvent extends QueryEvent { /** * Creates a new full query event. * - * @param serverFacade + * @param minecraftServer * @param sender the sender * @param sessionID the sessionID */ - public FullQueryEvent(ServerFacade serverFacade, @NotNull SocketAddress sender, int sessionID) { - super(sender, sessionID, new FullQueryResponse(serverFacade)); + public FullQueryEvent(MinecraftServer minecraftServer, @NotNull SocketAddress sender, int sessionID) { + super(sender, sessionID, new FullQueryResponse(minecraftServer)); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java index 586baa089cc..288ac8c694b 100644 --- a/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/BasicQueryResponse.java @@ -1,6 +1,6 @@ package net.minestom.server.extras.query.response; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.Query; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.Writeable; @@ -13,18 +13,18 @@ */ public class BasicQueryResponse implements Writeable { @NotNull - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; private String motd, gametype, map, numPlayers, maxPlayers; /** * Creates a new basic query response with pre-filled default values. */ - public BasicQueryResponse(ServerFacade serverFacade) { - this.serverFacade = serverFacade; + public BasicQueryResponse(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; this.motd = "A Minestom Server"; this.gametype = "SMP"; this.map = "world"; - this.numPlayers = String.valueOf(serverFacade.getConnectionManager().getOnlinePlayerCount()); + this.numPlayers = String.valueOf(minecraftServer.getConnectionManager().getOnlinePlayerCount()); this.maxPlayers = String.valueOf(Integer.parseInt(this.numPlayers) + 1); } @@ -145,7 +145,7 @@ public void write(@NotNull BinaryWriter writer) { writer.writeNullTerminatedString(this.map, Query.CHARSET); writer.writeNullTerminatedString(this.numPlayers, Query.CHARSET); writer.writeNullTerminatedString(this.maxPlayers, Query.CHARSET); - writer.writeShort((short) serverFacade.getServer().getPort()); // TODO little endian? - writer.writeNullTerminatedString(Objects.requireNonNullElse(serverFacade.getServer().getAddress(), ""), Query.CHARSET); + writer.writeShort((short) minecraftServer.getServer().getPort()); // TODO little endian? + writer.writeNullTerminatedString(Objects.requireNonNullElse(minecraftServer.getServer().getAddress(), ""), Query.CHARSET); } } diff --git a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java index 8132a15d45d..54961fc185e 100644 --- a/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java +++ b/src/main/java/net/minestom/server/extras/query/response/FullQueryResponse.java @@ -1,8 +1,7 @@ package net.minestom.server.extras.query.response; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; -import net.minestom.server.ServerConsts; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.query.Query; import net.minestom.server.utils.binary.BinaryWriter; import net.minestom.server.utils.binary.Writeable; @@ -17,7 +16,7 @@ public class FullQueryResponse implements Writeable { private static final PlainTextComponentSerializer PLAIN = PlainTextComponentSerializer.plainText(); private static final byte[] PADDING_10 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, PADDING_11 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - private final ServerFacade serverFacade; + private final MinecraftServer minecraftServer; private Map kv; private List players; @@ -25,16 +24,16 @@ public class FullQueryResponse implements Writeable { /** * Creates a new full query response with default values set. */ - public FullQueryResponse(ServerFacade serverFacade) { - this.serverFacade = serverFacade; + public FullQueryResponse(MinecraftServer minecraftServer) { + this.minecraftServer = minecraftServer; this.kv = new HashMap<>(); // populate defaults for (QueryKey key : QueryKey.VALUES) { - this.kv.put(key.getKey(), key.getValue(serverFacade)); + this.kv.put(key.getKey(), key.getValue(minecraftServer)); } - this.players = serverFacade.getConnectionManager().getOnlinePlayers() + this.players = minecraftServer.getConnectionManager().getOnlinePlayers() .stream() .map(player -> PLAIN.serialize(player.getName())) .toList(); @@ -120,10 +119,10 @@ public void setPlayers(@NotNull List players) { * * @return the string result */ - public static String generatePluginsValue(ServerFacade serverFacade) { - StringBuilder builder = new StringBuilder(serverFacade.getServerSettings().getBrandName()) + public static String generatePluginsValue(MinecraftServer minecraftServer) { + StringBuilder builder = new StringBuilder(minecraftServer.getServerSettings().getBrandName()) .append(' ') - .append(ServerConsts.VERSION_NAME); + .append(MinecraftServer.VERSION_NAME); return builder.toString(); } diff --git a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java index aa7e1a75aa7..9161cb36a8e 100644 --- a/src/main/java/net/minestom/server/extras/query/response/QueryKey.java +++ b/src/main/java/net/minestom/server/extras/query/response/QueryKey.java @@ -1,7 +1,6 @@ package net.minestom.server.extras.query.response; -import net.minestom.server.ServerConsts; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -16,7 +15,7 @@ public enum QueryKey { HOSTNAME((serverProcess) -> "A Minestom Server"), GAME_TYPE((serverProcess) -> "SMP"), GAME_ID("game_id", (serverProcess) -> "MINECRAFT"), - VERSION((serverProcess) -> ServerConsts.VERSION_NAME), + VERSION((serverProcess) -> MinecraftServer.VERSION_NAME), PLUGINS(FullQueryResponse::generatePluginsValue), MAP((serverProcess) -> "world"), NUM_PLAYERS("numplayers", (serverProcess) -> String.valueOf(serverProcess.getConnectionManager().getOnlinePlayerCount())), @@ -27,13 +26,13 @@ public enum QueryKey { static QueryKey[] VALUES = QueryKey.values(); private final String key; - private final Function value; + private final Function value; - QueryKey(@NotNull Function value) { + QueryKey(@NotNull Function value) { this(null, value); } - QueryKey(@Nullable String key, @NotNull Function value) { + QueryKey(@Nullable String key, @NotNull Function value) { this.key = Objects.requireNonNullElse(key, this.name().toLowerCase(Locale.ROOT).replace('_', ' ')); this.value = value; } @@ -52,7 +51,7 @@ public enum QueryKey { * * @return the value */ - public @NotNull String getValue(ServerFacade serverFacade) { - return this.value.apply(serverFacade); + public @NotNull String getValue(MinecraftServer minecraftServer) { + return this.value.apply(minecraftServer); } } diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index ccbe3fe3e17..5cd18a098c0 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -1,7 +1,7 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -94,21 +94,21 @@ public class InstanceContainer extends Instance { protected InstanceContainer srcInstance; // only present if this instance has been created using a copy private long lastBlockChangeTime; // Time at which the last block change happened (#setBlock) - public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { - this(serverFacade, uniqueId, dimensionType, null, dimensionType.getName()); + public InstanceContainer(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType) { + this(minecraftServer, uniqueId, dimensionType, null, dimensionType.getName()); } - public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { - this(serverFacade, uniqueId, dimensionType, null, dimensionName); + public InstanceContainer(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName) { + this(minecraftServer, uniqueId, dimensionType, null, dimensionName); } @ApiStatus.Experimental - public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - this(serverFacade, uniqueId, dimensionType, loader, dimensionType.getName()); + public InstanceContainer(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { + this(minecraftServer, uniqueId, dimensionType, loader, dimensionType.getName()); } - public InstanceContainer(ServerFacade serverFacade, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { - this(serverFacade.getGlobalEventHandler(), serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, uniqueId, dimensionType, loader, dimensionName); + public InstanceContainer(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { + this(minecraftServer.getGlobalEventHandler(), minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, uniqueId, dimensionType, loader, dimensionName); } @ApiStatus.Experimental diff --git a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java index 52fada4e17e..cabd9831b2d 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java +++ b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java @@ -1,7 +1,7 @@ package net.minestom.server.instance; import lombok.RequiredArgsConstructor; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.instance.InstanceRegisterEvent; @@ -31,8 +31,8 @@ public final class InstanceManagerImpl implements InstanceManager { private final BlockManagerProvider blockManagerProvider; private final BiomeManagerProvider biomeManagerProvider; - public InstanceManagerImpl(ServerFacade serverFacade) { - this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + public InstanceManagerImpl(MinecraftServer minecraftServer) { + this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } private final Set instances = new CopyOnWriteArraySet<>(); diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index 1d1e0c305b6..168e73ea2bf 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -2,7 +2,7 @@ import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.collision.Shape; import net.minestom.server.coordinate.Point; @@ -82,8 +82,8 @@ private enum QueueType { Block.LAVA.namespace() ); - public LightingChunk(ServerFacade serverFacade, @NotNull Instance instance, int chunkX, int chunkZ) { - this(serverFacade, serverFacade, serverFacade, instance, chunkX, chunkZ); + public LightingChunk(MinecraftServer minecraftServer, @NotNull Instance instance, int chunkX, int chunkZ) { + this(minecraftServer, minecraftServer, minecraftServer, instance, chunkX, chunkZ); } public LightingChunk(BiomeManagerProvider biomeManagerProvider, ServerSettingsProvider serverSettingsProvider, SchedulerManagerProvider schedulerManagerProvider, @NotNull Instance instance, int chunkX, int chunkZ) { diff --git a/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java index a9397e0d023..628bcb5dab4 100644 --- a/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java +++ b/src/main/java/net/minestom/server/listener/manager/PacketListenerManagerImpl.java @@ -1,6 +1,6 @@ package net.minestom.server.listener.manager; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.player.PlayerPacketEvent; import net.minestom.server.exception.ExceptionHandlerProvider; @@ -45,8 +45,8 @@ public final class PacketListenerManagerImpl implements PacketListenerManager { private final GlobalEventHandlerProvider globalEventHandlerProvider; private final ExceptionHandlerProvider exceptionHandlerProvider; - public PacketListenerManagerImpl(ServerFacade serverFacade) { - this(serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + public PacketListenerManagerImpl(MinecraftServer minecraftServer) { + this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } public PacketListenerManagerImpl(GlobalEventHandlerProvider globalEventHandlerProvider, ExceptionHandlerProvider exceptionHandlerProvider, MojangAuthProvider mojangAuthProvider, ConnectionManagerProvider connectionManagerProvider, SchedulerManagerProvider schedulerManagerProvider, ServerProvider serverProvider) { diff --git a/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java b/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java index 17ba8bef387..13ea23024e7 100644 --- a/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/HandshakeListener.java @@ -6,7 +6,7 @@ import com.google.gson.JsonParser; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerConsts; +import net.minestom.server.MinecraftServer; import net.minestom.server.extras.bungee.BungeeCordProxy; import net.minestom.server.network.ConnectionState; import net.minestom.server.network.packet.client.handshake.ClientHandshakePacket; @@ -30,7 +30,7 @@ public final class HandshakeListener { /** * Text sent if a player tries to connect with an invalid version of the client */ - private static final Component INVALID_VERSION_TEXT = Component.text("Invalid Version, please use " + ServerConsts.VERSION_NAME, NamedTextColor.RED); + private static final Component INVALID_VERSION_TEXT = Component.text("Invalid Version, please use " + MinecraftServer.VERSION_NAME, NamedTextColor.RED); /** * Indicates that a BungeeGuard authentication was invalid due to missing, multiple, or invalid tokens. @@ -43,7 +43,7 @@ public static void listener(@NotNull ClientHandshakePacket packet, @NotNull Play case 1 -> connection.setConnectionState(ConnectionState.STATUS); case 2 -> { connection.setConnectionState(ConnectionState.LOGIN); - if (packet.protocolVersion() != ServerConsts.PROTOCOL_VERSION) { + if (packet.protocolVersion() != MinecraftServer.PROTOCOL_VERSION) { // Incorrect client version disconnect(connection, INVALID_VERSION_TEXT); } diff --git a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java index 37c1e24114d..955216c9655 100644 --- a/src/main/java/net/minestom/server/listener/preplay/LoginListener.java +++ b/src/main/java/net/minestom/server/listener/preplay/LoginListener.java @@ -5,7 +5,7 @@ import com.google.gson.JsonObject; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.exception.ExceptionHandler; import net.minestom.server.extras.MojangAuth; @@ -101,14 +101,14 @@ public static void loginEncryptionResponseListener(MojangAuth mojangAuth, Except mojangAuth.getMojangCrypt().decryptUsingKey(mojangAuth.getKeyPair().getPrivate(), packet.encryptedVerifyToken())); if (verificationFailed) { - ServerFacade.LOGGER.error("Encryption failed for {}", loginUsername); + MinecraftServer.LOGGER.error("Encryption failed for {}", loginUsername); return; } final byte[] digestedData = mojangAuth.getMojangCrypt().digestData("", mojangAuth.getKeyPair().getPublic(), getSecretKey(mojangAuth, packet.sharedSecret())); if (digestedData == null) { // Incorrect key, probably because of the client - ServerFacade.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); + MinecraftServer.LOGGER.error("Connection {} failed initializing encryption.", socketConnection.getRemoteAddress()); connection.disconnect(); return; } @@ -142,7 +142,7 @@ public static void loginEncryptionResponseListener(MojangAuth mojangAuth, Except .replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); final String profileName = gameProfile.get("name").getAsString(); - ServerFacade.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); + MinecraftServer.LOGGER.info("UUID of player {} is {}", loginUsername, profileUUID); connectionManager.createPlayer(connection, profileUUID, profileName); List propertyList = new ArrayList<>(); for (JsonElement element : gameProfile.get("properties").getAsJsonArray()) { diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java index c72755c4ed4..134d61c4281 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java @@ -3,7 +3,7 @@ import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; import lombok.RequiredArgsConstructor; -import net.minestom.server.ServerConsts; +import net.minestom.server.MinecraftServer; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -27,8 +27,8 @@ public final class BenchmarkManagerImpl implements BenchmarkManager { private static final List THREADS = new ArrayList<>(); static { - THREADS.add(ServerConsts.THREAD_NAME_TICK_SCHEDULER); - THREADS.add(ServerConsts.THREAD_NAME_TICK); + THREADS.add(MinecraftServer.THREAD_NAME_TICK_SCHEDULER); + THREADS.add(MinecraftServer.THREAD_NAME_TICK); } private final Long2LongMap lastCpuTimeMap = new Long2LongOpenHashMap(); @@ -67,7 +67,7 @@ public void enable(@NotNull Duration duration) { } } stop = false; - }, ServerConsts.THREAD_NAME_BENCHMARK); + }, MinecraftServer.THREAD_NAME_BENCHMARK); thread.setDaemon(true); thread.start(); diff --git a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java index a0565edd8e5..e1a838933ef 100644 --- a/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java +++ b/src/main/java/net/minestom/server/network/ConnectionManagerImpl.java @@ -2,7 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.adventure.bossbar.BossBarManagerProvider; import net.minestom.server.command.CommandManagerProvider; @@ -92,8 +92,8 @@ public final class ConnectionManagerImpl implements ConnectionManager { private final PlayerProvider defaultPlayerProvider; private volatile PlayerProvider playerProvider; - public ConnectionManagerImpl(TagManager tagManager, ServerFacade serverFacade) { - this(tagManager, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade, serverFacade); + public ConnectionManagerImpl(TagManager tagManager, MinecraftServer minecraftServer) { + this(tagManager, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } public ConnectionManagerImpl( diff --git a/src/main/java/net/minestom/server/network/player/PlayerConnection.java b/src/main/java/net/minestom/server/network/player/PlayerConnection.java index ec414a923ad..b487aebcdab 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerConnection.java @@ -2,7 +2,7 @@ import lombok.Getter; import lombok.Setter; -import net.minestom.server.ServerConsts; +import net.minestom.server.MinecraftServer; import net.minestom.server.crypto.PlayerPublicKey; import net.minestom.server.entity.Entity; import net.minestom.server.entity.Player; @@ -87,7 +87,7 @@ public void sendPackets(@NotNull SendablePacket... packets) { * @return the protocol version */ public int getProtocolVersion() { - return ServerConsts.PROTOCOL_VERSION; + return MinecraftServer.PROTOCOL_VERSION; } /** diff --git a/src/main/java/net/minestom/server/network/socket/ServerImpl.java b/src/main/java/net/minestom/server/network/socket/ServerImpl.java index 1cd89e6d995..bdd495c1a50 100644 --- a/src/main/java/net/minestom/server/network/socket/ServerImpl.java +++ b/src/main/java/net/minestom/server/network/socket/ServerImpl.java @@ -1,6 +1,6 @@ package net.minestom.server.network.socket; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.exception.ExceptionHandlerProvider; @@ -36,8 +36,8 @@ public final class ServerImpl implements Server { private String address; private int port; - public ServerImpl(ServerSettings serverSettings, ServerFacade serverFacade) { - this(serverSettings, serverFacade, serverFacade, serverFacade, serverFacade); + public ServerImpl(ServerSettings serverSettings, MinecraftServer minecraftServer) { + this(serverSettings, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } public ServerImpl(ServerSettings serverSettings, ConnectionManagerProvider connectionManagerProvider, GlobalEventHandlerProvider globalEventHandlerProvider, ExceptionHandlerProvider exceptionHandlerProvider, PacketProcessorProvider packetProcessorProvider) { diff --git a/src/main/java/net/minestom/server/ping/ResponseData.java b/src/main/java/net/minestom/server/ping/ResponseData.java index b225ed404c7..1ad5425508c 100644 --- a/src/main/java/net/minestom/server/ping/ResponseData.java +++ b/src/main/java/net/minestom/server/ping/ResponseData.java @@ -5,7 +5,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; -import net.minestom.server.ServerConsts; +import net.minestom.server.MinecraftServer; import net.minestom.server.entity.Player; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.network.ConnectionManager; @@ -41,8 +41,8 @@ public class ResponseData { public ResponseData(ConnectionManager connectionManager, Server server) { this.server = server; this.entries = new ArrayList<>(); - this.version = ServerConsts.VERSION_NAME; - this.protocol = ServerConsts.PROTOCOL_VERSION; + this.version = MinecraftServer.VERSION_NAME; + this.protocol = MinecraftServer.PROTOCOL_VERSION; this.online = connectionManager.getOnlinePlayerCount(); this.maxPlayer = this.online + 1; this.description = DEFAULT_DESCRIPTION; diff --git a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java index 016075e5120..634a6258cfd 100644 --- a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java +++ b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerConsts; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.ServerStarter; import net.minestom.server.Ticker; @@ -20,7 +20,7 @@ public final class TickSchedulerThread extends MinestomThread { private long tick = 1; public TickSchedulerThread(ServerSettings serverSettings, Ticker ticker, ServerStarter serverStarter, ExceptionHandler exceptionHandler) { - super(ServerConsts.THREAD_NAME_TICK_SCHEDULER); + super(MinecraftServer.THREAD_NAME_TICK_SCHEDULER); this.serverSettings = serverSettings; this.ticker = ticker; this.serverStarter = serverStarter; diff --git a/src/main/java/net/minestom/server/thread/TickThread.java b/src/main/java/net/minestom/server/thread/TickThread.java index 189fa216cc5..68600b0e306 100644 --- a/src/main/java/net/minestom/server/thread/TickThread.java +++ b/src/main/java/net/minestom/server/thread/TickThread.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerConsts; +import net.minestom.server.MinecraftServer; import net.minestom.server.Tickable; import net.minestom.server.entity.Entity; import net.minestom.server.exception.ExceptionHandlerProvider; @@ -33,7 +33,7 @@ public final class TickThread extends MinestomThread { private final List entries = new ArrayList<>(); public TickThread(ExceptionHandlerProvider exceptionHandlerProvider, int number) { - super(ServerConsts.THREAD_NAME_TICK + "-" + number); + super(MinecraftServer.THREAD_NAME_TICK + "-" + number); this.exceptionHandlerProvider = exceptionHandlerProvider; } diff --git a/src/main/java/net/minestom/server/utils/PacketUtils.java b/src/main/java/net/minestom/server/utils/PacketUtils.java index 6d36e86f4d3..6ac3c0562e5 100644 --- a/src/main/java/net/minestom/server/utils/PacketUtils.java +++ b/src/main/java/net/minestom/server/utils/PacketUtils.java @@ -10,7 +10,7 @@ import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TranslatableComponent; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Viewable; @@ -83,16 +83,16 @@ private PacketUtils() { * @param packet the packet */ @SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience - public static void sendPacket(ServerFacade serverFacade, @NotNull Audience audience, @NotNull ServerPacket packet) { + public static void sendPacket(MinecraftServer minecraftServer, @NotNull Audience audience, @NotNull ServerPacket packet) { if (audience instanceof Player player) { player.sendPacket(packet); } else if (audience instanceof PacketGroupingAudience groupingAudience) { - PacketUtils.sendGroupedPacket(serverFacade, groupingAudience.getPlayers(), packet); + PacketUtils.sendGroupedPacket(minecraftServer, groupingAudience.getPlayers(), packet); } else if (audience instanceof ForwardingAudience.Single singleAudience) { - PacketUtils.sendPacket(serverFacade, singleAudience.audience(), packet); + PacketUtils.sendPacket(minecraftServer, singleAudience.audience(), packet); } else if (audience instanceof ForwardingAudience forwardingAudience) { for (Audience member : forwardingAudience.audiences()) { - PacketUtils.sendPacket(serverFacade, member, packet); + PacketUtils.sendPacket(minecraftServer, member, packet); } } } diff --git a/src/test/java/net/minestom/server/ServerProcessTest.java b/src/test/java/net/minestom/server/ServerProcessTest.java index 8a6cc973b61..c6856e0a12d 100644 --- a/src/test/java/net/minestom/server/ServerProcessTest.java +++ b/src/test/java/net/minestom/server/ServerProcessTest.java @@ -16,8 +16,8 @@ public void init() { // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); - AtomicReference process = new AtomicReference<>(); - assertDoesNotThrow(() -> process.set(ServerFacade.of(ServerSettings.builder().build()))); + AtomicReference process = new AtomicReference<>(); + assertDoesNotThrow(() -> process.set(MinecraftServer.of(ServerSettings.builder().build()))); assertDoesNotThrow(() -> process.get().start(new InetSocketAddress("localhost", 25565))); assertThrows(Exception.class, () -> process.get().start(new InetSocketAddress("localhost", 25566))); assertDoesNotThrow(() -> process.get().stop()); @@ -28,7 +28,7 @@ public void tick() { // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); - var process = ServerFacade.of(ServerSettings.builder().build()); + var process = MinecraftServer.of(ServerSettings.builder().build()); process.start(new InetSocketAddress("localhost", 25565)); var ticker = process.getTicker(); assertDoesNotThrow(() -> ticker.tick(System.currentTimeMillis())); diff --git a/src/test/java/net/minestom/server/command/ArgumentTest.java b/src/test/java/net/minestom/server/command/ArgumentTest.java index 63a92f30bbf..1b17d87b732 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.CommandContext; import net.minestom.server.command.builder.arguments.Argument; @@ -17,9 +17,9 @@ public class ArgumentTest { @Test public void testParseSelf() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - assertEquals("example", Argument.parse(new ServerSender(serverFacade), ArgumentType.String("example"))); - assertEquals(55, Argument.parse(new ServerSender(serverFacade), ArgumentType.Integer("55"))); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + assertEquals("example", Argument.parse(new ServerSender(minecraftServer), ArgumentType.String("example"))); + assertEquals(55, Argument.parse(new ServerSender(minecraftServer), ArgumentType.Integer("55"))); } @Test @@ -34,18 +34,18 @@ public void testCallback() { @Test public void testDefaultValue() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var arg = ArgumentType.String("id"); assertFalse(arg.isOptional()); arg.setDefaultValue("default value"); assertTrue(arg.isOptional()); - assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(serverFacade))); + assertEquals("default value", arg.getDefaultValue().apply(new ServerSender(minecraftServer))); } @Test public void testSuggestionCallback() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var arg = ArgumentType.String("id"); assertFalse(arg.hasSuggestion()); @@ -54,7 +54,7 @@ public void testSuggestionCallback() { assertTrue(arg.hasSuggestion()); Suggestion suggestion = new Suggestion("input", 2, 4); - arg.getSuggestionCallback().apply(new ServerSender(serverFacade), new CommandContext("input"), suggestion); + arg.getSuggestionCallback().apply(new ServerSender(minecraftServer), new CommandContext("input"), suggestion); assertEquals(suggestion.getEntries(), List.of(new SuggestionEntry("entry"))); } diff --git a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java index 0e529078832..dd1a380f41a 100644 --- a/src/test/java/net/minestom/server/command/ArgumentTypeTest.java +++ b/src/test/java/net/minestom/server/command/ArgumentTypeTest.java @@ -5,7 +5,7 @@ import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.arguments.Argument; import net.minestom.server.command.builder.arguments.ArgumentEnum; @@ -378,17 +378,17 @@ enum ExampleEnum {FIRST, SECOND, Third, fourth} @Test public void testArgumentGroup() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var arg = ArgumentType.Group("group", ArgumentType.Integer("integer"), ArgumentType.String("string"), ArgumentType.Double("double")); // Test normal input - var context1 = arg.parse(new ServerSender(serverFacade), "1234 1234 1234"); + var context1 = arg.parse(new ServerSender(minecraftServer), "1234 1234 1234"); assertEquals(1234, context1.get("integer")); assertEquals("1234", context1.get("string")); assertEquals(1234.0, context1.get("double")); // Test different input + trailing spaces - var context2 = arg.parse(new ServerSender(serverFacade), "1234 abcd 1234.5678 "); + var context2 = arg.parse(new ServerSender(minecraftServer), "1234 abcd 1234.5678 "); assertEquals(1234, context2.get("integer")); assertEquals("abcd", context2.get("string")); assertEquals(1234.5678, context2.get("double")); @@ -455,8 +455,8 @@ public void testArgumentWord() { @Test public void testArgumentMapWithSender() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var serverSender = new ServerSender(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var serverSender = new ServerSender(minecraftServer); var arg = ArgumentType.Word("word").from("word1", "word2", "word3") .map((sender, s) -> { @@ -468,22 +468,22 @@ public void testArgumentMapWithSender() { } private static void assertArg(Argument arg, T expected, String input) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - assertEquals(expected, arg.parse(new ServerSender(serverFacade), input)); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + assertEquals(expected, arg.parse(new ServerSender(minecraftServer), input)); } private static void assertArrayArg(Argument arg, T[] expected, String input) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - assertArrayEquals(expected, arg.parse(new ServerSender(serverFacade), input)); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + assertArrayEquals(expected, arg.parse(new ServerSender(minecraftServer), input)); } private static void assertValidArg(Argument arg, String input) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - assertDoesNotThrow(() -> arg.parse(new ServerSender(serverFacade), input)); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + assertDoesNotThrow(() -> arg.parse(new ServerSender(minecraftServer), input)); } private static void assertInvalidArg(Argument arg, String input) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(serverFacade), input)); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + assertThrows(ArgumentSyntaxException.class, () -> arg.parse(new ServerSender(minecraftServer), input)); } } diff --git a/src/test/java/net/minestom/server/command/CommandConditionTest.java b/src/test/java/net/minestom/server/command/CommandConditionTest.java index c37a3759661..d105d3d4b34 100644 --- a/src/test/java/net/minestom/server/command/CommandConditionTest.java +++ b/src/test/java/net/minestom/server/command/CommandConditionTest.java @@ -1,7 +1,7 @@ package net.minestom.server.command; import net.kyori.adventure.identity.Identity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; @@ -19,8 +19,8 @@ public class CommandConditionTest { @Test public void mainCondition() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var dispatcher = new CommandDispatcher(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(minecraftServer); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -43,8 +43,8 @@ public void mainCondition() { @Test public void subCondition() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var dispatcher = new CommandDispatcher(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(minecraftServer); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -88,8 +88,8 @@ public void subCondition() { @Test public void subConditionOverride() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var dispatcher = new CommandDispatcher(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var dispatcher = new CommandDispatcher(minecraftServer); assertNull(dispatcher.findCommand("name")); var sender = new Sender(); var sender2 = new Sender(); @@ -147,7 +147,7 @@ private static final class Sender implements CommandSender { } @Override - public ServerFacade getServerProcess() { + public MinecraftServer getServerProcess() { return null; } } diff --git a/src/test/java/net/minestom/server/command/CommandManagerTest.java b/src/test/java/net/minestom/server/command/CommandManagerTest.java index 41a7016b7e7..7d345fd1f7e 100644 --- a/src/test/java/net/minestom/server/command/CommandManagerTest.java +++ b/src/test/java/net/minestom/server/command/CommandManagerTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandResult; @@ -16,8 +16,8 @@ public class CommandManagerTest { @Test public void testCommandRegistration() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); var command = new Command("name1", "name2"); @@ -36,8 +36,8 @@ public void testCommandRegistration() { @Test public void testUnknownCommandCallback() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); AtomicBoolean check = new AtomicBoolean(false); manager.setUnknownCommandCallback((sender, command) -> check.set(true)); @@ -53,8 +53,8 @@ public void testUnknownCommandCallback() { @Test public void testSharedArgumentSyntaxABFirst() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); @@ -82,8 +82,8 @@ public void testSharedArgumentSyntaxABFirst() { @Test public void testSharedArgumentSyntaxAFirst() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); var checkA = new AtomicBoolean(false); var checkAB = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java index 1da4df2f121..3ee7d0ac897 100644 --- a/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java +++ b/src/test/java/net/minestom/server/command/CommandPacketFilteringTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.ArgumentType; @@ -13,7 +13,7 @@ @SuppressWarnings("ConstantConditions") public class CommandPacketFilteringTest { - private static final ServerFacade SERVER_FACADE = ServerFacade.of(ServerSettings.builder().build()); + private static final MinecraftServer SERVER_FACADE = MinecraftServer.of(ServerSettings.builder().build()); private static final Player PLAYER = new Player(SERVER_FACADE, UUID.randomUUID(), "", null); @Test diff --git a/src/test/java/net/minestom/server/command/CommandParseTest.java b/src/test/java/net/minestom/server/command/CommandParseTest.java index b7ef9762b35..214173e17c8 100644 --- a/src/test/java/net/minestom/server/command/CommandParseTest.java +++ b/src/test/java/net/minestom/server/command/CommandParseTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.arguments.ArgumentType; import org.jetbrains.annotations.NotNull; @@ -145,8 +145,8 @@ private static void assertValid(Graph graph, String input, AtomicBoolean executo } private static CommandParser.Result parseCommand(Graph graph, String input) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - return CommandParser.parser().parse(new ServerSender(serverFacade), graph, input); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + return CommandParser.parser().parse(new ServerSender(minecraftServer), graph, input); } @NotNull diff --git a/src/test/java/net/minestom/server/command/CommandSenderTest.java b/src/test/java/net/minestom/server/command/CommandSenderTest.java index d4805b73d41..1e4111f791d 100644 --- a/src/test/java/net/minestom/server/command/CommandSenderTest.java +++ b/src/test/java/net/minestom/server/command/CommandSenderTest.java @@ -4,7 +4,7 @@ import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.permission.Permission; import net.minestom.server.tag.TagHandler; import org.jetbrains.annotations.NotNull; @@ -85,7 +85,7 @@ public void sendMessage(@NotNull Identity source, @NotNull Component message, @N } @Override - public ServerFacade getServerProcess() { + public MinecraftServer getServerProcess() { return null; } } diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java index f3943e3b0f6..06e351726fe 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxMultiTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.arguments.Argument; @@ -46,10 +46,10 @@ public void similarArgs() { } private static void assertSyntax(List>> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); final String commandName = "name"; - var manager = new CommandManagerImpl(serverFacade); + var manager = new CommandManagerImpl(minecraftServer); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java index cecf85f2141..4745b2e8148 100644 --- a/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java +++ b/src/test/java/net/minestom/server/command/CommandSyntaxSingleTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -148,10 +148,10 @@ public void singleLoopDoubleGroup() { } private static void assertSyntax(List> args, String input, ExpectedExecution expectedExecution, Map expectedValues) { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); final String commandName = "name"; - var manager = new CommandManagerImpl(serverFacade); + var manager = new CommandManagerImpl(minecraftServer); var command = new Command(commandName); manager.register(command); diff --git a/src/test/java/net/minestom/server/command/CommandTest.java b/src/test/java/net/minestom/server/command/CommandTest.java index b9d7afb6587..583e36c1b0e 100644 --- a/src/test/java/net/minestom/server/command/CommandTest.java +++ b/src/test/java/net/minestom/server/command/CommandTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandContext; @@ -30,8 +30,8 @@ public void testNames() { @Test public void testGlobalListener() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); AtomicBoolean hasRun = new AtomicBoolean(false); diff --git a/src/test/java/net/minestom/server/command/SubcommandTest.java b/src/test/java/net/minestom/server/command/SubcommandTest.java index 732bc0de300..dcc20a952c5 100644 --- a/src/test/java/net/minestom/server/command/SubcommandTest.java +++ b/src/test/java/net/minestom/server/command/SubcommandTest.java @@ -1,6 +1,6 @@ package net.minestom.server.command; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.command.builder.Command; import org.junit.jupiter.api.Test; @@ -14,8 +14,8 @@ public class SubcommandTest { @Test public void testSubCommands() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); var parent = new Command("parent"); var child = new Command("child"); @@ -37,8 +37,8 @@ public void testSubCommands() { @Test public void testSubCommandConditions() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var manager = new CommandManagerImpl(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var manager = new CommandManagerImpl(minecraftServer); var parent = new Command("parent"); var child = new Command("child"); diff --git a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java index e9edb7f2523..7f8ead2cbb5 100644 --- a/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java +++ b/src/test/java/net/minestom/server/entity/EntityRemovalIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.entity; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.event.entity.EntityTickEvent; import net.minestom.server.network.packet.server.play.DestroyEntitiesPacket; @@ -98,8 +98,8 @@ public void entityNodeGC(Env env) { } static final class TestEntity extends Entity { - public TestEntity(ServerFacade serverFacade, long delay, TemporalUnit unit) { - super(serverFacade, EntityType.ZOMBIE); + public TestEntity(MinecraftServer minecraftServer, long delay, TemporalUnit unit) { + super(minecraftServer, EntityType.ZOMBIE); scheduleRemove(delay, unit); } } diff --git a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java index 6a511ea269a..bb745277454 100644 --- a/src/test/java/net/minestom/server/event/EventNodeGraphTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeGraphTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import org.junit.jupiter.api.Test; @@ -12,16 +12,16 @@ public class EventNodeGraphTest { @Test public void single() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - EventNode node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + EventNode node = EventNode.all(minecraftServer,"main"); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of())); } @Test public void singleChild() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - EventNode node = EventNode.all(serverFacade,"main"); - node.addChild(EventNode.all(serverFacade,"child")); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + EventNode node = EventNode.all(minecraftServer,"main"); + node.addChild(EventNode.all(minecraftServer,"child")); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child", "Event", 0, List.of()) ))); @@ -29,20 +29,20 @@ public void singleChild() { @Test public void childrenPriority() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); { - EventNode node = EventNode.all(serverFacade,"main"); - node.addChild(EventNode.all(serverFacade,"child1").setPriority(5)); - node.addChild(EventNode.all(serverFacade,"child2").setPriority(10)); + EventNode node = EventNode.all(minecraftServer,"main"); + node.addChild(EventNode.all(minecraftServer,"child1").setPriority(5)); + node.addChild(EventNode.all(minecraftServer,"child2").setPriority(10)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) ))); } { - EventNode node = EventNode.all(serverFacade, "main"); - node.addChild(EventNode.all(serverFacade,"child2").setPriority(10)); - node.addChild(EventNode.all(serverFacade,"child1").setPriority(5)); + EventNode node = EventNode.all(minecraftServer, "main"); + node.addChild(EventNode.all(minecraftServer,"child2").setPriority(10)); + node.addChild(EventNode.all(minecraftServer,"child1").setPriority(5)); verifyGraph(node, new EventNodeImpl.Graph("main", "Event", 0, List.of(new EventNodeImpl.Graph("child1", "Event", 5, List.of()), new EventNodeImpl.Graph("child2", "Event", 10, List.of()) diff --git a/src/test/java/net/minestom/server/event/EventNodeMapTest.java b/src/test/java/net/minestom/server/event/EventNodeMapTest.java index 7be2f5f36c8..d69e43106d9 100644 --- a/src/test/java/net/minestom/server/event/EventNodeMapTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeMapTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -18,9 +18,9 @@ public class EventNodeMapTest { @Test public void uniqueMapping() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(serverFacade,"main"); + var node = EventNode.all(minecraftServer,"main"); var itemNode1 = node.map(item, EventFilter.ITEM); var itemNode2 = node.map(item, EventFilter.ITEM); assertNotNull(itemNode1); @@ -34,9 +34,9 @@ public void uniqueMapping() { @Test public void lazyRegistration() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all(serverFacade,"main"); + var node = (EventNodeImpl) EventNode.all(minecraftServer,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertFalse(node.registeredMappedNode.containsKey(item)); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { @@ -46,9 +46,9 @@ public void lazyRegistration() { @Test public void secondMap() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = (EventNodeImpl) EventNode.all(serverFacade,"main"); + var node = (EventNodeImpl) EventNode.all(minecraftServer,"main"); var itemNode = node.map(item, EventFilter.ITEM); assertSame(itemNode, itemNode.map(item, EventFilter.ITEM)); assertThrows(Exception.class, () -> itemNode.map(ItemStack.AIR, EventFilter.ITEM)); @@ -56,9 +56,9 @@ public void secondMap() { @Test public void map() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(serverFacade, "main"); + var node = EventNode.all(minecraftServer, "main"); AtomicBoolean result = new AtomicBoolean(false); var itemNode = node.map(item, EventFilter.ITEM); @@ -82,9 +82,9 @@ public void map() { @Test public void entityLocal() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = serverFacade.getGlobalEventHandler(); - var entity = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = minecraftServer.getGlobalEventHandler(); + var entity = new Entity(minecraftServer, EntityType.ZOMBIE); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventNodeTest.EntityTestEvent.class, event -> result.set(true)); @@ -108,10 +108,10 @@ public void entityLocal() { @Test public void ownerGC() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // Ensure that the mapped object gets GCed var item = ItemStack.of(Material.DIAMOND); - var node = EventNode.all(serverFacade,"main"); + var node = EventNode.all(minecraftServer,"main"); var itemNode = node.map(item, EventFilter.ITEM); itemNode.addListener(EventNodeTest.ItemTestEvent.class, event -> { }); diff --git a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java index 871e9b7d4df..c8729b77016 100644 --- a/src/test/java/net/minestom/server/event/EventNodeQueryTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeQueryTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.event.trait.EntityEvent; import net.minestom.server.event.trait.PlayerEvent; @@ -15,13 +15,13 @@ public class EventNodeQueryTest { @Test public void find() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade, "main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer, "main"); assertEquals(List.of(), node.findChildren("test")); - var child1 = EventNode.all(serverFacade,"test"); - var child2 = EventNode.all(serverFacade,"test"); - var child3 = EventNode.all(serverFacade,"test3"); + var child1 = EventNode.all(minecraftServer,"test"); + var child2 = EventNode.all(minecraftServer,"test"); + var child3 = EventNode.all(minecraftServer,"test3"); node.addChild(child1); node.addChild(child2); @@ -37,13 +37,13 @@ public void find() { @Test public void findType() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); assertEquals(List.of(), node.findChildren("test", Event.class)); - var child1 = EventNode.type(serverFacade, "test", EventFilter.PLAYER); - var child2 = EventNode.type(serverFacade, "test", EventFilter.ENTITY); - var child3 = EventNode.type(serverFacade, "test3", EventFilter.ENTITY); + var child1 = EventNode.type(minecraftServer, "test", EventFilter.PLAYER); + var child2 = EventNode.type(minecraftServer, "test", EventFilter.ENTITY); + var child3 = EventNode.type(minecraftServer, "test3", EventFilter.ENTITY); node.addChild(child1); node.addChild(child2); @@ -63,19 +63,19 @@ public void findType() { @Test public void replace() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); - var child1 = EventNode.all(serverFacade,"test"); - var child2 = EventNode.all(serverFacade,"test"); - var child3 = EventNode.all(serverFacade,"test3"); + var child1 = EventNode.all(minecraftServer,"test"); + var child2 = EventNode.all(minecraftServer,"test"); + var child3 = EventNode.all(minecraftServer,"test3"); node.addChild(child1); node.addChild(child2); node.addChild(child3); - var tmp1 = EventNode.all(serverFacade,"tmp1"); - var tmp2 = EventNode.all(serverFacade,"tmp2"); + var tmp1 = EventNode.all(minecraftServer,"tmp1"); + var tmp2 = EventNode.all(minecraftServer,"tmp2"); node.replaceChildren("test", tmp1); assertEqualsIgnoreOrder(List.of(child2), node.findChildren("test")); diff --git a/src/test/java/net/minestom/server/event/EventNodeTest.java b/src/test/java/net/minestom/server/event/EventNodeTest.java index db63e2a7235..55bf35f8f3d 100644 --- a/src/test/java/net/minestom/server/event/EventNodeTest.java +++ b/src/test/java/net/minestom/server/event/EventNodeTest.java @@ -1,6 +1,6 @@ package net.minestom.server.event; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.event.trait.CancellableEvent; @@ -60,8 +60,8 @@ record EntityTestEvent(Entity entity) implements EntityEvent { @Test public void testCall() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.of(EventTest.class, eventTest -> result.set(true)); node.addListener(listener); @@ -78,8 +78,8 @@ public void testCall() { @Test public void testHandle() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); var handle = node.getHandle(EventTest.class); assertSame(handle, node.getHandle(EventTest.class)); @@ -89,8 +89,8 @@ public void testHandle() { @Test public void testCancellable() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result = new AtomicBoolean(false); var listener = EventListener.builder(CancellableTest.class) .handler(event -> { @@ -109,8 +109,8 @@ public void testCancellable() { @Test public void recursiveSub() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result1 = new AtomicBoolean(false); AtomicBoolean result2 = new AtomicBoolean(false); var listener1 = EventListener.of(Recursive1.class, event -> result1.set(true)); @@ -151,15 +151,15 @@ public void recursiveSub() { @Test public void testChildren() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); AtomicInteger result = new AtomicInteger(0); - var child1 = EventNode.all(serverFacade,"child1").setPriority(1) + var child1 = EventNode.all(minecraftServer,"child1").setPriority(1) .addListener(EventTest.class, eventTest -> { assertEquals(0, result.get(), "child1 should be called before child2"); result.set(1); }); - var child2 = EventNode.all(serverFacade,"child2").setPriority(2) + var child2 = EventNode.all(minecraftServer,"child2").setPriority(2) .addListener(EventTest.class, eventTest -> { assertEquals(1, result.get(), "child2 should be called after child1"); result.set(2); @@ -186,13 +186,13 @@ public void testChildren() { @Test public void testFiltering() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); AtomicBoolean result = new AtomicBoolean(false); AtomicBoolean childResult = new AtomicBoolean(false); - var node = EventNode.type(serverFacade,"item_node", EventFilter.ITEM, + var node = EventNode.type(minecraftServer,"item_node", EventFilter.ITEM, (event, item) -> item.material() == Material.DIAMOND); - var child = EventNode.type(serverFacade,"item_node2", EventFilter.ITEM) + var child = EventNode.type(minecraftServer,"item_node2", EventFilter.ITEM) .addListener(ItemTestEvent.class, event -> childResult.set(true)); node.addChild(child); @@ -211,8 +211,8 @@ public void testFiltering() { @Test public void testBinding() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); AtomicBoolean result = new AtomicBoolean(false); var binding = EventBinding.filtered(EventFilter.ITEM, itemStack -> itemStack.material() == Material.DIAMOND) @@ -234,8 +234,8 @@ public void testBinding() { @Test public void nodeEmptyGC() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); var ref = new WeakReference<>(node); //noinspection UnusedAssignment @@ -245,8 +245,8 @@ public void nodeEmptyGC() { @Test public void nodeGC() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); var ref = new WeakReference<>(node); node.addListener(EventTest.class, event -> { }); @@ -273,8 +273,8 @@ public void nodeGC() { @Test public void nodeMapGC() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var node = EventNode.all(serverFacade,"main"); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var node = EventNode.all(minecraftServer,"main"); var handler = ItemStack.AIR; var mapped = node.map(handler, EventFilter.ITEM); diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java index 4157ed3d26c..5b7a2d2e474 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -129,8 +129,8 @@ public void viewableShared(Env env) { assertEquals(1, viewable.getViewers().size()); } - private Player createTestPlayer(ServerFacade serverFacade) { - return new Player(serverFacade, UUID.randomUUID(), "TestPlayer", new PlayerConnection(serverFacade) { + private Player createTestPlayer(MinecraftServer minecraftServer) { + return new Player(minecraftServer, UUID.randomUUID(), "TestPlayer", new PlayerConnection(minecraftServer) { @Override public void sendPacket(@NotNull SendablePacket packet) { // nothing diff --git a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java index 51c30305a71..66015188414 100644 --- a/src/test/java/net/minestom/server/instance/EntityTrackerTest.java +++ b/src/test/java/net/minestom/server/instance/EntityTrackerTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Entity; @@ -16,8 +16,8 @@ public class EntityTrackerTest { @Test public void register() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -31,7 +31,7 @@ public void remove(@NotNull Entity entity) { fail("No other entity should be registered yet"); } }; - EntityTracker tracker = EntityTracker.newTracker(serverFacade); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); assertTrue(chunkEntities.isEmpty()); @@ -44,8 +44,8 @@ public void remove(@NotNull Entity entity) { @Test public void move() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -58,7 +58,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverFacade); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, updater); assertEquals(1, tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES).size()); @@ -70,11 +70,11 @@ public void remove(@NotNull Entity entity) { @Test public void tracking() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); - var ent2 = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); - EntityTracker tracker = EntityTracker.newTracker(serverFacade); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -130,10 +130,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearby() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); - var ent2 = new Entity(serverFacade, EntityType.ZOMBIE); - var ent3 = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent3 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -146,7 +146,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverFacade); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent2, new Vec(5, 0, 0), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(50, 0, 0), EntityTracker.Target.ENTITIES, updater); @@ -184,10 +184,10 @@ public void remove(@NotNull Entity entity) { @Test public void nearbySingleChunk() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); - var ent2 = new Entity(serverFacade, EntityType.ZOMBIE); - var ent3 = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent2 = new Entity(minecraftServer, EntityType.ZOMBIE); + var ent3 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -200,7 +200,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverFacade); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); tracker.register(ent1, new Vec(5, 0, 5), EntityTracker.Target.ENTITIES, updater); tracker.register(ent2, new Vec(8, 0, 8), EntityTracker.Target.ENTITIES, updater); tracker.register(ent3, new Vec(17, 0, 17), EntityTracker.Target.ENTITIES, updater); @@ -225,8 +225,8 @@ public void remove(@NotNull Entity entity) { @Test public void collectionView() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var ent1 = new Entity(serverFacade, EntityType.ZOMBIE); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var ent1 = new Entity(minecraftServer, EntityType.ZOMBIE); var updater = new EntityTracker.Update<>() { @Override public void add(@NotNull Entity entity) { @@ -241,7 +241,7 @@ public void remove(@NotNull Entity entity) { } }; - EntityTracker tracker = EntityTracker.newTracker(serverFacade); + EntityTracker tracker = EntityTracker.newTracker(minecraftServer); var entities = tracker.entities(); var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES); @@ -251,7 +251,7 @@ public void remove(@NotNull Entity entity) { assertEquals(1, entities.size()); assertEquals(1, chunkEntities.size()); - assertThrows(Exception.class, () -> entities.add(new Entity(serverFacade, EntityType.ZOMBIE))); - assertThrows(Exception.class, () -> chunkEntities.add(new Entity(serverFacade, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> entities.add(new Entity(minecraftServer, EntityType.ZOMBIE))); + assertThrows(Exception.class, () -> chunkEntities.add(new Entity(minecraftServer, EntityType.ZOMBIE))); } } diff --git a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java index fc2d0926647..8ce3b1c9d76 100644 --- a/src/test/java/net/minestom/server/instance/InstanceContainerTest.java +++ b/src/test/java/net/minestom/server/instance/InstanceContainerTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.tag.Tag; import net.minestom.server.world.DimensionType; @@ -19,9 +19,9 @@ public class InstanceContainerTest { @Test public void copyPreservesTag() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var tag = Tag.String("test"); - var instance = new InstanceContainer(serverFacade, UUID.randomUUID(), DimensionType.OVERWORLD); + var instance = new InstanceContainer(minecraftServer, UUID.randomUUID(), DimensionType.OVERWORLD); instance.setTag(tag, "123"); var copyInstance = instance.copy(); diff --git a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java index 2317d4f4188..be1712fab10 100644 --- a/src/test/java/net/minestom/server/instance/light/BlockLightTest.java +++ b/src/test/java/net/minestom/server/instance/light/BlockLightTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.block.Block; @@ -19,8 +19,8 @@ public class BlockLightTest { @Test public void empty() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); var result = LightCompute.compute(palette); for (byte light : result.light()) { assertEquals(0, light); @@ -29,8 +29,8 @@ public void empty() { @Test public void glowstone() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -41,8 +41,8 @@ public void glowstone() { @Test public void doubleGlowstone() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); @@ -56,8 +56,8 @@ public void doubleGlowstone() { @Test public void glowstoneBorder() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); var result = LightCompute.compute(palette); assertLight(result, Map.of( @@ -75,8 +75,8 @@ public void glowstoneBorder() { @Test public void glowstoneBlock() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(0, 1, 0, Block.GLOWSTONE.stateId()); palette.set(0, 1, 1, Block.STONE.stateId()); var result = LightCompute.compute(palette); @@ -88,8 +88,8 @@ public void glowstoneBlock() { @Test public void isolated() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.STONE.stateId()); @@ -116,8 +116,8 @@ public void isolated() { @Test public void isolatedStair() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "east", @@ -139,8 +139,8 @@ public void isolatedStair() { @Test public void isolatedStairOpposite() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -167,8 +167,8 @@ public void isolatedStairOpposite() { @Test public void isolatedStairWest() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "west", @@ -198,8 +198,8 @@ public void isolatedStairWest() { @Test public void isolatedStairSouth() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = Palette.blocks(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = Palette.blocks(minecraftServer); palette.set(4, 1, 4, Block.GLOWSTONE.stateId()); palette.set(3, 1, 4, Block.OAK_STAIRS.withProperties(Map.of( "facing", "south", diff --git a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java index 352389a8c8c..d9d7e6f5834 100644 --- a/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/LightParityIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.*; import net.minestom.server.instance.block.Block; @@ -127,7 +127,7 @@ public void test(Env env) throws URISyntaxException, IOException, AnvilException record SectionEntry(Palette blocks, byte[] sky, byte[] block) { } - private static Map retrieveSections(ServerFacade serverFacade) throws IOException, URISyntaxException, AnvilException { + private static Map retrieveSections(MinecraftServer minecraftServer) throws IOException, URISyntaxException, AnvilException { URL defaultImage = LightParityIntegrationTest.class.getResource("/net/minestom/server/instance/lighting/region/r.0.0.mca"); assert defaultImage != null; File imageFile = new File(defaultImage.toURI()); @@ -143,7 +143,7 @@ private static Map retrieveSections(ServerFacade serverFacade for (int yLevel = chunk.getMinY(); yLevel <= chunk.getMaxY(); yLevel += 16) { var section = chunk.getSection((byte) (yLevel/16)); - var palette = loadBlocks(serverFacade, section); + var palette = loadBlocks(minecraftServer, section); var sky = section.getSkyLights(); var block = section.getBlockLights(); sections.put(new Vec(x, section.getY(), z), new SectionEntry(palette, sky, block)); @@ -153,8 +153,8 @@ private static Map retrieveSections(ServerFacade serverFacade return sections; } - private static Palette loadBlocks(ServerFacade serverFacade, ChunkSection section) throws AnvilException { - var palette = Palette.blocks(serverFacade); + private static Palette loadBlocks(MinecraftServer minecraftServer, ChunkSection section) throws AnvilException { + var palette = Palette.blocks(minecraftServer); for (int x = 0; x < Chunk.CHUNK_SECTION_SIZE; x++) { for (int z = 0; z < Chunk.CHUNK_SECTION_SIZE; z++) { for (int y = 0; y < Chunk.CHUNK_SECTION_SIZE; y++) { diff --git a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java index ecdce962a8e..a6631dc244b 100644 --- a/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java +++ b/src/test/java/net/minestom/server/instance/light/WorldRelightIntegrationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.light; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import net.minestom.server.instance.Instance; import net.minestom.server.instance.LightingChunk; @@ -17,7 +17,7 @@ @EnvTest public class WorldRelightIntegrationTest { - private @NotNull Instance createLightingInstance(@NotNull ServerFacade process) { + private @NotNull Instance createLightingInstance(@NotNull MinecraftServer process) { var instance = process.getInstanceManager().createInstanceContainer(process); instance.setGenerator(unit -> { unit.modifier().fillHeight(39, 40, Block.STONE); diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java index cbed9307d1e..0b9f6c36cab 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteOptimizationTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.palette; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.network.NetworkBuffer; import org.junit.jupiter.api.Test; @@ -14,24 +14,24 @@ public class PaletteOptimizationTest { @Test public void empty() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = createPalette(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = createPalette(minecraftServer); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void single() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = createPalette(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = createPalette(minecraftServer); palette.set(0, 0, 0, 1); paletteEquals(palette.palette, palette.optimizedPalette()); } @Test public void random() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var random = new Random(12345); - var palette = createPalette(serverFacade); + var palette = createPalette(minecraftServer); palette.setAll((x, y, z) -> random.nextInt(256)); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> random.nextInt(2)); @@ -40,8 +40,8 @@ public void random() { @Test public void manualFill() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palette = createPalette(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palette = createPalette(minecraftServer); palette.setAll((x, y, z) -> 1); paletteEquals(palette.palette, palette.optimizedPalette()); palette.setAll((x, y, z) -> 2); @@ -50,8 +50,8 @@ public void manualFill() { paletteEquals(palette.palette, palette.optimizedPalette()); } - AdaptivePalette createPalette(ServerFacade serverFacade) { - return (AdaptivePalette) Palette.blocks(serverFacade); + AdaptivePalette createPalette(MinecraftServer minecraftServer) { + return (AdaptivePalette) Palette.blocks(minecraftServer); } void paletteEquals(Palette palette, Palette optimized) { diff --git a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java index 9a2881908cb..ae94e0a9b3b 100644 --- a/src/test/java/net/minestom/server/instance/palette/PaletteTest.java +++ b/src/test/java/net/minestom/server/instance/palette/PaletteTest.java @@ -1,6 +1,6 @@ package net.minestom.server.instance.palette; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -24,8 +24,8 @@ public void singlePlacement() { @Test public void placement() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { final int dimension = palette.dimension(); assertEquals(0, palette.get(0, 0, 0), "Default value should be 0"); @@ -60,9 +60,9 @@ public void placement() { @Test public void placementHighValue() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); final int value = 250_000; - for (Palette palette : testPalettes(serverFacade)) { + for (Palette palette : testPalettes(minecraftServer)) { palette.set(0, 0, 1, value); assertEquals(value, palette.get(0, 0, 1)); } @@ -70,8 +70,8 @@ public void placementHighValue() { @Test public void negPlacement() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { assertThrows(IllegalArgumentException.class, () -> palette.set(-1, 0, 0, 64)); assertThrows(IllegalArgumentException.class, () -> palette.set(0, -1, 0, 64)); @@ -104,8 +104,8 @@ public void resize() { @Test public void fill() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { assertEquals(0, palette.count()); palette.set(0, 0, 0, 5); @@ -136,8 +136,8 @@ public void fill() { @Test public void bulk() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { final int dimension = palette.dimension(); // Place @@ -162,8 +162,8 @@ public void bulk() { @Test public void bulkAll() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { // Fill all entries palette.setAll((x, y, z) -> x + y + z + 1); @@ -181,8 +181,8 @@ public void bulkAll() { @Test public void bulkAllOrder() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { AtomicInteger count = new AtomicInteger(); @@ -220,8 +220,8 @@ public void bulkAllOrder() { @Test public void setAllConstant() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.setAll((x, y, z) -> 1); palette.getAll((x, y, z, value) -> assertEquals(1, value)); @@ -230,8 +230,8 @@ public void setAllConstant() { @Test public void getAllPresent() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.getAllPresent((x, y, z, value) -> fail("The palette should be empty")); palette.set(0, 0, 1, 1); @@ -246,8 +246,8 @@ public void getAllPresent() { @Test public void replaceAll() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.setAll((x, y, z) -> x + y + z + 1); palette.replaceAll((x, y, z, value) -> { @@ -260,8 +260,8 @@ public void replaceAll() { @Test public void replace() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var palettes = testPalettes(serverFacade); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var palettes = testPalettes(minecraftServer); for (Palette palette : palettes) { palette.set(0, 0, 0, 1); palette.replace(0, 0, 0, operand -> { @@ -274,7 +274,7 @@ public void replace() { @Test public void replaceLoop() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); var palette = Palette.newPalette(2, 15, 4); palette.setAll((x, y, z) -> x + y + z); final int dimension = palette.dimension(); @@ -289,7 +289,7 @@ public void replaceLoop() { @Test public void dimension() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); assertThrows(Exception.class, () -> Palette.newPalette(-4, 5, 3)); assertThrows(Exception.class, () -> Palette.newPalette(0, 5, 3)); assertThrows(Exception.class, () -> Palette.newPalette(1, 5, 3)); @@ -300,7 +300,7 @@ public void dimension() { assertDoesNotThrow(() -> Palette.newPalette(16, 5, 3)); } - private static List testPalettes(ServerFacade serverFacade) { + private static List testPalettes(MinecraftServer minecraftServer) { return List.of( Palette.newPalette(2, 5, 3), Palette.newPalette(4, 5, 3), diff --git a/src/test/java/net/minestom/server/inventory/InventoryTest.java b/src/test/java/net/minestom/server/inventory/InventoryTest.java index 0c2b544011a..b7339d0d64b 100644 --- a/src/test/java/net/minestom/server/inventory/InventoryTest.java +++ b/src/test/java/net/minestom/server/inventory/InventoryTest.java @@ -1,7 +1,7 @@ package net.minestom.server.inventory; import net.kyori.adventure.text.Component; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; @@ -11,11 +11,11 @@ public class InventoryTest { - private static ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + private static MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); @Test public void testCreation() { - Inventory inventory = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); assertEquals(InventoryType.CHEST_1_ROW, inventory.getInventoryType()); assertEquals(Component.text("title"), inventory.getTitle()); @@ -28,7 +28,7 @@ public void testEntry() { var item1 = ItemStack.of(Material.DIAMOND); var item2 = ItemStack.of(Material.GOLD_INGOT); - Inventory inventory = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); assertSame(ItemStack.AIR, inventory.getItemStack(0)); inventory.setItemStack(0, item1); assertSame(item1, inventory.getItemStack(0)); @@ -52,7 +52,7 @@ public void testEntry() { @Test public void testTake() { ItemStack item = ItemStack.of(Material.DIAMOND, 32); - Inventory inventory = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title"); inventory.setItemStack(0, item); assertTrue(inventory.takeItemStack(item, TransactionOption.DRY_RUN)); assertTrue(inventory.takeItemStack(item.withAmount(31), TransactionOption.DRY_RUN)); @@ -65,7 +65,7 @@ public void testTake() { @Test public void testAdd() { - Inventory inventory = new Inventory(serverFacade, InventoryType.HOPPER, "title"); + Inventory inventory = new Inventory(minecraftServer, InventoryType.HOPPER, "title"); assertTrue(inventory.addItemStack(ItemStack.of(Material.DIAMOND, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.GOLD_BLOCK, 32), TransactionOption.ALL_OR_NOTHING)); assertTrue(inventory.addItemStack(ItemStack.of(Material.MAP, 32), TransactionOption.ALL_OR_NOTHING)); @@ -77,7 +77,7 @@ public void testAdd() { @Test public void testIds() { for (int i = 0; i <= 1000; ++i) { - final byte windowId = new Inventory(serverFacade, InventoryType.CHEST_1_ROW, "title").getWindowId(); + final byte windowId = new Inventory(minecraftServer, InventoryType.CHEST_1_ROW, "title").getWindowId(); assertTrue(windowId > 0); } } diff --git a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java index 12b0aad8e9c..9220fae4c94 100644 --- a/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java +++ b/src/test/java/net/minestom/server/network/socket/ServerAddressTest.java @@ -1,6 +1,6 @@ package net.minestom.server.network.socket; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.listener.manager.PacketListenerManagerImpl; import net.minestom.server.network.PacketProcessorImpl; @@ -18,12 +18,12 @@ public class ServerAddressTest { @Test public void inetAddressTest() throws IOException { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 25565); - var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); + var server = new ServerImpl(minecraftServer, new PacketProcessorImpl(new PacketListenerManagerImpl(minecraftServer))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -35,12 +35,12 @@ public void inetAddressTest() throws IOException { @Test public void inetAddressDynamicTest() throws IOException { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); InetSocketAddress address = new InetSocketAddress("localhost", 0); - var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); + var server = new ServerImpl(minecraftServer, new PacketProcessorImpl(new PacketListenerManagerImpl(minecraftServer))); server.init(address); assertSame(address, server.socketAddress()); assertEquals(address.getHostString(), server.getAddress()); @@ -52,12 +52,12 @@ public void inetAddressDynamicTest() throws IOException { @Test public void unixAddressTest() throws IOException { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // These like to fail on github actions assumeTrue(System.getenv("GITHUB_ACTIONS") == null); UnixDomainSocketAddress address = UnixDomainSocketAddress.of("minestom.sock"); - var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); + var server = new ServerImpl(minecraftServer, new PacketProcessorImpl(new PacketListenerManagerImpl(minecraftServer))); server.init(address); assertTrue(Files.exists(address.getPath())); assertSame(address, server.socketAddress()); @@ -71,8 +71,8 @@ public void unixAddressTest() throws IOException { @Test public void noAddressTest() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); - var server = new ServerImpl(serverFacade, new PacketProcessorImpl(new PacketListenerManagerImpl(serverFacade))); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + var server = new ServerImpl(minecraftServer, new PacketProcessorImpl(new PacketListenerManagerImpl(minecraftServer))); assertDoesNotThrow(server::stop); } } diff --git a/src/test/java/net/minestom/server/permission/TestPermissions.java b/src/test/java/net/minestom/server/permission/TestPermissions.java index 7ffbdff68ce..fdcb6c93160 100644 --- a/src/test/java/net/minestom/server/permission/TestPermissions.java +++ b/src/test/java/net/minestom/server/permission/TestPermissions.java @@ -1,6 +1,6 @@ package net.minestom.server.permission; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; import org.jglrxavpok.hephaistos.nbt.NBT; @@ -20,12 +20,12 @@ public class TestPermissions { private Player player; private Permission permission1, permission2, permission3, wildcard; - private ServerFacade serverFacade; + private MinecraftServer minecraftServer; @BeforeEach public void init() { - serverFacade = ServerFacade.of(ServerSettings.builder().build()); - player = new Player(serverFacade, UUID.randomUUID(), "TestPlayer", null) { + minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); + player = new Player(minecraftServer, UUID.randomUUID(), "TestPlayer", null) { @Override protected void playerConnectionInit() { } diff --git a/src/test/java/net/minestom/server/thread/AcquirableTest.java b/src/test/java/net/minestom/server/thread/AcquirableTest.java index e133229ab9e..ce74b12d904 100644 --- a/src/test/java/net/minestom/server/thread/AcquirableTest.java +++ b/src/test/java/net/minestom/server/thread/AcquirableTest.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; @@ -15,9 +15,9 @@ public class AcquirableTest { @Test public void assignation() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); AtomicReference tickThread = new AtomicReference<>(); - Entity entity = new Entity(serverFacade, EntityType.ZOMBIE) { + Entity entity = new Entity(minecraftServer, EntityType.ZOMBIE) { @Override public void tick(long time) { super.tick(time); @@ -27,7 +27,7 @@ public void tick(long time) { Object first = new Object(); Object second = new Object(); - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverFacade.getExceptionHandler(), ThreadProvider.counter(), 2); + ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer.getExceptionHandler(), ThreadProvider.counter(), 2); dispatcher.createPartition(first); dispatcher.createPartition(second); diff --git a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java index 93824fc1912..d7241a156a7 100644 --- a/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java +++ b/src/test/java/net/minestom/server/thread/ThreadDispatcherTest.java @@ -1,6 +1,6 @@ package net.minestom.server.thread; -import net.minestom.server.ServerFacade; +import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettings; import net.minestom.server.Tickable; import org.jetbrains.annotations.NotNull; @@ -20,11 +20,11 @@ public class ThreadDispatcherTest { @Test public void elementTick() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); final AtomicInteger counter = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverFacade.getExceptionHandler()); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(minecraftServer.getExceptionHandler()); assertEquals(1, dispatcher.threads().size()); - assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(serverFacade.getExceptionHandler(),1))); + assertThrows(Exception.class, () -> dispatcher.threads().add(new TickThread(minecraftServer.getExceptionHandler(),1))); var partition = new Object(); Tickable element = (time) -> counter.incrementAndGet(); @@ -49,11 +49,11 @@ public void elementTick() { @Test public void partitionTick() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // Partitions implementing Tickable should be ticked same as elements final AtomicInteger counter1 = new AtomicInteger(); final AtomicInteger counter2 = new AtomicInteger(); - ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(serverFacade.getExceptionHandler()); + ThreadDispatcher dispatcher = ThreadDispatcher.singleThread(minecraftServer.getExceptionHandler()); assertEquals(1, dispatcher.threads().size()); Tickable partition = (time) -> counter1.incrementAndGet(); @@ -79,10 +79,10 @@ public void partitionTick() { @Test public void uniqueThread() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // Ensure that partitions are properly dispatched across threads final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverFacade.getExceptionHandler(), ThreadProvider.counter(), threadCount); + ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer.getExceptionHandler(), ThreadProvider.counter(), threadCount); assertEquals(threadCount, dispatcher.threads().size()); final AtomicInteger counter = new AtomicInteger(); @@ -109,7 +109,7 @@ public void uniqueThread() { @Test public void threadUpdate() { - ServerFacade serverFacade = ServerFacade.of(ServerSettings.builder().build()); + MinecraftServer minecraftServer = MinecraftServer.of(ServerSettings.builder().build()); // Ensure that partitions threads are properly updated every tick // when RefreshType.ALWAYS is used interface Updater extends Tickable { @@ -117,7 +117,7 @@ interface Updater extends Tickable { } final int threadCount = 10; - ThreadDispatcher dispatcher = ThreadDispatcher.of(serverFacade.getExceptionHandler(), new ThreadProvider<>() { + ThreadDispatcher dispatcher = ThreadDispatcher.of(minecraftServer.getExceptionHandler(), new ThreadProvider<>() { @Override public int findThread(@NotNull Updater partition) { return partition.getValue(); From 0f3148160f195974d9c7410b865440e62780eb86 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Thu, 1 Feb 2024 10:25:53 +0300 Subject: [PATCH 13/16] Delombok :( --- build.gradle.kts | 1 - .../minestom/server/MinecraftServerImpl.java | 98 +++++++- .../net/minestom/server/ServerSettings.java | 228 +++++++++++++++--- .../net/minestom/server/ServerStarter.java | 17 +- .../java/net/minestom/server/TickerImpl.java | 12 +- .../advancements/AdvancementManagerImpl.java | 6 +- .../adventure/bossbar/BossBarListener.java | 7 +- .../server/command/CommandManagerImpl.java | 7 +- .../command/builder/CommandDispatcher.java | 6 +- .../net/minestom/server/entity/Entity.java | 11 +- .../net/minestom/server/entity/Player.java | 88 +++++-- .../minestom/server/extras/MojangAuth.java | 16 +- .../minestom/server/extras/lan/OpenToLAN.java | 9 +- .../server/instance/EntityTracker.java | 4 + .../server/instance/EntityTrackerImpl.java | 8 +- .../minestom/server/instance/Instance.java | 103 +++++--- .../server/instance/InstanceManagerImpl.java | 11 +- .../monitoring/BenchmarkManagerImpl.java | 11 +- .../network/player/PlayerConnection.java | 37 ++- .../minestom/server/ping/ResponseData.java | 6 +- .../server/scoreboard/BelowNameTag.java | 6 +- .../server/scoreboard/TeamManagerImpl.java | 6 +- .../server/utils/entity/EntityFinder.java | 11 +- 23 files changed, 577 insertions(+), 132 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 69aa92770da..5ebffdc00bd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,6 @@ plugins { `maven-publish` signing alias(libs.plugins.nexuspublish) - id("io.freefair.lombok") version "8.4" } // Read env vars (used for publishing generally) diff --git a/src/main/java/net/minestom/server/MinecraftServerImpl.java b/src/main/java/net/minestom/server/MinecraftServerImpl.java index f1759bec205..37e40881131 100644 --- a/src/main/java/net/minestom/server/MinecraftServerImpl.java +++ b/src/main/java/net/minestom/server/MinecraftServerImpl.java @@ -1,6 +1,5 @@ package net.minestom.server; -import lombok.Getter; import net.minestom.server.advancements.AdvancementManager; import net.minestom.server.advancements.AdvancementManagerImpl; import net.minestom.server.adventure.audience.AudienceManager; @@ -42,7 +41,6 @@ import net.minestom.server.world.biomes.BiomeManager; import net.minestom.server.world.biomes.BiomeManagerImpl; -@Getter final class MinecraftServerImpl implements MinecraftServer { private final ExceptionHandler exceptionHandler; @@ -101,4 +99,100 @@ public MinecraftServerImpl(ServerSettings serverSettings) { this.serverStarter = new ServerStarter(this); this.mojangAuth = new MojangAuth(this, this); } + + public ExceptionHandler getExceptionHandler() { + return this.exceptionHandler; + } + + public ConnectionManager getConnectionManager() { + return this.connectionManager; + } + + public PacketListenerManager getPacketListenerManager() { + return this.packetListenerManager; + } + + public PacketProcessor getPacketProcessor() { + return this.packetProcessor; + } + + public InstanceManager getInstanceManager() { + return this.instanceManager; + } + + public BlockManager getBlockManager() { + return this.blockManager; + } + + public CommandManager getCommandManager() { + return this.commandManager; + } + + public RecipeManager getRecipeManager() { + return this.recipeManager; + } + + public TeamManager getTeamManager() { + return this.teamManager; + } + + public GlobalEventHandler getGlobalEventHandler() { + return this.globalEventHandler; + } + + public SchedulerManager getSchedulerManager() { + return this.schedulerManager; + } + + public BenchmarkManager getBenchmarkManager() { + return this.benchmarkManager; + } + + public DimensionTypeManager getDimensionTypeManager() { + return this.dimensionTypeManager; + } + + public BiomeManager getBiomeManager() { + return this.biomeManager; + } + + public AdvancementManager getAdvancementManager() { + return this.advancementManager; + } + + public BossBarManager getBossBarManager() { + return this.bossBarManager; + } + + public TagManager getTagManager() { + return this.tagManager; + } + + public Server getServer() { + return this.server; + } + + public ChunkDispatcher getChunkDispatcher() { + return this.chunkDispatcher; + } + + public Ticker getTicker() { + return this.ticker; + } + + public ServerSettings getServerSettings() { + return this.serverSettings; + } + + public AudienceManager getAudienceManager() { + return this.audienceManager; + } + + public MojangAuth getMojangAuth() { + return this.mojangAuth; + } + + public ServerStarter getServerStarter() { + return this.serverStarter; + } } diff --git a/src/main/java/net/minestom/server/ServerSettings.java b/src/main/java/net/minestom/server/ServerSettings.java index 22f1c99f9a7..2f9b1d0c9b8 100644 --- a/src/main/java/net/minestom/server/ServerSettings.java +++ b/src/main/java/net/minestom/server/ServerSettings.java @@ -1,9 +1,5 @@ package net.minestom.server; -import lombok.Builder; -import lombok.Builder.Default; -import lombok.Getter; -import lombok.Setter; import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.server.common.PluginMessagePacket; import net.minestom.server.network.packet.server.play.ServerDifficultyPacket; @@ -11,37 +7,37 @@ import net.minestom.server.world.Difficulty; import org.jetbrains.annotations.NotNull; -@Getter -@Setter -@Builder(builderClassName = "Builder") public final class ServerSettings { - @Default - private final int chunkViewDistance = 8; - @Default - private final int entityViewDistance = 5; - @Default - private final int compressionThreshold = 256; - @Default - private final int tickPerSecond = 20; - @Default - private final boolean shutdownOnSignal = true; - @Default - private final int workers = Runtime.getRuntime().availableProcessors(); - @Default - private final int maxPacketSize = 2_097_151; // 3 bytes var-int - @Default - private final int sendBufferSize = 262_143; - @Default - private final int receiveBufferSize = 32_767; - @Default - private final int pooledBufferSize = 262_143; - @Default - private final boolean tcpNoDelay = true; - - @Default - private @NotNull String brandName = "Minestom"; - @Default - private @NotNull Difficulty difficulty = Difficulty.NORMAL; + private final int chunkViewDistance; + private final int entityViewDistance; + private final int compressionThreshold; + private final int tickPerSecond; + private final boolean shutdownOnSignal; + private final int workers; + private final int maxPacketSize; // 3 bytes var-int + private final int sendBufferSize; + private final int receiveBufferSize; + private final int pooledBufferSize; + private final boolean tcpNoDelay; + + private @NotNull String brandName; + private @NotNull Difficulty difficulty; + + public ServerSettings(int chunkViewDistance, int entityViewDistance, int compressionThreshold, int tickPerSecond, boolean shutdownOnSignal, int workers, int maxPacketSize, int sendBufferSize, int receiveBufferSize, int pooledBufferSize, boolean tcpNoDelay, @NotNull String brandName, @NotNull Difficulty difficulty) { + this.chunkViewDistance = chunkViewDistance; + this.entityViewDistance = entityViewDistance; + this.compressionThreshold = compressionThreshold; + this.tickPerSecond = tickPerSecond; + this.shutdownOnSignal = shutdownOnSignal; + this.workers = workers; + this.maxPacketSize = maxPacketSize; + this.sendBufferSize = sendBufferSize; + this.receiveBufferSize = receiveBufferSize; + this.pooledBufferSize = pooledBufferSize; + this.tcpNoDelay = tcpNoDelay; + this.brandName = brandName; + this.difficulty = difficulty; + } public int getTickMs() { return 1000 / tickPerSecond; @@ -56,4 +52,168 @@ public void updateDifficulty(@NotNull Difficulty difficulty, @NotNull Connection setDifficulty(difficulty); PacketUtils.broadcastPlayPacket(connectionManager, serverSettingsProvider, new ServerDifficultyPacket(difficulty, true)); } + + public int getChunkViewDistance() { + return this.chunkViewDistance; + } + + public int getEntityViewDistance() { + return this.entityViewDistance; + } + + public int getCompressionThreshold() { + return this.compressionThreshold; + } + + public int getTickPerSecond() { + return this.tickPerSecond; + } + + public boolean isShutdownOnSignal() { + return this.shutdownOnSignal; + } + + public int getWorkers() { + return this.workers; + } + + public int getMaxPacketSize() { + return this.maxPacketSize; + } + + public int getSendBufferSize() { + return this.sendBufferSize; + } + + public int getReceiveBufferSize() { + return this.receiveBufferSize; + } + + public int getPooledBufferSize() { + return this.pooledBufferSize; + } + + public boolean isTcpNoDelay() { + return this.tcpNoDelay; + } + + public @NotNull String getBrandName() { + return this.brandName; + } + + public @NotNull Difficulty getDifficulty() { + return this.difficulty; + } + + public void setBrandName(@NotNull String brandName) { + this.brandName = brandName; + } + + public void setDifficulty(@NotNull Difficulty difficulty) { + this.difficulty = difficulty; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private int chunkViewDistance = 8; + private int entityViewDistance = 5; + private int compressionThreshold = 256; + private int tickPerSecond = 20; + private boolean shutdownOnSignal = true; + private int workers = Runtime.getRuntime().availableProcessors(); + private int maxPacketSize = 2_097_151; // 3 bytes var-int + private int sendBufferSize = 262_143; + private int receiveBufferSize = 32_767; + private int pooledBufferSize = 262_143; + private boolean tcpNoDelay = true; + + private @NotNull String brandName = "Minestom"; + private @NotNull Difficulty difficulty = Difficulty.NORMAL; + + public Builder chunkViewDistance(int chunkViewDistance) { + this.chunkViewDistance = chunkViewDistance; + return this; + } + + public Builder entityViewDistance(int entityViewDistance) { + this.entityViewDistance = entityViewDistance; + return this; + } + + public Builder compressionThreshold(int compressionThreshold) { + this.compressionThreshold = compressionThreshold; + return this; + } + + public Builder tickPerSecond(int tickPerSecond) { + this.tickPerSecond = tickPerSecond; + return this; + } + + public Builder shutdownOnSignal(boolean shutdownOnSignal) { + this.shutdownOnSignal = shutdownOnSignal; + return this; + } + + public Builder workers(int workers) { + this.workers = workers; + return this; + } + + public Builder maxPacketSize(int maxPacketSize) { + this.maxPacketSize = maxPacketSize; + return this; + } + + public Builder sendBufferSize(int sendBufferSize) { + this.sendBufferSize = sendBufferSize; + return this; + } + + public Builder receiveBufferSize(int receiveBufferSize) { + this.receiveBufferSize = receiveBufferSize; + return this; + } + + public Builder pooledBufferSize(int pooledBufferSize) { + this.pooledBufferSize = pooledBufferSize; + return this; + } + + public Builder tcpNoDelay(boolean tcpNoDelay) { + this.tcpNoDelay = tcpNoDelay; + return this; + } + + public Builder brandName(@NotNull String brandName) { + this.brandName = brandName; + return this; + } + + public Builder difficulty(@NotNull Difficulty difficulty) { + this.difficulty = difficulty; + return this; + } + + public ServerSettings build() { + return new ServerSettings( + chunkViewDistance, + entityViewDistance, + compressionThreshold, + tickPerSecond, + shutdownOnSignal, + workers, + maxPacketSize, + sendBufferSize, + receiveBufferSize, + pooledBufferSize, + tcpNoDelay, + brandName, + difficulty + ); + } + } } diff --git a/src/main/java/net/minestom/server/ServerStarter.java b/src/main/java/net/minestom/server/ServerStarter.java index c2cf13b41b3..725b29bd53b 100644 --- a/src/main/java/net/minestom/server/ServerStarter.java +++ b/src/main/java/net/minestom/server/ServerStarter.java @@ -1,6 +1,5 @@ package net.minestom.server; -import lombok.RequiredArgsConstructor; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.monitoring.BenchmarkManagerProvider; import net.minestom.server.network.ConnectionManagerProvider; @@ -17,7 +16,6 @@ import java.net.SocketAddress; import java.util.concurrent.atomic.AtomicBoolean; -@RequiredArgsConstructor public class ServerStarter { private static final Logger LOGGER = LoggerFactory.getLogger(ServerStarter.class); @@ -36,6 +34,18 @@ public ServerStarter(MinecraftServer minecraftServer) { private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); + + public ServerStarter(ServerSettingsProvider serverSettingsProvider, ServerProvider serverProvider, ExceptionHandlerProvider exceptionHandlerProvider, SchedulerManagerProvider schedulerManagerProvider, ConnectionManagerProvider connectionManagerProvider, BenchmarkManagerProvider benchmarkManagerProvider, ChunkDispatcherProvider chunkDispatcherProvider, TickerProvider tickerProvider) { + this.serverSettingsProvider = serverSettingsProvider; + this.serverProvider = serverProvider; + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.schedulerManagerProvider = schedulerManagerProvider; + this.connectionManagerProvider = connectionManagerProvider; + this.benchmarkManagerProvider = benchmarkManagerProvider; + this.chunkDispatcherProvider = chunkDispatcherProvider; + this.tickerProvider = tickerProvider; + } + public void start(@NotNull SocketAddress socketAddress) { if (!started.compareAndSet(false, true)) { throw new IllegalStateException("Server already started"); @@ -57,7 +67,8 @@ public void start(@NotNull SocketAddress socketAddress) { LOGGER.info(serverSettingsProvider.getServerSettings().getBrandName() + " server started successfully."); // Stop the server on SIGINT - if (serverSettingsProvider.getServerSettings().isShutdownOnSignal()) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); + if (serverSettingsProvider.getServerSettings().isShutdownOnSignal()) + Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); new TickSchedulerThread(serverSettingsProvider.getServerSettings(), tickerProvider.getTicker(), this, exceptionHandlerProvider.getExceptionHandler()).start(); } diff --git a/src/main/java/net/minestom/server/TickerImpl.java b/src/main/java/net/minestom/server/TickerImpl.java index 4e7478b0d77..ecab3cbddea 100644 --- a/src/main/java/net/minestom/server/TickerImpl.java +++ b/src/main/java/net/minestom/server/TickerImpl.java @@ -1,6 +1,5 @@ package net.minestom.server; -import lombok.RequiredArgsConstructor; import net.minestom.server.event.GlobalEventHandlerProvider; import net.minestom.server.event.server.ServerTickMonitorEvent; import net.minestom.server.exception.ExceptionHandlerProvider; @@ -14,7 +13,6 @@ import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.PacketUtils; -@RequiredArgsConstructor public final class TickerImpl implements Ticker { private final ConnectionManagerProvider connectionManagerProvider; private final SchedulerManagerProvider schedulerManagerProvider; @@ -28,6 +26,16 @@ public TickerImpl(MinecraftServer minecraftServer) { this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } + public TickerImpl(ConnectionManagerProvider connectionManagerProvider, SchedulerManagerProvider schedulerManagerProvider, ServerProvider serverProvider, GlobalEventHandlerProvider globalEventHandlerProvider, ExceptionHandlerProvider exceptionHandlerProvider, InstanceManagerProvider instanceManagerProvider, ChunkDispatcherProvider chunkDispatcherProvider) { + this.connectionManagerProvider = connectionManagerProvider; + this.schedulerManagerProvider = schedulerManagerProvider; + this.serverProvider = serverProvider; + this.globalEventHandlerProvider = globalEventHandlerProvider; + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.instanceManagerProvider = instanceManagerProvider; + this.chunkDispatcherProvider = chunkDispatcherProvider; + } + @Override public void tick(long nanoTime) { final long msTime = System.currentTimeMillis(); diff --git a/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java b/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java index 9416983e809..fbf9f9d999d 100644 --- a/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java +++ b/src/main/java/net/minestom/server/advancements/AdvancementManagerImpl.java @@ -1,6 +1,5 @@ package net.minestom.server.advancements; -import lombok.RequiredArgsConstructor; import net.minestom.server.ServerSettings; import net.minestom.server.utils.validate.Check; import org.jetbrains.annotations.NotNull; @@ -10,13 +9,16 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -@RequiredArgsConstructor public class AdvancementManagerImpl implements AdvancementManager { private final ServerSettings serverSettings; // root identifier = its advancement tab private final Map advancementTabMap = new ConcurrentHashMap<>(); + public AdvancementManagerImpl(ServerSettings serverSettings) { + this.serverSettings = serverSettings; + } + @Override @NotNull public AdvancementTab createTab(@NotNull String rootIdentifier, @NotNull AdvancementRoot root) { diff --git a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java index 4144b46e5fa..0200ea22f91 100644 --- a/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java +++ b/src/main/java/net/minestom/server/adventure/bossbar/BossBarListener.java @@ -1,6 +1,5 @@ package net.minestom.server.adventure.bossbar; -import lombok.RequiredArgsConstructor; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; @@ -17,13 +16,17 @@ * {@link Audience}, instead you should use {@link BossBarManagerImpl} to manage boss bars * for players. */ -@RequiredArgsConstructor class BossBarListener implements BossBar.Listener { private final ServerSettingsProvider serverSettingsProvider; private final BossBarManagerImpl manager; + public BossBarListener(ServerSettingsProvider serverSettingsProvider, BossBarManagerImpl manager) { + this.serverSettingsProvider = serverSettingsProvider; + this.manager = manager; + } + @Override public void bossBarNameChanged(@NotNull BossBar bar, @NotNull Component oldName, @NotNull Component newName) { this.doIfRegistered(bar, holder -> PacketUtils.sendGroupedPacket(serverSettingsProvider, holder.players, holder.createTitleUpdate(newName))); diff --git a/src/main/java/net/minestom/server/command/CommandManagerImpl.java b/src/main/java/net/minestom/server/command/CommandManagerImpl.java index d6d0cf77d8a..0995cb97e65 100644 --- a/src/main/java/net/minestom/server/command/CommandManagerImpl.java +++ b/src/main/java/net/minestom/server/command/CommandManagerImpl.java @@ -1,6 +1,5 @@ package net.minestom.server.command; -import lombok.RequiredArgsConstructor; import net.minestom.server.command.builder.Command; import net.minestom.server.command.builder.CommandDispatcher; import net.minestom.server.command.builder.CommandResult; @@ -19,7 +18,6 @@ import java.util.*; import java.util.concurrent.Callable; -@RequiredArgsConstructor public final class CommandManagerImpl implements CommandManager { private final ExceptionHandlerProvider exceptionHandlerProvider; @@ -36,6 +34,11 @@ public final class CommandManagerImpl implements CommandManager { private CommandCallback unknownCommandCallback; + public CommandManagerImpl(ExceptionHandlerProvider exceptionHandlerProvider, GlobalEventHandlerProvider globalEventHandlerProvider) { + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.globalEventHandlerProvider = globalEventHandlerProvider; + } + @Override public synchronized void register(@NotNull Command command) { Check.stateCondition(commandExists(command.getName()), diff --git a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java index bdad9918af6..224a199e98a 100644 --- a/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java +++ b/src/main/java/net/minestom/server/command/builder/CommandDispatcher.java @@ -2,7 +2,6 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; -import lombok.RequiredArgsConstructor; import net.minestom.server.command.CommandManager; import net.minestom.server.command.CommandManagerImpl; import net.minestom.server.command.CommandParser; @@ -18,7 +17,6 @@ /** * Class responsible for parsing {@link Command}. */ -@RequiredArgsConstructor public class CommandDispatcher { private final CommandManager manager; @@ -30,6 +28,10 @@ public CommandDispatcher(ExceptionHandlerProvider exceptionHandlerProvider, Glob this(new CommandManagerImpl(exceptionHandlerProvider, globalEventHandlerProvider)); } + public CommandDispatcher(CommandManager manager) { + this.manager = manager; + } + /** * Registers a command, * be aware that registering a command name or alias will override the previous entry. diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index 099bd631fab..314d07c0139 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -1,6 +1,5 @@ package net.minestom.server.entity; -import lombok.Getter; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.HoverEvent; @@ -96,11 +95,9 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev private static final AtomicInteger LAST_ENTITY_ID = new AtomicInteger(); private final CachedPacket destroyPacketCache; - @Getter // FIXME bad shit protected final ServerSettingsProvider serverSettingsProvider; protected final ChunkDispatcherProvider chunkDispatcherProvider; protected final ExceptionHandlerProvider exceptionHandlerProvider; - @Getter // FIXME bad shit protected final GlobalEventHandler globalEventHandler; protected Instance instance; @@ -1849,6 +1846,14 @@ public boolean hasCollision() { return hasCollision; } + public ServerSettingsProvider getServerSettingsProvider() { + return this.serverSettingsProvider; + } + + public GlobalEventHandler getGlobalEventHandler() { + return this.globalEventHandler; + } + public enum Pose { STANDING, FALL_FLYING, diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index 0f53c160e8c..b317f3d387c 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.longs.LongArrayPriorityQueue; import it.unimi.dsi.fastutil.longs.LongPriorityQueue; -import lombok.Getter; import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.identity.Identified; @@ -142,36 +141,27 @@ public class Player extends LivingEntity implements CommandSender, Localizable, public static final boolean EXPERIMENT_PERFORM_POSE_UPDATES = Boolean.getBoolean("minestom.experiment.pose-updates"); - @Getter private long lastKeepAlive; private boolean answerKeepAlive; - @Getter // FIXME bad shit protected final ConnectionManagerProvider connectionManagerProvider; protected final TeamManagerProvider teamManagerProvider; protected final RecipeManagerProvider recipeManagerProvider; - @Getter // FIXME bad shit private final CommandManagerProvider commandManagerProvider; private final BossBarManagerProvider bossBarManagerProvider; private final SchedulerManagerProvider schedulerManagerProvider; private final PacketListenerManagerProvider packetListenerManagerProvider; - @Getter // FIXME bad shit private final BlockManagerProvider blockManagerProvider; private String username; private Component usernameComponent; - @Getter protected final PlayerConnection playerConnection; - @Getter private int latency; private Component displayName; - @Getter private PlayerSkin skin; private Instance pendingInstance = null; - @Getter private DimensionType dimensionType; - @Getter private GameMode gameMode; private DeathLocation deathLocation; @@ -194,27 +184,22 @@ public class Player extends LivingEntity implements CommandSender, Localizable, final IntegerBiConsumer chunkRemover; private final AtomicInteger teleportId = new AtomicInteger(); - @lombok.Setter - @Getter + private int lastReceivedTeleportId; private final MessagePassingQueue packets = new MpscUnboundedXaddArrayQueue<>(32); private final boolean levelFlat; - @Getter + private final PlayerSettings settings; private float exp; private int level; - @Getter - @lombok.Setter private int portalCooldown = 0; - @Getter protected PlayerInventory inventory; private Inventory openInventory; // Used internally to allow the closing of inventory within the inventory listener private boolean didCloseInventory; - @Getter private byte heldSlot; private Pos respawnPoint; @@ -235,7 +220,6 @@ public class Player extends LivingEntity implements CommandSender, Localizable, private BelowNameTag belowNameTag; - @Getter private int permissionLevel; private boolean reducedDebugScreenInformation; @@ -2334,6 +2318,74 @@ protected void sendChunkUpdates(Chunk newChunk) { return super.teleport(position, chunks); } + public long getLastKeepAlive() { + return this.lastKeepAlive; + } + + public ConnectionManagerProvider getConnectionManagerProvider() { + return this.connectionManagerProvider; + } + + public CommandManagerProvider getCommandManagerProvider() { + return this.commandManagerProvider; + } + + public BlockManagerProvider getBlockManagerProvider() { + return this.blockManagerProvider; + } + + public PlayerConnection getPlayerConnection() { + return this.playerConnection; + } + + public int getLatency() { + return this.latency; + } + + public PlayerSkin getSkin() { + return this.skin; + } + + public DimensionType getDimensionType() { + return this.dimensionType; + } + + public GameMode getGameMode() { + return this.gameMode; + } + + public int getLastReceivedTeleportId() { + return this.lastReceivedTeleportId; + } + + public PlayerSettings getSettings() { + return this.settings; + } + + public int getPortalCooldown() { + return this.portalCooldown; + } + + public PlayerInventory getInventory() { + return this.inventory; + } + + public byte getHeldSlot() { + return this.heldSlot; + } + + public int getPermissionLevel() { + return this.permissionLevel; + } + + public void setLastReceivedTeleportId(int lastReceivedTeleportId) { + this.lastReceivedTeleportId = lastReceivedTeleportId; + } + + public void setPortalCooldown(int portalCooldown) { + this.portalCooldown = portalCooldown; + } + /** * Represents the main or off hand of the player. */ diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index 5b023c248a6..caf81fffc24 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -1,6 +1,5 @@ package net.minestom.server.extras; -import lombok.Getter; import net.minestom.server.ServerStarterProvider; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.extras.mojangAuth.MojangCrypt; @@ -10,12 +9,9 @@ public final class MojangAuth { public final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); - @Getter private volatile boolean enabled = false; - @Getter private volatile KeyPair keyPair; private final ServerStarterProvider serverStarterProvider; - @Getter private final MojangCrypt mojangCrypt; public MojangAuth(ServerStarterProvider serverStarterProvider, ExceptionHandlerProvider exceptionHandlerProvider) { @@ -35,4 +31,16 @@ public void init() { // Generate necessary fields... keyPair = mojangCrypt.generateKeyPair(); } + + public boolean isEnabled() { + return this.enabled; + } + + public KeyPair getKeyPair() { + return this.keyPair; + } + + public MojangCrypt getMojangCrypt() { + return this.mojangCrypt; + } } diff --git a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java index 60aa9a53805..b3eea010405 100644 --- a/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java +++ b/src/main/java/net/minestom/server/extras/lan/OpenToLAN.java @@ -1,6 +1,5 @@ package net.minestom.server.extras.lan; -import lombok.RequiredArgsConstructor; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ServerListPingEvent; import net.minestom.server.network.ConnectionManager; @@ -31,7 +30,6 @@ * * @see wiki.vg */ -@RequiredArgsConstructor public class OpenToLAN { private final InetSocketAddress PING_ADDRESS = new InetSocketAddress("224.0.2.60", 4445); @@ -47,6 +45,13 @@ public class OpenToLAN { private final SchedulerManager schedulerManager; private final GlobalEventHandler globalEventHandler; + public OpenToLAN(ConnectionManager connectionManager, Server server, SchedulerManager schedulerManager, GlobalEventHandler globalEventHandler) { + this.connectionManager = connectionManager; + this.server = server; + this.schedulerManager = schedulerManager; + this.globalEventHandler = globalEventHandler; + } + /** * Opens the server to LAN with the default config. * diff --git a/src/main/java/net/minestom/server/instance/EntityTracker.java b/src/main/java/net/minestom/server/instance/EntityTracker.java index 41bffafd226..e121601dfca 100644 --- a/src/main/java/net/minestom/server/instance/EntityTracker.java +++ b/src/main/java/net/minestom/server/instance/EntityTracker.java @@ -89,6 +89,7 @@ void nearbyEntities(@NotNull Point point, double range, */ @ApiStatus.NonExtendable interface Target { + Target ENTITIES = create(Entity.class); Target PLAYERS = create(Player.class); Target ITEMS = create(ItemEntity.class); @@ -114,12 +115,14 @@ public int ordinal() { } }; } + } /** * Callback to know the newly visible entities and those to remove. */ interface Update { + void add(@NotNull E entity); void remove(@NotNull E entity); @@ -127,5 +130,6 @@ interface Update { default void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracker) { // Empty } + } } diff --git a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java index 4089fd7df85..d3851a9f1e1 100644 --- a/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java +++ b/src/main/java/net/minestom/server/instance/EntityTrackerImpl.java @@ -1,7 +1,6 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import lombok.RequiredArgsConstructor; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.Viewable; import net.minestom.server.coordinate.Point; @@ -27,9 +26,8 @@ import static net.minestom.server.instance.Chunk.CHUNK_SIZE_Z; import static net.minestom.server.utils.chunk.ChunkUtils.*; -@RequiredArgsConstructor final class EntityTrackerImpl implements EntityTracker { - + private final ServerSettingsProvider serverSettingsProvider; static final AtomicInteger TARGET_COUNTER = new AtomicInteger(); @@ -39,7 +37,9 @@ final class EntityTrackerImpl implements EntityTracker { final TargetEntry[] entries = EntityTracker.Target.TARGETS.stream().map((Function, TargetEntry>) TargetEntry::new).toArray(TargetEntry[]::new); private final Int2ObjectSyncMap entityPositions = Int2ObjectSyncMap.hashmap(); - + public EntityTrackerImpl(ServerSettingsProvider serverSettingsProvider) { + this.serverSettingsProvider = serverSettingsProvider; + } @Override public void register(@NotNull Entity entity, @NotNull Point point, diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index f05aed5fa09..da5c1a56d09 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -1,9 +1,6 @@ package net.minestom.server.instance; import it.unimi.dsi.fastutil.objects.ObjectArraySet; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointers; import net.minestom.server.ServerSettings; @@ -64,71 +61,51 @@ * with {@link InstanceManagerImpl#registerInstance(Instance)}, and * you need to be sure to signal the {@link ThreadDispatcherImpl} of every partition/element changes. */ -public abstract class Instance implements Block.Getter, Block.Setter, - Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { +public abstract class Instance implements Block.Getter, Block.Setter, Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { - @Getter // FIXME bad shit private final ServerSettingsProvider serverSettingsProvider; private final EventNode globalEventHandler; - @Getter - @Setter(lombok.AccessLevel.PROTECTED) - private boolean registered; + private boolean registered; - @Getter private final DimensionType dimensionType; - @Getter private final NamespaceID dimensionName; - @Getter private final WorldBorder worldBorder; - // Tick since the creation of the instance - @Getter private long worldAge; // The time of the instance - @Getter private long time; - @Getter + private int timeRate = 1; - @Setter - @Getter + private Duration timeUpdate = Duration.of(1, TimeUnit.SECOND); private long lastTimeUpdate; // Field for tick events private long lastTickAge = System.currentTimeMillis(); - @Getter private final EntityTracker entityTracker; private final ChunkCache blockRetriever = new ChunkCache(this, null, null); // the uuid of this instance - @Getter protected UUID uniqueId; // instance custom data - @Getter - @Accessors(fluent = true) protected TagHandler tagHandler = TagHandler.newHandler(); - @Getter private final Scheduler scheduler = Scheduler.newScheduler(); - @Getter private final EventNode eventNode; // the explosion supplier private ExplosionSupplier explosionSupplier; // Pathfinder - @Getter private final PFInstanceSpace instanceSpace = new PFInstanceSpace(this); // Adventure - @Getter - @Accessors(fluent = true) private final Pointers pointers; /** @@ -668,4 +645,76 @@ public void setExplosionSupplier(@Nullable ExplosionSupplier supplier) { public ServerSettings getServerSettings() { return serverSettingsProvider.getServerSettings(); } + + public ServerSettingsProvider getServerSettingsProvider() { + return this.serverSettingsProvider; + } + + public boolean isRegistered() { + return this.registered; + } + + public DimensionType getDimensionType() { + return this.dimensionType; + } + + public NamespaceID getDimensionName() { + return this.dimensionName; + } + + public WorldBorder getWorldBorder() { + return this.worldBorder; + } + + public long getWorldAge() { + return this.worldAge; + } + + public long getTime() { + return this.time; + } + + public int getTimeRate() { + return this.timeRate; + } + + public Duration getTimeUpdate() { + return this.timeUpdate; + } + + public EntityTracker getEntityTracker() { + return this.entityTracker; + } + + public UUID getUniqueId() { + return this.uniqueId; + } + + public TagHandler tagHandler() { + return this.tagHandler; + } + + public Scheduler getScheduler() { + return this.scheduler; + } + + public EventNode getEventNode() { + return this.eventNode; + } + + public PFInstanceSpace getInstanceSpace() { + return this.instanceSpace; + } + + public Pointers pointers() { + return this.pointers; + } + + protected void setRegistered(boolean registered) { + this.registered = registered; + } + + public void setTimeUpdate(Duration timeUpdate) { + this.timeUpdate = timeUpdate; + } } diff --git a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java index cabd9831b2d..4cf4ed0250b 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java +++ b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java @@ -1,6 +1,5 @@ package net.minestom.server.instance; -import lombok.RequiredArgsConstructor; import net.minestom.server.MinecraftServer; import net.minestom.server.ServerSettingsProvider; import net.minestom.server.event.GlobalEventHandlerProvider; @@ -22,7 +21,6 @@ import java.util.UUID; import java.util.concurrent.CopyOnWriteArraySet; -@RequiredArgsConstructor public final class InstanceManagerImpl implements InstanceManager { private final ChunkDispatcherProvider chunkDispatcherProvider; private final GlobalEventHandlerProvider globalEventHandlerProvider; @@ -37,6 +35,15 @@ public InstanceManagerImpl(MinecraftServer minecraftServer) { private final Set instances = new CopyOnWriteArraySet<>(); + public InstanceManagerImpl(ChunkDispatcherProvider chunkDispatcherProvider, GlobalEventHandlerProvider globalEventHandlerProvider, ServerSettingsProvider serverSettingsProvider, ExceptionHandlerProvider exceptionHandlerProvider, BlockManagerProvider blockManagerProvider, BiomeManagerProvider biomeManagerProvider) { + this.chunkDispatcherProvider = chunkDispatcherProvider; + this.globalEventHandlerProvider = globalEventHandlerProvider; + this.serverSettingsProvider = serverSettingsProvider; + this.exceptionHandlerProvider = exceptionHandlerProvider; + this.blockManagerProvider = blockManagerProvider; + this.biomeManagerProvider = biomeManagerProvider; + } + @Override public void registerInstance(@NotNull Instance instance) { Check.stateCondition(instance instanceof SharedInstance, "Please use InstanceManager#registerSharedInstance to register a shared instance"); diff --git a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java index 134d61c4281..f97861681d7 100644 --- a/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java +++ b/src/main/java/net/minestom/server/monitoring/BenchmarkManagerImpl.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; -import lombok.RequiredArgsConstructor; import net.minestom.server.MinecraftServer; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.utils.validate.Check; @@ -20,7 +19,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -@RequiredArgsConstructor public final class BenchmarkManagerImpl implements BenchmarkManager { private final static Logger LOGGER = LoggerFactory.getLogger(BenchmarkManagerImpl.class); private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); @@ -37,12 +35,15 @@ public final class BenchmarkManagerImpl implements BenchmarkManager { private final Long2LongMap lastBlockedMap = new Long2LongOpenHashMap(); private final Map resultMap = new ConcurrentHashMap<>(); - @lombok.Getter private boolean enabled = false; private volatile boolean stop = false; private long time; private final ExceptionHandlerProvider exceptionHandlerProvider; + public BenchmarkManagerImpl(ExceptionHandlerProvider exceptionHandlerProvider) { + this.exceptionHandlerProvider = exceptionHandlerProvider; + } + @Override public void enable(@NotNull Duration duration) { Check.stateCondition(enabled, "A benchmark is already running, please disable it first."); @@ -133,4 +134,8 @@ private void refreshData() { resultMap.put(name, threadResult); } } + + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/net/minestom/server/network/player/PlayerConnection.java b/src/main/java/net/minestom/server/network/player/PlayerConnection.java index b487aebcdab..97b9c127833 100644 --- a/src/main/java/net/minestom/server/network/player/PlayerConnection.java +++ b/src/main/java/net/minestom/server/network/player/PlayerConnection.java @@ -1,7 +1,5 @@ package net.minestom.server.network.player; -import lombok.Getter; -import lombok.Setter; import net.minestom.server.MinecraftServer; import net.minestom.server.crypto.PlayerPublicKey; import net.minestom.server.entity.Entity; @@ -25,16 +23,9 @@ public abstract class PlayerConnection { private final ServerProvider serverProvider; private final ConnectionManagerProvider connectionManagerProvider; - @Setter - @Getter private Player player; - @Setter - @Getter private volatile ConnectionState connectionState; - @Getter - @Setter private PlayerPublicKey playerPublicKey; - @Getter volatile boolean online; public PlayerConnection(ServerProvider serverProvider, ConnectionManagerProvider connectionManagerProvider) { @@ -132,4 +123,32 @@ public String toString() { ", identifier=" + getIdentifier() + '}'; } + + public Player getPlayer() { + return this.player; + } + + public ConnectionState getConnectionState() { + return this.connectionState; + } + + public PlayerPublicKey getPlayerPublicKey() { + return this.playerPublicKey; + } + + public boolean isOnline() { + return this.online; + } + + public void setPlayer(Player player) { + this.player = player; + } + + public void setConnectionState(ConnectionState connectionState) { + this.connectionState = connectionState; + } + + public void setPlayerPublicKey(PlayerPublicKey playerPublicKey) { + this.playerPublicKey = playerPublicKey; + } } diff --git a/src/main/java/net/minestom/server/ping/ResponseData.java b/src/main/java/net/minestom/server/ping/ResponseData.java index 1ad5425508c..76847dea930 100644 --- a/src/main/java/net/minestom/server/ping/ResponseData.java +++ b/src/main/java/net/minestom/server/ping/ResponseData.java @@ -1,7 +1,6 @@ package net.minestom.server.ping; import com.google.gson.JsonObject; -import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; @@ -24,7 +23,6 @@ public class ResponseData { private static final Component DEFAULT_DESCRIPTION = Component.text("Minestom Server"); private final List entries; - @Getter private final Server server; private String version; @@ -330,6 +328,10 @@ public boolean arePlayersHidden() { return ServerListPingType.getModernPingResponse(this, true); } + public Server getServer() { + return this.server; + } + /** * Represents a player line in the server list hover. * diff --git a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java index 610a4038fae..ead7dbe7448 100644 --- a/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java +++ b/src/main/java/net/minestom/server/scoreboard/BelowNameTag.java @@ -1,6 +1,5 @@ package net.minestom.server.scoreboard; -import lombok.Getter; import net.kyori.adventure.text.Component; import net.minestom.server.ServerSettings; import net.minestom.server.entity.Player; @@ -26,7 +25,6 @@ public class BelowNameTag implements Scoreboard { private final String objectiveName; private final ScoreboardObjectivePacket scoreboardObjectivePacket; - @Getter private final ServerSettings serverSettings; /** @@ -84,4 +82,8 @@ public boolean removeViewer(@NotNull Player player) { public Set getViewers() { return unmodifiableViewers; } + + public ServerSettings getServerSettings() { + return this.serverSettings; + } } diff --git a/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java b/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java index 10732012286..4b3c4ac0851 100644 --- a/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java +++ b/src/main/java/net/minestom/server/scoreboard/TeamManagerImpl.java @@ -1,6 +1,5 @@ package net.minestom.server.scoreboard; -import lombok.RequiredArgsConstructor; import net.minestom.server.ServerSettings; import net.minestom.server.network.ConnectionManager; import net.minestom.server.utils.PacketUtils; @@ -12,7 +11,6 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; -@RequiredArgsConstructor public final class TeamManagerImpl implements TeamManager { /** @@ -22,6 +20,10 @@ public final class TeamManagerImpl implements TeamManager { private final ServerSettings serverSettings; + public TeamManagerImpl(ServerSettings serverSettings) { + this.serverSettings = serverSettings; + } + /** * Registers a new {@link Team} * diff --git a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java index f7d5fc90d6b..243ee92d82d 100644 --- a/src/main/java/net/minestom/server/utils/entity/EntityFinder.java +++ b/src/main/java/net/minestom/server/utils/entity/EntityFinder.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.objects.Object2BooleanMaps; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; -import lombok.RequiredArgsConstructor; import net.minestom.server.command.CommandSender; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -28,7 +27,6 @@ * Represents a query which can be call to find one or multiple entities. * It is based on the target selectors used in commands. */ -@RequiredArgsConstructor public class EntityFinder { private final InstanceManager instanceManager; private final ConnectionManager connectionManager; @@ -55,6 +53,11 @@ public class EntityFinder { private final ToggleableMap gameModes = new ToggleableMap<>(); private IntRange level; + public EntityFinder(InstanceManager instanceManager, ConnectionManager connectionManager) { + this.instanceManager = instanceManager; + this.connectionManager = connectionManager; + } + public EntityFinder setTargetSelector(@NotNull TargetSelector targetSelector) { this.targetSelector = targetSelector; return this; @@ -310,8 +313,8 @@ private static class ToggleableMap extends Object2BooleanOpenHashMap { } private @NotNull List<@NotNull Entity> findTarget(@Nullable Instance instance, - @NotNull TargetSelector targetSelector, - @NotNull Point startPosition, @Nullable Entity self) { + @NotNull TargetSelector targetSelector, + @NotNull Point startPosition, @Nullable Entity self) { final var players = instance != null ? instance.getPlayers() : connectionManager.getOnlinePlayers(); if (targetSelector == TargetSelector.NEAREST_PLAYER) { return players.stream() From 727317625a78319cca22a031cf21c63cb653c44f Mon Sep 17 00:00:00 2001 From: MelonHell Date: Thu, 1 Feb 2024 10:31:09 +0300 Subject: [PATCH 14/16] rename ServerStarter to ServerProcess --- demo/src/main/java/net/minestom/demo/Main.java | 2 +- .../demo/commands/ShutdownCommand.java | 2 +- .../net/minestom/server/MinecraftServer.java | 2 +- .../minestom/server/MinecraftServerImpl.java | 8 ++++---- .../net/minestom/server/ServerProcess.java | 18 ++++++++++++++++++ ...rverStarter.java => ServerProcessImpl.java} | 16 +++++++--------- .../minestom/server/ServerProcessProvider.java | 5 +++++ .../minestom/server/ServerStarterProvider.java | 5 ----- .../net/minestom/server/extras/MojangAuth.java | 10 +++++----- .../server/thread/TickSchedulerThread.java | 10 +++++----- 10 files changed, 47 insertions(+), 31 deletions(-) create mode 100644 src/main/java/net/minestom/server/ServerProcess.java rename src/main/java/net/minestom/server/{ServerStarter.java => ServerProcessImpl.java} (85%) create mode 100644 src/main/java/net/minestom/server/ServerProcessProvider.java delete mode 100644 src/main/java/net/minestom/server/ServerStarterProvider.java diff --git a/demo/src/main/java/net/minestom/demo/Main.java b/demo/src/main/java/net/minestom/demo/Main.java index f2c0c7c2ee0..0e8f9ec8621 100644 --- a/demo/src/main/java/net/minestom/demo/Main.java +++ b/demo/src/main/java/net/minestom/demo/Main.java @@ -140,7 +140,7 @@ public boolean shouldShow(@NotNull Player player) { // useful for testing - we don't need to worry about event calls so just set this to a long time new OpenToLAN(minecraftServer.getConnectionManager(), minecraftServer.getServer(), minecraftServer.getSchedulerManager(), minecraftServer.getGlobalEventHandler()).open(new OpenToLANConfig().eventCallDelay(Duration.of(1, TimeUnit.DAY))); - minecraftServer.getServerStarter().start("0.0.0.0", 25565); + minecraftServer.getServerProcess().start("0.0.0.0", 25565); // minecraftServer.start(java.net.UnixDomainSocketAddress.of("minestom-demo.sock")); //Runtime.getRuntime().addShutdownHook(new Thread(MinecraftServer::stopCleanly)); } diff --git a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java index 16c43721d48..28949337240 100644 --- a/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java +++ b/demo/src/main/java/net/minestom/demo/commands/ShutdownCommand.java @@ -20,6 +20,6 @@ public ShutdownCommand(MinecraftServer minecraftServer) { } private void execute(@NotNull CommandSender commandSender, @NotNull CommandContext commandContext) { - minecraftServer.getServerStarter().stop(); + minecraftServer.getServerProcess().stop(); } } diff --git a/src/main/java/net/minestom/server/MinecraftServer.java b/src/main/java/net/minestom/server/MinecraftServer.java index 8879f9125e6..9f38e92c14c 100644 --- a/src/main/java/net/minestom/server/MinecraftServer.java +++ b/src/main/java/net/minestom/server/MinecraftServer.java @@ -47,7 +47,7 @@ public interface MinecraftServer extends ServerSettingsProvider, AudienceManagerProvider, MojangAuthProvider, - ServerStarterProvider + ServerProcessProvider { ComponentLogger LOGGER = ComponentLogger.logger(MinecraftServer.class); String VERSION_NAME = "1.20.4"; diff --git a/src/main/java/net/minestom/server/MinecraftServerImpl.java b/src/main/java/net/minestom/server/MinecraftServerImpl.java index 37e40881131..2e602f19e1f 100644 --- a/src/main/java/net/minestom/server/MinecraftServerImpl.java +++ b/src/main/java/net/minestom/server/MinecraftServerImpl.java @@ -68,7 +68,7 @@ final class MinecraftServerImpl implements MinecraftServer { private final ServerSettings serverSettings; private final AudienceManager audienceManager; private final MojangAuth mojangAuth; - private final ServerStarter serverStarter; + private final ServerProcess serverProcess; public MinecraftServerImpl(ServerSettings serverSettings) { @@ -96,7 +96,7 @@ public MinecraftServerImpl(ServerSettings serverSettings) { this.server = new ServerImpl(serverSettings, this); this.audienceManager = new AudienceManagerImpl(commandManager, this, this); this.ticker = new TickerImpl(this); - this.serverStarter = new ServerStarter(this); + this.serverProcess = new ServerProcessImpl(this); this.mojangAuth = new MojangAuth(this, this); } @@ -192,7 +192,7 @@ public MojangAuth getMojangAuth() { return this.mojangAuth; } - public ServerStarter getServerStarter() { - return this.serverStarter; + public ServerProcess getServerProcess() { + return this.serverProcess; } } diff --git a/src/main/java/net/minestom/server/ServerProcess.java b/src/main/java/net/minestom/server/ServerProcess.java new file mode 100644 index 00000000000..f0f15ea871c --- /dev/null +++ b/src/main/java/net/minestom/server/ServerProcess.java @@ -0,0 +1,18 @@ +package net.minestom.server; + +import org.jetbrains.annotations.NotNull; + +import java.net.InetSocketAddress; +import java.net.SocketAddress; + +public interface ServerProcess { + void start(@NotNull SocketAddress socketAddress); + + default void start(@NotNull String hostname, int port) { + start(new InetSocketAddress(hostname, port)); + } + + void stop(); + + boolean isAlive(); +} diff --git a/src/main/java/net/minestom/server/ServerStarter.java b/src/main/java/net/minestom/server/ServerProcessImpl.java similarity index 85% rename from src/main/java/net/minestom/server/ServerStarter.java rename to src/main/java/net/minestom/server/ServerProcessImpl.java index 725b29bd53b..f840c1b19e3 100644 --- a/src/main/java/net/minestom/server/ServerStarter.java +++ b/src/main/java/net/minestom/server/ServerProcessImpl.java @@ -12,12 +12,11 @@ import org.slf4j.LoggerFactory; import java.io.IOException; -import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.atomic.AtomicBoolean; -public class ServerStarter { - private static final Logger LOGGER = LoggerFactory.getLogger(ServerStarter.class); +public class ServerProcessImpl implements ServerProcess { + private static final Logger LOGGER = LoggerFactory.getLogger(ServerProcessImpl.class); private final ServerSettingsProvider serverSettingsProvider; private final ServerProvider serverProvider; @@ -28,14 +27,14 @@ public class ServerStarter { private final ChunkDispatcherProvider chunkDispatcherProvider; private final TickerProvider tickerProvider; - public ServerStarter(MinecraftServer minecraftServer) { + public ServerProcessImpl(MinecraftServer minecraftServer) { this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); - public ServerStarter(ServerSettingsProvider serverSettingsProvider, ServerProvider serverProvider, ExceptionHandlerProvider exceptionHandlerProvider, SchedulerManagerProvider schedulerManagerProvider, ConnectionManagerProvider connectionManagerProvider, BenchmarkManagerProvider benchmarkManagerProvider, ChunkDispatcherProvider chunkDispatcherProvider, TickerProvider tickerProvider) { + public ServerProcessImpl(ServerSettingsProvider serverSettingsProvider, ServerProvider serverProvider, ExceptionHandlerProvider exceptionHandlerProvider, SchedulerManagerProvider schedulerManagerProvider, ConnectionManagerProvider connectionManagerProvider, BenchmarkManagerProvider benchmarkManagerProvider, ChunkDispatcherProvider chunkDispatcherProvider, TickerProvider tickerProvider) { this.serverSettingsProvider = serverSettingsProvider; this.serverProvider = serverProvider; this.exceptionHandlerProvider = exceptionHandlerProvider; @@ -46,6 +45,7 @@ public ServerStarter(ServerSettingsProvider serverSettingsProvider, ServerProvid this.tickerProvider = tickerProvider; } + @Override public void start(@NotNull SocketAddress socketAddress) { if (!started.compareAndSet(false, true)) { throw new IllegalStateException("Server already started"); @@ -73,10 +73,7 @@ public void start(@NotNull SocketAddress socketAddress) { new TickSchedulerThread(serverSettingsProvider.getServerSettings(), tickerProvider.getTicker(), this, exceptionHandlerProvider.getExceptionHandler()).start(); } - public void start(@NotNull String hostname, int port) { - start(new InetSocketAddress(hostname, port)); - } - + @Override public void stop() { if (!stopped.compareAndSet(false, true)) return; @@ -90,6 +87,7 @@ public void stop() { LOGGER.info(serverSettingsProvider.getServerSettings().getBrandName() + " server stopped successfully."); } + @Override public boolean isAlive() { return started.get() && !stopped.get(); } diff --git a/src/main/java/net/minestom/server/ServerProcessProvider.java b/src/main/java/net/minestom/server/ServerProcessProvider.java new file mode 100644 index 00000000000..f653834c0d0 --- /dev/null +++ b/src/main/java/net/minestom/server/ServerProcessProvider.java @@ -0,0 +1,5 @@ +package net.minestom.server; + +public interface ServerProcessProvider { + ServerProcess getServerProcess(); +} diff --git a/src/main/java/net/minestom/server/ServerStarterProvider.java b/src/main/java/net/minestom/server/ServerStarterProvider.java deleted file mode 100644 index 3157e9631f7..00000000000 --- a/src/main/java/net/minestom/server/ServerStarterProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package net.minestom.server; - -public interface ServerStarterProvider { - ServerStarter getServerStarter(); -} diff --git a/src/main/java/net/minestom/server/extras/MojangAuth.java b/src/main/java/net/minestom/server/extras/MojangAuth.java index caf81fffc24..8b878fad54e 100644 --- a/src/main/java/net/minestom/server/extras/MojangAuth.java +++ b/src/main/java/net/minestom/server/extras/MojangAuth.java @@ -1,6 +1,6 @@ package net.minestom.server.extras; -import net.minestom.server.ServerStarterProvider; +import net.minestom.server.ServerProcessProvider; import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.extras.mojangAuth.MojangCrypt; import net.minestom.server.utils.validate.Check; @@ -11,11 +11,11 @@ public final class MojangAuth { public final String AUTH_URL = System.getProperty("minestom.auth.url", "https://sessionserver.mojang.com/session/minecraft/hasJoined").concat("?username=%s&serverId=%s"); private volatile boolean enabled = false; private volatile KeyPair keyPair; - private final ServerStarterProvider serverStarterProvider; + private final ServerProcessProvider serverProcessProvider; private final MojangCrypt mojangCrypt; - public MojangAuth(ServerStarterProvider serverStarterProvider, ExceptionHandlerProvider exceptionHandlerProvider) { - this.serverStarterProvider = serverStarterProvider; + public MojangAuth(ServerProcessProvider serverProcessProvider, ExceptionHandlerProvider exceptionHandlerProvider) { + this.serverProcessProvider = serverProcessProvider; this.mojangCrypt = new MojangCrypt(exceptionHandlerProvider); } @@ -26,7 +26,7 @@ public MojangAuth(ServerStarterProvider serverStarterProvider, ExceptionHandlerP */ public void init() { Check.stateCondition(enabled, "Mojang auth is already enabled!"); - Check.stateCondition(serverStarterProvider.getServerStarter().isAlive(), "The server has already been started!"); + Check.stateCondition(serverProcessProvider.getServerProcess().isAlive(), "The server has already been started!"); enabled = true; // Generate necessary fields... keyPair = mojangCrypt.generateKeyPair(); diff --git a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java index 634a6258cfd..d37ab861569 100644 --- a/src/main/java/net/minestom/server/thread/TickSchedulerThread.java +++ b/src/main/java/net/minestom/server/thread/TickSchedulerThread.java @@ -1,8 +1,8 @@ package net.minestom.server.thread; import net.minestom.server.MinecraftServer; +import net.minestom.server.ServerProcess; import net.minestom.server.ServerSettings; -import net.minestom.server.ServerStarter; import net.minestom.server.Ticker; import net.minestom.server.exception.ExceptionHandler; import org.jetbrains.annotations.ApiStatus; @@ -15,22 +15,22 @@ public final class TickSchedulerThread extends MinestomThread { private final long startTickNs = System.nanoTime(); private final ServerSettings serverSettings; private final Ticker ticker; - private final ServerStarter serverStarter; + private final ServerProcess serverProcess; private final ExceptionHandler exceptionHandler; private long tick = 1; - public TickSchedulerThread(ServerSettings serverSettings, Ticker ticker, ServerStarter serverStarter, ExceptionHandler exceptionHandler) { + public TickSchedulerThread(ServerSettings serverSettings, Ticker ticker, ServerProcess serverProcess, ExceptionHandler exceptionHandler) { super(MinecraftServer.THREAD_NAME_TICK_SCHEDULER); this.serverSettings = serverSettings; this.ticker = ticker; - this.serverStarter = serverStarter; + this.serverProcess = serverProcess; this.exceptionHandler = exceptionHandler; } @Override public void run() { final long tickNs = (long) (serverSettings.getTickMs() * 1e6); - while (serverStarter.isAlive()) { + while (serverProcess.isAlive()) { final long tickStart = System.nanoTime(); try { ticker.tick(tickStart); From ea581510106f04dda0e1b2ec1d5f8b43fefa25ae Mon Sep 17 00:00:00 2001 From: MelonHell Date: Thu, 1 Feb 2024 10:45:21 +0300 Subject: [PATCH 15/16] fix getters after delombok (Player) --- .../net/minestom/server/entity/Player.java | 148 +++++++++++------- .../listener/PlayerPositionListener.java | 2 +- 2 files changed, 96 insertions(+), 54 deletions(-) diff --git a/src/main/java/net/minestom/server/entity/Player.java b/src/main/java/net/minestom/server/entity/Player.java index b317f3d387c..f85c5842e34 100644 --- a/src/main/java/net/minestom/server/entity/Player.java +++ b/src/main/java/net/minestom/server/entity/Player.java @@ -185,7 +185,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable, private final AtomicInteger teleportId = new AtomicInteger(); - private int lastReceivedTeleportId; + private int receivedTeleportId; private final MessagePassingQueue packets = new MpscUnboundedXaddArrayQueue<>(32); private final boolean levelFlat; @@ -1210,6 +1210,16 @@ public void setDisplayName(@Nullable Component displayName) { PacketUtils.broadcastPlayPacket(connectionManagerProvider.getConnectionManager(), serverSettingsProvider, new PlayerInfoUpdatePacket(PlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, infoEntry())); } + /** + * Gets the player skin. + * + * @return the player skin object, + * null means that the player has his {@link #getUuid()} default skin + */ + public @Nullable PlayerSkin getSkin() { + return skin; + } + /** * Changes the player skin. *

          @@ -1512,6 +1522,14 @@ public void setLevel(int level) { sendPacket(new SetExperiencePacket(exp, level, 0)); } + public int getPortalCooldown() { + return portalCooldown; + } + + public void setPortalCooldown(int portalCooldown) { + this.portalCooldown = portalCooldown; + } + /** * Shortcut for {@link PlayerConnection#sendPacket(SendablePacket)}. * @@ -1541,6 +1559,47 @@ public boolean isOnline() { return playerConnection.isOnline(); } + /** + * Gets the player settings. + * + * @return the player settings + */ + public @NotNull PlayerSettings getSettings() { + return settings; + } + + /** + * Gets the player dimension. + * + * @return the player current dimension + */ + public DimensionType getDimensionType() { + return dimensionType; + } + + public @NotNull PlayerInventory getInventory() { + return inventory; + } + + /** + * Used to get the player latency, + * computed by seeing how long it takes the client to answer the {@link KeepAlivePacket} packet. + * + * @return the player latency + */ + public int getLatency() { + return latency; + } + + /** + * Gets the player {@link GameMode}. + * + * @return the player current gamemode + */ + public GameMode getGameMode() { + return gameMode; + } + /** * Changes the player {@link GameMode} * @@ -1655,6 +1714,15 @@ public void setHeldItemSlot(byte slot) { sendPacket(new HeldItemChangePacket(slot)); } + /** + * Gets the player held slot (0-8). + * + * @return the current held slot for the player + */ + public byte getHeldSlot() { + return heldSlot; + } + /** * Changes the tag below the name. * @@ -1782,6 +1850,14 @@ public int getLastSentTeleportId() { return teleportId.get(); } + public int getLastReceivedTeleportId() { + return receivedTeleportId; + } + + public void refreshReceivedTeleportId(int receivedTeleportId) { + this.receivedTeleportId = receivedTeleportId; + } + /** * @see Entity#synchronizePosition(boolean) */ @@ -1794,6 +1870,15 @@ protected void synchronizePosition(boolean includeSelf) { super.synchronizePosition(includeSelf); } + /** + * Gets the player permission level. + * + * @return the player permission level + */ + public int getPermissionLevel() { + return permissionLevel; + } + /** * Changes the player permission level. * @@ -2137,6 +2222,15 @@ public void refreshVehicleSteer(float sideways, float forward, boolean jump, boo this.vehicleInformation.refresh(sideways, forward, jump, unmount); } + /** + * Gets the last sent keep alive id. + * + * @return the last keep alive id sent to the player + */ + public long getLastKeepAlive() { + return lastKeepAlive; + } + @Override public @NotNull HoverEvent asHoverEvent(@NotNull UnaryOperator op) { return HoverEvent.showEntity(ShowEntity.showEntity(EntityType.PLAYER, this.uuid, this.displayName)); @@ -2318,10 +2412,6 @@ protected void sendChunkUpdates(Chunk newChunk) { return super.teleport(position, chunks); } - public long getLastKeepAlive() { - return this.lastKeepAlive; - } - public ConnectionManagerProvider getConnectionManagerProvider() { return this.connectionManagerProvider; } @@ -2338,54 +2428,6 @@ public PlayerConnection getPlayerConnection() { return this.playerConnection; } - public int getLatency() { - return this.latency; - } - - public PlayerSkin getSkin() { - return this.skin; - } - - public DimensionType getDimensionType() { - return this.dimensionType; - } - - public GameMode getGameMode() { - return this.gameMode; - } - - public int getLastReceivedTeleportId() { - return this.lastReceivedTeleportId; - } - - public PlayerSettings getSettings() { - return this.settings; - } - - public int getPortalCooldown() { - return this.portalCooldown; - } - - public PlayerInventory getInventory() { - return this.inventory; - } - - public byte getHeldSlot() { - return this.heldSlot; - } - - public int getPermissionLevel() { - return this.permissionLevel; - } - - public void setLastReceivedTeleportId(int lastReceivedTeleportId) { - this.lastReceivedTeleportId = lastReceivedTeleportId; - } - - public void setPortalCooldown(int portalCooldown) { - this.portalCooldown = portalCooldown; - } - /** * Represents the main or off hand of the player. */ diff --git a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java index c817f89f150..98bdbfd4ff4 100644 --- a/src/main/java/net/minestom/server/listener/PlayerPositionListener.java +++ b/src/main/java/net/minestom/server/listener/PlayerPositionListener.java @@ -28,7 +28,7 @@ public static void playerPositionAndLookListener(ClientPlayerPositionAndRotation } public static void teleportConfirmListener(ClientTeleportConfirmPacket packet, Player player) { - player.setLastReceivedTeleportId(packet.teleportId()); + player.refreshReceivedTeleportId(packet.teleportId()); } private static void processMovement(@NotNull Player player, @NotNull Pos packetPosition, boolean onGround) { From dce8a8f8fa961a1aa0e31d2bad78a325e0b66928 Mon Sep 17 00:00:00 2001 From: MelonHell Date: Thu, 8 Feb 2024 00:43:48 +0300 Subject: [PATCH 16/16] simplify chunk constructor "The server from the Instance should be passed into the chunk supplier, this should remain a method reference." --- .../java/net/minestom/demo/PlayerInit.java | 4 +- .../server/instance/DynamicChunk.java | 15 +++---- .../minestom/server/instance/Instance.java | 40 +++++++++++++++---- .../server/instance/InstanceContainer.java | 13 ++++-- .../server/instance/InstanceManagerImpl.java | 21 +++++++--- .../server/instance/LightingChunk.java | 24 +++-------- .../server/instance/SharedInstance.java | 8 ++-- .../server/utils/time/TickTimeUnit.java | 26 ++++++++++++ 8 files changed, 102 insertions(+), 49 deletions(-) create mode 100644 src/main/java/net/minestom/server/utils/time/TickTimeUnit.java diff --git a/demo/src/main/java/net/minestom/demo/PlayerInit.java b/demo/src/main/java/net/minestom/demo/PlayerInit.java index 5d67f56e2ff..bace93fa3f1 100644 --- a/demo/src/main/java/net/minestom/demo/PlayerInit.java +++ b/demo/src/main/java/net/minestom/demo/PlayerInit.java @@ -55,7 +55,7 @@ public PlayerInit(MinecraftServer minecraftServer) { InstanceContainer instanceContainer = instanceManager.createInstanceContainer(DimensionType.OVERWORLD); instanceContainer.setGenerator(unit -> unit.modifier().fillHeight(0, 40, Block.STONE)); - instanceContainer.setChunkSupplier((instance, chunkX, chunkZ) -> new LightingChunk(minecraftServer, instance, chunkX, chunkZ)); + instanceContainer.setChunkSupplier(LightingChunk::new); // var i2 = new InstanceContainer(UUID.randomUUID(), DimensionType.OVERWORLD, null, NamespaceID.from("minestom:demo")); // instanceManager.registerInstance(i2); @@ -225,4 +225,4 @@ public void init() { minecraftServer.getAudienceManager().players().sendPlayerListHeaderAndFooter(header, footer); }).repeat(10, TimeUnit.getServerTick(minecraftServer.getServerSettings())); //.schedule(); } -} +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java index a5853a54f08..8bf1055f209 100644 --- a/src/main/java/net/minestom/server/instance/DynamicChunk.java +++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java @@ -23,7 +23,6 @@ import net.minestom.server.utils.ObjectPool; import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.world.biomes.Biome; -import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jglrxavpok.hephaistos.nbt.NBT; @@ -42,7 +41,6 @@ */ public class DynamicChunk extends Chunk { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicChunk.class); - protected final BiomeManagerProvider biomeManagerProvider; protected List

          sections; @@ -53,13 +51,12 @@ public class DynamicChunk extends Chunk { private long lastChange; final CachedPacket chunkCache; - public DynamicChunk(BiomeManagerProvider biomeManagerProvider, @NotNull Instance instance, int chunkX, int chunkZ) { + public DynamicChunk(@NotNull Instance instance, int chunkX, int chunkZ) { super(instance, chunkX, chunkZ, true); - this.biomeManagerProvider = biomeManagerProvider; var sectionsTemp = new Section[maxSection - minSection]; Arrays.setAll(sectionsTemp, value -> new Section()); this.sections = List.of(sectionsTemp); - chunkCache = new CachedPacket(instance.getServerSettingsProvider(), this::createChunkPacket); + chunkCache = new CachedPacket(instance::getServerSettings, this::createChunkPacket); } @Override @@ -183,7 +180,7 @@ public void tick(long time) { final Section section = getSectionAt(y); final int id = section.biomePalette() .get(toSectionRelativeCoordinate(x) / 4, toSectionRelativeCoordinate(y) / 4, toSectionRelativeCoordinate(z) / 4); - return biomeManagerProvider.getBiomeManager().getById(id); + return instance.getBiomeManager().getById(id); } @Override @@ -198,7 +195,7 @@ public long getLastChangeTime() { @Override public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) { - DynamicChunk dynamicChunk = new DynamicChunk(biomeManagerProvider, instance, chunkX, chunkZ); + DynamicChunk dynamicChunk = new DynamicChunk(instance, chunkX, chunkZ); dynamicChunk.sections = sections.stream().map(Section::clone).toList(); dynamicChunk.entries.putAll(entries); return dynamicChunk; @@ -316,7 +313,7 @@ protected LightData createLightData(boolean sendLater) { clonedSections[i] = sections.get(i).clone(); var entities = instance.getEntityTracker().chunkEntities(chunkX, chunkZ, EntityTracker.Target.ENTITIES); final int[] entityIds = ArrayUtils.mapToIntArray(entities, Entity::getEntityId); - return new SnapshotImpl.Chunk(biomeManagerProvider, minSection, chunkX, chunkZ, + return new SnapshotImpl.Chunk(instance::getBiomeManager, minSection, chunkX, chunkZ, clonedSections, entries.clone(), entityIds, updater.reference(instance), tagHandler().readableCopy()); } @@ -367,4 +364,4 @@ private static long[] encodeBlocks(int[] blocks, int bitsPerEntry) { return data; } -} +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/Instance.java b/src/main/java/net/minestom/server/instance/Instance.java index da5c1a56d09..0ddfd957ee9 100644 --- a/src/main/java/net/minestom/server/instance/Instance.java +++ b/src/main/java/net/minestom/server/instance/Instance.java @@ -13,7 +13,10 @@ import net.minestom.server.entity.ExperienceOrb; import net.minestom.server.entity.Player; import net.minestom.server.entity.pathfinding.PFInstanceSpace; -import net.minestom.server.event.*; +import net.minestom.server.event.EventFilter; +import net.minestom.server.event.EventHandler; +import net.minestom.server.event.EventNode; +import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.instance.InstanceTickEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; import net.minestom.server.event.trait.InstanceEvent; @@ -31,6 +34,8 @@ import net.minestom.server.thread.ThreadDispatcherImpl; import net.minestom.server.timer.Schedulable; import net.minestom.server.timer.Scheduler; +import net.minestom.server.timer.SchedulerManager; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.chunk.ChunkCache; @@ -40,6 +45,8 @@ import net.minestom.server.utils.time.TimeUnit; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; +import net.minestom.server.world.biomes.BiomeManager; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -64,7 +71,9 @@ public abstract class Instance implements Block.Getter, Block.Setter, Tickable, Schedulable, Snapshotable, EventHandler, Taggable, PacketGroupingAudience { private final ServerSettingsProvider serverSettingsProvider; - private final EventNode globalEventHandler; + private final SchedulerManagerProvider schedulerManagerProvider; + private final BiomeManagerProvider biomeManagerProvider; + private final GlobalEventHandler globalEventHandler; private boolean registered; @@ -117,10 +126,13 @@ public abstract class Instance implements Block.Getter, Block.Setter, Tickable, public Instance( @NotNull GlobalEventHandler globalEventHandler, @NotNull ServerSettingsProvider serverSettingsProvider, + @NotNull SchedulerManagerProvider schedulerManagerProvider, + @NotNull BiomeManagerProvider biomeManagerProvider, + @NotNull UUID uniqueId, @NotNull DimensionType dimensionType ) { - this(globalEventHandler, serverSettingsProvider, uniqueId, dimensionType, dimensionType.getName()); + this(globalEventHandler, serverSettingsProvider, schedulerManagerProvider, biomeManagerProvider, uniqueId, dimensionType, dimensionType.getName()); } /** @@ -132,15 +144,19 @@ public Instance( public Instance( @NotNull GlobalEventHandler globalEventHandler, @NotNull ServerSettingsProvider serverSettingsProvider, + @NotNull SchedulerManagerProvider schedulerManagerProvider, + @NotNull BiomeManagerProvider biomeManagerProvider, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @NotNull NamespaceID dimensionName ) { + Check.argCondition(!dimensionType.isRegistered(), "The dimension " + dimensionType.getName() + " is not registered! Please use DimensionTypeManager#addDimension"); this.globalEventHandler = globalEventHandler; - Check.argCondition(!dimensionType.isRegistered(), - "The dimension " + dimensionType.getName() + " is not registered! Please use DimensionTypeManager#addDimension"); this.serverSettingsProvider = serverSettingsProvider; + this.schedulerManagerProvider = schedulerManagerProvider; + this.biomeManagerProvider = biomeManagerProvider; + this.uniqueId = uniqueId; this.dimensionType = dimensionType; this.dimensionName = dimensionName; @@ -646,8 +662,16 @@ public ServerSettings getServerSettings() { return serverSettingsProvider.getServerSettings(); } - public ServerSettingsProvider getServerSettingsProvider() { - return this.serverSettingsProvider; + public BiomeManager getBiomeManager() { + return biomeManagerProvider.getBiomeManager(); + } + + public GlobalEventHandler getGlobalEventHandler() { + return globalEventHandler; + } + + public SchedulerManager getSchedulerManager() { + return schedulerManagerProvider.getSchedulerManager(); } public boolean isRegistered() { @@ -717,4 +741,4 @@ protected void setRegistered(boolean registered) { public void setTimeUpdate(Duration timeUpdate) { this.timeUpdate = timeUpdate; } -} +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/InstanceContainer.java b/src/main/java/net/minestom/server/instance/InstanceContainer.java index 5cd18a098c0..13816ab955d 100644 --- a/src/main/java/net/minestom/server/instance/InstanceContainer.java +++ b/src/main/java/net/minestom/server/instance/InstanceContainer.java @@ -24,6 +24,7 @@ import net.minestom.server.network.packet.server.play.EffectPacket; import net.minestom.server.network.packet.server.play.UnloadChunkPacket; import net.minestom.server.thread.ChunkDispatcherProvider; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.PacketUtils; import net.minestom.server.utils.async.AsyncUtils; @@ -70,6 +71,7 @@ public class InstanceContainer extends Instance { private final ServerSettingsProvider serverSettingsProvider; private final GlobalEventHandler globalEventHandler; private final ChunkDispatcherProvider chunkDispatcherProvider; + private final SchedulerManagerProvider schedulerManagerProvider; // the chunk generator used, can be null private volatile Generator generator; @@ -108,7 +110,7 @@ public InstanceContainer(MinecraftServer minecraftServer, @NotNull UUID uniqueId } public InstanceContainer(MinecraftServer minecraftServer, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName) { - this(minecraftServer.getGlobalEventHandler(), minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, uniqueId, dimensionType, loader, dimensionName); + this(minecraftServer.getGlobalEventHandler(), minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, uniqueId, dimensionType, loader, dimensionName); } @ApiStatus.Experimental @@ -120,20 +122,22 @@ public InstanceContainer( @NotNull BiomeManagerProvider biomeManagerProvider, @NotNull ServerSettingsProvider serverSettingsProvider, @NotNull ChunkDispatcherProvider chunkDispatcherProvider, + @NotNull SchedulerManagerProvider schedulerManagerProvider, @NotNull UUID uniqueId, @NotNull DimensionType dimensionType, @Nullable IChunkLoader loader, @NotNull NamespaceID dimensionName ) { - super(globalEventHandler, serverSettingsProvider, uniqueId, dimensionType, dimensionName); + super(globalEventHandler, serverSettingsProvider, schedulerManagerProvider, biomeManagerProvider, uniqueId, dimensionType, dimensionName); this.exceptionHandlerProvider = exceptionHandlerProvider; this.blockManagerProvider = blockManagerProvider; this.biomeManagerProvider = biomeManagerProvider; this.serverSettingsProvider = serverSettingsProvider; this.globalEventHandler = globalEventHandler; this.chunkDispatcherProvider = chunkDispatcherProvider; - setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(biomeManagerProvider, instance, chunkX, chunkZ)); + this.schedulerManagerProvider = schedulerManagerProvider; + setChunkSupplier((instance, chunkX, chunkZ) -> new DynamicChunk(instance, chunkX, chunkZ)); setChunkLoader(Objects.requireNonNullElseGet(loader, () -> new AnvilLoader(exceptionHandlerProvider, blockManagerProvider, biomeManagerProvider, "world"))); this.chunkLoader.loadInstance(this); } @@ -551,6 +555,7 @@ public synchronized InstanceContainer copy() { biomeManagerProvider, serverSettingsProvider, chunkDispatcherProvider, + schedulerManagerProvider, UUID.randomUUID(), getDimensionType(), null, getDimensionName()); copiedInstance.srcInstance = this; copiedInstance.tagHandler = this.tagHandler.copy(); @@ -708,4 +713,4 @@ private void cacheChunk(@NotNull Chunk chunk) { this.chunks.put(getChunkIndex(chunk), chunk); chunkDispatcherProvider.getChunkDispatcher().createPartition(chunk); } -} +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java index 4cf4ed0250b..58d0017b5ae 100644 --- a/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java +++ b/src/main/java/net/minestom/server/instance/InstanceManagerImpl.java @@ -8,6 +8,7 @@ import net.minestom.server.exception.ExceptionHandlerProvider; import net.minestom.server.instance.block.BlockManagerProvider; import net.minestom.server.thread.ChunkDispatcherProvider; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.validate.Check; import net.minestom.server.world.DimensionType; import net.minestom.server.world.biomes.BiomeManagerProvider; @@ -28,20 +29,30 @@ public final class InstanceManagerImpl implements InstanceManager { private final ExceptionHandlerProvider exceptionHandlerProvider; private final BlockManagerProvider blockManagerProvider; private final BiomeManagerProvider biomeManagerProvider; + private final SchedulerManagerProvider schedulerManagerProvider; public InstanceManagerImpl(MinecraftServer minecraftServer) { - this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); + this(minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer, minecraftServer); } private final Set instances = new CopyOnWriteArraySet<>(); - public InstanceManagerImpl(ChunkDispatcherProvider chunkDispatcherProvider, GlobalEventHandlerProvider globalEventHandlerProvider, ServerSettingsProvider serverSettingsProvider, ExceptionHandlerProvider exceptionHandlerProvider, BlockManagerProvider blockManagerProvider, BiomeManagerProvider biomeManagerProvider) { + public InstanceManagerImpl( + ChunkDispatcherProvider chunkDispatcherProvider, + GlobalEventHandlerProvider globalEventHandlerProvider, + ServerSettingsProvider serverSettingsProvider, + ExceptionHandlerProvider exceptionHandlerProvider, + BlockManagerProvider blockManagerProvider, + BiomeManagerProvider biomeManagerProvider, + SchedulerManagerProvider schedulerManagerProvider + ) { this.chunkDispatcherProvider = chunkDispatcherProvider; this.globalEventHandlerProvider = globalEventHandlerProvider; this.serverSettingsProvider = serverSettingsProvider; this.exceptionHandlerProvider = exceptionHandlerProvider; this.blockManagerProvider = blockManagerProvider; this.biomeManagerProvider = biomeManagerProvider; + this.schedulerManagerProvider = schedulerManagerProvider; } @Override @@ -53,7 +64,7 @@ public void registerInstance(@NotNull Instance instance) { @Override @ApiStatus.Experimental public @NotNull InstanceContainer createInstanceContainer(@NotNull DimensionType dimensionType, @Nullable IChunkLoader loader) { - final InstanceContainer instanceContainer = new InstanceContainer(globalEventHandlerProvider.getGlobalEventHandler(), exceptionHandlerProvider, blockManagerProvider, biomeManagerProvider, serverSettingsProvider, chunkDispatcherProvider, UUID.randomUUID(), dimensionType, loader, dimensionType.getName()); + final InstanceContainer instanceContainer = new InstanceContainer(globalEventHandlerProvider.getGlobalEventHandler(), exceptionHandlerProvider, blockManagerProvider, biomeManagerProvider, serverSettingsProvider, chunkDispatcherProvider, schedulerManagerProvider, UUID.randomUUID(), dimensionType, loader, dimensionType.getName()); registerInstance(instanceContainer); return instanceContainer; } @@ -73,7 +84,7 @@ public void registerInstance(@NotNull Instance instance) { Check.notNull(instanceContainer, "Instance container cannot be null when creating a SharedInstance!"); Check.stateCondition(!instanceContainer.isRegistered(), "The container needs to be register in the InstanceManager"); - final SharedInstance sharedInstance = new SharedInstance(globalEventHandlerProvider.getGlobalEventHandler(), serverSettingsProvider, UUID.randomUUID(), instanceContainer); + final SharedInstance sharedInstance = new SharedInstance(globalEventHandlerProvider.getGlobalEventHandler(), serverSettingsProvider, schedulerManagerProvider, biomeManagerProvider, UUID.randomUUID(), instanceContainer); return registerSharedInstance(sharedInstance); } @@ -123,4 +134,4 @@ private void UNSAFE_registerInstance(@NotNull Instance instance) { InstanceRegisterEvent event = new InstanceRegisterEvent(instance); globalEventHandlerProvider.getGlobalEventHandler().call(event); } -} +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/instance/LightingChunk.java b/src/main/java/net/minestom/server/instance/LightingChunk.java index 168e73ea2bf..79e66ccc498 100644 --- a/src/main/java/net/minestom/server/instance/LightingChunk.java +++ b/src/main/java/net/minestom/server/instance/LightingChunk.java @@ -2,8 +2,6 @@ import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minestom.server.MinecraftServer; -import net.minestom.server.ServerSettingsProvider; import net.minestom.server.collision.Shape; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Vec; @@ -15,12 +13,10 @@ import net.minestom.server.network.packet.server.CachedPacket; import net.minestom.server.network.packet.server.play.data.LightData; import net.minestom.server.timer.ExecutionType; -import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.timer.Task; import net.minestom.server.timer.TaskSchedule; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.chunk.ChunkUtils; -import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,8 +35,6 @@ public class LightingChunk extends DynamicChunk { private static final int LIGHTING_CHUNKS_SEND_DELAY = Integer.getInteger("minestom.lighting.chunks-send-delay", 100); private static final ExecutorService pool = Executors.newWorkStealingPool(); - private final ServerSettingsProvider serverSettingsProvider; - private final SchedulerManagerProvider schedulerManagerProvider; private int[] heightmap; final CachedPacket lightCache; @@ -82,15 +76,9 @@ private enum QueueType { Block.LAVA.namespace() ); - public LightingChunk(MinecraftServer minecraftServer, @NotNull Instance instance, int chunkX, int chunkZ) { - this(minecraftServer, minecraftServer, minecraftServer, instance, chunkX, chunkZ); - } - - public LightingChunk(BiomeManagerProvider biomeManagerProvider, ServerSettingsProvider serverSettingsProvider, SchedulerManagerProvider schedulerManagerProvider, @NotNull Instance instance, int chunkX, int chunkZ) { - super(biomeManagerProvider, instance, chunkX, chunkZ); - this.serverSettingsProvider = serverSettingsProvider; - this.schedulerManagerProvider = schedulerManagerProvider; - this.lightCache = new CachedPacket(serverSettingsProvider, this::createLightPacket); + public LightingChunk(@NotNull Instance instance, int chunkX, int chunkZ) { + super(instance, chunkX, chunkZ); + this.lightCache = new CachedPacket(instance::getServerSettings, this::createLightPacket); } private boolean checkSkyOcclusion(Block block) { @@ -141,7 +129,7 @@ public void setBlock(int x, int y, int z, @NotNull Block block, public void sendLighting() { if (!isLoaded()) return; - sendPacketToViewers(serverSettingsProvider, lightCache); + sendPacketToViewers(instance::getServerSettings, lightCache); } @Override @@ -269,7 +257,7 @@ static void updateAfterGeneration(LightingChunk chunk) { return; } - sendingTask = chunk.schedulerManagerProvider.getSchedulerManager().scheduleTask(() -> { + sendingTask = chunk.instance.getSchedulerManager().scheduleTask(() -> { queueLock.lock(); var copy = new ArrayList<>(sendQueue); sendQueue.clear(); @@ -441,7 +429,7 @@ private static void relight(Instance instance, Set queue, LightType type) @Override public @NotNull Chunk copy(@NotNull Instance instance, int chunkX, int chunkZ) { - LightingChunk lightingChunk = new LightingChunk(biomeManagerProvider, serverSettingsProvider, schedulerManagerProvider, instance, chunkX, chunkZ); + LightingChunk lightingChunk = new LightingChunk(instance, chunkX, chunkZ); lightingChunk.sections = sections.stream().map(Section::clone).toList(); lightingChunk.entries.putAll(entries); return lightingChunk; diff --git a/src/main/java/net/minestom/server/instance/SharedInstance.java b/src/main/java/net/minestom/server/instance/SharedInstance.java index 667c9d12902..9ec2e1a9345 100644 --- a/src/main/java/net/minestom/server/instance/SharedInstance.java +++ b/src/main/java/net/minestom/server/instance/SharedInstance.java @@ -9,7 +9,9 @@ import net.minestom.server.instance.block.BlockFace; import net.minestom.server.instance.block.BlockHandler; import net.minestom.server.instance.generator.Generator; +import net.minestom.server.timer.SchedulerManagerProvider; import net.minestom.server.utils.chunk.ChunkSupplier; +import net.minestom.server.world.biomes.BiomeManagerProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -24,8 +26,8 @@ public class SharedInstance extends Instance { private final InstanceContainer instanceContainer; - public SharedInstance(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { - super(globalEventHandler, serverSettingsProvider, uniqueId, instanceContainer.getDimensionType()); + public SharedInstance(GlobalEventHandler globalEventHandler, ServerSettingsProvider serverSettingsProvider, SchedulerManagerProvider schedulerManagerProvider, BiomeManagerProvider biomeManagerProvider, @NotNull UUID uniqueId, @NotNull InstanceContainer instanceContainer) { + super(globalEventHandler, serverSettingsProvider, schedulerManagerProvider, biomeManagerProvider, uniqueId, instanceContainer.getDimensionType()); this.instanceContainer = instanceContainer; } @@ -133,4 +135,4 @@ public boolean isInVoid(@NotNull Point point) { public ServerSettings getServerSettings() { return null; } -} +} \ No newline at end of file diff --git a/src/main/java/net/minestom/server/utils/time/TickTimeUnit.java b/src/main/java/net/minestom/server/utils/time/TickTimeUnit.java new file mode 100644 index 00000000000..55f209ad5e9 --- /dev/null +++ b/src/main/java/net/minestom/server/utils/time/TickTimeUnit.java @@ -0,0 +1,26 @@ +package net.minestom.server.utils.time; + +import net.minestom.server.ServerSettings; + +public enum TickTimeUnit { + DAY(24 * 60 * 60 * 1000), + HOUR(60 * 60 * 1000), + MINUTE(60 * 1000), + SECOND(1000), + MILLISECOND(1); + + private final long millis; + + TickTimeUnit(long millis) { + this.millis = millis; + } + + public long millis(int value) { + return millis * value; + } + + public long ticks(int value, ServerSettings serverSettings) { + int tps = serverSettings.getTickPerSecond(); + return millis * value * tps / 1000; + } +} \ No newline at end of file