diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5d4d795d..2cb00018 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,6 +18,7 @@ jobs: with: curse-publish-task: "" maven-snapshots: true + java-version: 21 secrets: ftb-maven-token: ${{ secrets.FTB_MAVEN_TOKEN }} - saps-token: ${{ secrets.SAPS_TOKEN }} \ No newline at end of file + saps-token: ${{ secrets.SAPS_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7f875fc0..715eb75b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,8 @@ jobs: uses: FTBTeam/mods-meta/.github/workflows/standard-release.yml@main with: curse-publish-task: curseforge + java-version: 21 secrets: ftb-maven-token: ${{ secrets.FTB_MAVEN_TOKEN }} saps-token: ${{ secrets.SAPS_TOKEN }} - curse-token: ${{ secrets.CURSEFORGE_KEY }} \ No newline at end of file + curse-token: ${{ secrets.CURSEFORGE_KEY }} diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf4731e..edff620a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2006.1.0] + +### Changed +* Ported to Minecraft 1.20.6. Support for Fabric and NeoForge. + * Forge support may be re-added if/when Architectury adds support for Forge + ## [2004.1.3] ### Fixed diff --git a/build.gradle b/build.gradle index 907fe0f7..5a0a8e98 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ plugins { id "architectury-plugin" version "3.4-SNAPSHOT" - id "dev.architectury.loom" version "1.5-SNAPSHOT" apply false + id "dev.architectury.loom" version "1.6-SNAPSHOT" apply false } architectury { @@ -18,6 +18,10 @@ subprojects { minecraft "com.mojang:minecraft:${rootProject.minecraft_version}" mappings loom.officialMojangMappings() } + + configurations.configureEach { + resolutionStrategy.cacheChangingModulesFor 0, 'seconds' + } } allprojects { @@ -33,7 +37,7 @@ allprojects { // needs to be done AFTER version is set apply from: "https://raw.githubusercontent.com/FTBTeam/mods-meta/main/gradle/publishing.gradle" - sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = 17 + sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = 21 compileJava { options.encoding = "UTF-8" diff --git a/common/build.gradle b/common/build.gradle index eb09e058..62bc7f0c 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -9,7 +9,7 @@ dependencies { def ENV = System.getenv() architectury { - common("forge", "fabric", "neoforge") + common(/* "forge", */ "fabric", "neoforge") } configurations { diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunks.java b/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunks.java index f5a09607..91418d4b 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunks.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunks.java @@ -6,6 +6,7 @@ import dev.architectury.event.EventResult; import dev.architectury.event.events.common.*; import dev.architectury.hooks.level.entity.PlayerHooks; +import dev.architectury.networking.NetworkManager; import dev.architectury.registry.registries.Registrar; import dev.architectury.registry.registries.RegistrarManager; import dev.architectury.utils.Env; @@ -18,6 +19,7 @@ import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import dev.ftb.mods.ftbchunks.data.*; import dev.ftb.mods.ftbchunks.net.*; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; import dev.ftb.mods.ftblibrary.integration.stages.StageHelper; import dev.ftb.mods.ftblibrary.math.ChunkDimPos; import dev.ftb.mods.ftblibrary.math.MathUtils; @@ -181,7 +183,7 @@ private void serverLevelLoad(ServerLevel level) { if (ClaimedChunkManagerImpl.getInstance() != null) { ClaimedChunkManagerImpl.getInstance().initForceLoadedChunks(level); } else { - FTBChunks.LOGGER.warn("Level " + level.dimension().location() + " loaded before FTB Chunks manager was initialized! Unable to force-load chunks"); + FTBChunks.LOGGER.warn("Level {} loaded before FTB Chunks manager was initialized! Unable to force-load chunks", level.dimension().location() ); } } @@ -205,16 +207,16 @@ private void loggedIn(PlayerLoggedInAfterTeamEvent event) { SNBTCompoundTag config = new SNBTCompoundTag(); FTBChunksWorldConfig.CONFIG.write(config); UUID managerId = FTBTeamsAPI.api().getManager().getId(); - new LoginDataPacket(managerId, config).sendTo(player); + NetworkManager.sendToPlayer(player, new LoginDataPacket(managerId, config)); SendGeneralDataPacket.send(data, player); FTBChunks.LOGGER.debug("server config and team data sent to {}", playerId); long now = System.currentTimeMillis(); - Map, UUID>, List> chunksToSend = new HashMap<>(); + Map, UUID>, List> chunksToSend = new HashMap<>(); for (ClaimedChunkImpl chunk : ClaimedChunkManagerImpl.getInstance().getAllClaimedChunks()) { chunksToSend.computeIfAbsent(Pair.of(chunk.getPos().dimension(), chunk.getTeamData().getTeamId()), s -> new ArrayList<>()) - .add(new SendChunkPacket.SingleChunk(now, chunk.getPos().x(), chunk.getPos().z(), chunk)); + .add(ChunkSyncInfo.create(now, chunk.getPos().x(), chunk.getPos().z(), chunk)); } chunksToSend.forEach((dimensionAndId, chunkPackets) -> { @@ -222,7 +224,7 @@ private void loggedIn(PlayerLoggedInAfterTeamEvent event) { ChunkTeamDataImpl teamData = ClaimedChunkManagerImpl.getInstance().getOrCreateData(team); if (teamData.canPlayerUse(player, FTBChunksProperties.CLAIM_VISIBILITY)) { SendManyChunksPacket packet = new SendManyChunksPacket(dimensionAndId.getLeft(), dimensionAndId.getRight(), chunkPackets); - packet.sendTo(player); + NetworkManager.sendToPlayer(player, packet); } }); }); @@ -414,7 +416,7 @@ private void playerCloned(ServerPlayer oldPlayer, ServerPlayer newPlayer, boolea if (!wonGame) { newPlayer.getLastDeathLocation().ifPresent(loc -> { int num = newPlayer.getStats().getValue(Stats.CUSTOM.get(Stats.DEATHS)); - new PlayerDeathPacket(loc, num).sendTo(newPlayer); + NetworkManager.sendToPlayer(newPlayer, new PlayerDeathPacket(loc, num)); }); } } @@ -425,7 +427,8 @@ private void playerChangedDimension(ServerPlayer serverPlayer, ResourceKey chunksToTransfer) { + @SuppressWarnings("UnreachableCode") + private void transferClaims(ChunkTeamDataImpl transferFrom, ChunkTeamDataImpl transferTo, Collection chunksToTransfer) { CommandSourceStack sourceStack = ClaimedChunkManagerImpl.getInstance().getMinecraftServer().createCommandSourceStack(); String fromName = transferFrom.getTeam().getShortName(); @@ -495,8 +499,8 @@ private void transferClaims(ChunkTeamDataImpl transferFrom, ChunkTeamDataImpl tr int nChunks = transferTo.getClaimedChunks().size(); - Map, List> chunksToSend = new HashMap<>(); - Map, List> chunksToUnclaim = new HashMap<>(); + Map, List> chunksToSend = new HashMap<>(); + Map, List> chunksToUnclaim = new HashMap<>(); int transferred = 0; int unclaimed = 0; long now = System.currentTimeMillis(); @@ -508,11 +512,11 @@ private void transferClaims(ChunkTeamDataImpl transferFrom, ChunkTeamDataImpl tr ChunkDimPos cdp = chunk.getPos(); if (total >= transferTo.getMaxClaimChunks()) { chunk.unclaim(sourceStack, false); - chunksToUnclaim.computeIfAbsent(cdp.dimension(), s -> new ArrayList<>()).add(new SendChunkPacket.SingleChunk(now, cdp.x(), cdp.z(), null)); + chunksToUnclaim.computeIfAbsent(cdp.dimension(), s -> new ArrayList<>()).add(ChunkSyncInfo.create(now, cdp.x(), cdp.z(), null)); unclaimed++; } else { chunk.setTeamData(transferTo); - chunksToSend.computeIfAbsent(cdp.dimension(), s -> new ArrayList<>()).add(new SendChunkPacket.SingleChunk(now, cdp.x(), cdp.z(), chunk)); + chunksToSend.computeIfAbsent(cdp.dimension(), s -> new ArrayList<>()).add(ChunkSyncInfo.create(now, cdp.x(), cdp.z(), chunk)); transferred++; } @@ -536,13 +540,14 @@ private void transferClaims(ChunkTeamDataImpl transferFrom, ChunkTeamDataImpl tr if (transferred > 0 || unclaimed > 0) { chunksToSend.forEach((dimension, chunkPackets) -> { if (!chunkPackets.isEmpty()) { - ChunkSendingUtils.sendManyChunksToAll(sourceStack.getServer(), transferTo, new SendManyChunksPacket(dimension, transferTo.getTeamId(), chunkPackets)); + new SendManyChunksPacket(dimension, transferTo.getTeamId(), chunkPackets) + .sendToAll(sourceStack.getServer(), transferTo); } }); chunksToUnclaim.forEach((dimension, chunkPackets) -> { if (!chunkPackets.isEmpty()) { - new SendManyChunksPacket(dimension, Util.NIL_UUID, chunkPackets).sendToAll(sourceStack.getServer()); + NetworkManager.sendToPlayers(sourceStack.getServer().getPlayerList().getPlayers(), new SendManyChunksPacket(dimension, Util.NIL_UUID, chunkPackets)); } }); } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksCommands.java b/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksCommands.java index a7d5d94b..267869c9 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksCommands.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksCommands.java @@ -8,6 +8,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; import com.mojang.util.UndashedUuid; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.api.ChunkTeamData; import dev.ftb.mods.ftbchunks.api.ClaimResult; import dev.ftb.mods.ftbchunks.api.ClaimedChunk; @@ -180,7 +181,7 @@ public static void registerCommands(CommandDispatcher dispat .then(Commands.literal("block_color") // .requires(source -> source.getServer().isSingleplayer()) .executes(context -> { - new RequestBlockColorPacket().sendTo(context.getSource().getPlayerOrException()); + NetworkManager.sendToPlayer(context.getSource().getPlayerOrException(), new RequestBlockColorPacket()); return 1; }) ) @@ -203,8 +204,7 @@ public static void registerCommands(CommandDispatcher dispat private static int addWaypoint(CommandSourceStack source, String name, BlockPos position, ChatFormatting color) throws CommandSyntaxException { if (color.getColor() != null) { - ServerPlayer player = source.getPlayerOrException(); - new AddWaypointPacket(name, position, color.getColor()).sendTo(player); + NetworkManager.sendToPlayer(source.getPlayerOrException(), new AddWaypointPacket(name, position, color.getColor())); } return 1; } @@ -465,13 +465,13 @@ private static int viewLoadedChunks(CommandSourceStack source, ServerLevel level } source.sendSuccess(() -> Component.literal(String.format("Chunks Loaded: %d. Check the map to see loaded chunks", chunks.size())), false); - new LoadedChunkViewPacket(level.dimension(), chunks).sendTo(source.getPlayerOrException()); + NetworkManager.sendToPlayer(source.getPlayerOrException(), new LoadedChunkViewPacket(level.dimension(), chunks)); return 1; } private static int resetLoadedChunks(CommandSourceStack source, ServerLevel level) throws CommandSyntaxException { - new LoadedChunkViewPacket(level.dimension(), Long2IntMaps.EMPTY_MAP).sendTo(source.getPlayerOrException()); + NetworkManager.sendToPlayer(source.getPlayerOrException(), new LoadedChunkViewPacket(level.dimension(), Long2IntMaps.EMPTY_MAP)); return 1; } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksWorldConfig.java b/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksWorldConfig.java index ef639b11..b2bdfd8b 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksWorldConfig.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunksWorldConfig.java @@ -19,28 +19,34 @@ public interface FTBChunksWorldConfig { SNBTConfig CONFIG = SNBTConfig.create(FTBChunks.MOD_ID + "-world"); - EnumValue FAKE_PLAYERS = CONFIG.addEnum("fake_players", NameMap.of(ProtectionPolicy.CHECK, ProtectionPolicy.values()).create()).comment("Override to disable/enable fake players like miners and auto-clickers globally.","Default will check this setting for each team"); - IntValue MAX_CLAIMED_CHUNKS = CONFIG.addInt("max_claimed_chunks", 500).comment("Max claimed chunks.", "You can override this with FTB Ranks 'ftbchunks.max_claimed' permission"); - IntValue MAX_FORCE_LOADED_CHUNKS = CONFIG.addInt("max_force_loaded_chunks", 25).comment("Max force loaded chunks.", "You can override this with FTB Ranks 'ftbchunks.max_force_loaded' permission"); - EnumValue FORCE_LOAD_MODE = CONFIG.addEnum("force_load_mode", ForceLoadMode.NAME_MAP).comment("Control how force-loaded chunks work.","NEVER: only allow chunk force-loading if the owning team has at least one online player.","ALWAYS: always allow force-loading, even if no players are online.","DEFAULT: allow force-loading IF the team has at least one player with the 'ftbchunks.chunk_load_offline' FTB Ranks permission."); BooleanValue DISABLE_PROTECTION = CONFIG.addBoolean("disable_protection", false).comment("Disables all land protection. Useful for private servers where everyone is trusted and claims are only used for force-loading"); EnumValue ALLY_MODE = CONFIG.addEnum("ally_mode", AllyMode.NAME_MAP).comment("Forced modes won't let players change their ally settings"); EnumValue PVP_MODE = CONFIG.addEnum("pvp_mode", PvPMode.NAME_MAP).comment("Should PvP combat be allowed in claimed chunks? Default is ALWAYS; NEVER prevents it in all claimed chunks; PER_TEAM allows teams to decide if PvP is allowed in their claims"); - StringListValue CLAIM_DIMENSION_BLACKLIST = CONFIG.addStringList("claim_dimension_blacklist", Collections.emptyList()).comment("Dimension ID's where chunks may not be claimed. Add \"minecraft:the_end\" to this list if you want to disable chunk claiming in The End, or \"othermod:*\" to disable chunk claiming in *all* dimensions added by \"othermod\""); - StringListValue CLAIM_DIMENSION_WHITELIST = CONFIG.addStringList("claim_dimension_whitelist", Collections.emptyList()).comment("Dimension ID's where chunks may be claimed. If non-empty, chunks may be claimed *only* in these dimensions (and the dimension is not in \"claim_dimension_blacklist\"). Same syntax as for \"claim_dimension_blacklist\"."); BooleanValue NO_WILDERNESS = CONFIG.addBoolean("no_wilderness", false).comment("Requires you to claim chunks in order to edit and interact with blocks"); StringListValue NO_WILDERNESS_DIMENSIONS = CONFIG.addStringList("no_wilderness_dimensions", Collections.emptyList()).comment("Dimension ID's where the no_wilderness rule is enforced - building is only allowed in claimed chunks. If this is non-empty, it overrides the 'no_wilderness' setting."); BooleanValue FORCE_DISABLE_MINIMAP = CONFIG.addBoolean("force_disable_minimap", false).comment("Minimap for clients connecting to this server will be disabled"); - DoubleValue MAX_IDLE_DAYS_BEFORE_UNCLAIM = CONFIG.addDouble("max_idle_days_before_unclaim", 0D, 0D, 3650D).comment("Maximum time (in real-world days) where if no player in a team logs in, the team automatically loses their claims.", "Prevents chunks being claimed indefinitely by teams who no longer play.","Default of 0 means no automatic loss of claims."); - DoubleValue MAX_IDLE_DAYS_BEFORE_UNFORCE = CONFIG.addDouble("max_idle_days_before_unforce", 0D, 0D, 3650D).comment("Maximum time (in real-world days) where if no player in a team logs in, any forceloaded chunks owned by the team are no longer forceloaded.", "Prevents chunks being forceloaded indefinitely by teams who no longer play.","Default of 0 means no automatic loss of forceloading."); IntValue LONG_RANGE_TRACKER_INTERVAL = CONFIG.addInt("long_range_tracker_interval", 20, 0, Integer.MAX_VALUE).comment("Interval in ticks to send updates to clients with long-range player tracking data.","Lower values mean more frequent updates but more server load and network traffic; be careful with this, especially on busy servers.","Setting this to 0 disables long-range tracking."); BooleanValue PROTECT_UNKNOWN_EXPLOSIONS = CONFIG.addBoolean("protect_unknown_explosions", true).comment("When true, standard FTB Chunk explosion protection is applied in protected chunks when the source of the explosion cannot be determined","(Ghast fireballs are a common case - vanilla supplies a null entity source)"); - IntValue HARD_TEAM_CLAIM_LIMIT = CONFIG.addInt("hard_team_claim_limit", 0, 0, Integer.MAX_VALUE).comment("Hard limit for the number of chunks a team can claim, regardless of how many members. Default of 0 means no hard limit."); - IntValue HARD_TEAM_FORCE_LIMIT = CONFIG.addInt("hard_team_force_limit", 0, 0, Integer.MAX_VALUE).comment("Hard limit for the number of chunks a team can force-load, regardless of how many members. Default of 0 means no hard limit."); - EnumValue PARTY_LIMIT_MODE = CONFIG.addEnum("party_limit_mode", PartyLimitMode.NAME_MAP).comment("Method by which party claim & force-load limits are calculated.","LARGEST: use the limits of the member with the largest limits","SUM: add up all the members' limits","OWNER: use the party owner's limits only","AVERAGE: use the average of all members' limits."); BooleanValue REQUIRE_GAME_STAGE = CONFIG.addBoolean("require_game_stage", false).comment("If true, the player must have the 'ftbchunks_mapping' Game stage to be able to use the map and minimap.\nRequires KubeJS and/or Gamestages to be installed."); BooleanValue LOCATION_MODE_OVERRIDE = CONFIG.addBoolean("location_mode_override", false).comment("If true, \"Location Visibility\" team settings are ignored, and all players can see each other anywhere on the map."); - IntValue MAX_PREVENTED_LOG_AGE = CONFIG.addInt("max_prevented_log_age", 7, 1, Integer.MAX_VALUE).comment("Maximum time in days to keep logs of prevented fakeplayer access to a team's claims."); + + SNBTConfig FAKE_PLAYERS = CONFIG.addGroup("fake_players"); + EnumValue ALLOW_FAKE_PLAYERS = FAKE_PLAYERS.addEnum("fake_players", NameMap.of(ProtectionPolicy.CHECK, ProtectionPolicy.values()).create()).comment("Override to disable/enable fake players like miners and auto-clickers globally.","Default will check this setting for each team"); + IntValue MAX_PREVENTED_LOG_AGE = FAKE_PLAYERS.addInt("max_prevented_log_age", 7, 1, Integer.MAX_VALUE).comment("Maximum time in days to keep logs of prevented fakeplayer access to a team's claims."); + + SNBTConfig CLAIMING = CONFIG.addGroup("claiming"); + IntValue MAX_CLAIMED_CHUNKS = CLAIMING.addInt("max_claimed_chunks", 500).comment("Max claimed chunks.", "You can override this with FTB Ranks 'ftbchunks.max_claimed' permission"); + StringListValue CLAIM_DIMENSION_BLACKLIST = CLAIMING.addStringList("claim_dimension_blacklist", Collections.emptyList()).comment("Dimension ID's where chunks may not be claimed. Add \"minecraft:the_end\" to this list if you want to disable chunk claiming in The End, or \"othermod:*\" to disable chunk claiming in *all* dimensions added by \"othermod\""); + StringListValue CLAIM_DIMENSION_WHITELIST = CLAIMING.addStringList("claim_dimension_whitelist", Collections.emptyList()).comment("Dimension ID's where chunks may be claimed. If non-empty, chunks may be claimed *only* in these dimensions (and the dimension is not in \"claim_dimension_blacklist\"). Same syntax as for \"claim_dimension_blacklist\"."); + DoubleValue MAX_IDLE_DAYS_BEFORE_UNCLAIM = CLAIMING.addDouble("max_idle_days_before_unclaim", 0D, 0D, 3650D).comment("Maximum time (in real-world days) where if no player in a team logs in, the team automatically loses their claims.", "Prevents chunks being claimed indefinitely by teams who no longer play.","Default of 0 means no automatic loss of claims."); + IntValue HARD_TEAM_CLAIM_LIMIT = CLAIMING.addInt("hard_team_claim_limit", 0, 0, Integer.MAX_VALUE).comment("Hard limit for the number of chunks a team can claim, regardless of how many members. Default of 0 means no hard limit."); + EnumValue PARTY_LIMIT_MODE = CLAIMING.addEnum("party_limit_mode", PartyLimitMode.NAME_MAP).comment("Method by which party claim & force-load limits are calculated.","LARGEST: use the limits of the member with the largest limits","SUM: add up all the members' limits","OWNER: use the party owner's limits only","AVERAGE: use the average of all members' limits."); + + SNBTConfig FORCE_LOADING = CONFIG.addGroup("force_loading"); + EnumValue FORCE_LOAD_MODE = FORCE_LOADING.addEnum("force_load_mode", ForceLoadMode.NAME_MAP).comment("Control how force-loaded chunks work.","NEVER: only allow chunk force-loading if the owning team has at least one online player.","ALWAYS: always allow force-loading, even if no players are online.","DEFAULT: allow force-loading IF the team has at least one player with the 'ftbchunks.chunk_load_offline' FTB Ranks permission."); + IntValue MAX_FORCE_LOADED_CHUNKS = FORCE_LOADING.addInt("max_force_loaded_chunks", 25).comment("Max force loaded chunks.", "You can override this with FTB Ranks 'ftbchunks.max_force_loaded' permission"); + DoubleValue MAX_IDLE_DAYS_BEFORE_UNFORCE = FORCE_LOADING.addDouble("max_idle_days_before_unforce", 0D, 0D, 3650D).comment("Maximum time (in real-world days) where if no player in a team logs in, any forceloaded chunks owned by the team are no longer forceloaded.", "Prevents chunks being forceloaded indefinitely by teams who no longer play.","Default of 0 means no automatic loss of forceloading."); + IntValue HARD_TEAM_FORCE_LIMIT = FORCE_LOADING.addInt("hard_team_force_limit", 0, 0, Integer.MAX_VALUE).comment("Hard limit for the number of chunks a team can force-load, regardless of how many members. Default of 0 means no hard limit."); static int getMaxClaimedChunks(ChunkTeamData playerData, ServerPlayer player) { if (player != null) { diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/LongRangePlayerTracker.java b/common/src/main/java/dev/ftb/mods/ftbchunks/LongRangePlayerTracker.java index ce6d34ce..4f44616a 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/LongRangePlayerTracker.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/LongRangePlayerTracker.java @@ -2,6 +2,7 @@ import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.api.FTBChunksProperties; import dev.ftb.mods.ftbchunks.data.ChunkTeamDataImpl; import dev.ftb.mods.ftbchunks.data.ClaimedChunkManagerImpl; @@ -39,19 +40,19 @@ public void tick(MinecraftServer server) { // 16 blocks in chunk int maxDistSq = server.getPlayerList().getViewDistance() * server.getPlayerList().getViewDistance() * 256; - players.forEach(p1 -> p1.level().players().forEach(p2a -> { - if (p2a instanceof ServerPlayer p2) { - if (shouldTrack(p1, p2, maxDistSq)) { - // send a tracking update to p1 IF p2's pos has changed by more than 4 blocks - BlockPos lastPos = trackingMap.get(p1.getUUID(), p2.getUUID()); - if (lastPos == null || p2.blockPosition().distSqr(lastPos) > 16) { - new SendPlayerPositionPacket(p2, p2.blockPosition()).sendTo(p1); - trackingMap.put(p1.getUUID(), p2.getUUID(), p2.blockPosition()); + players.forEach(trackingPlayer -> trackingPlayer.level().players().forEach(p2a -> { + if (p2a instanceof ServerPlayer trackedPlayer) { + if (shouldTrack(trackingPlayer, trackedPlayer, maxDistSq)) { + // send a tracking update to p1's client IF p2's pos has changed by more than 4 blocks + BlockPos lastPos = trackingMap.get(trackingPlayer.getUUID(), trackedPlayer.getUUID()); + if (lastPos == null || trackedPlayer.blockPosition().distSqr(lastPos) > 16) { + NetworkManager.sendToPlayer(trackingPlayer, SendPlayerPositionPacket.startTracking(trackedPlayer)); + trackingMap.put(trackingPlayer.getUUID(), trackedPlayer.getUUID(), trackedPlayer.blockPosition()); } - } else if (trackingMap.contains(p1.getUUID(), p2.getUUID())) { - // send an invalid pos to tell p1's client to stop tracking p2 - new SendPlayerPositionPacket(p2, null).sendTo(p1); - trackingMap.remove(p1.getUUID(), p2.getUUID()); + } else if (trackingMap.contains(trackingPlayer.getUUID(), trackedPlayer.getUUID())) { + // tell p1's client to stop tracking p2 + NetworkManager.sendToPlayer(trackingPlayer, SendPlayerPositionPacket.stopTracking(trackedPlayer)); + trackingMap.remove(trackingPlayer.getUUID(), trackedPlayer.getUUID()); } } })); @@ -73,7 +74,7 @@ public void stopTracking(ServerPlayer player) { toRemove.forEach((trackingId, disconnectedId) -> { ServerPlayer trackingPlayer = player.getServer().getPlayerList().getPlayer(trackingId); if (trackingPlayer != null) { - new SendPlayerPositionPacket(player, null).sendTo(trackingPlayer); + NetworkManager.sendToPlayer(trackingPlayer, SendPlayerPositionPacket.stopTracking(player)); } trackingMap.remove(trackingId, disconnectedId); }); diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/api/Protection.java b/common/src/main/java/dev/ftb/mods/ftbchunks/api/Protection.java index 1e278526..d7609a23 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/api/Protection.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/api/Protection.java @@ -1,16 +1,17 @@ package dev.ftb.mods.ftbchunks.api; import net.minecraft.core.BlockPos; +import net.minecraft.core.component.DataComponents; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.entity.Entity; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.PotionItem; -import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; +import java.util.stream.StreamSupport; + @FunctionalInterface public interface Protection { /** @@ -57,7 +58,7 @@ public interface Protection { Protection RIGHT_CLICK_ITEM = (player, pos, hand, chunk, entity) -> { ItemStack stack = player.getItemInHand(hand); - if (stack.isEdible() || isBeneficialPotion(stack) || stack.is(FTBChunksTags.Items.RIGHT_CLICK_WHITELIST_TAG)) { + if (isFood(stack) || isBeneficialPotion(stack) || stack.is(FTBChunksTags.Items.RIGHT_CLICK_WHITELIST_TAG)) { return ProtectionPolicy.ALLOW; } else if (chunk != null && chunk.getTeamData().canPlayerUse(player, FTBChunksProperties.BLOCK_INTERACT_MODE)) { return ProtectionPolicy.ALLOW; @@ -68,9 +69,17 @@ public interface Protection { return ProtectionPolicy.ALLOW; }; + static boolean isFood(ItemStack stack) { + //noinspection DataFlowIssue + return stack.has(DataComponents.FOOD) && stack.get(DataComponents.FOOD).nutrition() > 0; + } + static boolean isBeneficialPotion(ItemStack stack) { - return stack.getItem() instanceof PotionItem && PotionUtils.getMobEffects(stack).stream() - .noneMatch(effect -> effect.getEffect().getCategory() == MobEffectCategory.HARMFUL); + if (stack.has(DataComponents.POTION_CONTENTS)) { + return StreamSupport.stream(stack.get(DataComponents.POTION_CONTENTS).getAllEffects().spliterator(), false) + .noneMatch(effect -> effect.getEffect().value().getCategory() == MobEffectCategory.HARMFUL); + } + return false; } Protection EDIT_FLUID = (player, pos, hand, chunk, entity) -> { diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClient.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClient.java index 9f1e6561..8dd4a405 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClient.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClient.java @@ -87,7 +87,7 @@ import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; @@ -98,7 +98,7 @@ import java.util.*; -import static dev.ftb.mods.ftbchunks.net.SendChunkPacket.SingleChunk; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; public enum FTBChunksClient { INSTANCE; @@ -243,11 +243,11 @@ public void updateGeneralData(GeneralChunkData chunkData) { generalChunkData = chunkData; } - public void updateChunksFromServer(ResourceKey dimId, UUID teamId, Collection chunks) { + public void updateChunksFromServer(ResourceKey dimId, UUID teamId, Collection chunkSyncInfoList) { MapManager.getInstance().ifPresent(manager -> { MapDimension dimension = manager.getDimension(dimId); Date now = new Date(); - chunks.forEach(c -> ClientTaskQueue.queue(new UpdateChunkFromServerTask(dimension, c, teamId, now))); + chunkSyncInfoList.forEach(chunkSyncInfo -> ClientTaskQueue.queue(new UpdateChunkFromServerTask(dimension, chunkSyncInfo, teamId, now))); }); } @@ -759,8 +759,8 @@ private List buildMinimapTextData(Minecraft mc, double playerX, doubl private void drawInWorldIcons(Minecraft mc, GuiGraphics graphics, float tickDelta, double playerX, double playerY, double playerZ, int scaledWidth, int scaledHeight) { GuiHelper.setupDrawing(); - float ww2 = scaledWidth / 2F; - float wh2 = scaledHeight / 2F; + float scaledWidth2 = scaledWidth / 2F; + float scaledHeight2 = scaledHeight / 2F; InWorldMapIcon focusedIcon = null; for (MapIcon icon : mapIcons) { @@ -773,9 +773,9 @@ private void drawInWorldIcons(Minecraft mc, GuiGraphics graphics, float tickDelt if (lookAngle > 0) { // icon in front of the player worldMatrix.transform(v); v.div(v.w()); - float ix = ww2 + v.x() * ww2; - float iy = wh2 - v.y() * wh2; - double mouseDist = MathUtils.dist(ix, iy, ww2, wh2); + float ix = scaledWidth2 + v.x() * scaledWidth2; + float iy = scaledHeight2 - v.y() * scaledHeight2; + double mouseDist = MathUtils.dist(ix, iy, scaledWidth2, scaledHeight2); InWorldMapIcon inWorldMapIcon = new InWorldMapIcon(icon, ix, iy, playerDist, mouseDist); if (mouseDist <= 5D * FTBChunksClientConfig.WAYPOINT_FOCUS_DISTANCE.get() && (focusedIcon == null || focusedIcon.distanceToMouse() > mouseDist)) { @@ -813,7 +813,7 @@ private void drawInWorldIcons(Minecraft mc, GuiGraphics graphics, float tickDelt inWorldMapIcons.clear(); } - public void renderWorldLast(PoseStack poseStack, Matrix4f projectionMatrix, Camera camera, float tickDelta) { + public void renderWorldLast(PoseStack poseStack, Matrix4f projectionMatrix, Matrix4f modelViewMatrix, Camera camera, float tickDelta) { Minecraft mc = Minecraft.getInstance(); if (mc.options.hideGui || MapManager.getInstance().isEmpty() || mc.level == null || mc.player == null @@ -822,7 +822,7 @@ public void renderWorldLast(PoseStack poseStack, Matrix4f projectionMatrix, Came } worldMatrix = new Matrix4f(projectionMatrix); - worldMatrix.mul(poseStack.last().pose()); + worldMatrix.mul(modelViewMatrix); cameraPos = camera.getPosition(); if (!FTBChunksClientConfig.IN_WORLD_WAYPOINTS.get()) { @@ -1113,11 +1113,11 @@ public void maybeClearDeathpoint(Player player) { }); } - public void updateTrackedPlayerPos(GameProfile profile, BlockPos pos, boolean valid) { + public void updateTrackedPlayerPos(GameProfile profile, BlockPos pos) { // called periodically when a player (outside of vanilla entity tracking range) that this client is tracking moves boolean changed = false; - if (!valid) { - // invalid block pos indicates player should no longer be tracked on this client + if (pos == null) { + // null block pos indicates player should no longer be tracked on this client // - player is either no longer in this world, or is now within the vanilla tracking range changed = longRangePlayerTracker.remove(profile.getId()) != null; } else { diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClientConfig.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClientConfig.java index 2d820667..e1bd37f2 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClientConfig.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/FTBChunksClientConfig.java @@ -1,5 +1,6 @@ package dev.ftb.mods.ftbchunks.client; +import dev.architectury.networking.NetworkManager; import dev.architectury.platform.Platform; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.FTBChunksWorldConfig; @@ -111,7 +112,7 @@ static void openServerSettings(Screen screen) { if (accepted) { SNBTCompoundTag config = new SNBTCompoundTag(); FTBChunksWorldConfig.CONFIG.write(config); - new ServerConfigRequestPacket(config).sendToServer(); + NetworkManager.sendToServer(new ServerConfigRequestPacket(config)); } Minecraft.getInstance().setScreen(screen); }); diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/ChunkScreen.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/ChunkScreen.java index f1710d69..c6bd3739 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/ChunkScreen.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/ChunkScreen.java @@ -2,6 +2,7 @@ import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.systems.RenderSystem; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.FTBChunksWorldConfig; import dev.ftb.mods.ftbchunks.api.ClaimResult; @@ -103,9 +104,10 @@ public void addWidgets() { } addAll(chunkButtons); - new RequestMapDataPacket(chunkPos.x - FTBChunks.TILE_OFFSET, chunkPos.z - FTBChunks.TILE_OFFSET, - chunkPos.x + FTBChunks.TILE_OFFSET, chunkPos.z + FTBChunks.TILE_OFFSET - ).sendToServer(); + NetworkManager.sendToServer(new RequestMapDataPacket( + chunkPos.x - FTBChunks.TILE_OFFSET, chunkPos.z - FTBChunks.TILE_OFFSET, + chunkPos.x + FTBChunks.TILE_OFFSET, chunkPos.z + FTBChunks.TILE_OFFSET) + ); add(new SimpleButton(this, Component.translatable("ftbchunks.gui.large_map"), Icons.MAP, (simpleButton, mouseButton) -> LargeMapScreen.openMap() @@ -121,7 +123,7 @@ public void mouseReleased(MouseButton button) { super.mouseReleased(button); if (!selectedChunks.isEmpty()) { - new RequestChunkChangePacket(ChunkChangeOp.create(button.isLeft(), isShiftKeyDown()), selectedChunks).sendToServer(); + NetworkManager.sendToServer(new RequestChunkChangePacket(ChunkChangeOp.create(button.isLeft(), isShiftKeyDown()), selectedChunks)); selectedChunks.clear(); playClickSound(); } @@ -313,7 +315,7 @@ public void tick() { if (lastAdjust > 0L && System.currentTimeMillis() - lastAdjust > 1000L) { // send update to server, but not more than once a second - avoid flood of updates while adjusting mouse wheel - new UpdateForceLoadExpiryPacket(chunkPos.dim(Minecraft.getInstance().level), chunk.getForceLoadExpiryDate().orElse(null)).sendToServer(); + NetworkManager.sendToServer(new UpdateForceLoadExpiryPacket(chunkPos.dim(Minecraft.getInstance().level), chunk.getForceLoadExpiryDate().orElse(null))); lastAdjust = 0L; } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/LargeMapScreen.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/LargeMapScreen.java index 8bd90a04..2df8625b 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/LargeMapScreen.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/LargeMapScreen.java @@ -2,6 +2,7 @@ import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.vertex.PoseStack; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import dev.ftb.mods.ftbchunks.client.FTBChunksClientConfig; @@ -253,7 +254,7 @@ public boolean keyPressed(Key key) { movedToPlayer = false; return true; } else if (key.is(GLFW.GLFW_KEY_T)) { - new TeleportFromMapPacket(regionPanel.blockPos().above(), regionPanel.blockY == HeightUtils.UNKNOWN, dimension.dimension).sendToServer(); + NetworkManager.sendToServer(new TeleportFromMapPacket(regionPanel.blockPos().above(), regionPanel.blockY == HeightUtils.UNKNOWN, dimension.dimension)); closeGui(false); return true; } else if (key.is(GLFW.GLFW_KEY_G) && InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_F3)) { diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/WaypointEditorScreen.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/WaypointEditorScreen.java index 462c1234..bbe4b048 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/WaypointEditorScreen.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/gui/WaypointEditorScreen.java @@ -1,6 +1,7 @@ package dev.ftb.mods.ftbchunks.client.gui; import com.mojang.blaze3d.systems.RenderSystem; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.client.map.MapManager; import dev.ftb.mods.ftbchunks.client.map.WaypointImpl; import dev.ftb.mods.ftbchunks.net.TeleportFromMapPacket; @@ -18,7 +19,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Style; import net.minecraft.resources.ResourceLocation; @@ -30,7 +30,7 @@ import java.util.Objects; public class WaypointEditorScreen extends BaseScreen { - public static final Color4I COLOR_BACKGROUND = Color4I.rgba(0x99333333); + public static final Color4I COLOR_BACKGROUND = Color4I.rgba(0xC0333333); private static final Icon PEARL_ICON = ImageIcon.getIcon(new ResourceLocation("minecraft", "textures/item/ender_pearl.png")); public static final Theme THEME = new Theme() { @@ -143,6 +143,7 @@ public Component getTitle() { @Override public void drawBackground(GuiGraphics graphics, Theme theme, int x, int y, int w, int h) { + Color4I.BLACK.withAlpha(128).draw(graphics, 0, 0, w, h); COLOR_BACKGROUND.draw(graphics, 0, 0, w, 20); theme.drawString(graphics, getTitle(), 6, 6, Theme.SHADOW); } @@ -249,7 +250,7 @@ public void addWidgets() { LocalPlayer player = Minecraft.getInstance().player; String distStr = player.level().dimension().equals(wp.getDimension()) ? String.format("%.1fm", Math.sqrt(wp.getDistanceSq(player))) : ""; - add(new TextField(this).setText(distStr).setColor(Color4I.GRAY)); + add(new TextField(this).setText(distStr).setColor(Color4I.WHITE)); } @Override @@ -308,8 +309,7 @@ public boolean mousePressed(MouseButton button) { } if (Minecraft.getInstance().player.hasPermissions(2)) { // permissions are checked again on server! list.add(new ContextMenuItem(Component.translatable("ftbchunks.gui.teleport"), PEARL_ICON, btn -> { - BlockPos pos = wp.getPos().above(); - new TeleportFromMapPacket(pos, false, wp.getDimension()).sendToServer(); + NetworkManager.sendToServer(new TeleportFromMapPacket(wp.getPos().above(), false, wp.getDimension())); closeGui(false); })); } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapChunk.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapChunk.java index 1ec217b4..c10550c2 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapChunk.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapChunk.java @@ -1,6 +1,6 @@ package dev.ftb.mods.ftbchunks.client.map; -import dev.ftb.mods.ftbchunks.net.SendChunkPacket; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; import dev.ftb.mods.ftblibrary.math.XZ; import dev.ftb.mods.ftbteams.api.FTBTeamsAPI; import dev.ftb.mods.ftbteams.api.Team; @@ -110,7 +110,7 @@ public MapChunk offsetBlocking(int x, int z) { return region.dimension.getRegion(XZ.regionFromChunk(pos.x(), pos.z())).getDataBlocking().getChunk(pos); } - public void updateFromServer(Date now, SendChunkPacket.SingleChunk packet, UUID teamId) { + public void updateFromServer(Date now, ChunkSyncInfo packet, UUID teamId) { team = FTBTeamsAPI.api().getClientManager().getTeamByID(teamId).orElse(null); dateInfo = packet.getDateInfo(team != null, now.getTime()); region.update(false); diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapManager.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapManager.java index dcec33a3..d038d33c 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapManager.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/MapManager.java @@ -20,6 +20,7 @@ import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import org.jetbrains.annotations.NotNull; import java.nio.file.Files; import java.nio.file.Path; @@ -177,6 +178,7 @@ public Map, MapDimension> getDimensions() { } } + @NotNull public synchronized MapDimension getDimension(ResourceKey dim) { return getDimensions().computeIfAbsent(dim, dimKey -> { needsSave = true; diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/RegionSyncKey.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/RegionSyncKey.java index e9e6fde8..a4ca03a2 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/RegionSyncKey.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/RegionSyncKey.java @@ -2,55 +2,17 @@ import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; -import java.util.Objects; - -public class RegionSyncKey { - private final ResourceKey dim; - private final int x; - private final int z; - private final int random; - - public RegionSyncKey(FriendlyByteBuf buf) { - dim = ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()); - x = buf.readVarInt(); - z = buf.readVarInt(); - random = buf.readInt(); - } - - public RegionSyncKey(ResourceKey dim, int x, int z, int random) { - this.dim = dim; - this.x = x; - this.z = z; - this.random = random; - } - - public void write(FriendlyByteBuf buf) { - buf.writeResourceLocation(dim.location()); - buf.writeVarInt(x); - buf.writeVarInt(z); - buf.writeInt(random); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - RegionSyncKey key = (RegionSyncKey) o; - return x == key.x && - z == key.z && - random == key.random && - dim.equals(key.dim); - } - - @Override - public int hashCode() { - return Objects.hash(dim, x, z, random); - } +public record RegionSyncKey(ResourceKey dim, int x, int z, int random) { + public static StreamCodec STREAM_CODEC = StreamCodec.composite( + ResourceKey.streamCodec(Registries.DIMENSION), RegionSyncKey::dim, + ByteBufCodecs.INT, RegionSyncKey::x, + ByteBufCodecs.INT, RegionSyncKey::z, + ByteBufCodecs.INT, RegionSyncKey::random, + RegionSyncKey::new + ); } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/SyncTXTask.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/SyncTXTask.java index 2278e001..b6edb689 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/SyncTXTask.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/SyncTXTask.java @@ -1,6 +1,6 @@ package dev.ftb.mods.ftbchunks.client.map; -import dev.architectury.networking.simple.BaseC2SMessage; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.net.PartialPackets; import java.io.BufferedOutputStream; @@ -44,7 +44,7 @@ public void runMapTask() throws Exception { */ } - PartialPackets.REGION.write(region.getSyncKey(), out.toByteArray()).forEach(BaseC2SMessage::sendToServer); + PartialPackets.REGION.write(region.getSyncKey(), out.toByteArray()).forEach(NetworkManager::sendToServer); } @Override diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/UpdateChunkFromServerTask.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/UpdateChunkFromServerTask.java index b3a3e97d..76f4f0dc 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/UpdateChunkFromServerTask.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/map/UpdateChunkFromServerTask.java @@ -1,33 +1,16 @@ package dev.ftb.mods.ftbchunks.client.map; -import dev.ftb.mods.ftbchunks.net.SendChunkPacket; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; import dev.ftb.mods.ftblibrary.math.XZ; import java.util.Date; import java.util.UUID; -public class UpdateChunkFromServerTask implements MapTask { - private final MapDimension dimension; - private final SendChunkPacket.SingleChunk chunk; - private final UUID teamId; - private final Date now; - - public UpdateChunkFromServerTask(MapDimension d, SendChunkPacket.SingleChunk c, UUID i, Date date) { - dimension = d; - chunk = c; - teamId = i; - now = date; - } - +public record UpdateChunkFromServerTask(MapDimension dimension, ChunkSyncInfo info, UUID teamId, Date date) implements MapTask { @Override public void runMapTask() { - dimension.getRegion(XZ.regionFromChunk(chunk.getX(), chunk.getZ())) - .getChunkForAbsoluteChunkPos(XZ.of(chunk.getX(), chunk.getZ())) - .updateFromServer(now, chunk, teamId); - } - - @Override - public String toString() { - return "UpdateChunkFromServerTask@" + dimension + ":" + chunk.getX() + "," + chunk.getZ(); + dimension.getRegion(XZ.regionFromChunk(info.x(), info.z())) + .getChunkForAbsoluteChunkPos(XZ.of(info.x(), info.z())) + .updateFromServer(date, info, teamId); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/client/mapicon/StaticMapIcon.java b/common/src/main/java/dev/ftb/mods/ftbchunks/client/mapicon/StaticMapIcon.java index a1f0855c..b5c355c9 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/client/mapicon/StaticMapIcon.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/client/mapicon/StaticMapIcon.java @@ -1,5 +1,6 @@ package dev.ftb.mods.ftbchunks.client.mapicon; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.api.client.icon.MapIcon; import dev.ftb.mods.ftbchunks.client.gui.LargeMapScreen; import dev.ftb.mods.ftbchunks.net.TeleportFromMapPacket; @@ -21,7 +22,7 @@ public boolean onKeyPressed(BaseScreen screen, Key key) { static boolean handleKeypress(MapIcon icon, BaseScreen screen, Key key) { if (screen instanceof LargeMapScreen lms && key.is(GLFW.GLFW_KEY_T)) { - new TeleportFromMapPacket(BlockPos.containing(icon.getPos(1F)).above(), false, lms.currentDimension()).sendToServer(); + NetworkManager.sendToServer(new TeleportFromMapPacket(BlockPos.containing(icon.getPos(1F)).above(), false, lms.currentDimension())); screen.closeGui(false); return true; } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkSyncInfo.java b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkSyncInfo.java new file mode 100644 index 00000000..466d210c --- /dev/null +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkSyncInfo.java @@ -0,0 +1,91 @@ +package dev.ftb.mods.ftbchunks.data; + +import com.google.common.primitives.Ints; +import dev.ftb.mods.ftbchunks.api.ClaimedChunk; +import dev.ftb.mods.ftbchunks.client.map.MapChunk; +import dev.ftb.mods.ftbchunks.net.SendChunkPacket; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import org.jetbrains.annotations.Nullable; + +import java.util.Date; + +public record ChunkSyncInfo(int x, int z, boolean claimed, int relativeTimeClaimed, boolean forceLoaded, + int relativeTimeForceLoaded, boolean expires, int relativeForceLoadExpiryTime) { + // NOTE: relative times are sent in seconds rather than milliseconds + // (int rather than long for network sync efficiency) + // allows for offsets of up to ~2 billion seconds, which is 62 years - should be enough... + // (come back to me with a bug report in 2085 if not) + + public static StreamCodec STREAM_CODEC = new StreamCodec<>() { + @Override + public ChunkSyncInfo decode(FriendlyByteBuf buf) { + int x = buf.readInt(); + int z = buf.readInt(); + + if (buf.readBoolean()) { + int relativeTimeClaimed = buf.readInt(); + byte flags = buf.readByte(); + boolean forceLoaded = (flags & 0x01) != 0; + boolean expires = (flags & 0x02) != 0; + int relativeTimeForceLoaded = forceLoaded ? buf.readInt() : 0; + int relativeForceLoadExpiryTime = expires ? buf.readInt() : 0; + return new ChunkSyncInfo(x, z, true, relativeTimeClaimed, forceLoaded, relativeTimeForceLoaded, expires, relativeForceLoadExpiryTime); + } else { + return new ChunkSyncInfo(x, z, false, 0, false, 0, false, 0); + } + } + + @Override + public void encode(FriendlyByteBuf buf, ChunkSyncInfo chunkSyncInfo) { + buf.writeInt(chunkSyncInfo.x); + buf.writeInt(chunkSyncInfo.z); + buf.writeBoolean(chunkSyncInfo.claimed); + + if (chunkSyncInfo.claimed) { + byte flags = 0x0; + if (chunkSyncInfo.forceLoaded) flags |= 0x1; + if (chunkSyncInfo.expires) flags |= 0x2; + + buf.writeInt(chunkSyncInfo.relativeTimeClaimed); + buf.writeByte(flags); + if (chunkSyncInfo.forceLoaded) buf.writeInt(chunkSyncInfo.relativeTimeForceLoaded); + if (chunkSyncInfo.expires) buf.writeInt(chunkSyncInfo.relativeForceLoadExpiryTime); + } + } + }; + + public static ChunkSyncInfo create(long now, int x, int z, @Nullable ClaimedChunk claimedChunk) { + if (claimedChunk != null) { + boolean forceLoaded = claimedChunk.isForceLoaded(); + boolean expires = claimedChunk.getForceLoadExpiryTime() > 0L; + return new ChunkSyncInfo(x, z, true, + millisToSeconds(now - claimedChunk.getTimeClaimed()), + forceLoaded, + forceLoaded ? millisToSeconds(now - claimedChunk.getForceLoadedTime()) : 0, + expires, + expires ? millisToSeconds(claimedChunk.getForceLoadExpiryTime() - now) : 0); + } else { + return new ChunkSyncInfo(x, z, false, 0, false, 0, false, 0); + } + } + + public ChunkSyncInfo hidden() { + return ChunkSyncInfo.create(0L, x, z, null); + } + + private static int millisToSeconds(long ms) { + return Ints.saturatedCast(ms / 1000L); + } + + public MapChunk.DateInfo getDateInfo(boolean isClaimed, long now) { + if (!isClaimed) { + return MapChunk.NO_DATE_INFO; + } + + Date claimed = new Date(now - relativeTimeClaimed * 1000L); + Date forceLoaded = this.forceLoaded ? new Date(now - relativeTimeForceLoaded * 1000L) : null; + Date expiry = this.forceLoaded && expires ? new Date(now + relativeForceLoadExpiryTime * 1000L) : null; + return new MapChunk.DateInfo(claimed, forceLoaded, expiry); + } +} diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkTeamDataImpl.java b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkTeamDataImpl.java index 0a4897da..b3eadcbf 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkTeamDataImpl.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ChunkTeamDataImpl.java @@ -11,8 +11,6 @@ import dev.ftb.mods.ftbchunks.api.ClaimResult; import dev.ftb.mods.ftbchunks.api.FTBChunksProperties; import dev.ftb.mods.ftbchunks.api.event.ClaimedChunkEvent; -import dev.ftb.mods.ftbchunks.net.ChunkSendingUtils; -import dev.ftb.mods.ftbchunks.net.SendChunkPacket; import dev.ftb.mods.ftbchunks.net.SendGeneralDataPacket; import dev.ftb.mods.ftbchunks.net.SendManyChunksPacket; import dev.ftb.mods.ftbchunks.util.DimensionFilter; @@ -537,7 +535,7 @@ public boolean shouldHideClaims() { public void syncChunksToPlayer(ServerPlayer recipient) { chunksByDimension().forEach((dimension, chunkPackets) -> { if (!chunkPackets.isEmpty()) { - ChunkSendingUtils.sendManyChunksToPlayer(recipient, this, new SendManyChunksPacket(dimension, getTeamId(), chunkPackets)); + new SendManyChunksPacket(dimension, getTeamId(), chunkPackets).sendToPlayer(recipient, this); } }); } @@ -545,16 +543,16 @@ public void syncChunksToPlayer(ServerPlayer recipient) { public void syncChunksToAll(MinecraftServer server) { chunksByDimension().forEach((dimension, chunkPackets) -> { if (!chunkPackets.isEmpty()) { - ChunkSendingUtils.sendManyChunksToAll(server, this, new SendManyChunksPacket(dimension, getTeamId(), chunkPackets)); + new SendManyChunksPacket(dimension, getTeamId(), chunkPackets).sendToAll(server, this); } }); } - private Map, List> chunksByDimension() { + private Map, List> chunksByDimension() { long now = System.currentTimeMillis(); return getClaimedChunks().stream() .collect(Collectors.groupingBy( - c -> c.getPos().dimension(), Collectors.mapping(c -> new SendChunkPacket.SingleChunk(now, c.getPos().x(), c.getPos().z(), c), Collectors.toList()) + c -> c.getPos().dimension(), Collectors.mapping(c -> ChunkSyncInfo.create(now, c.getPos().x(), c.getPos().z(), c), Collectors.toList()) )); } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimExpirationManager.java b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimExpirationManager.java index 1bb33eb3..786ce0c1 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimExpirationManager.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimExpirationManager.java @@ -1,11 +1,11 @@ package dev.ftb.mods.ftbchunks.data; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.FTBChunksWorldConfig; import dev.ftb.mods.ftbchunks.api.ChunkTeamData; import dev.ftb.mods.ftbchunks.api.ClaimedChunk; import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; -import dev.ftb.mods.ftbchunks.net.SendChunkPacket; import dev.ftb.mods.ftbchunks.net.SendManyChunksPacket; import dev.ftb.mods.ftbteams.data.ServerTeam; import net.minecraft.Util; @@ -69,7 +69,7 @@ private void checkForIdleTeams(MinecraftServer server, final long now, Map, List> toSync = new HashMap<>(); + Map, List> toSync = new HashMap<>(); if (!expiredForceloads.isEmpty()) { expiredForceloads.forEach(cc -> unloadChunk(now, cc, toSync, sourceStack)); @@ -90,7 +90,7 @@ private void checkForTemporaryClaims(MinecraftServer server, final long now, Map if (!expired.isEmpty()) { ChunkTeamData teamData = expired.get(0).getTeamData(); CommandSourceStack sourceStack = server.createCommandSourceStack(); - Map, List> toSync = new HashMap<>(); + Map, List> toSync = new HashMap<>(); expired.forEach(cc -> { FTBChunks.LOGGER.info("un-forceloading chunk {} - expiry time {} passed", cc, cc.getForceLoadExpiryTime()); unloadChunk(now, cc, toSync, sourceStack); @@ -100,20 +100,20 @@ private void checkForTemporaryClaims(MinecraftServer server, final long now, Map }); } - private static void unclaimChunk(long now, ClaimedChunk c, Map, List> toSync, CommandSourceStack sourceStack) { + private static void unclaimChunk(long now, ClaimedChunk c, Map, List> toSync, CommandSourceStack sourceStack) { c.unclaim(sourceStack, false); - toSync.computeIfAbsent(c.getPos().dimension(), s -> new ArrayList<>()).add(new SendChunkPacket.SingleChunk(now, c.getPos().x(), c.getPos().z(), null)); + toSync.computeIfAbsent(c.getPos().dimension(), s -> new ArrayList<>()).add(ChunkSyncInfo.create(now, c.getPos().x(), c.getPos().z(), null)); } - private static void unloadChunk(long now, ClaimedChunk c, Map, List> toSync, CommandSourceStack sourceStack) { + private static void unloadChunk(long now, ClaimedChunk c, Map, List> toSync, CommandSourceStack sourceStack) { c.unload(sourceStack); - toSync.computeIfAbsent(c.getPos().dimension(), s -> new ArrayList<>()).add(new SendChunkPacket.SingleChunk(now, c.getPos().x(), c.getPos().z(), c)); + toSync.computeIfAbsent(c.getPos().dimension(), s -> new ArrayList<>()).add(ChunkSyncInfo.create(now, c.getPos().x(), c.getPos().z(), c)); } - private static void syncChunks(Map, List> toSync, MinecraftServer server, UUID teamId) { + private static void syncChunks(Map, List> toSync, MinecraftServer server, UUID teamId) { toSync.forEach((dimension, chunkPackets) -> { if (!chunkPackets.isEmpty()) { - new SendManyChunksPacket(dimension, teamId, chunkPackets).sendToAll(server); + NetworkManager.sendToPlayers(server.getPlayerList().getPlayers(), new SendManyChunksPacket(dimension, teamId, chunkPackets)); } }); } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkImpl.java b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkImpl.java index aa5bbd7d..71b04cba 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkImpl.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkImpl.java @@ -1,10 +1,10 @@ package dev.ftb.mods.ftbchunks.data; +import dev.architectury.networking.NetworkManager; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.FTBChunksExpected; import dev.ftb.mods.ftbchunks.api.ClaimedChunk; import dev.ftb.mods.ftbchunks.api.event.ClaimedChunkEvent; -import dev.ftb.mods.ftbchunks.net.ChunkSendingUtils; import dev.ftb.mods.ftbchunks.net.SendChunkPacket; import dev.ftb.mods.ftblibrary.math.ChunkDimPos; import dev.ftb.mods.ftblibrary.snbt.SNBTCompoundTag; @@ -113,7 +113,7 @@ public void setForceLoadedTime(long time) { } ServerChunkCache cache = level.getChunkSource(); - ChunkPos chunkPos = pos.getChunkPos(); + ChunkPos chunkPos = pos.chunkPos(); if (cache != null) { FTBChunksExpected.addChunkToForceLoaded(level, FTBChunks.MOD_ID, this.teamData.getTeamId(), chunkPos.x, chunkPos.z, forceLoaded > 0L); @@ -137,8 +137,8 @@ public boolean allowMobGriefing() { } public void sendUpdateToAll() { - SendChunkPacket packet = new SendChunkPacket(pos.dimension(), teamData.getTeamId(), new SendChunkPacket.SingleChunk(System.currentTimeMillis(), pos.x(), pos.z(), this)); - ChunkSendingUtils.sendChunkToAll(teamData.getManager().getMinecraftServer(), teamData, packet); + new SendChunkPacket(pos.dimension(), teamData.getTeamId(), ChunkSyncInfo.create(System.currentTimeMillis(), pos.x(), pos.z(), this)) + .sendToAll(teamData.getManager().getMinecraftServer(), teamData); } @Override @@ -162,8 +162,8 @@ public void unclaim(CommandSourceStack source, boolean sync) { teamData.markDirty(); if (sync) { - SendChunkPacket packet = new SendChunkPacket(pos.dimension(), Util.NIL_UUID, new SendChunkPacket.SingleChunk(System.currentTimeMillis(), pos.x(), pos.z(), null)); - packet.sendToAll(source.getServer()); + SendChunkPacket packet = new SendChunkPacket(pos.dimension(), Util.NIL_UUID, ChunkSyncInfo.create(System.currentTimeMillis(), pos.x(), pos.z(), null)); + NetworkManager.sendToPlayers(source.getServer().getPlayerList().getPlayers(), packet); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkManagerImpl.java b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkManagerImpl.java index 37aed95b..9359b51b 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkManagerImpl.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/data/ClaimedChunkManagerImpl.java @@ -203,8 +203,8 @@ public boolean shouldPreventInteraction(@Nullable Entity actor, InteractionHand } boolean isFake = PlayerHooks.isFake(player); - if (isFake && FTBChunksWorldConfig.FAKE_PLAYERS.get().isOverride()) { - return FTBChunksWorldConfig.FAKE_PLAYERS.get().shouldPreventInteraction(); + if (isFake && FTBChunksWorldConfig.ALLOW_FAKE_PLAYERS.get().isOverride()) { + return FTBChunksWorldConfig.ALLOW_FAKE_PLAYERS.get().shouldPreventInteraction(); } ClaimedChunkImpl chunk = getChunk(new ChunkDimPos(player.level(), pos)); @@ -261,7 +261,7 @@ public Long2ObjectMap getForceLoadedChunks(ResourceKey dimension) { @Override public boolean isChunkForceLoaded(ChunkDimPos chunkDimPos) { - return getForceLoadedChunks(chunkDimPos.dimension()).containsKey(chunkDimPos.getChunkPos().toLong()); + return getForceLoadedChunks(chunkDimPos.dimension()).containsKey(chunkDimPos.chunkPos().toLong()); } public void registerClaim(ChunkDimPos pos, ClaimedChunk chunk) { diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/AddWaypointPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/AddWaypointPacket.java index 147e79a5..8083743f 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/AddWaypointPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/AddWaypointPacket.java @@ -1,43 +1,30 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -public class AddWaypointPacket extends BaseS2CMessage { - private final String name; - private final BlockPos position; - private final int color; +public record AddWaypointPacket(String name, BlockPos position, int color) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("add_waypoint_packet")); - public AddWaypointPacket(String name, BlockPos position, int color) { - this.name = name; - this.position = position; - this.color = color; - } - - public AddWaypointPacket(FriendlyByteBuf buf) { - name = buf.readUtf(); - position = buf.readBlockPos(); - color = buf.readInt(); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.STRING_UTF8, AddWaypointPacket::name, + BlockPos.STREAM_CODEC, AddWaypointPacket::position, + ByteBufCodecs.INT, AddWaypointPacket::color, + AddWaypointPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.ADD_WAYPOINT; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeUtf(name); - buf.writeBlockPos(position); - buf.writeInt(color); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.addWaypoint(context.getPlayer(), name, position, color); + public static void handle(AddWaypointPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.addWaypoint(context.getPlayer(), message.name, message.position, message.color)); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkChangeResponsePacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkChangeResponsePacket.java index 87945d7e..d073bbc9 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkChangeResponsePacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkChangeResponsePacket.java @@ -1,56 +1,33 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; -import dev.ftb.mods.ftbchunks.api.ClaimResult; +import dev.ftb.mods.ftbchunks.api.ClaimResult.StandardProblem; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.gui.ChunkScreen; +import dev.ftb.mods.ftblibrary.util.NetworkHelper; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import java.util.EnumMap; -public class ChunkChangeResponsePacket extends BaseS2CMessage { - private final int totalChunks; - private final int changedChunks; - private final EnumMap problems; +public record ChunkChangeResponsePacket(int totalChunks, int changedChunks, EnumMap problems) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("chunk_change_response_packet")); - public ChunkChangeResponsePacket(int totalChunks, int changedChunks, EnumMap problems) { - this.totalChunks = totalChunks; - this.changedChunks = changedChunks; - this.problems = problems; - } - - ChunkChangeResponsePacket(FriendlyByteBuf buf) { - totalChunks = buf.readVarInt(); - changedChunks = buf.readVarInt(); - problems = new EnumMap<>(ClaimResult.StandardProblem.class); - - int nProblems = buf.readVarInt(); - for (int i = 0; i < nProblems; i++) { - String name = buf.readUtf(Short.MAX_VALUE); - int count = buf.readVarInt(); - ClaimResult.StandardProblem.forName(name).ifPresent(res -> problems.put(res, count)); - } - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, ChunkChangeResponsePacket::totalChunks, + ByteBufCodecs.VAR_INT, ChunkChangeResponsePacket::changedChunks, + ByteBufCodecs.map(i -> new EnumMap<>(StandardProblem.class), NetworkHelper.enumStreamCodec(StandardProblem.class), ByteBufCodecs.VAR_INT), ChunkChangeResponsePacket::problems, + ChunkChangeResponsePacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.CHUNK_CHANGE_RESPONSE; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeVarInt(totalChunks); - buf.writeVarInt(changedChunks); - buf.writeVarInt(problems.size()); - problems.forEach((res, count) -> { - buf.writeUtf(res.getResultId()); - buf.writeVarInt(count); - }); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - ChunkScreen.notifyChunkUpdates(totalChunks, changedChunks, problems); + public static void handle(ChunkChangeResponsePacket message, NetworkManager.PacketContext context) { + context.queue(() -> ChunkScreen.notifyChunkUpdates(message.totalChunks, message.changedChunks, message.problems)); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkSendingUtils.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkSendingUtils.java deleted file mode 100644 index d830126d..00000000 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ChunkSendingUtils.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.ftb.mods.ftbchunks.net; - -import dev.ftb.mods.ftbchunks.api.ChunkTeamData; -import dev.ftb.mods.ftbchunks.net.SendChunkPacket.SingleChunk; -import net.minecraft.Util; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; - -public class ChunkSendingUtils { - public static void sendChunkToAll(MinecraftServer server, ChunkTeamData teamData, SendChunkPacket packet) { - if (!teamData.shouldHideClaims()) { - packet.sendToAll(server); - } else { - SendChunkPacket hiddenPacket = new SendChunkPacket(packet.dimension, Util.NIL_UUID, packet.chunk.hidden()); - for (ServerPlayer player : server.getPlayerList().getPlayers()) { - (teamData.isAlly(player.getUUID()) ? packet : hiddenPacket).sendTo(player); - } - } - } - - public static void sendManyChunksToAll(MinecraftServer server, ChunkTeamData teamData, SendManyChunksPacket packet) { - if (!teamData.shouldHideClaims()) { - packet.sendToAll(server); - } else { - // shallow copy of packet.chunks OK here, it only contains primitive elements - SendManyChunksPacket hiddenPacket = new SendManyChunksPacket(packet.dimension, Util.NIL_UUID, - packet.chunks.stream().map(SingleChunk::hidden).toList()); - for (ServerPlayer player : server.getPlayerList().getPlayers()) { - (teamData.isAlly(player.getUUID()) ? packet : hiddenPacket).sendTo(player); - } - } - } - - public static void sendManyChunksToPlayer(ServerPlayer player, ChunkTeamData teamData, SendManyChunksPacket packet) { - if (!teamData.shouldHideClaims()) { - packet.sendTo(player); - } else { - // shallow copy of packet.chunks OK here, it only contains primitive elements - SendManyChunksPacket hiddenPacket = new SendManyChunksPacket(packet.dimension, Util.NIL_UUID, - packet.chunks.stream().map(SingleChunk::hidden).toList()); - (teamData.isAlly(player.getUUID()) ? packet : hiddenPacket).sendTo(player); - } - } -} diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/FTBChunksNet.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/FTBChunksNet.java index 0990fc8b..430a9c53 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/FTBChunksNet.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/FTBChunksNet.java @@ -1,32 +1,28 @@ package dev.ftb.mods.ftbchunks.net; -import dev.architectury.networking.simple.MessageType; -import dev.architectury.networking.simple.SimpleNetworkManager; -import dev.ftb.mods.ftbchunks.FTBChunks; +import dev.ftb.mods.ftblibrary.util.NetworkHelper; -public interface FTBChunksNet { - SimpleNetworkManager MAIN = SimpleNetworkManager.create(FTBChunks.MOD_ID); +public class FTBChunksNet { + public static void init() { + NetworkHelper.registerC2S(RequestChunkChangePacket.TYPE, RequestChunkChangePacket.STREAM_CODEC, RequestChunkChangePacket::handle); + NetworkHelper.registerC2S(RequestMapDataPacket.TYPE, RequestMapDataPacket.STREAM_CODEC, RequestMapDataPacket::handle); + NetworkHelper.registerC2S(ServerConfigRequestPacket.TYPE, ServerConfigRequestPacket.STREAM_CODEC, ServerConfigRequestPacket::handle); + NetworkHelper.registerC2S(TeleportFromMapPacket.TYPE, TeleportFromMapPacket.STREAM_CODEC, TeleportFromMapPacket::handle); + NetworkHelper.registerC2S(UpdateForceLoadExpiryPacket.TYPE, UpdateForceLoadExpiryPacket.STREAM_CODEC, UpdateForceLoadExpiryPacket::handle); + NetworkHelper.registerC2S(SyncTXPacket.TYPE, SyncTXPacket.STREAM_CODEC, SyncTXPacket::handle); - MessageType REQUEST_MAP_DATA = MAIN.registerC2S("request_map_data", RequestMapDataPacket::new); - MessageType SEND_ALL_CHUNKS = MAIN.registerS2C("send_all_chunks", SendManyChunksPacket::new); - MessageType LOGIN_DATA = MAIN.registerS2C("login_data", LoginDataPacket::new); - MessageType REQUEST_CHUNK_CHANGE = MAIN.registerC2S("request_chunk_change", RequestChunkChangePacket::new); - MessageType SEND_CHUNK = MAIN.registerS2C("send_chunk", SendChunkPacket::new); - MessageType SEND_GENERAL_DATA = MAIN.registerS2C("send_general_data", SendGeneralDataPacket::new); - MessageType TELEPORT_FROM_MAP = MAIN.registerC2S("teleport_from_map", TeleportFromMapPacket::new); - MessageType PLAYER_DEATH = MAIN.registerS2C("player_death", PlayerDeathPacket::new); - MessageType SEND_VISIBLE_PLAYER_LIST = MAIN.registerS2C("send_visible_player_list", PlayerVisibilityPacket::new); - MessageType SYNC_TX = MAIN.registerC2S("sync_tx", SyncTXPacket::new); - MessageType SYNC_RX = MAIN.registerS2C("sync_rx", SyncRXPacket::new); - MessageType LOADED_CHUNK_VIEW = MAIN.registerS2C("loaded_chunk_view", LoadedChunkViewPacket::new); - MessageType SEND_PLAYER_POSITION = MAIN.registerS2C("send_player_position", SendPlayerPositionPacket::new); - MessageType UPDATE_FORCE_LOAD_EXPIRY = MAIN.registerC2S("update_force_load_expiry", UpdateForceLoadExpiryPacket::new); - MessageType SERVER_CONFIG_REQUEST = MAIN.registerC2S("server_config_request", ServerConfigRequestPacket::new); - MessageType SERVER_CONFIG_RESPONSE = MAIN.registerS2C("server_config_response", ServerConfigResponsePacket::new); - MessageType CHUNK_CHANGE_RESPONSE = MAIN.registerS2C("chunk_change_response", ChunkChangeResponsePacket::new); - MessageType REQUEST_BLOCK_COLOR = MAIN.registerS2C("request_block_color", RequestBlockColorPacket::new); - MessageType ADD_WAYPOINT = MAIN.registerS2C("add_waypoint", AddWaypointPacket::new); - - static void init() { + NetworkHelper.registerS2C(AddWaypointPacket.TYPE, AddWaypointPacket.STREAM_CODEC, AddWaypointPacket::handle); + NetworkHelper.registerS2C(ChunkChangeResponsePacket.TYPE, ChunkChangeResponsePacket.STREAM_CODEC, ChunkChangeResponsePacket::handle); + NetworkHelper.registerS2C(LoadedChunkViewPacket.TYPE, LoadedChunkViewPacket.STREAM_CODEC, LoadedChunkViewPacket::handle); + NetworkHelper.registerS2C(LoginDataPacket.TYPE, LoginDataPacket.STREAM_CODEC, LoginDataPacket::handle); + NetworkHelper.registerS2C(PlayerDeathPacket.TYPE, PlayerDeathPacket.STREAM_CODEC, PlayerDeathPacket::handle); + NetworkHelper.registerS2C(PlayerVisibilityPacket.TYPE, PlayerVisibilityPacket.STREAM_CODEC, PlayerVisibilityPacket::handle); + NetworkHelper.registerS2C(RequestBlockColorPacket.TYPE, RequestBlockColorPacket.STREAM_CODEC, RequestBlockColorPacket::handle); + NetworkHelper.registerS2C(SendChunkPacket.TYPE, SendChunkPacket.STREAM_CODEC, SendChunkPacket::handle); + NetworkHelper.registerS2C(SendGeneralDataPacket.TYPE, SendGeneralDataPacket.STREAM_CODEC, SendGeneralDataPacket::handle); + NetworkHelper.registerS2C(SendManyChunksPacket.TYPE, SendManyChunksPacket.STREAM_CODEC, SendManyChunksPacket::handle); + NetworkHelper.registerS2C(SendPlayerPositionPacket.TYPE, SendPlayerPositionPacket.STREAM_CODEC, SendPlayerPositionPacket::handle); + NetworkHelper.registerS2C(ServerConfigResponsePacket.TYPE, ServerConfigResponsePacket.STREAM_CODEC, ServerConfigResponsePacket::handle); + NetworkHelper.registerS2C(SyncRXPacket.TYPE, SyncRXPacket.STREAM_CODEC, SyncRXPacket::handle); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoadedChunkViewPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoadedChunkViewPacket.java index a06c974e..b80a3137 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoadedChunkViewPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoadedChunkViewPacket.java @@ -1,46 +1,36 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import it.unimi.dsi.fastutil.longs.Long2IntMap; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; -public class LoadedChunkViewPacket extends BaseS2CMessage { - public static final int LOADED = 1; - public static final int FORCE_LOADED = 2; - - private final ResourceKey dimension; - private final Long2IntMap chunks; +public record LoadedChunkViewPacket(ResourceKey dimension, Long2IntMap chunks) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("loaded_chunk_view_packet")); - public LoadedChunkViewPacket(ResourceKey dimension, Long2IntMap chunks) { - this.dimension = dimension; - this.chunks = chunks; - } - - LoadedChunkViewPacket(FriendlyByteBuf buf) { - dimension = ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()); - chunks = buf.readMap(Long2IntOpenHashMap::new, FriendlyByteBuf::readLong, FriendlyByteBuf::readVarInt); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ResourceKey.streamCodec(Registries.DIMENSION), LoadedChunkViewPacket::dimension, + ByteBufCodecs.map(Long2IntOpenHashMap::new, ByteBufCodecs.VAR_LONG, ByteBufCodecs.INT), LoadedChunkViewPacket::chunks, + LoadedChunkViewPacket::new + ); - @Override - public MessageType getType() { - return FTBChunksNet.LOADED_CHUNK_VIEW; - } + public static final int LOADED = 1; + public static final int FORCE_LOADED = 2; @Override - public void write(FriendlyByteBuf buf) { - buf.writeResourceLocation(dimension.location()); - buf.writeMap(chunks, FriendlyByteBuf::writeLong, FriendlyByteBuf::writeVarInt); + public Type type() { + return TYPE; } - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.syncLoadedChunkViewFromServer(dimension, chunks); + public static void handle(LoadedChunkViewPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.syncLoadedChunkViewFromServer(message.dimension, message.chunks)); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoginDataPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoginDataPacket.java index b4870e0a..e43d7622 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoginDataPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/LoginDataPacket.java @@ -1,42 +1,31 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import dev.ftb.mods.ftblibrary.snbt.SNBTCompoundTag; -import dev.ftb.mods.ftblibrary.snbt.SNBTNet; +import net.minecraft.core.UUIDUtil; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import java.util.UUID; -public class LoginDataPacket extends BaseS2CMessage { - private final UUID serverId; - private final SNBTCompoundTag config; +public record LoginDataPacket(UUID serverId, SNBTCompoundTag config) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("login_data_packet")); - public LoginDataPacket(UUID serverId, SNBTCompoundTag config) { - this.serverId = serverId; - this.config = config; - } - - LoginDataPacket(FriendlyByteBuf buf) { - serverId = buf.readUUID(); - config = SNBTNet.readCompound(buf); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + UUIDUtil.STREAM_CODEC, LoginDataPacket::serverId, + SNBTCompoundTag.STREAM_CODEC, LoginDataPacket::config, + LoginDataPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.LOGIN_DATA; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeUUID(serverId); - SNBTNet.write(buf, config); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.handlePlayerLogin(serverId, config); + public static void handle(LoginDataPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.handlePlayerLogin(message.serverId, message.config)); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/PartialPackets.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/PartialPackets.java index 5db9b4da..15f61d5d 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/PartialPackets.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/PartialPackets.java @@ -7,8 +7,8 @@ import java.util.*; public class PartialPackets { - public static final PartialPackets REGION - = new PartialPackets<>(SyncTXPacket::new, (key, data) -> ClientTaskQueue.queue(new SyncRXTask(key, data))); + public static final PartialPackets REGION + = new PartialPackets<>(SyncRXPacket::new, (key, data) -> ClientTaskQueue.queue(new SyncRXTask(key, data))); public static class PartialData { private int remaining; diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerDeathPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerDeathPacket.java index be40e56b..d672c204 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerDeathPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerDeathPacket.java @@ -1,42 +1,29 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import net.minecraft.core.GlobalPos; -import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceKey; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -public class PlayerDeathPacket extends BaseS2CMessage { - private final GlobalPos pos; - private final int number; +public record PlayerDeathPacket(GlobalPos pos, int number) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("player_death_packet")); - public PlayerDeathPacket(GlobalPos pos, int num) { - this.pos = pos; - number = num; - } - - PlayerDeathPacket(FriendlyByteBuf buf) { - pos = GlobalPos.of(ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()), buf.readBlockPos()); - number = buf.readVarInt(); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + GlobalPos.STREAM_CODEC, PlayerDeathPacket::pos, + ByteBufCodecs.INT, PlayerDeathPacket::number, + PlayerDeathPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.PLAYER_DEATH; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeResourceLocation(pos.dimension().location()); - buf.writeBlockPos(pos.pos()); - buf.writeVarInt(number); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.handlePlayerDeath(pos, number); + public static void handle(PlayerDeathPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.handlePlayerDeath(message.pos, message.number)); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerVisibilityPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerVisibilityPacket.java index b08bdd01..dea308ca 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerVisibilityPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/PlayerVisibilityPacket.java @@ -1,14 +1,17 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; import dev.ftb.mods.ftbchunks.FTBChunksWorldConfig; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.api.FTBChunksProperties; import dev.ftb.mods.ftbchunks.client.VisibleClientPlayers; import dev.ftb.mods.ftbchunks.data.ChunkTeamDataImpl; import dev.ftb.mods.ftbchunks.data.ClaimedChunkManagerImpl; +import net.minecraft.core.UUIDUtil; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; @@ -16,32 +19,22 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import java.util.stream.Collectors; -public class PlayerVisibilityPacket extends BaseS2CMessage { - private final List uuids; +public record PlayerVisibilityPacket(List uuids) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("player_visibility_packet")); - private PlayerVisibilityPacket(List uuids) { - this.uuids = uuids; - } - - PlayerVisibilityPacket(FriendlyByteBuf buf) { - uuids = buf.readList(FriendlyByteBuf::readUUID); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + UUIDUtil.STREAM_CODEC.apply(ByteBufCodecs.list()), PlayerVisibilityPacket::uuids, + PlayerVisibilityPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.SEND_VISIBLE_PLAYER_LIST; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeCollection(uuids, FriendlyByteBuf::writeUUID); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - VisibleClientPlayers.updatePlayerList(uuids); + public static void handle(PlayerVisibilityPacket message, NetworkManager.PacketContext context) { + context.queue(() -> VisibleClientPlayers.updatePlayerList(message.uuids)); } public static void syncToLevel(Level level) { @@ -62,7 +55,7 @@ public static void syncToPlayers(List players) { } playerList = players.stream() .map(player -> new VisiblePlayerItem(player, ClaimedChunkManagerImpl.getInstance().getOrCreateData(player))) - .collect(Collectors.toList()); + .toList(); boolean override = FTBChunksWorldConfig.LOCATION_MODE_OVERRIDE.get(); for (VisiblePlayerItem recipient : playerList) { @@ -74,7 +67,7 @@ public static void syncToPlayers(List players) { } } - new PlayerVisibilityPacket(playerIds).sendTo(recipient.player); + NetworkManager.sendToPlayer(recipient.player, new PlayerVisibilityPacket(playerIds)); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestBlockColorPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestBlockColorPacket.java index b3e346ef..b64a78f0 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestBlockColorPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestBlockColorPacket.java @@ -1,29 +1,25 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -public class RequestBlockColorPacket extends BaseS2CMessage { - public RequestBlockColorPacket() { - } +public record RequestBlockColorPacket() implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("request_block_color_packet")); - public RequestBlockColorPacket(FriendlyByteBuf buf) { - } + private static final RequestBlockColorPacket INSTANCE = new RequestBlockColorPacket(); - @Override - public MessageType getType() { - return FTBChunksNet.REQUEST_BLOCK_COLOR; - } + public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); @Override - public void write(FriendlyByteBuf buf) { + public Type type() { + return TYPE; } - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.handleBlockColorRequest(); + public static void handle(RequestBlockColorPacket message, NetworkManager.PacketContext context) { + context.queue(FTBChunksClient.INSTANCE::handleBlockColorRequest); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestChunkChangePacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestChunkChangePacket.java index fa2b1ce9..3f541ff4 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestChunkChangePacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestChunkChangePacket.java @@ -1,56 +1,44 @@ package dev.ftb.mods.ftbchunks.net; -import com.google.common.collect.Sets; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseC2SMessage; -import dev.architectury.networking.simple.MessageType; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.api.ChunkTeamData; import dev.ftb.mods.ftbchunks.api.ClaimResult; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.data.ClaimedChunkManagerImpl; import dev.ftb.mods.ftblibrary.math.XZ; +import dev.ftb.mods.ftblibrary.util.NetworkHelper; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; import java.util.EnumMap; +import java.util.HashSet; import java.util.Set; import java.util.function.Function; -public class RequestChunkChangePacket extends BaseC2SMessage { - private final ChunkChangeOp action; - private final Set chunks; +public record RequestChunkChangePacket(ChunkChangeOp action, Set chunks) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("request_chunk_change_packet")); - public RequestChunkChangePacket(ChunkChangeOp action, Set chunks) { - this.action = action; - this.chunks = chunks; - } - - RequestChunkChangePacket(FriendlyByteBuf buf) { - action = buf.readEnum(ChunkChangeOp.class); - chunks = buf.readCollection(Sets::newHashSetWithExpectedSize, buf1 -> XZ.of(buf1.readVarInt(), buf1.readVarInt())); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + NetworkHelper.enumStreamCodec(ChunkChangeOp.class), RequestChunkChangePacket::action, + XZ.STREAM_CODEC.apply(ByteBufCodecs.collection(HashSet::new)), RequestChunkChangePacket::chunks, + RequestChunkChangePacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.REQUEST_CHUNK_CHANGE; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeEnum(action); - buf.writeCollection(chunks, (buf1, xz) -> { - buf1.writeVarInt(xz.x()); - buf1.writeVarInt(xz.z()); - }); - } - - @Override - public void handle(NetworkManager.PacketContext context) { + public static void handle(RequestChunkChangePacket message, NetworkManager.PacketContext context) { ServerPlayer player = (ServerPlayer) context.getPlayer(); CommandSourceStack source = player.createCommandSourceStack(); ChunkTeamData data = ClaimedChunkManagerImpl.getInstance().getOrCreateData(player); - Function consumer = switch (action) { + Function consumer = switch (message.action) { case CLAIM -> pos -> data.claim(source, pos.dim(player.level()), false); case UNCLAIM -> pos -> data.unclaim(source, pos.dim(player.level()), false); case LOAD -> pos -> data.forceLoad(source, pos.dim(player.level()), false); @@ -59,11 +47,11 @@ public void handle(NetworkManager.PacketContext context) { EnumMap problems = new EnumMap<>(ClaimResult.StandardProblem.class); int changed = 0; - for (XZ pos : chunks) { + for (XZ pos : message.chunks) { ClaimResult r = consumer.apply(pos); if (!r.isSuccess()) { FTBChunks.LOGGER.debug(String.format("%s tried to %s @ %s:%d:%d but got result %s", player.getScoreboardName(), - action.name, player.level().dimension().location(), pos.x(), pos.z(), r)); + message.action.name, player.level().dimension().location(), pos.x(), pos.z(), r)); if (r instanceof ClaimResult.StandardProblem cr) { problems.put(cr, problems.getOrDefault(cr, 0) + 1); } @@ -72,7 +60,7 @@ public void handle(NetworkManager.PacketContext context) { } } - new ChunkChangeResponsePacket(chunks.size(), changed, problems).sendTo(player); + NetworkManager.sendToPlayer(player, new ChunkChangeResponsePacket(message.chunks.size(), changed, problems)); SendGeneralDataPacket.send(data, player); } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestMapDataPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestMapDataPacket.java index 29021aaf..568da67b 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestMapDataPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/RequestMapDataPacket.java @@ -1,45 +1,32 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseC2SMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; /** * @author LatvianModder */ -public class RequestMapDataPacket extends BaseC2SMessage { - private final int fromX, fromZ, toX, toZ; +public record RequestMapDataPacket(int fromX, int fromZ, int toX, int toZ) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("request_map_data_packet")); - public RequestMapDataPacket(int fx, int fz, int tx, int tz) { - fromX = fx; - fromZ = fz; - toX = tx; - toZ = tz; - } - - RequestMapDataPacket(FriendlyByteBuf buf) { - fromX = buf.readVarInt(); - fromZ = buf.readVarInt(); - toX = buf.readVarInt(); - toZ = buf.readVarInt(); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, RequestMapDataPacket::fromX, + ByteBufCodecs.INT, RequestMapDataPacket::fromZ, + ByteBufCodecs.INT, RequestMapDataPacket::toX, + ByteBufCodecs.INT, RequestMapDataPacket::toZ, + RequestMapDataPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.REQUEST_MAP_DATA; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeVarInt(fromX); - buf.writeVarInt(fromZ); - buf.writeVarInt(toX); - buf.writeVarInt(toZ); - } - - @Override - public void handle(NetworkManager.PacketContext context) { + public static void handle(RequestMapDataPacket message, NetworkManager.PacketContext context) { //FIXME: SendMapDataPacket.send(Objects.requireNonNull(context.get().getSender()))); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendChunkPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendChunkPacket.java index 245bdf64..46c6f053 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendChunkPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendChunkPacket.java @@ -1,143 +1,53 @@ package dev.ftb.mods.ftbchunks.net; -import com.google.common.primitives.Ints; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; -import dev.ftb.mods.ftbchunks.api.ClaimedChunk; +import dev.ftb.mods.ftbchunks.api.ChunkTeamData; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; -import dev.ftb.mods.ftbchunks.client.map.MapChunk; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; import net.minecraft.Util; +import net.minecraft.core.UUIDUtil; import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; -import org.jetbrains.annotations.Nullable; -import java.util.Date; import java.util.List; import java.util.UUID; -public class SendChunkPacket extends BaseS2CMessage { - public final ResourceKey dimension; - public final UUID teamId; - public final SingleChunk chunk; - - public SendChunkPacket(ResourceKey dimension, UUID teamId, SingleChunk chunk) { - this.dimension = dimension; - this.teamId = teamId; - this.chunk = chunk; - } - - SendChunkPacket(FriendlyByteBuf buf) { - dimension = ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()); - teamId = buf.readUUID(); - chunk = new SingleChunk(buf, teamId); - } - - @Override - public MessageType getType() { - return FTBChunksNet.SEND_CHUNK; - } - - @Override - public void write(FriendlyByteBuf buf) { - buf.writeResourceLocation(dimension.location()); - buf.writeUUID(teamId); - chunk.write(buf, teamId); - } +public record SendChunkPacket(ResourceKey dimension, UUID teamId, ChunkSyncInfo chunk) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("send_chunk_packet")); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ResourceKey.streamCodec(Registries.DIMENSION), SendChunkPacket::dimension, + UUIDUtil.STREAM_CODEC, SendChunkPacket::teamId, + ChunkSyncInfo.STREAM_CODEC, SendChunkPacket::chunk, + SendChunkPacket::new + ); + + public void sendToAll(MinecraftServer server, ChunkTeamData teamData) { + if (teamData.shouldHideClaims()) { + // only send to those players who are allies of the team + SendChunkPacket hiddenPacket = new SendChunkPacket(dimension(), Util.NIL_UUID, chunk().hidden()); + for (ServerPlayer player : server.getPlayerList().getPlayers()) { + NetworkManager.sendToPlayer(player, teamData.isAlly(player.getUUID()) ? this : hiddenPacket); + } + } else { + // just send to everyone + NetworkManager.sendToPlayers(server.getPlayerList().getPlayers(), this); + } + } @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.updateChunksFromServer(dimension, teamId, List.of(chunk)); + public Type type() { + return TYPE; } - public static class SingleChunk { - // NOTE: relative times are sent in seconds rather than milliseconds - // (int rather than long for network sync efficiency) - // allows for offsets of up to ~2 billion seconds, which is 62 years - should be enough... - // (come back to me with a bug report in 2085 if not) - private final int x, z; - private final int relativeTimeClaimed; - private final boolean forceLoaded; - private final int relativeTimeForceLoaded; - private final boolean expires; - private final int relativeForceLoadExpiryTime; - - public SingleChunk(long now, int x, int z, @Nullable ClaimedChunk claimedChunk) { - this.x = x; - this.z = z; - - if (claimedChunk != null) { - relativeTimeClaimed = millisToSeconds(now - claimedChunk.getTimeClaimed()); - forceLoaded = claimedChunk.isForceLoaded(); - expires = claimedChunk.getForceLoadExpiryTime() > 0L; - relativeTimeForceLoaded = forceLoaded ? millisToSeconds(now - claimedChunk.getForceLoadedTime()) : 0; - relativeForceLoadExpiryTime = expires ? millisToSeconds(claimedChunk.getForceLoadExpiryTime() - now) : 0; - } else { - relativeTimeClaimed = relativeTimeForceLoaded = relativeForceLoadExpiryTime = 0; - forceLoaded = expires = false; - } - } - - private static int millisToSeconds(long ms) { - return Ints.saturatedCast(ms / 1000L); - } - - public int getX() { - return x; - } - - public int getZ() { - return z; - } - - public SingleChunk(FriendlyByteBuf buf, UUID teamId) { - x = buf.readVarInt(); - z = buf.readVarInt(); - - if (!teamId.equals(Util.NIL_UUID)) { - relativeTimeClaimed = buf.readInt(); - byte b = buf.readByte(); - forceLoaded = (b & 0x01) != 0; - expires = (b & 0x02) != 0; - relativeTimeForceLoaded = forceLoaded ? buf.readInt() : 0; - relativeForceLoadExpiryTime = expires ? buf.readInt() : 0; - } else { - relativeTimeClaimed = relativeTimeForceLoaded = relativeForceLoadExpiryTime = 0; - forceLoaded = expires = false; - } - } - - public void write(FriendlyByteBuf buf, UUID teamId) { - buf.writeVarInt(x); - buf.writeVarInt(z); - - if (!teamId.equals(Util.NIL_UUID)) { - byte b = 0x0; - if (forceLoaded) b |= 0x1; - if (expires) b |= 0x2; - - buf.writeInt(relativeTimeClaimed); - buf.writeByte(b); - if (forceLoaded) buf.writeInt(relativeTimeForceLoaded); - if (expires) buf.writeInt(relativeForceLoadExpiryTime); - } - } - - public SingleChunk hidden() { - return new SingleChunk(0L, x, z, null); - } - - public MapChunk.DateInfo getDateInfo(boolean isClaimed, long now) { - if (!isClaimed) { - return MapChunk.NO_DATE_INFO; - } - - Date claimed = new Date(now - relativeTimeClaimed * 1000L); - Date forceLoaded = this.forceLoaded ? new Date(now - relativeTimeForceLoaded * 1000L) : null; - Date expiry = this.forceLoaded && expires ? new Date(now + relativeForceLoadExpiryTime * 1000L) : null; - return new MapChunk.DateInfo(claimed, forceLoaded, expiry); - } + public static void handle(SendChunkPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.updateChunksFromServer(message.dimension, message.teamId, List.of(message.chunk))); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendGeneralDataPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendGeneralDataPacket.java index 1971d4ef..746f938e 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendGeneralDataPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendGeneralDataPacket.java @@ -1,41 +1,34 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; import dev.ftb.mods.ftbchunks.api.ChunkTeamData; import dev.ftb.mods.ftbchunks.api.ClaimedChunk; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; import java.util.Collection; import java.util.List; -public class SendGeneralDataPacket extends BaseS2CMessage { - private final GeneralChunkData data; +public record SendGeneralDataPacket(GeneralChunkData data) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("send_general_data_packet")); - private SendGeneralDataPacket(int claimed, int loaded, int maxClaimChunks, int maxForceLoadChunks) { - data = new GeneralChunkData(claimed, loaded, maxClaimChunks, maxForceLoadChunks); - } - - SendGeneralDataPacket(FriendlyByteBuf buf) { - data = GeneralChunkData.fromNetwork(buf); - } - - @Override - public MessageType getType() { - return FTBChunksNet.SEND_GENERAL_DATA; - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + GeneralChunkData.STREAM_CODEC, SendGeneralDataPacket::data, + SendGeneralDataPacket::new + ); @Override - public void write(FriendlyByteBuf buf) { - data.toNetwork(buf); + public Type type() { + return TYPE; } - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.updateGeneralData(data); + public static void handle(SendGeneralDataPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.updateGeneralData(message.data)); } public static void send(ChunkTeamData teamData, ServerPlayer player) { @@ -45,26 +38,23 @@ public static void send(ChunkTeamData teamData, ServerPlayer player) { public static void send(ChunkTeamData teamData, Collection players) { var cc = teamData.getClaimedChunks(); int loaded = (int) cc.stream().filter(ClaimedChunk::isForceLoaded).count(); - SendGeneralDataPacket data = new SendGeneralDataPacket(cc.size(), loaded, teamData.getMaxClaimChunks(), teamData.getMaxForceLoadChunks()); + SendGeneralDataPacket data = new SendGeneralDataPacket(new GeneralChunkData(cc.size(), loaded, teamData.getMaxClaimChunks(), teamData.getMaxForceLoadChunks())); players.forEach(player -> teamData.getTeamManager().getTeamForPlayer(player).ifPresent(team -> { if (team.getId().equals(teamData.getTeam().getId())) { - data.sendTo(player); + NetworkManager.sendToPlayer(player, data); } })); } public record GeneralChunkData(int claimed, int loaded, int maxClaimChunks, int maxForceLoadChunks) { - public static GeneralChunkData fromNetwork(FriendlyByteBuf buf) { - return new GeneralChunkData(buf.readVarInt(), buf.readVarInt(), buf.readVarInt(), buf.readVarInt()); - } - - public void toNetwork(FriendlyByteBuf buf) { - buf.writeVarInt(claimed); - buf.writeVarInt(loaded); - buf.writeVarInt(maxClaimChunks); - buf.writeVarInt(maxForceLoadChunks); - } + public static StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, GeneralChunkData::claimed, + ByteBufCodecs.VAR_INT, GeneralChunkData::loaded, + ByteBufCodecs.VAR_INT, GeneralChunkData::maxClaimChunks, + ByteBufCodecs.VAR_INT, GeneralChunkData::maxForceLoadChunks, + GeneralChunkData::new + ); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendManyChunksPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendManyChunksPacket.java index 54fd5942..742eb348 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendManyChunksPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendManyChunksPacket.java @@ -1,49 +1,65 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.ChunkTeamData; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; -import dev.ftb.mods.ftbchunks.net.SendChunkPacket.SingleChunk; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; +import net.minecraft.Util; +import net.minecraft.core.UUIDUtil; import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; import java.util.List; import java.util.UUID; -public class SendManyChunksPacket extends BaseS2CMessage { - public final ResourceKey dimension; - public final UUID teamId; - public final List chunks; +public record SendManyChunksPacket(ResourceKey dimension, UUID teamId, List chunks) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("send_many_chunks_packet")); - public SendManyChunksPacket(ResourceKey dimension, UUID teamId, List chunks) { - this.dimension = dimension; - this.teamId = teamId; - this.chunks = chunks; - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ResourceKey.streamCodec(Registries.DIMENSION), SendManyChunksPacket::dimension, + UUIDUtil.STREAM_CODEC, SendManyChunksPacket::teamId, + ChunkSyncInfo.STREAM_CODEC.apply(ByteBufCodecs.list()), SendManyChunksPacket::chunks, + SendManyChunksPacket::new + ); - @Override - public MessageType getType() { - return FTBChunksNet.SEND_ALL_CHUNKS; - } + public void sendToAll(MinecraftServer server, ChunkTeamData teamData) { + if (teamData.shouldHideClaims()) { + SendManyChunksPacket hiddenPacket = hidden(); + for (ServerPlayer player : server.getPlayerList().getPlayers()) { + NetworkManager.sendToPlayer(player, teamData.isAlly(player.getUUID()) ? this : hiddenPacket); + } + } else { + NetworkManager.sendToPlayers(server.getPlayerList().getPlayers(), this); + } + } - SendManyChunksPacket(FriendlyByteBuf buf) { - dimension = ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()); - teamId = buf.readUUID(); - chunks = buf.readList(buf1 -> new SingleChunk(buf1, teamId)); + public void sendToPlayer(ServerPlayer player, ChunkTeamData teamData) { + if (teamData.shouldHideClaims()) { + NetworkManager.sendToPlayer(player, teamData.isAlly(player.getUUID()) ? this : hidden()); + } else { + NetworkManager.sendToPlayer(player, this); + } + } + + public SendManyChunksPacket hidden() { + // shallow copy of packet.chunks OK here, it only contains primitive elements + return new SendManyChunksPacket(dimension(), Util.NIL_UUID, chunks().stream().map(ChunkSyncInfo::hidden).toList()); } @Override - public void write(FriendlyByteBuf buf) { - buf.writeResourceLocation(dimension.location()); - buf.writeUUID(teamId); - buf.writeCollection(chunks, (buf1, chunk) -> chunk.write(buf1, teamId)); + public Type type() { + return TYPE; } - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.updateChunksFromServer(dimension, teamId, chunks); + public static void handle(SendManyChunksPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.updateChunksFromServer(message.dimension, message.teamId, message.chunks)); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendPlayerPositionPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendPlayerPositionPacket.java index 62b09181..4f3391a1 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendPlayerPositionPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SendPlayerPositionPacket.java @@ -1,46 +1,41 @@ package dev.ftb.mods.ftbchunks.net; -import com.mojang.authlib.GameProfile; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.item.component.ResolvableProfile; -public class SendPlayerPositionPacket extends BaseS2CMessage { - private final GameProfile gameProfile; - private final BlockPos pos; - private final boolean valid; +import java.util.Optional; - public SendPlayerPositionPacket(ServerPlayer player, BlockPos pos) { - this.pos = pos == null ? BlockPos.ZERO : pos; - this.valid = pos != null; - this.gameProfile = player.getGameProfile(); - } +public record SendPlayerPositionPacket(ResolvableProfile profile, Optional pos) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("send_player_position_packet")); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ResolvableProfile.STREAM_CODEC, SendPlayerPositionPacket::profile, + ByteBufCodecs.optional(BlockPos.STREAM_CODEC), SendPlayerPositionPacket::pos, + SendPlayerPositionPacket::new + ); - SendPlayerPositionPacket(FriendlyByteBuf buf) { - pos = buf.readBlockPos(); - valid = buf.readBoolean(); - gameProfile = new GameProfile(buf.readUUID(), buf.readUtf()); + public static SendPlayerPositionPacket startTracking(ServerPlayer player) { + return new SendPlayerPositionPacket(new ResolvableProfile(player.getGameProfile()), Optional.of(player.blockPosition())); } - @Override - public MessageType getType() { - return FTBChunksNet.SEND_PLAYER_POSITION; + public static SendPlayerPositionPacket stopTracking(ServerPlayer player) { + return new SendPlayerPositionPacket(new ResolvableProfile(player.getGameProfile()), Optional.empty()); } @Override - public void write(FriendlyByteBuf buf) { - buf.writeBlockPos(pos); - buf.writeBoolean(valid); - buf.writeUUID(gameProfile.getId()); - buf.writeUtf(gameProfile.getName()); + public Type type() { + return TYPE; } - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.updateTrackedPlayerPos(gameProfile, pos, valid); + public static void handle(SendPlayerPositionPacket message, NetworkManager.PacketContext context) { + FTBChunksClient.INSTANCE.updateTrackedPlayerPos(message.profile.gameProfile(), message.pos.orElse(null)); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigRequestPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigRequestPacket.java index 0235c357..7f523fc8 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigRequestPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigRequestPacket.java @@ -1,64 +1,57 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseC2SMessage; -import dev.architectury.networking.simple.MessageType; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.FTBChunksWorldConfig; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.data.ClaimedChunkManagerImpl; import dev.ftb.mods.ftbchunks.util.DimensionFilter; import dev.ftb.mods.ftblibrary.snbt.SNBTCompoundTag; -import dev.ftb.mods.ftblibrary.snbt.SNBTNet; import dev.ftb.mods.ftblibrary.snbt.config.ConfigUtil; import dev.ftb.mods.ftbteams.api.FTBTeamsAPI; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import java.nio.file.Path; -public class ServerConfigRequestPacket extends BaseC2SMessage { - private final SNBTCompoundTag config; +public record ServerConfigRequestPacket(SNBTCompoundTag config) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("server_config_request_packet")); - public ServerConfigRequestPacket(SNBTCompoundTag config) { - this.config = config; - } - - public ServerConfigRequestPacket(FriendlyByteBuf buf) { - config = SNBTNet.readCompound(buf); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + SNBTCompoundTag.STREAM_CODEC, ServerConfigRequestPacket::config, + ServerConfigRequestPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.SERVER_CONFIG_REQUEST; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - SNBTNet.write(buf, config); - } - - @Override - public void handle(NetworkManager.PacketContext context) { + public static void handle(ServerConfigRequestPacket message, NetworkManager.PacketContext context) { if (context.getPlayer() instanceof ServerPlayer sp && sp.hasPermissions(2)) { - MinecraftServer server = sp.getServer(); + context.queue(() -> { + MinecraftServer server = sp.getServer(); - FTBChunks.LOGGER.info("FTB Chunks server config updated from client by player {}", sp.getName().getString()); - FTBChunksWorldConfig.CONFIG.read(config); + FTBChunks.LOGGER.info("FTB Chunks server config updated from client by player {}", sp.getName().getString()); + FTBChunksWorldConfig.CONFIG.read(message.config); - DimensionFilter.clearMatcherCaches(); + DimensionFilter.clearMatcherCaches(); - Path file = server.getWorldPath(ConfigUtil.SERVER_CONFIG_DIR).resolve(FTBChunksWorldConfig.CONFIG.key + ".snbt"); - FTBChunksWorldConfig.CONFIG.save(file); + Path file = server.getWorldPath(ConfigUtil.SERVER_CONFIG_DIR).resolve(FTBChunksWorldConfig.CONFIG.key + ".snbt"); + FTBChunksWorldConfig.CONFIG.save(file); - for (ServerPlayer player : server.getPlayerList().getPlayers()) { - if (!sp.getUUID().equals(player.getUUID())) { - new ServerConfigResponsePacket(config).sendTo(player); + for (ServerPlayer player : server.getPlayerList().getPlayers()) { + if (!sp.getUUID().equals(player.getUUID())) { + NetworkManager.sendToPlayer(player, new ServerConfigResponsePacket(message.config)); + } } - } - FTBTeamsAPI.api().getManager().getTeams().forEach(team -> - ClaimedChunkManagerImpl.getInstance().getOrCreateData(team).updateLimits()); + FTBTeamsAPI.api().getManager().getTeams().forEach(team -> + ClaimedChunkManagerImpl.getInstance().getOrCreateData(team).updateLimits()); + }); } } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigResponsePacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigResponsePacket.java index ef506d92..e0e346b1 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigResponsePacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/ServerConfigResponsePacket.java @@ -1,38 +1,29 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; import dev.ftb.mods.ftbchunks.FTBChunks; import dev.ftb.mods.ftbchunks.FTBChunksWorldConfig; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftblibrary.snbt.SNBTCompoundTag; -import dev.ftb.mods.ftblibrary.snbt.SNBTNet; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -public class ServerConfigResponsePacket extends BaseS2CMessage { - private final SNBTCompoundTag config; +public record ServerConfigResponsePacket(SNBTCompoundTag config) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("server_config_response_packet")); - public ServerConfigResponsePacket(SNBTCompoundTag config) { - this.config = config; - } - - public ServerConfigResponsePacket(FriendlyByteBuf buf) { - config = SNBTNet.readCompound(buf); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + SNBTCompoundTag.STREAM_CODEC, ServerConfigResponsePacket::config, + ServerConfigResponsePacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.SERVER_CONFIG_RESPONSE; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - SNBTNet.write(buf, config); - } - - @Override - public void handle(NetworkManager.PacketContext context) { + public static void handle(ServerConfigResponsePacket message, NetworkManager.PacketContext context) { FTBChunks.LOGGER.info("Received FTB Chunks server config from server"); - FTBChunksWorldConfig.CONFIG.read(config); + context.queue(() -> FTBChunksWorldConfig.CONFIG.read(message.config)); } } diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncRXPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncRXPacket.java index 5701536c..65cbe830 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncRXPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncRXPacket.java @@ -1,47 +1,31 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseS2CMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import dev.ftb.mods.ftbchunks.client.map.RegionSyncKey; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -public class SyncRXPacket extends BaseS2CMessage { - public final RegionSyncKey key; - public final int offset; - public final int total; - public final byte[] data; +public record SyncRXPacket(RegionSyncKey key, int offset, int total, byte[] data) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("sync_rx_packet")); - public SyncRXPacket(RegionSyncKey k, int o, int t, byte[] d) { - key = k; - offset = o; - total = t; - data = d; - } - - SyncRXPacket(FriendlyByteBuf buf) { - key = new RegionSyncKey(buf); - offset = buf.readVarInt(); - total = buf.readVarInt(); - data = buf.readByteArray(Integer.MAX_VALUE); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + RegionSyncKey.STREAM_CODEC, SyncRXPacket::key, + ByteBufCodecs.VAR_INT, SyncRXPacket::offset, + ByteBufCodecs.VAR_INT, SyncRXPacket::total, + ByteBufCodecs.BYTE_ARRAY, SyncRXPacket::data, + SyncRXPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.SYNC_RX; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - key.write(buf); - buf.writeVarInt(offset); - buf.writeVarInt(total); - buf.writeByteArray(data); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - FTBChunksClient.INSTANCE.syncRegionFromServer(key, offset, total, data); + public static void handle(SyncRXPacket message, NetworkManager.PacketContext context) { + context.queue(() -> FTBChunksClient.INSTANCE.syncRegionFromServer(message.key, message.offset, message.total, message.data)); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncTXPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncTXPacket.java index 3c6d4b54..9bf2f602 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncTXPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/SyncTXPacket.java @@ -1,58 +1,42 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseC2SMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.client.map.RegionSyncKey; import dev.ftb.mods.ftbchunks.data.ChunkTeamDataImpl; import dev.ftb.mods.ftbchunks.data.ClaimedChunkManagerImpl; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; -public class SyncTXPacket extends BaseC2SMessage { - public final RegionSyncKey key; - public final int offset; - public final int total; - public final byte[] data; +public record SyncTXPacket(RegionSyncKey key, int offset, int total, byte[] data) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("sync_tx_packet")); - public SyncTXPacket(RegionSyncKey k, int o, int t, byte[] d) { - key = k; - offset = o; - total = t; - data = d; - } - - SyncTXPacket(FriendlyByteBuf buf) { - key = new RegionSyncKey(buf); - offset = buf.readVarInt(); - total = buf.readVarInt(); - data = buf.readByteArray(Integer.MAX_VALUE); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + RegionSyncKey.STREAM_CODEC, SyncTXPacket::key, + ByteBufCodecs.VAR_INT, SyncTXPacket::offset, + ByteBufCodecs.VAR_INT, SyncTXPacket::total, + ByteBufCodecs.BYTE_ARRAY, SyncTXPacket::data, + SyncTXPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.SYNC_TX; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - key.write(buf); - buf.writeVarInt(offset); - buf.writeVarInt(total); - buf.writeByteArray(data); - } - - @Override - public void handle(NetworkManager.PacketContext context) { - ServerPlayer p = (ServerPlayer) context.getPlayer(); - ChunkTeamDataImpl pd = ClaimedChunkManagerImpl.getInstance().getOrCreateData(p); + public static void handle(SyncTXPacket message, NetworkManager.PacketContext context) { + context.queue(() -> { + ServerPlayer serverPlayer = (ServerPlayer) context.getPlayer(); + ChunkTeamDataImpl teamData = ClaimedChunkManagerImpl.getInstance().getOrCreateData(serverPlayer); - for (ServerPlayer p1 : p.getServer().getPlayerList().getPlayers()) { - if (p1 != p) { - if (pd.isAlly(p.getUUID())) { - new SyncRXPacket(key, offset, total, data).sendTo(p1); + for (ServerPlayer p1 : serverPlayer.getServer().getPlayerList().getPlayers()) { + if (p1 != serverPlayer && teamData.isAlly(serverPlayer.getUUID())) { + NetworkManager.sendToPlayer(p1, message); } } - } + }); } } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/TeleportFromMapPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/TeleportFromMapPacket.java index 2cc0ad30..948890d3 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/TeleportFromMapPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/TeleportFromMapPacket.java @@ -1,12 +1,14 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseC2SMessage; -import dev.architectury.networking.simple.MessageType; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.util.HeightUtils; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; @@ -14,66 +16,54 @@ import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.levelgen.Heightmap; -public class TeleportFromMapPacket extends BaseC2SMessage { - private final BlockPos pos; - private final boolean unknownY; - private final ResourceKey dimension; +public record TeleportFromMapPacket(BlockPos pos, boolean unknownY, ResourceKey dimension) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("teleport_from_map_packet")); - public TeleportFromMapPacket(BlockPos pos, boolean unknownY, ResourceKey dimension) { - this.pos = pos; - this.unknownY = unknownY; - this.dimension = dimension; - } - - TeleportFromMapPacket(FriendlyByteBuf buf) { - pos = buf.readBlockPos(); - unknownY = buf.readBoolean(); - dimension = ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, TeleportFromMapPacket::pos, + ByteBufCodecs.BOOL, TeleportFromMapPacket::unknownY, + ResourceKey.streamCodec(Registries.DIMENSION), TeleportFromMapPacket::dimension, + TeleportFromMapPacket::new + ); @Override - public MessageType getType() { - return FTBChunksNet.TELEPORT_FROM_MAP; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeBlockPos(pos); - buf.writeBoolean(unknownY); - buf.writeResourceLocation(dimension.location()); - } + public static void handle(TeleportFromMapPacket message, NetworkManager.PacketContext context) { + context.queue(() -> { + ServerPlayer p = (ServerPlayer) context.getPlayer(); + ServerLevel level = p.getServer().getLevel(message.dimension); - @Override - public void handle(NetworkManager.PacketContext context) { - ServerPlayer p = (ServerPlayer) context.getPlayer(); - ServerLevel level = p.getServer().getLevel(dimension); + if (level != null && p.hasPermissions(2)) { + int x1 = message.pos.getX(); + int y1 = message.pos.getY(); + int z1 = message.pos.getZ(); - if (level != null && p.hasPermissions(2)) { - int x1 = pos.getX(); - int y1 = pos.getY(); - int z1 = pos.getZ(); + if (message.unknownY) { + ChunkAccess chunkAccess = level.getChunkAt(message.pos); - if (unknownY) { - ChunkAccess chunkAccess = level.getChunkAt(pos); + int topY = chunkAccess.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x1, z1); + if (topY == chunkAccess.getMinBuildHeight() - 1) { + return; + } - int topY = chunkAccess.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x1, z1); - if (topY == chunkAccess.getMinBuildHeight() - 1) { - return; - } + BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos(x1, topY + 2, z1); + int water = HeightUtils.getHeight(level, chunkAccess, blockPos); - BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos(x1, topY + 2, z1); - int water = HeightUtils.getHeight(level, chunkAccess, blockPos); + if (blockPos.getY() == HeightUtils.UNKNOWN) { + blockPos.setY(70); + } else if (water != HeightUtils.UNKNOWN) { + blockPos.setY(Math.max(blockPos.getY(), water)); + } - if (blockPos.getY() == HeightUtils.UNKNOWN) { - blockPos.setY(70); - } else if (water != HeightUtils.UNKNOWN) { - blockPos.setY(Math.max(blockPos.getY(), water)); + y1 = blockPos.getY() + 1; } - y1 = blockPos.getY() + 1; + p.teleportTo(level, x1 + 0.5D, y1 + 0.1D, z1 + 0.5D, p.getYRot(), p.getXRot()); } - - p.teleportTo(level, x1 + 0.5D, y1 + 0.1D, z1 + 0.5D, p.getYRot(), p.getXRot()); - } + }); } + } \ No newline at end of file diff --git a/common/src/main/java/dev/ftb/mods/ftbchunks/net/UpdateForceLoadExpiryPacket.java b/common/src/main/java/dev/ftb/mods/ftbchunks/net/UpdateForceLoadExpiryPacket.java index 12350fe3..5a1450cd 100644 --- a/common/src/main/java/dev/ftb/mods/ftbchunks/net/UpdateForceLoadExpiryPacket.java +++ b/common/src/main/java/dev/ftb/mods/ftbchunks/net/UpdateForceLoadExpiryPacket.java @@ -1,54 +1,47 @@ package dev.ftb.mods.ftbchunks.net; import dev.architectury.networking.NetworkManager; -import dev.architectury.networking.simple.BaseC2SMessage; -import dev.architectury.networking.simple.MessageType; import dev.ftb.mods.ftbchunks.api.ClaimedChunk; +import dev.ftb.mods.ftbchunks.api.FTBChunksAPI; import dev.ftb.mods.ftbchunks.data.ClaimedChunkManagerImpl; +import dev.ftb.mods.ftbchunks.data.ChunkSyncInfo; import dev.ftb.mods.ftblibrary.math.ChunkDimPos; -import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceKey; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; import java.util.Date; -public class UpdateForceLoadExpiryPacket extends BaseC2SMessage { - private final ChunkDimPos pos; - private final long relativeExpiryTime; +public record UpdateForceLoadExpiryPacket(ChunkDimPos pos, long relativeExpiryTime) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(FTBChunksAPI.rl("update_force_load_expiry_packet")); - public UpdateForceLoadExpiryPacket(ChunkDimPos pos, Date expiryDate) { - this.pos = pos; - this.relativeExpiryTime = expiryDate == null ? 0L : Math.max(0L, expiryDate.getTime() - System.currentTimeMillis()); - } + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ChunkDimPos.STREAM_CODEC, UpdateForceLoadExpiryPacket::pos, + ByteBufCodecs.VAR_LONG, UpdateForceLoadExpiryPacket::relativeExpiryTime, + UpdateForceLoadExpiryPacket::new + ); - public UpdateForceLoadExpiryPacket(FriendlyByteBuf buf) { - pos = new ChunkDimPos(ResourceKey.create(Registries.DIMENSION, buf.readResourceLocation()), buf.readInt(), buf.readInt()); - relativeExpiryTime = buf.readLong(); + public UpdateForceLoadExpiryPacket(ChunkDimPos pos, Date expiryDate) { + this(pos, expiryDate == null ? 0L : Math.max(0L, expiryDate.getTime() - System.currentTimeMillis())); } @Override - public MessageType getType() { - return FTBChunksNet.UPDATE_FORCE_LOAD_EXPIRY; + public Type type() { + return TYPE; } - @Override - public void write(FriendlyByteBuf buf) { - buf.writeResourceLocation(pos.dimension().location()); - buf.writeInt(pos.x()); - buf.writeInt(pos.z()); - buf.writeLong(relativeExpiryTime); - } + public static void handle(UpdateForceLoadExpiryPacket message, NetworkManager.PacketContext context) { + ChunkDimPos pos = message.pos; - @Override - public void handle(NetworkManager.PacketContext context) { if (context.getPlayer() instanceof ServerPlayer sp && sp.level().dimension().equals(pos.dimension())) { ClaimedChunk chunk = ClaimedChunkManagerImpl.getInstance().getChunk(pos); if (chunk != null && chunk.getTeamData().getTeam().getRankForPlayer(sp.getUUID()).isMemberOrBetter() && chunk.isForceLoaded()) { - chunk.setForceLoadExpiryTime(relativeExpiryTime == 0L ? 0L : System.currentTimeMillis() + relativeExpiryTime); + chunk.setForceLoadExpiryTime(message.relativeExpiryTime == 0L ? 0L : System.currentTimeMillis() + message.relativeExpiryTime); SendChunkPacket packet = new SendChunkPacket(pos.dimension(), chunk.getTeamData().getTeam().getId(), - new SendChunkPacket.SingleChunk(System.currentTimeMillis(), chunk.getPos().x(), chunk.getPos().z(), chunk)); - packet.sendTo(sp); + ChunkSyncInfo.create(System.currentTimeMillis(), chunk.getPos().x(), chunk.getPos().z(), chunk)); + NetworkManager.sendToPlayer(sp, packet); } } } diff --git a/common/src/main/resources/assets/ftbchunks/lang/en_us.json b/common/src/main/resources/assets/ftbchunks/lang/en_us.json index b31e0e65..2604d1b6 100644 --- a/common/src/main/resources/assets/ftbchunks/lang/en_us.json +++ b/common/src/main/resources/assets/ftbchunks/lang/en_us.json @@ -143,49 +143,52 @@ "ftbteamsconfig.ftbchunks.location_mode.tooltip": "Controls who can see you on the map or minimap (outside the normal vanilla tracking range)", "ftbteamsconfig.ftbchunks.claim_visibility": "Claim Visibility", "ftbteamsconfig.ftbchunks.claim_visibility.tooltip": "Controls who can see your claims on the map or minimap", - "ftbchunks.fake_players": "Allow Fake Players", - "ftbchunks.fake_players.tooltip": "CHECK: check fake player access like any real player\nDENY: never allow fake players\nALLOW: always allow fake players", - "ftbchunks.max_claimed_chunks": "Max Claimed Chunks per Player", - "ftbchunks.max_claimed_chunks.tooltip": "This default can be overridden by the FTB Ranks 'ftbchunks.max_claimed` permission node.", - "ftbchunks.max_force_loaded_chunks": "Max Forcedloaded Chunks per Player", - "ftbchunks.max_force_loaded_chunks.tooltip": "This default can be overridden by the FTB Ranks 'ftbchunks.max_force_loaded` permission node.", - "ftbchunks.force_load_mode": "Forceloading Mode", - "ftbchunks.force_load_mode.tooltip": "NEVER: only allow chunk force-loading if the owning team has at least one online player\nALWAYS: always allow force-loading, even if no players are online\nDEFAULT: allow force-loading IF the team has at least one player with the FTB Ranks 'ftbchunks.chunk_load_offline' permission", + "ftbchunks.fake_players": "Fake Players", + "ftbchunks.claiming": "Chunk Claiming", + "ftbchunks.force_loading": "Force-Loading", + "ftbchunks.fake_players.fake_players": "Allow Fake Players", + "ftbchunks.fake_players.fake_players.tooltip": "CHECK: check fake player access like any real player\nDENY: never allow fake players\nALLOW: always allow fake players", + "ftbchunks.claiming.max_claimed_chunks": "Max Claimed Chunks per Player", + "ftbchunks.claiming.max_claimed_chunks.tooltip": "This default can be overridden by the FTB Ranks 'ftbchunks.max_claimed` permission node.", + "ftbchunks.force_loading.max_force_loaded_chunks": "Max Forcedloaded Chunks per Player", + "ftbchunks.force_loading.max_force_loaded_chunks.tooltip": "This default can be overridden by the FTB Ranks 'ftbchunks.max_force_loaded` permission node.", + "ftbchunks.force_loading.force_load_mode": "Offline Forceloading Mode", + "ftbchunks.force_loading.force_load_mode.tooltip": "NEVER: only allow chunk force-loading if the owning team has at least one online player\nALWAYS: always allow force-loading, even if no players are online\nDEFAULT: allow force-loading IF the team has at least one player with the FTB Ranks 'ftbchunks.chunk_load_offline' permission", "ftbchunks.disable_protection": "Disable Claim Protection", "ftbchunks.disable_protection.tooltip": "Useful for private servers where everyone is trusted, and claims are only used for force-loading", "ftbchunks.pvp_mode": "Allow PvP Combat in Claimed Chunks", "ftbchunks.pvp_mode.tooltip": "ALWAYS: allow PvP combat in all claimed chunks\nNEVER: prevent PvP in all claimed chunks\nPER_TEAM: teams can decide if PvP is allowed in their claims via team property", "ftbchunks.ally_mode": "Allow Player to Change Ally Settings", "ftbchunks.ally_mode.tooltip": "DEFAULT: FTB Teams ally status is checked to decide if players are allied\nFORCED_ALL: all players are always considered to be allied\nFORCED_NONE: no players are ever considered to be allied", - "ftbchunks.claim_dimension_blacklist": "Dimension Blacklist", - "ftbchunks.claim_dimension_blacklist.tooltip": "Blacklist for dimension ID's where chunks may not be claimed.\nE.g. add \"minecraft:the_end\" to this list if you want to disable chunk claiming in The End\nWildcards are allowed, e.g. \"othermod:*\" matches all dimensions added by \"othermod\"", - "ftbchunks.claim_dimension_whitelist": "Dimension Whitelist", - "ftbchunks.claim_dimension_whitelist.tooltip": "Whitelist for dimension ID's where chunks may be claimed. If non-empty, dimension *must* be in this list (and also not in \"Dimension Blacklist\".\nSame syntax as for \"Dimension Blacklist\"", + "ftbchunks.claiming.claim_dimension_blacklist": "Dimension Blacklist", + "ftbchunks.claiming.claim_dimension_blacklist.tooltip": "Blacklist for dimension ID's where chunks may not be claimed.\nE.g. add \"minecraft:the_end\" to this list if you want to disable chunk claiming in The End\nWildcards are allowed, e.g. \"othermod:*\" matches all dimensions added by \"othermod\"", + "ftbchunks.claiming.claim_dimension_whitelist": "Dimension Whitelist", + "ftbchunks.claiming.claim_dimension_whitelist.tooltip": "Whitelist for dimension ID's where chunks may be claimed. If non-empty, dimension *must* be in this list (and also not in \"Dimension Blacklist\".\nSame syntax as for \"Dimension Blacklist\"", "ftbchunks.no_wilderness": "Protect Unclaimed Regions", "ftbchunks.no_wilderness.tooltip": "If true, chunks must be claimed before they can be built on", "ftbchunks.no_wilderness_dimensions": "Protect Unclaimed Regions Per-Dimension", "ftbchunks.no_wilderness_dimensions.tooltip": "List of dimension ID's where chunks must be claimed before modifying.\nE.g. add \"minecraft:the_nether\" to require chunks to be claimed in the Nether.\nWildcards are allowed, e.g. \"othermod:*\" matches all dimensions added by \"othermod\"", "ftbchunks.force_disable_minimap": "Disable Minimap for Clients", - "ftbchunks.max_idle_days_before_unclaim": "Max Idle Days Before Unclaim", - "ftbchunks.max_idle_days_before_unclaim.tooltip": "If no team member logs in for this many days, the team's claims will be released.\nSetting this to 0 disables auto-unclaiming.", - "ftbchunks.max_idle_days_before_unforce": "Max Idle Days Before Unforceload", - "ftbchunks.max_idle_days_before_unforce.tooltip": "If no team member logs in for this many days, any force-loaded chunks will no longer be force-loaded.\nSetting this to 0 disables auto-unforceloading.", + "ftbchunks.claiming.max_idle_days_before_unclaim": "Max Idle Days Before Unclaim", + "ftbchunks.claiming.max_idle_days_before_unclaim.tooltip": "If no team member logs in for this many days, the team's claims will be released.\nSetting this to 0 disables auto-unclaiming.", + "ftbchunks.force_loading.max_idle_days_before_unforce": "Max Idle Days Before Unforceload", + "ftbchunks.force_loading.max_idle_days_before_unforce.tooltip": "If no team member logs in for this many days, any force-loaded chunks will no longer be force-loaded.\nSetting this to 0 disables auto-unforceloading.", "ftbchunks.long_range_tracker_interval": "Long Range Player Tracker Interval", "ftbchunks.long_range_tracker_interval.tooltip": "Interval in ticks to send updates to clients with long-range player tracking data.\nLower values mean more frequent updates but more server load and network traffic; be careful with this, especially on busy servers.\nSetting this to 0 disables long-range tracking.", "ftbchunks.protect_unknown_explosions": "Prevent Explosions from Unknown Sources", "ftbchunks.protect_unknown_explosions.tooltip": "Some explosion sources (e.g. Ghasts) can't be determined in code.\nIf this setting is true, damage from these explosion is prevented in protected chunks.", - "ftbchunks.hard_team_claim_limit": "Hard Max Team Claim Limit", - "ftbchunks.hard_team_claim_limit.tooltip": "Hard claim limit for party teams, regardless of member count or Party Limit Calculation mode.\nDefault of 0 means no hard limit.", - "ftbchunks.hard_team_force_limit": "Hard Max Team Forceload Limit", - "ftbchunks.hard_team_force_limit.tooltip": "Hard force-load limit for party teams, regardless of member count or Party Limit Calculation mode.\nDefault of 0 means no hard limit.", - "ftbchunks.party_limit_mode": "Party Limit Calculation Mode", - "ftbchunks.party_limit_mode.tooltip": "Method by which party claim & force-load limits are calculated.\nLARGEST: use the limits of the member with the largest limits\nSUM: add up all the members' limits\nOWNER: use the party owner's limits only\nAVERAGE: use the average of all members' limits.", + "ftbchunks.claiming.hard_team_claim_limit": "Hard Max Team Claim Limit", + "ftbchunks.claiming.hard_team_claim_limit.tooltip": "Hard claim limit for party teams, regardless of member count or Party Limit Calculation mode.\nDefault of 0 means no hard limit.", + "ftbchunks.force_loading.hard_team_force_limit": "Hard Max Team Forceload Limit", + "ftbchunks.force_loading.hard_team_force_limit.tooltip": "Hard force-load limit for party teams, regardless of member count or Party Limit Calculation mode.\nDefault of 0 means no hard limit.", + "ftbchunks.claiming.party_limit_mode": "Party Limit Calculation Mode", + "ftbchunks.claiming.party_limit_mode.tooltip": "Method by which party claim & force-load limits are calculated.\nLARGEST: use the limits of the member with the largest limits\nSUM: add up all the members' limits\nOWNER: use the party owner's limits only\nAVERAGE: use the average of all members' limits.", "ftbchunks.require_game_stage": "Require Game Stage for Mapping", "ftbchunks.require_game_stage.tooltip": "If true, players must have the 'ftbchunks_mapping' game stage (KubeJS and/or Gamestages required) to be able to open the map or see the minimap", "ftbchunks.location_mode_override": "Override Team \"Location Visibility\"", "ftbchunks.location_mode_override.tooltip": "If true, team \"Location Visibility\" settings are ignored, and all players can see each other anywhere on the map", - "ftbchunks.max_prevented_log_age": "Fake Player Prevented Access Log Age", - "ftbchunks.max_prevented_log_age.tooltip": "Age in days to keep logs of prevented fake player access\nNote: not fully implemented feature; will be used in future to display & control access by fake players to your claims", + "ftbchunks.fake_players.max_prevented_log_age": "Fake Player Prevented Access Log Age", + "ftbchunks.fake_players.max_prevented_log_age.tooltip": "Age in days to keep logs of prevented fake player access\nNote: not fully implemented feature; will be used in future to display & control access by fake players to your claims", "ftbchunks.claim_result": "Chunks modified: %d / %d", "ftbchunks.claim_result.other": "Unknown issues", "ftbchunks.claim_result.not_owner": "Not the chunk owner", diff --git a/fabric/src/main/java/dev/ftb/mods/ftbchunks/client/fabric/FTBChunksClientImpl.java b/fabric/src/main/java/dev/ftb/mods/ftbchunks/client/fabric/FTBChunksClientImpl.java index dd42f463..9c557476 100644 --- a/fabric/src/main/java/dev/ftb/mods/ftbchunks/client/fabric/FTBChunksClientImpl.java +++ b/fabric/src/main/java/dev/ftb/mods/ftbchunks/client/fabric/FTBChunksClientImpl.java @@ -11,7 +11,7 @@ public static void registerPlatform() { } private static void renderWorldLastFabric(WorldRenderContext context) { - FTBChunksClient.INSTANCE.renderWorldLast(context.matrixStack(), context.projectionMatrix(), context.camera(), context.tickDelta()); + FTBChunksClient.INSTANCE.renderWorldLast(context.matrixStack(), context.projectionMatrix(), context.positionMatrix(), context.camera(), context.tickDelta()); } public static boolean doesKeybindMatch(KeyMapping keyMapping, int keyCode, int scanCode, int modifiers) { diff --git a/gradle.properties b/gradle.properties index 23ff50b2..6c1f538d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,21 +5,21 @@ org.gradle.daemon=false mod_id=ftbchunks archives_base_name=ftb-chunks maven_group=dev.ftb.mods -mod_version=2004.1.3 +mod_version=2006.1.0 mod_author=FTB Team -minecraft_version=1.20.4 +minecraft_version=1.20.6 # Deps -forge_version=49.0.31 -neoforge_version=20.4.196 +forge_version=50.0.9 +neoforge_version=20.6.100-beta neoforge_loader_version=1 -fabric_loader_version=0.15.7 -fabric_api_version=0.96.4+1.20.4 -architectury_version=11.1.17 +fabric_loader_version=0.15.10 +fabric_api_version=0.99.0+1.20.6 +architectury_version=12.1.3 -ftb_library_version=2004.2.0 -ftb_teams_version=2004.1.2 +ftb_library_version=2006.1.1 +ftb_teams_version=2006.1.0 curseforge_id_forge=314906 curseforge_id_fabric=472657 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b8bfcfe3..ed1d832b 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ #Tue Dec 19 01:11:27 EET 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https://services.gradle.org/distributions/gradle-8.4-bin.zip +distributionUrl=https://services.gradle.org/distributions/gradle-8.7-bin.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/neoforge/build.gradle b/neoforge/build.gradle index 6dbc6934..b570c9a4 100644 --- a/neoforge/build.gradle +++ b/neoforge/build.gradle @@ -48,7 +48,7 @@ dependencies { apply from: "https://raw.githubusercontent.com/FTBTeam/mods-meta/main/gradle/extra-local-mods.gradle" processResources { - def file = new File("./build/resources/main/META-INF/mods.toml") + def file = new File("./build/resources/main/META-INF/neoforge.mods.toml") if (file.exists()) { file.delete() } @@ -56,7 +56,7 @@ processResources { exclude '.cache' inputs.property "version", project.version - filesMatching("META-INF/mods.toml") { + filesMatching("META-INF/neoforge.mods.toml") { expand "version": project.version, "archversion": project.architectury_version, "neoforgeversion": project.neoforge_version, diff --git a/neoforge/src/main/java/dev/ftb/mods/ftbchunks/client/neoforge/FTBChunksClientImpl.java b/neoforge/src/main/java/dev/ftb/mods/ftbchunks/client/neoforge/FTBChunksClientImpl.java index dcabe636..4ed6d407 100644 --- a/neoforge/src/main/java/dev/ftb/mods/ftbchunks/client/neoforge/FTBChunksClientImpl.java +++ b/neoforge/src/main/java/dev/ftb/mods/ftbchunks/client/neoforge/FTBChunksClientImpl.java @@ -2,7 +2,6 @@ import dev.ftb.mods.ftbchunks.client.FTBChunksClient; import net.minecraft.client.KeyMapping; -import net.minecraft.client.Minecraft; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.neoforge.client.event.RenderLevelStageEvent; import net.neoforged.neoforge.common.NeoForge; @@ -16,7 +15,8 @@ public static void registerPlatform() { @SubscribeEvent public static void renderLevelStageForge(RenderLevelStageEvent event) { if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_PARTICLES) { - FTBChunksClient.INSTANCE.renderWorldLast(event.getPoseStack(), event.getProjectionMatrix(), Minecraft.getInstance().getEntityRenderDispatcher().camera, event.getPartialTick()); + FTBChunksClient.INSTANCE.renderWorldLast(event.getPoseStack(), event.getProjectionMatrix(), + event.getModelViewMatrix(), event.getCamera(), event.getPartialTick()); } } diff --git a/neoforge/src/main/java/dev/ftb/mods/ftbchunks/neoforge/FTBChunksForge.java b/neoforge/src/main/java/dev/ftb/mods/ftbchunks/neoforge/FTBChunksForge.java index 84b6bb91..1cccb301 100644 --- a/neoforge/src/main/java/dev/ftb/mods/ftbchunks/neoforge/FTBChunksForge.java +++ b/neoforge/src/main/java/dev/ftb/mods/ftbchunks/neoforge/FTBChunksForge.java @@ -7,7 +7,6 @@ import dev.ftb.mods.ftblibrary.math.ChunkDimPos; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.monster.EnderMan; -import net.neoforged.bus.api.Event; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.common.Mod; import net.neoforged.neoforge.common.NeoForge; @@ -48,7 +47,7 @@ private void mobGriefing(EntityMobGriefingEvent event) { ClaimedChunkImpl cc = ClaimedChunkManagerImpl.getInstance().getChunk(new ChunkDimPos(event.getEntity())); if (cc != null && !cc.allowMobGriefing()) { - event.setResult(Event.Result.DENY); + event.setCanGrief(false); } } } diff --git a/neoforge/src/main/resources/META-INF/mods.toml b/neoforge/src/main/resources/META-INF/neoforge.mods.toml similarity index 100% rename from neoforge/src/main/resources/META-INF/mods.toml rename to neoforge/src/main/resources/META-INF/neoforge.mods.toml diff --git a/settings.gradle b/settings.gradle index cbdf8ccb..e070e314 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,11 +1,11 @@ pluginManagement { repositories { - maven { url "https://maven.creeperhost.net/" } maven { url "https://maven.architectury.dev/" } + maven { url "https://maven.creeperhost.net/" } gradlePluginPortal() } } -include "common", "fabric", "forge", "neoforge" +include "common", "fabric", /* "forge", */ "neoforge" -rootProject.name = 'FTB-Chunks-1.20.4' +rootProject.name = 'FTB-Chunks-1.20.6'