From e23b2163f9d8721be704b0153b91f58b24a74639 Mon Sep 17 00:00:00 2001 From: Josiah Glosson Date: Sun, 11 Feb 2024 15:55:50 -0600 Subject: [PATCH] Port to Mojmap (#596) * Initial port * Optimize imports * Rename things to match Mojmap * Always use wildcard imports for import static, as per CONTRIBUTING.md * Update Parchment * Replace a few more names * More renames * Use a star import in ClientCommands * Fix some more names --- build.gradle | 10 +- .../clientAddon/cracker/SeedCracker.java | 48 +- .../clientcommands/ClientCommands.java | 48 +- .../ClientcommandsDataQueryHandler.java | 36 +- .../earthcomputer/clientcommands/Configs.java | 12 +- .../clientcommands/GuiBlocker.java | 2 +- .../clientcommands/IntegratedServerUtil.java | 50 +- .../clientcommands/MathUtil.java | 121 ++--- .../clientcommands/MultiVersionCompat.java | 20 +- .../clientcommands/ServerBrandManager.java | 12 +- .../clientcommands/c2c/C2CPacket.java | 4 +- .../clientcommands/c2c/CCNetworkHandler.java | 46 +- .../clientcommands/c2c/CCPacketHandler.java | 12 +- .../c2c/packets/MessageC2CPacket.java | 14 +- .../clientcommands/command/AliasCommand.java | 38 +- .../command/AreaStatsCommand.java | 80 ++-- .../clientcommands/command/BookCommand.java | 44 +- .../command/CEnchantCommand.java | 49 +- .../command/CFunctionCommand.java | 8 +- .../clientcommands/command/CGiveCommand.java | 26 +- .../command/CParticleCommand.java | 28 +- .../command/CPlaySoundCommand.java | 36 +- .../command/CStopSoundCommand.java | 32 +- .../command/CTeleportCommand.java | 24 +- .../command/CTellRawCommand.java | 8 +- .../clientcommands/command/CTimeCommand.java | 19 +- .../clientcommands/command/CTitleCommand.java | 36 +- .../clientcommands/command/CalcCommand.java | 18 +- .../command/CalcStackCommand.java | 33 +- .../clientcommands/command/ChatCommand.java | 6 +- .../clientcommands/command/ChorusCommand.java | 10 +- .../command/ClientCommandHelper.java | 71 +-- .../command/ClientEntitySelector.java | 30 +- .../command/CrackRNGCommand.java | 6 +- .../command/FakeCommandSource.java | 25 +- .../command/FindBlockCommand.java | 52 +-- .../clientcommands/command/FindCommand.java | 27 +- .../command/FindItemCommand.java | 270 +++++------ .../clientcommands/command/FishCommand.java | 32 +- .../clientcommands/command/Flag.java | 4 +- .../clientcommands/command/FovCommand.java | 9 +- .../clientcommands/command/GammaCommand.java | 9 +- .../command/GetDataCommand.java | 90 ++-- .../command/GhostBlockCommand.java | 62 +-- .../clientcommands/command/GlowCommand.java | 42 +- .../clientcommands/command/HotbarCommand.java | 56 +-- .../command/ItemGroupCommand.java | 160 +++---- .../clientcommands/command/KitCommand.java | 144 +++--- .../clientcommands/command/LookCommand.java | 16 +- .../clientcommands/command/MoteCommand.java | 4 +- .../clientcommands/command/NoteCommand.java | 12 +- .../command/PermissionLevelCommand.java | 4 +- .../clientcommands/command/PingCommand.java | 34 +- .../command/PluginsCommand.java | 22 +- .../clientcommands/command/PosCommand.java | 86 ++-- .../clientcommands/command/RelogCommand.java | 4 +- .../clientcommands/command/RenderCommand.java | 4 +- .../clientcommands/command/ShrugCommand.java | 10 +- .../command/SignSearchCommand.java | 36 +- .../clientcommands/command/SnakeCommand.java | 64 +-- .../command/StartupCommand.java | 12 +- .../clientcommands/command/TaskCommand.java | 16 +- .../command/TooltipCommand.java | 24 +- .../command/TranslateCommand.java | 18 +- .../command/UsageTreeCommand.java | 34 +- .../clientcommands/command/UuidCommand.java | 26 +- .../clientcommands/command/VarCommand.java | 40 +- .../command/WeatherCommand.java | 11 +- .../command/WhisperEncryptedCommand.java | 30 +- .../clientcommands/command/WikiCommand.java | 6 +- .../ClientBlockPredicateArgumentType.java | 104 ++--- .../ClientItemPredicateArgumentType.java | 58 +-- .../arguments/EntityUUIDArgumentType.java | 16 +- .../arguments/ExpressionArgumentType.java | 57 +-- ...va => FormattedComponentArgumentType.java} | 124 ++--- ...mAndEnchantmentsPredicateArgumentType.java | 118 ++--- .../command/arguments/ListArgumentType.java | 4 +- .../command/arguments/RegexArgumentType.java | 4 +- .../TranslationQueryArgumentType.java | 14 +- .../features/ChorusManipulation.java | 116 ++--- .../features/ClientCommandFunctions.java | 45 +- .../clientcommands/features/DebugRandom.java | 38 +- .../features/EnchantmentCracker.java | 184 ++++---- .../features/FishingCracker.java | 434 +++++++++--------- .../features/PathfindingHints.java | 10 +- .../features/PlayerRandCracker.java | 105 +++-- .../clientcommands/features/Relogger.java | 52 +-- .../features/RenderSettings.java | 29 +- .../features/SeedfindingUtil.java | 38 +- .../features/WikiRetriever.java | 46 +- ...ArmorStandEntity.java => IArmorStand.java} | 2 +- .../interfaces/IBlockChangeListener.java | 4 +- ...e.java => IClientSuggestionsProvider.java} | 4 +- .../IDroppableInventoryContainer.java | 4 +- .../{ITextFieldWidget.java => IEditBox.java} | 2 +- .../interfaces/IEnchantingTableContainer.java | 9 - .../interfaces/IEnchantmentMenu.java | 9 + .../interfaces/ILivingEntity.java | 6 +- .../mixin/AbstractContainerMenuAccessor.java | 12 + .../mixin/ChatInputSuggestorAccessor.java | 18 - .../mixin/CommandSuggestionsAccessor.java | 18 + .../clientcommands/mixin/GuiAccessor.java | 11 + .../mixin/HoverEventActionAccessor.java | 4 +- .../mixin/InGameHudAccessor.java | 11 - .../mixin/LandPathNodeMakerAccessor.java | 13 - ...r.java => LegacyRandomSourceAccessor.java} | 6 +- .../MixinAccountProfileKeyPairManager.java | 21 + .../mixin/MixinAnvilContainer.java | 23 - .../clientcommands/mixin/MixinAnvilMenu.java | 22 + ...rStandEntity.java => MixinArmorStand.java} | 8 +- .../mixin/MixinArmorStandEntityRenderer.java | 28 -- .../mixin/MixinArmorStandRenderer.java | 28 ++ .../mixin/MixinAxeHoeAndShovelItem.java | 16 +- .../mixin/MixinBowAndTridentItem.java | 14 +- .../mixin/MixinCartographyTableContainer.java | 15 - .../mixin/MixinCartographyTableMenu.java | 15 + ...inChatHud.java => MixinChatComponent.java} | 46 +- .../clientcommands/mixin/MixinChatScreen.java | 6 +- .../MixinClientCommonNetworkHandler.java | 22 - .../MixinClientCommonPacketListenerImpl.java | 22 + .../mixin/MixinClientLevel.java | 27 ++ ...perties.java => MixinClientLevelData.java} | 11 +- .../mixin/MixinClientPacketListener.java | 108 +++++ ...ixinClientPacketListenerHighPriority.java} | 10 +- .../mixin/MixinClientPlayNetworkHandler.java | 108 ----- .../mixin/MixinClientPlayerEntity.java | 59 --- .../MixinClientPlayerInteractionManager.java | 61 --- ...va => MixinClientSuggestionsProvider.java} | 21 +- .../mixin/MixinClientWorld.java | 27 -- .../mixin/MixinCloseHandledScreenPacket.java | 65 --- ...stor.java => MixinCommandSuggestions.java} | 24 +- .../mixin/MixinCraftingMenu.java | 20 + .../mixin/MixinCraftingTableContainer.java | 20 - ...eeperMooshroomSheepAndSnowGolemEntity.java | 23 - ...inCreeperMushroomCowSheepAndSnowGolem.java | 23 + .../mixin/MixinCrossbowItem.java | 16 +- .../mixin/MixinCustomCreativeSlot.java | 8 + .../mixin/MixinDamageEnchantment.java | 12 +- .../clientcommands/mixin/MixinDiggerItem.java | 25 + ...TextFieldWidget.java => MixinEditBox.java} | 8 +- .../mixin/MixinEnchantingTableContainer.java | 26 -- .../mixin/MixinEnchantmentHelper.java | 40 +- .../mixin/MixinEnchantmentMenu.java | 26 ++ ...eight.java => MixinEnchantmentRarity.java} | 4 +- ...creen.java => MixinEnchantmentScreen.java} | 32 +- .../clientcommands/mixin/MixinEntity.java | 50 +- .../mixin/MixinEntityRendererDispatcher.java | 17 +- ...obberEntity.java => MixinFishingHook.java} | 24 +- .../mixin/MixinFishingRodItem.java | 28 +- .../mixin/MixinFlintAndSteelItem.java | 12 +- .../mixin/MixinFoodOnAStickItem.java | 30 ++ .../mixin/MixinForgingScreenHandler.java | 19 - .../mixin/MixinGrindstoneContainer.java | 19 - .../mixin/MixinGrindstoneMenu.java | 19 + .../clientcommands/mixin/MixinInventory.java | 39 ++ .../mixin/MixinInventoryMenu.java | 20 + .../mixin/MixinItemCombinerMenu.java | 19 + .../clientcommands/mixin/MixinItemEntity.java | 22 +- .../clientcommands/mixin/MixinItemStack.java | 8 +- .../{MixinWorld.java => MixinLevel.java} | 14 +- .../mixin/MixinLivingEntity.java | 87 ++-- .../mixin/MixinLivingEntityRenderer.java | 21 +- .../mixin/MixinLocalPlayer.java | 59 +++ .../mixin/MixinLockableSlot.java | 8 - .../mixin/MixinLoomContainer.java | 19 - .../clientcommands/mixin/MixinLoomMenu.java | 19 + .../mixin/MixinMerchantContainer.java | 21 - .../mixin/MixinMerchantMenu.java | 21 + ...necraftClient.java => MixinMinecraft.java} | 44 +- .../mixin/MixinMiningToolItem.java | 25 - .../mixin/MixinMultiPlayerGameMode.java | 63 +++ .../mixin/MixinOnAStickItem.java | 30 -- .../clientcommands/mixin/MixinPlayer.java | 115 +++++ .../mixin/MixinPlayerContainer.java | 20 - .../mixin/MixinPlayerEntity.java | 111 ----- .../mixin/MixinPlayerInventory.java | 39 -- .../mixin/MixinProfileKeysImpl.java | 21 - .../mixin/MixinProtectionEnchantment.java | 14 +- .../mixin/MixinPumpkinBlock.java | 20 +- ...ServerWorld.java => MixinServerLevel.java} | 14 +- .../MixinServerboundContainerClosePacket.java | 65 +++ .../clientcommands/mixin/MixinShearsItem.java | 16 +- .../mixin/MixinStonecutterContainer.java | 15 - .../mixin/MixinStonecutterMenu.java | 15 + ...essor.java => OptionInstanceAccessor.java} | 6 +- .../mixin/ProjectileAccessor.java | 12 + .../mixin/ProjectileEntityAccessor.java | 12 - .../mixin/ScreenHandlerAccessor.java | 12 - .../mixin/WalkNodeEvaluatorAccessor.java | 12 + .../clientcommands/render/Cuboid.java | 50 +- .../clientcommands/render/Line.java | 46 +- .../clientcommands/render/RenderQueue.java | 50 +- .../clientcommands/render/Shape.java | 12 +- .../clientcommands/task/LongTask.java | 2 +- .../task/RenderDistanceScanTask.java | 88 ++-- .../clientcommands/task/TaskManager.java | 12 +- .../assets/clientcommands/lang/en_us.json | 6 +- .../assets/clientcommands/lang/zh_cn.json | 6 +- src/main/resources/clientcommands.aw | 16 +- src/main/resources/mixins.clientcommands.json | 88 ++-- 200 files changed, 3545 insertions(+), 3458 deletions(-) rename src/main/java/net/earthcomputer/clientcommands/command/arguments/{FormattedTextArgumentType.java => FormattedComponentArgumentType.java} (58%) rename src/main/java/net/earthcomputer/clientcommands/interfaces/{IArmorStandEntity.java => IArmorStand.java} (71%) rename src/main/java/net/earthcomputer/clientcommands/interfaces/{IClientCommandSource.java => IClientSuggestionsProvider.java} (74%) rename src/main/java/net/earthcomputer/clientcommands/interfaces/{ITextFieldWidget.java => IEditBox.java} (72%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/interfaces/IEnchantingTableContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/interfaces/IEnchantmentMenu.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/AbstractContainerMenuAccessor.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/ChatInputSuggestorAccessor.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/CommandSuggestionsAccessor.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/GuiAccessor.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/InGameHudAccessor.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/LandPathNodeMakerAccessor.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{CheckedRandomAccessor.java => LegacyRandomSourceAccessor.java} (62%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinAccountProfileKeyPairManager.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinAnvilContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinAnvilMenu.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinArmorStandEntity.java => MixinArmorStand.java} (50%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinArmorStandEntityRenderer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinArmorStandRenderer.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCartographyTableContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCartographyTableMenu.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinChatHud.java => MixinChatComponent.java} (62%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientCommonNetworkHandler.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientCommonPacketListenerImpl.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientLevel.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinClientWorldProperties.java => MixinClientLevelData.java} (73%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientPacketListener.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinClientPlayNetworkHandlerHighPriority.java => MixinClientPacketListenerHighPriority.java} (63%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientPlayNetworkHandler.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientPlayerEntity.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientPlayerInteractionManager.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinClientCommandSource.java => MixinClientSuggestionsProvider.java} (68%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinClientWorld.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCloseHandledScreenPacket.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinChatInputSuggestor.java => MixinCommandSuggestions.java} (60%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCraftingMenu.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCraftingTableContainer.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCreeperMooshroomSheepAndSnowGolemEntity.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCreeperMushroomCowSheepAndSnowGolem.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinCustomCreativeSlot.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinDiggerItem.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinTextFieldWidget.java => MixinEditBox.java} (51%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinEnchantingTableContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinEnchantmentMenu.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinEnchantmentWeight.java => MixinEnchantmentRarity.java} (91%) rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinEnchantingScreen.java => MixinEnchantmentScreen.java} (50%) rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinFishingBobberEntity.java => MixinFishingHook.java} (51%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinFoodOnAStickItem.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinForgingScreenHandler.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinGrindstoneContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinGrindstoneMenu.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinInventory.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinInventoryMenu.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinItemCombinerMenu.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinWorld.java => MixinLevel.java} (62%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinLocalPlayer.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinLockableSlot.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinLoomContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinLoomMenu.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinMerchantContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinMerchantMenu.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinMinecraftClient.java => MixinMinecraft.java} (67%) delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinMiningToolItem.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinMultiPlayerGameMode.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinOnAStickItem.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinPlayer.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinPlayerContainer.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinPlayerEntity.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinPlayerInventory.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinProfileKeysImpl.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{MixinServerWorld.java => MixinServerLevel.java} (59%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinServerboundContainerClosePacket.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinStonecutterContainer.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/MixinStonecutterMenu.java rename src/main/java/net/earthcomputer/clientcommands/mixin/{SimpleOptionAccessor.java => OptionInstanceAccessor.java} (63%) create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/ProjectileAccessor.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/ProjectileEntityAccessor.java delete mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/ScreenHandlerAccessor.java create mode 100644 src/main/java/net/earthcomputer/clientcommands/mixin/WalkNodeEvaluatorAccessor.java diff --git a/build.gradle b/build.gradle index e8569a04c..20439f0f7 100644 --- a/build.gradle +++ b/build.gradle @@ -27,6 +27,9 @@ repositories { maven { url = "https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1" } + maven { + url = "https://maven.parchmentmc.org" + } } loom { @@ -35,7 +38,12 @@ loom { dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + mappings loom.layered { + officialMojangMappings { + nameSyntheticMembers = true + } + parchment("org.parchmentmc.data:parchment-1.20.3:2023.12.31@zip") + } modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" diff --git a/src/main/java/net/cortex/clientAddon/cracker/SeedCracker.java b/src/main/java/net/cortex/clientAddon/cracker/SeedCracker.java index 91474201b..22ba5b459 100644 --- a/src/main/java/net/cortex/clientAddon/cracker/SeedCracker.java +++ b/src/main/java/net/cortex/clientAddon/cracker/SeedCracker.java @@ -4,17 +4,17 @@ import net.earthcomputer.clientcommands.command.ClientCommandHelper; import net.earthcomputer.clientcommands.features.EnchantmentCracker; import net.earthcomputer.clientcommands.features.PlayerRandCracker; -import net.earthcomputer.clientcommands.mixin.CheckedRandomAccessor; +import net.earthcomputer.clientcommands.mixin.LegacyRandomSourceAccessor; import net.earthcomputer.clientcommands.task.LongTask; import net.earthcomputer.clientcommands.task.TaskManager; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.entity.EntityType; -import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; -import net.minecraft.network.packet.s2c.play.EntitySpawnS2CPacket; -import net.minecraft.text.*; -import net.minecraft.util.Formatting; -import net.minecraft.util.math.random.Random; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.EntityType; public class SeedCracker { public interface OnCrack {void callback(long seed); } @@ -30,13 +30,13 @@ public interface OnCrack {void callback(long seed); } //returns True on success or false on failer private static boolean throwItems() { - ClientPlayerEntity player = MinecraftClient.getInstance().player; - player.refreshPositionAndAngles(player.getX(), player.getY(), player.getZ(), 0, 90); - MinecraftClient.getInstance().getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.LookAndOnGround(0, 90, true)); // point to correct location + LocalPlayer player = Minecraft.getInstance().player; + player.moveTo(player.getX(), player.getY(), player.getZ(), 0, 90); + Minecraft.getInstance().getConnection().send(new ServerboundMovePlayerPacket.Rot(0, 90, true)); // point to correct location for (int i = 0; i < 20; i++) { boolean success = PlayerRandCracker.throwItem(); if (!success) { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable("itemCrack.notEnoughItems").formatted(Formatting.RED)); + Minecraft.getInstance().gui.getChat().addMessage(Component.translatable("itemCrack.notEnoughItems").withStyle(ChatFormatting.RED)); EnchantmentCracker.LOGGER.info("Unable to use rng SeedCracker |not enough items|"); return false; } @@ -51,8 +51,8 @@ public static void attemptCrack() { attemptCount++; if (attemptCount > MAX_ATTEMPTS) { - ClientCommandHelper.sendError(Text.translatable("commands.ccrackrng.failed")); - ClientCommandHelper.sendHelp(Text.translatable("commands.ccrackrng.failed.help")); + ClientCommandHelper.sendError(Component.translatable("commands.ccrackrng.failed")); + ClientCommandHelper.sendHelp(Component.translatable("commands.ccrackrng.failed.help")); Configs.playerCrackState = PlayerRandCracker.CrackState.UNCRACKED; } else { SeedCracker.doCrack(SeedCracker.callback); @@ -63,11 +63,11 @@ public static void attemptCrack() Configs.playerCrackState = PlayerRandCracker.CrackState.CRACKED; - Random rand=Random.create(seed ^ 0x5deece66dL); + RandomSource rand=RandomSource.create(seed ^ 0x5deece66dL); rand.nextFloat(); rand.nextFloat(); //rand.nextFloat(); - + /* for(int i=0;i<13;i++) { long x = (((long) (rand.nextFloat() * ((float) (1 << 24)))) >> (24 - 4))&0xFL; @@ -77,7 +77,7 @@ public static void attemptCrack() System.out.print(padLeftZeros(Long.toBinaryString((((long) (rand.nextFloat() * ((float) (1 << 24)))) >> (24 - 4))&0xFL), 4)+" \n"); }*/ - callback.callback(((CheckedRandomAccessor) rand).getSeed().get());//extract seed and call callback + callback.callback(((LegacyRandomSourceAccessor) rand).getSeed().get());//extract seed and call callback } public static void crack(OnCrack callback) { @@ -87,7 +87,7 @@ public static void crack(OnCrack callback) { private static void doCrack(OnCrack Callback){ callback=Callback; - ClientCommandHelper.addOverlayMessage(Text.translatable("commands.ccrackrng.retries", attemptCount, MAX_ATTEMPTS), 100); + ClientCommandHelper.addOverlayMessage(Component.translatable("commands.ccrackrng.retries", attemptCount, MAX_ATTEMPTS), 100); if(throwItems()) { Configs.playerCrackState = PlayerRandCracker.CrackState.CRACKING; @@ -95,20 +95,20 @@ private static void doCrack(OnCrack Callback){ if (currentTask == null) { currentTask = new SeedCrackTask(); String taskName = TaskManager.addTask("ccrackrng", currentTask); - Text message = Text.translatable("commands.ccrackrng.starting") + Component message = Component.translatable("commands.ccrackrng.starting") .append(" ") .append(ClientCommandHelper.getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName)); - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(message); + Minecraft.getInstance().gui.getChat().addMessage(message); } } else { Configs.playerCrackState = PlayerRandCracker.CrackState.UNCRACKED; } } - public static void onEntityCreation(EntitySpawnS2CPacket packet) { - if (packet.getEntityType() == EntityType.ITEM && Configs.playerCrackState == PlayerRandCracker.CrackState.CRACKING) { + public static void onEntityCreation(ClientboundAddEntityPacket packet) { + if (packet.getType() == EntityType.ITEM && Configs.playerCrackState == PlayerRandCracker.CrackState.CRACKING) { if (SeedCracker.expectedItems > 0) { - long rand_val = (long) ((Math.atan2(packet.getVelocityZ(), packet.getVelocityX()) + Math.PI) / (Math.PI * 2) * ((float) (1 << 24))); + long rand_val = (long) ((Math.atan2(packet.getZa(), packet.getXa()) + Math.PI) / (Math.PI * 2) * ((float) (1 << 24))); long top_bits = rand_val; short value = (short) (((top_bits >> (24 - 4)) ^ 0x8L )&0xFL);//INSTEAD OF ^0x8L MAYBE DO +math.pi OR SOMETHING ELSE SeedCracker.bits[20-SeedCracker.expectedItems]=(long)value;//could be improved diff --git a/src/main/java/net/earthcomputer/clientcommands/ClientCommands.java b/src/main/java/net/earthcomputer/clientcommands/ClientCommands.java index e6e5fb338..80dd9b063 100644 --- a/src/main/java/net/earthcomputer/clientcommands/ClientCommands.java +++ b/src/main/java/net/earthcomputer/clientcommands/ClientCommands.java @@ -14,12 +14,12 @@ import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.MinecraftClient; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.Identifier; -import net.minecraft.util.Util; -import net.minecraft.util.math.Vec3d; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; import org.slf4j.Logger; import java.io.IOException; @@ -36,11 +36,11 @@ public class ClientCommands implements ClientModInitializer { private static final Logger LOGGER = LogUtils.getLogger(); public static Path configDir; private static final Set clientcommandsCommands = new HashSet<>(); - public static final Identifier COMMAND_EXECUTION_PACKET_ID = new Identifier("clientcommands", "command_execution"); + public static final ResourceLocation COMMAND_EXECUTION_PACKET_ID = new ResourceLocation("clientcommands", "command_execution"); private static final Set COMMANDS_TO_NOT_SEND_TO_SERVER = Set.of("cwe", "cnote"); // could contain private information public static final boolean SCRAMBLE_WINDOW_TITLE = Util.make(() -> { - String playerUUID = String.valueOf(MinecraftClient.getInstance().getSession().getUuidOrNull()); + String playerUUID = String.valueOf(Minecraft.getInstance().getUser().getProfileId()); Set victims = Set.of( "fa68270b-1071-46c6-ac5c-6c4a0b777a96", // Earthcomputer @@ -66,13 +66,13 @@ public void onInitializeClient() { ClientCommandRegistrationCallback.EVENT.register(ClientCommands::registerCommands); WorldRenderEvents.AFTER_ENTITIES.register(context -> { - context.matrixStack().push(); + context.matrixStack().pushPose(); - Vec3d cameraPos = context.camera().getPos(); + Vec3 cameraPos = context.camera().getPosition(); context.matrixStack().translate(-cameraPos.x, -cameraPos.y, -cameraPos.z); RenderQueue.render(RenderQueue.Layer.ON_TOP, Objects.requireNonNull(context.consumers()).getBuffer(RenderQueue.NO_DEPTH_LAYER), context.matrixStack(), context.tickDelta()); - context.matrixStack().pop(); + context.matrixStack().popPose(); }); configDir = FabricLoader.getInstance().getConfigDir().resolve("clientcommands"); @@ -97,14 +97,14 @@ public static void sendCommandExecutionToServer(String command) { String theCommand = reader.readUnquotedString(); if (clientcommandsCommands.contains(theCommand) && !COMMANDS_TO_NOT_SEND_TO_SERVER.contains(theCommand)) { if (ClientPlayNetworking.canSend(COMMAND_EXECUTION_PACKET_ID)) { - PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer()); - buf.writeString(command); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); + buf.writeUtf(command); ClientPlayNetworking.send(COMMAND_EXECUTION_PACKET_ID, buf); } } } - public static void registerCommands(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void registerCommands(CommandDispatcher dispatcher, CommandBuildContext context) { Set existingCommands = getCommands(dispatcher); AuditMixinsCommand.register(dispatcher); @@ -113,8 +113,8 @@ public static void registerCommands(CommandDispatcher NoteCommand.register(dispatcher); ShrugCommand.register(dispatcher); FindCommand.register(dispatcher); - FindBlockCommand.register(dispatcher, registryAccess); - FindItemCommand.register(dispatcher, registryAccess); + FindBlockCommand.register(dispatcher, context); + FindItemCommand.register(dispatcher, context); TaskCommand.register(dispatcher); CalcCommand.register(dispatcher); RenderCommand.register(dispatcher); @@ -123,34 +123,34 @@ public static void registerCommands(CommandDispatcher CEnchantCommand.register(dispatcher); GlowCommand.register(dispatcher); GetDataCommand.register(dispatcher); - CalcStackCommand.register(dispatcher, registryAccess); + CalcStackCommand.register(dispatcher, context); GammaCommand.register(dispatcher); MoteCommand.register(dispatcher); ChorusCommand.register(dispatcher); - FishCommand.register(dispatcher, registryAccess); + FishCommand.register(dispatcher, context); SignSearchCommand.register(dispatcher); - GhostBlockCommand.register(dispatcher, registryAccess); + GhostBlockCommand.register(dispatcher, context); RelogCommand.register(dispatcher); - CGiveCommand.register(dispatcher, registryAccess); + CGiveCommand.register(dispatcher, context); CPlaySoundCommand.register(dispatcher); CStopSoundCommand.register(dispatcher); FovCommand.register(dispatcher); HotbarCommand.register(dispatcher); KitCommand.register(dispatcher); - ItemGroupCommand.register(dispatcher, registryAccess); + ItemGroupCommand.register(dispatcher, context); CParticleCommand.register(dispatcher); PermissionLevelCommand.register(dispatcher); CTellRawCommand.register(dispatcher); CTimeCommand.register(dispatcher); AliasCommand.register(dispatcher); - AreaStatsCommand.register(dispatcher, registryAccess); + AreaStatsCommand.register(dispatcher, context); CTeleportCommand.register(dispatcher); // PlayerInfoCommand.register(dispatcher); PingCommand.register(dispatcher); UuidCommand.register(dispatcher); SnakeCommand.register(dispatcher); CTitleCommand.register(dispatcher); - TooltipCommand.register(dispatcher, registryAccess); + TooltipCommand.register(dispatcher, context); TranslateCommand.register(dispatcher); VarCommand.register(dispatcher); CFunctionCommand.register(dispatcher); @@ -163,7 +163,7 @@ public static void registerCommands(CommandDispatcher Calendar calendar = Calendar.getInstance(); boolean registerChatCommand = calendar.get(Calendar.MONTH) == Calendar.APRIL && calendar.get(Calendar.DAY_OF_MONTH) == 1; - registerChatCommand |= CHAT_COMMAND_USERS.contains(String.valueOf(MinecraftClient.getInstance().getSession().getUuidOrNull())); + registerChatCommand |= CHAT_COMMAND_USERS.contains(String.valueOf(Minecraft.getInstance().getUser().getProfileId())); registerChatCommand |= Boolean.getBoolean("clientcommands.debugChatCommand"); if (registerChatCommand) { ChatCommand.register(dispatcher); diff --git a/src/main/java/net/earthcomputer/clientcommands/ClientcommandsDataQueryHandler.java b/src/main/java/net/earthcomputer/clientcommands/ClientcommandsDataQueryHandler.java index 8450a4693..26038c1a9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/ClientcommandsDataQueryHandler.java +++ b/src/main/java/net/earthcomputer/clientcommands/ClientcommandsDataQueryHandler.java @@ -1,10 +1,10 @@ package net.earthcomputer.clientcommands; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.packet.c2s.play.QueryBlockNbtC2SPacket; -import net.minecraft.network.packet.c2s.play.QueryEntityNbtC2SPacket; -import net.minecraft.util.math.BlockPos; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.protocol.game.ServerboundBlockEntityTagQuery; +import net.minecraft.network.protocol.game.ServerboundEntityTagQuery; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -13,18 +13,18 @@ import java.util.function.Consumer; public class ClientcommandsDataQueryHandler { - private final ClientPlayNetworkHandler networkHandler; + private final ClientPacketListener packetListener; private final List callbacks = new ArrayList<>(); - public ClientcommandsDataQueryHandler(ClientPlayNetworkHandler networkHandler) { - this.networkHandler = networkHandler; + public ClientcommandsDataQueryHandler(ClientPacketListener packetListener) { + this.packetListener = packetListener; } - public static ClientcommandsDataQueryHandler get(ClientPlayNetworkHandler networkHandler) { - return ((IClientPlayNetworkHandler) networkHandler).clientcommands_getCCDataQueryHandler(); + public static ClientcommandsDataQueryHandler get(ClientPacketListener packetListener) { + return ((IClientPlayNetworkHandler) packetListener).clientcommands_getCCDataQueryHandler(); } - public boolean handleQueryResponse(int transactionId, @Nullable NbtCompound nbt) { + public boolean handleQueryResponse(int transactionId, @Nullable CompoundTag nbt) { Iterator callbacks = this.callbacks.iterator(); while (callbacks.hasNext()) { CallbackEntry callback = callbacks.next(); @@ -40,23 +40,23 @@ public boolean handleQueryResponse(int transactionId, @Nullable NbtCompound nbt) return false; } - private int nextQuery(Consumer<@Nullable NbtCompound> callback) { - int transactionId = ++networkHandler.getDataQueryHandler().expectedTransactionId; + private int nextQuery(Consumer<@Nullable CompoundTag> callback) { + int transactionId = ++packetListener.getDebugQueryHandler().transactionId; callbacks.add(new CallbackEntry(transactionId, callback)); return transactionId; } - public void queryEntityNbt(int entityNetworkId, Consumer<@Nullable NbtCompound> callback) { + public void queryEntityNbt(int entityNetworkId, Consumer<@Nullable CompoundTag> callback) { int transactionId = nextQuery(callback); - networkHandler.sendPacket(new QueryEntityNbtC2SPacket(transactionId, entityNetworkId)); + packetListener.send(new ServerboundEntityTagQuery(transactionId, entityNetworkId)); } - public void queryBlockNbt(BlockPos pos, Consumer<@Nullable NbtCompound> callback) { + public void queryBlockNbt(BlockPos pos, Consumer<@Nullable CompoundTag> callback) { int transactionId = nextQuery(callback); - networkHandler.sendPacket(new QueryBlockNbtC2SPacket(transactionId, pos)); + packetListener.send(new ServerboundBlockEntityTagQuery(transactionId, pos)); } - private record CallbackEntry(int transactionId, Consumer<@Nullable NbtCompound> callback) { + private record CallbackEntry(int transactionId, Consumer<@Nullable CompoundTag> callback) { } public interface IClientPlayNetworkHandler { diff --git a/src/main/java/net/earthcomputer/clientcommands/Configs.java b/src/main/java/net/earthcomputer/clientcommands/Configs.java index da095dda8..8dc91b7b8 100644 --- a/src/main/java/net/earthcomputer/clientcommands/Configs.java +++ b/src/main/java/net/earthcomputer/clientcommands/Configs.java @@ -5,8 +5,8 @@ import net.earthcomputer.clientcommands.features.EnchantmentCracker; import net.earthcomputer.clientcommands.features.FishingCracker; import net.earthcomputer.clientcommands.features.PlayerRandCracker; -import net.minecraft.util.StringIdentifiable; -import net.minecraft.util.math.MathHelper; +import net.minecraft.util.Mth; +import net.minecraft.util.StringRepresentable; import java.util.Locale; @@ -35,13 +35,13 @@ public static void setEnchantingPrediction(boolean enchantingPrediction) { } } - public enum FishingManipulation implements StringIdentifiable { + public enum FishingManipulation implements StringRepresentable { OFF, MANUAL, AFK; @Override - public String asString() { + public String getSerializedName() { return this.name().toLowerCase(Locale.ROOT); } @@ -76,7 +76,7 @@ public static int getMaxEnchantItemThrows() { return maxEnchantItemThrows; } public static void setMaxEnchantItemThrows(int maxEnchantItemThrows) { - Configs.maxEnchantItemThrows = MathHelper.clamp(maxEnchantItemThrows, 0, 1000000); + Configs.maxEnchantItemThrows = Mth.clamp(maxEnchantItemThrows, 0, 1000000); } @Config(setter = @Config.Setter("setChorusManipulation"), temporary = true) @@ -98,7 +98,7 @@ public static int getMaxChorusItemThrows() { return maxChorusItemThrows; } public static void setMaxChorusItemThrows(int maxChorusItemThrows) { - Configs.maxChorusItemThrows = MathHelper.clamp(maxChorusItemThrows, 0, 1000000); + Configs.maxChorusItemThrows = Mth.clamp(maxChorusItemThrows, 0, 1000000); } @Config(temporary = true) diff --git a/src/main/java/net/earthcomputer/clientcommands/GuiBlocker.java b/src/main/java/net/earthcomputer/clientcommands/GuiBlocker.java index 310754b22..4206c70f1 100644 --- a/src/main/java/net/earthcomputer/clientcommands/GuiBlocker.java +++ b/src/main/java/net/earthcomputer/clientcommands/GuiBlocker.java @@ -1,6 +1,6 @@ package net.earthcomputer.clientcommands; -import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screens.Screen; import java.util.ArrayList; import java.util.Iterator; diff --git a/src/main/java/net/earthcomputer/clientcommands/IntegratedServerUtil.java b/src/main/java/net/earthcomputer/clientcommands/IntegratedServerUtil.java index 926ef078a..a92b06904 100644 --- a/src/main/java/net/earthcomputer/clientcommands/IntegratedServerUtil.java +++ b/src/main/java/net/earthcomputer/clientcommands/IntegratedServerUtil.java @@ -1,13 +1,13 @@ package net.earthcomputer.clientcommands; -import net.earthcomputer.clientcommands.mixin.CheckedRandomAccessor; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; +import net.earthcomputer.clientcommands.mixin.LegacyRandomSourceAccessor; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; import org.jetbrains.annotations.Nullable; public final class IntegratedServerUtil { @@ -17,9 +17,9 @@ private IntegratedServerUtil() {} * Returns the corresponding server player to the client player in singleplayer */ @Nullable - public static ServerPlayerEntity getServerPlayer() { - Entity serverEntity = getServerEntityUnchecked(MinecraftClient.getInstance().player); - if (serverEntity instanceof ServerPlayerEntity serverPlayer) { + public static ServerPlayer getServerPlayer() { + Entity serverEntity = getServerEntityUnchecked(Minecraft.getInstance().player); + if (serverEntity instanceof ServerPlayer serverPlayer) { return serverPlayer; } return null; @@ -32,7 +32,7 @@ public static ServerPlayerEntity getServerPlayer() { @SuppressWarnings("unchecked") @Nullable public static T getServerEntity(T entity) { - if (entity instanceof PlayerEntity) { + if (entity instanceof Player) { return null; } @@ -45,27 +45,27 @@ public static T getServerEntity(T entity) { @Nullable private static Entity getServerEntityUnchecked(Entity entity) { - ServerWorld world = getServerWorld(); - if (world == null) { + ServerLevel level = getServerLevel(); + if (level == null) { return null; } - return world.getEntityById(entity.getId()); + return level.getEntity(entity.getId()); } /** * Returns the server world for the dimension the player is currently in, in singleplayer */ @Nullable - public static ServerWorld getServerWorld() { - MinecraftServer server = MinecraftClient.getInstance().getServer(); + public static ServerLevel getServerLevel() { + MinecraftServer server = Minecraft.getInstance().getSingleplayerServer(); if (server == null) { return null; } - ClientWorld world = MinecraftClient.getInstance().world; - if (world == null) { + ClientLevel level = Minecraft.getInstance().level; + if (level == null) { return null; } - return server.getWorld(world.getRegistryKey()); + return server.getLevel(level.dimension()); } /** @@ -74,15 +74,15 @@ public static ServerWorld getServerWorld() { @SuppressWarnings("unchecked") @Nullable public static T getClientEntity(T entity) { - if (entity instanceof PlayerEntity) { + if (entity instanceof Player) { return null; } - ClientWorld world = MinecraftClient.getInstance().world; - if (world == null) { + ClientLevel level = Minecraft.getInstance().level; + if (level == null) { return null; } - Entity clientEntity = world.getEntityById(entity.getId()); + Entity clientEntity = level.getEntity(entity.getId()); if (clientEntity != null && clientEntity.getClass() == entity.getClass()) { return (T) clientEntity; } @@ -93,10 +93,10 @@ public static T getClientEntity(T entity) { * Gets the random seed of the server player */ public static long getServerPlayerSeed() { - ServerPlayerEntity player = getServerPlayer(); + ServerPlayer player = getServerPlayer(); if (player == null) { return 0; } - return ((CheckedRandomAccessor) player.getRandom()).getSeed().get(); + return ((LegacyRandomSourceAccessor) player.getRandom()).getSeed().get(); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/MathUtil.java b/src/main/java/net/earthcomputer/clientcommands/MathUtil.java index 443a2952d..b845c5074 100644 --- a/src/main/java/net/earthcomputer/clientcommands/MathUtil.java +++ b/src/main/java/net/earthcomputer/clientcommands/MathUtil.java @@ -1,13 +1,20 @@ package net.earthcomputer.clientcommands; import com.google.common.collect.Iterables; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.*; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; - -import java.awt.geom.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.VoxelShape; + +import java.awt.geom.Area; +import java.awt.geom.Path2D; +import java.awt.geom.PathIterator; +import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; @@ -15,22 +22,22 @@ public class MathUtil { private static final double EPSILON = 0.001; - public static Vec3d getClosestPoint(BlockPos blockPos, VoxelShape voxel, Vec3d pos) { + public static Vec3 getClosestPoint(BlockPos blockPos, VoxelShape voxel, Vec3 pos) { return getClosestPoint(blockPos, voxel, pos, null); } - public static Vec3d getClosestPoint(BlockPos blockPos, VoxelShape voxel, Vec3d pos, Direction dir) { + public static Vec3 getClosestPoint(BlockPos blockPos, VoxelShape voxel, Vec3 pos, Direction dir) { ClosestPosResult result = new ClosestPosResult(); Direction[] dirs = dir == null ? Direction.values() : new Direction[] {dir}; - voxel.forEachBox((x1, y1, z1, x2, y2, z2) -> { - Box box = new Box(x1, y1, z1, x2, y2, z2).offset(blockPos); + voxel.forAllBoxes((x1, y1, z1, x2, y2, z2) -> { + AABB box = new AABB(x1, y1, z1, x2, y2, z2).move(blockPos); for (Direction face : dirs) { - Box faceBox = getFace(box, face); + AABB faceBox = getFace(box, face); // Since the faces are axis aligned, it's a simple clamp operation - Vec3d val = new Vec3d(MathHelper.clamp(pos.x, faceBox.minX, faceBox.maxX), - MathHelper.clamp(pos.y, faceBox.minY, faceBox.maxY), - MathHelper.clamp(pos.z, faceBox.minZ, faceBox.maxZ)); - double distanceSq = val.squaredDistanceTo(pos); + Vec3 val = new Vec3(Mth.clamp(pos.x, faceBox.minX, faceBox.maxX), + Mth.clamp(pos.y, faceBox.minY, faceBox.maxY), + Mth.clamp(pos.z, faceBox.minZ, faceBox.maxZ)); + double distanceSq = val.distanceToSqr(pos); if (distanceSq < result.distanceSq) { result.val = val; result.distanceSq = distanceSq; @@ -40,47 +47,47 @@ public static Vec3d getClosestPoint(BlockPos blockPos, VoxelShape voxel, Vec3d p return result.val; } - public static Vec3d getClosestVisiblePoint(World world, BlockPos targetPos, Vec3d sourcePos, Entity excludingEntity) { - return getClosestVisiblePoint(world, targetPos, sourcePos, excludingEntity, null); + public static Vec3 getClosestVisiblePoint(Level level, BlockPos targetPos, Vec3 sourcePos, Entity excludingEntity) { + return getClosestVisiblePoint(level, targetPos, sourcePos, excludingEntity, null); } - public static Vec3d getClosestVisiblePoint(World world, BlockPos targetPos, Vec3d sourcePos, Entity excludingEntity, Direction dir) { - if (targetPos.getSquaredDistance(sourcePos.x, sourcePos.y, sourcePos.z) > 7 * 7) { + public static Vec3 getClosestVisiblePoint(Level level, BlockPos targetPos, Vec3 sourcePos, Entity excludingEntity, Direction dir) { + if (targetPos.distToLowCornerSqr(sourcePos.x, sourcePos.y, sourcePos.z) > 7 * 7) { return null; } - Box totalArea = new Box(sourcePos, Vec3d.of(targetPos)); - List obscurers = new ArrayList<>(); - for (BlockPos pos : BlockPos.iterate(MathHelper.floor(totalArea.minX), MathHelper.floor(totalArea.minY), MathHelper.floor(totalArea.minZ), - MathHelper.ceil(totalArea.maxX), MathHelper.ceil(totalArea.maxY), MathHelper.ceil(totalArea.maxZ))) { + AABB totalArea = new AABB(sourcePos, Vec3.atLowerCornerOf(targetPos)); + List obscurers = new ArrayList<>(); + for (BlockPos pos : BlockPos.betweenClosed(Mth.floor(totalArea.minX), Mth.floor(totalArea.minY), Mth.floor(totalArea.minZ), + Mth.ceil(totalArea.maxX), Mth.ceil(totalArea.maxY), Mth.ceil(totalArea.maxZ))) { if (!pos.equals(targetPos)) { - world.getBlockState(pos).getOutlineShape(world, pos).forEachBox((x1, y1, z1, x2, y2, z2) -> - obscurers.add(new Box(x1, y1, z1, x2, y2, z2).offset(pos).expand(EPSILON))); + level.getBlockState(pos).getShape(level, pos).forAllBoxes((x1, y1, z1, x2, y2, z2) -> + obscurers.add(new AABB(x1, y1, z1, x2, y2, z2).move(pos).inflate(EPSILON))); } } - for (Entity entity : world.getOtherEntities(excludingEntity, totalArea, entity -> !entity.isSpectator() && entity.canHit())) { - obscurers.add(entity.getBoundingBox().expand(entity.getTargetingMargin() + EPSILON)); + for (Entity entity : level.getEntities(excludingEntity, totalArea, entity -> !entity.isSpectator() && entity.isPickable())) { + obscurers.add(entity.getBoundingBox().inflate(entity.getPickRadius() + EPSILON)); } - List targetBoxes = new ArrayList<>(); - world.getBlockState(targetPos).getOutlineShape(world, targetPos).forEachBox((x1, y1, z1, x2, y2, z2) -> - targetBoxes.add(new Box(x1, y1, z1, x2, y2, z2).offset(targetPos))); + List targetBoxes = new ArrayList<>(); + level.getBlockState(targetPos).getShape(level, targetPos).forAllBoxes((x1, y1, z1, x2, y2, z2) -> + targetBoxes.add(new AABB(x1, y1, z1, x2, y2, z2).move(targetPos))); - Vec3d resultVal = null; + Vec3 resultVal = null; double resultDistanceSq = Double.POSITIVE_INFINITY; Direction[] dirs = dir == null ? Direction.values() : new Direction[] {dir}; - for (Box box : targetBoxes) { + for (AABB box : targetBoxes) { for (Direction face : dirs) { - Box faceBox = getFace(box.expand(-EPSILON), face); + AABB faceBox = getFace(box.inflate(-EPSILON), face); if (sourcePos.subtract(faceBox.minX, faceBox.minY, faceBox.minZ) - .dotProduct(new Vec3d(face.getOffsetX(), face.getOffsetY(), face.getOffsetZ())) > 0) { + .dot(new Vec3(face.getStepX(), face.getStepY(), face.getStepZ())) > 0) { //noinspection StaticPseudoFunctionalStyleMethod - Vec3d val = getClosestVisiblePoint(world, + Vec3 val = getClosestVisiblePoint(level, Iterables.concat(obscurers, Iterables.transform(Iterables.filter(targetBoxes, it -> it != box), - b -> b.expand(EPSILON))), + b -> b.inflate(EPSILON))), faceBox, sourcePos, face); if (val != null) { - double distanceSq = val.squaredDistanceTo(sourcePos); + double distanceSq = val.distanceToSqr(sourcePos); if (distanceSq < resultDistanceSq) { resultVal = val; resultDistanceSq = distanceSq; @@ -93,7 +100,7 @@ public static Vec3d getClosestVisiblePoint(World world, BlockPos targetPos, Vec3 return resultVal; } - private static Vec3d getClosestVisiblePoint(BlockView world, Iterable obscurers, Box face, Vec3d sourcePos, Direction dir) { + private static Vec3 getClosestVisiblePoint(BlockGetter level, Iterable obscurers, AABB face, Vec3 sourcePos, Direction dir) { Direction.Axis xAxis, yAxis; switch (dir.getAxis()) { case X -> { @@ -121,9 +128,9 @@ private static Vec3d getClosestVisiblePoint(BlockView world, Iterable obscu double s = getComponent(sourcePos, dir.getAxis()); double sx = getComponent(sourcePos, xAxis); double sy = getComponent(sourcePos, yAxis); - for (Box obscurer : obscurers) { + for (AABB obscurer : obscurers) { for (Direction obscurerSide : Direction.values()) { - Box obscurerFace = getFace(obscurer, obscurerSide); + AABB obscurerFace = getFace(obscurer, obscurerSide); Path2D.Double path = getShadow(sourcePos, obscurerFace, obscurerSide, f, dir, minX + (maxX - minX) * .5, minY + (maxY - minY) * .5, xAxis, yAxis); if (path != null) @@ -192,15 +199,15 @@ private static Vec3d getClosestVisiblePoint(BlockView world, Iterable obscu } /** @noinspection DuplicatedCode it's a painful truth, deal with it :) */ - private static Path2D.Double getShadow(Vec3d sourcePos, Box obscurerFace, Direction obscurerFaceNormal, double targetPlaneCoord, Direction targetPlaneNormal, double targetCenterX, double targetCenterY, Direction.Axis xAxis, Direction.Axis yAxis) { + private static Path2D.Double getShadow(Vec3 sourcePos, AABB obscurerFace, Direction obscurerFaceNormal, double targetPlaneCoord, Direction targetPlaneNormal, double targetCenterX, double targetCenterY, Direction.Axis xAxis, Direction.Axis yAxis) { double sourceOffset = getComponent(sourcePos, targetPlaneNormal.getAxis()); double[][] obscurer = new double[4][3]; boolean[] behindSource = new boolean[4]; { - Direction dirB = obscurerFaceNormal.getAxis() == Direction.Axis.Y ? Direction.WEST : obscurerFaceNormal.rotateYClockwise(); + Direction dirB = obscurerFaceNormal.getAxis() == Direction.Axis.Y ? Direction.WEST : obscurerFaceNormal.getClockWise(); Direction dirC = rotateClockwise(obscurerFaceNormal, dirB.getAxis()); for (int i = 0; i < 4; i++) { - Box vertex = getFace(getFace(obscurerFace, i < 2 ? dirB : dirB.getOpposite()), i == 0 || i == 3 ? dirC : dirC.getOpposite()); + AABB vertex = getFace(getFace(obscurerFace, i < 2 ? dirB : dirB.getOpposite()), i == 0 || i == 3 ? dirC : dirC.getOpposite()); obscurer[i][0] = vertex.minX; obscurer[i][1] = vertex.minY; obscurer[i][2] = vertex.minZ; @@ -242,7 +249,7 @@ private static Path2D.Double getShadow(Vec3d sourcePos, Box obscurerFace, Direct return null; // only possible if the player is inside the obstacle } // actually find the point on the target plane - Vec3d projected = sourcePos.add((obscurer[i][0] - sourcePos.x) * lambda, (obscurer[i][1] - sourcePos.y) * lambda, (obscurer[i][2] - sourcePos.z) * lambda); + Vec3 projected = sourcePos.add((obscurer[i][0] - sourcePos.x) * lambda, (obscurer[i][1] - sourcePos.y) * lambda, (obscurer[i][2] - sourcePos.z) * lambda); double x = getComponent(projected, xAxis); double y = getComponent(projected, yAxis); if (i == firstInFront) { @@ -381,7 +388,7 @@ private static Path2D.Double getShadow(Vec3d sourcePos, Box obscurerFace, Direct return path; } - private static double getComponent(Vec3d vec, Direction.Axis axis) { + private static double getComponent(Vec3 vec, Direction.Axis axis) { return getComponent(vec.x, vec.y, vec.z, axis); } @@ -394,7 +401,7 @@ private static double getComponent(double x, double y, double z, Direction.Axis } /** @noinspection DuplicatedCode */ - private static Vec3d createFromComponents(double a, Direction.Axis aAxis, double b, Direction.Axis bAxis, double c, Direction.Axis cAxis) { + private static Vec3 createFromComponents(double a, Direction.Axis aAxis, double b, Direction.Axis bAxis, double c, Direction.Axis cAxis) { double x = 0, y = 0, z = 0; switch (aAxis) { case X -> x = a; @@ -411,17 +418,17 @@ private static Vec3d createFromComponents(double a, Direction.Axis aAxis, double case Y -> y = c; case Z -> z = c; } - return new Vec3d(x, y, z); + return new Vec3(x, y, z); } - private static Box getFace(Box box, Direction dir) { + private static AABB getFace(AABB box, Direction dir) { return switch (dir) { - case WEST -> new Box(box.minX, box.minY, box.minZ, box.minX, box.maxY, box.maxZ); - case EAST -> new Box(box.maxX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ); - case DOWN -> new Box(box.minX, box.minY, box.minZ, box.maxX, box.minY, box.maxZ); - case UP -> new Box(box.minX, box.maxY, box.minZ, box.maxX, box.maxY, box.maxZ); - case NORTH -> new Box(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.minZ); - case SOUTH -> new Box(box.minX, box.minY, box.maxZ, box.maxX, box.maxY, box.maxZ); + case WEST -> new AABB(box.minX, box.minY, box.minZ, box.minX, box.maxY, box.maxZ); + case EAST -> new AABB(box.maxX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ); + case DOWN -> new AABB(box.minX, box.minY, box.minZ, box.maxX, box.minY, box.maxZ); + case UP -> new AABB(box.minX, box.maxY, box.minZ, box.maxX, box.maxY, box.maxZ); + case NORTH -> new AABB(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.minZ); + case SOUTH -> new AABB(box.minX, box.minY, box.maxZ, box.maxX, box.maxY, box.maxZ); }; } @@ -435,7 +442,7 @@ public static Direction rotateClockwise(Direction dir, Direction.Axis axis) { } case Y -> { if (dir != Direction.UP && dir != Direction.DOWN) { - return dir.rotateYClockwise(); + return dir.getClockWise(); } return dir; } @@ -470,7 +477,7 @@ public static Direction rotateZClockwise(Direction dir) { } private static class ClosestPosResult { - Vec3d val; + Vec3 val; double distanceSq = Double.POSITIVE_INFINITY; } diff --git a/src/main/java/net/earthcomputer/clientcommands/MultiVersionCompat.java b/src/main/java/net/earthcomputer/clientcommands/MultiVersionCompat.java index 43024e3ae..acfa95e11 100644 --- a/src/main/java/net/earthcomputer/clientcommands/MultiVersionCompat.java +++ b/src/main/java/net/earthcomputer/clientcommands/MultiVersionCompat.java @@ -6,11 +6,11 @@ import io.netty.channel.ChannelHandler; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.SharedConstants; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.item.Item; -import net.minecraft.network.ClientConnection; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.Connection; +import net.minecraft.world.item.Item; import org.slf4j.Logger; import java.lang.reflect.Field; @@ -61,7 +61,7 @@ public int getProtocolVersion() { @Override public String getProtocolName() { - return SharedConstants.getGameVersion().getName(); + return SharedConstants.getCurrentVersion().getName(); } } @@ -119,7 +119,7 @@ private ViaFabric() throws ReflectiveOperationException { getProtocol = protocolVersion.getMethod("getProtocol", int.class); Field channelField = null; - for (Field field : ClientConnection.class.getDeclaredFields()) { + for (Field field : Connection.class.getDeclaredFields()) { if (field.getType() == Channel.class) { channelField = field; channelField.setAccessible(true); @@ -155,9 +155,9 @@ private int doGetProtocolVersion() throws ReflectiveOperationException { int protocolVersion = SharedConstants.getProtocolVersion(); // https://github.com/ViaVersion/ViaFabric/blob/fda8d39147d46c80698d204538ede790f02589f6/viafabric-mc18/src/main/java/com/viaversion/fabric/mc18/mixin/debug/client/MixinDebugHud.java - ClientPlayNetworkHandler networkHandler = MinecraftClient.getInstance().getNetworkHandler(); - if (networkHandler != null) { - Channel channel = (Channel) this.channel.get(networkHandler.getConnection()); + ClientPacketListener packetListener = Minecraft.getInstance().getConnection(); + if (packetListener != null) { + Channel channel = (Channel) this.channel.get(packetListener.getConnection()); ChannelHandler viaDecoder = channel.pipeline().get("via-decoder"); if (fabricDecodeHandler.isInstance(viaDecoder)) { Object user = getInfo.invoke(viaDecoder); diff --git a/src/main/java/net/earthcomputer/clientcommands/ServerBrandManager.java b/src/main/java/net/earthcomputer/clientcommands/ServerBrandManager.java index 06cf8ec09..862d40b07 100644 --- a/src/main/java/net/earthcomputer/clientcommands/ServerBrandManager.java +++ b/src/main/java/net/earthcomputer/clientcommands/ServerBrandManager.java @@ -1,9 +1,9 @@ package net.earthcomputer.clientcommands; import net.earthcomputer.clientcommands.features.Relogger; -import net.minecraft.client.MinecraftClient; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; public class ServerBrandManager { @@ -30,9 +30,9 @@ public static void onDisconnect() { } public static void rngWarning() { - if (!isVanilla() && !hasWarnedRng && !MinecraftClient.getInstance().isIntegratedServerRunning()) { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage( - Text.translatable("playerManip.serverBrandWarning").formatted(Formatting.YELLOW)); + if (!isVanilla() && !hasWarnedRng && !Minecraft.getInstance().hasSingleplayerServer()) { + Minecraft.getInstance().gui.getChat().addMessage( + Component.translatable("playerManip.serverBrandWarning").withStyle(ChatFormatting.YELLOW)); hasWarnedRng = true; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/c2c/C2CPacket.java b/src/main/java/net/earthcomputer/clientcommands/c2c/C2CPacket.java index b07112279..3e82e65f2 100644 --- a/src/main/java/net/earthcomputer/clientcommands/c2c/C2CPacket.java +++ b/src/main/java/net/earthcomputer/clientcommands/c2c/C2CPacket.java @@ -1,9 +1,9 @@ package net.earthcomputer.clientcommands.c2c; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; public interface C2CPacket { - void write(PacketByteBuf buf); + void write(FriendlyByteBuf buf); void apply(CCPacketListener listener); } diff --git a/src/main/java/net/earthcomputer/clientcommands/c2c/CCNetworkHandler.java b/src/main/java/net/earthcomputer/clientcommands/c2c/CCNetworkHandler.java index 44ebde8b5..109e2f234 100644 --- a/src/main/java/net/earthcomputer/clientcommands/c2c/CCNetworkHandler.java +++ b/src/main/java/net/earthcomputer/clientcommands/c2c/CCNetworkHandler.java @@ -6,23 +6,23 @@ import com.mojang.logging.LogUtils; import net.earthcomputer.clientcommands.c2c.packets.MessageC2CPacket; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.encryption.PlayerPublicKey; -import net.minecraft.network.encryption.PublicPlayerSession; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.RemoteChatSession; +import net.minecraft.world.entity.player.ProfilePublicKey; import org.slf4j.Logger; import java.security.PublicKey; public class CCNetworkHandler implements CCPacketListener { - private static final DynamicCommandExceptionType MESSAGE_TOO_LONG_EXCEPTION = new DynamicCommandExceptionType(d -> Text.translatable("ccpacket.messageTooLong", d)); - private static final SimpleCommandExceptionType PUBLIC_KEY_NOT_FOUND_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("ccpacket.publicKeyNotFound")); - private static final SimpleCommandExceptionType ENCRYPTION_FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("ccpacket.encryptionFailed")); + private static final DynamicCommandExceptionType MESSAGE_TOO_LONG_EXCEPTION = new DynamicCommandExceptionType(d -> Component.translatable("ccpacket.messageTooLong", d)); + private static final SimpleCommandExceptionType PUBLIC_KEY_NOT_FOUND_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("ccpacket.publicKeyNotFound")); + private static final SimpleCommandExceptionType ENCRYPTION_FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("ccpacket.encryptionFailed")); private static final CCNetworkHandler instance = new CCNetworkHandler(); @@ -35,22 +35,22 @@ public static CCNetworkHandler getInstance() { return instance; } - public void sendPacket(C2CPacket packet, PlayerListEntry recipient) throws CommandSyntaxException { + public void sendPacket(C2CPacket packet, PlayerInfo recipient) throws CommandSyntaxException { Integer id = CCPacketHandler.getId(packet.getClass()); if (id == null) { LOGGER.warn("Could not send the packet because the id was not recognised"); return; } - PublicPlayerSession session = recipient.getSession(); + RemoteChatSession session = recipient.getChatSession(); if (session == null) { throw PUBLIC_KEY_NOT_FOUND_EXCEPTION.create(); } - PlayerPublicKey ppk = session.publicKeyData(); + ProfilePublicKey ppk = session.profilePublicKey(); if (ppk == null) { throw PUBLIC_KEY_NOT_FOUND_EXCEPTION.create(); } PublicKey key = ppk.data().key(); - PacketByteBuf buf = PacketByteBufs.create(); + FriendlyByteBuf buf = PacketByteBufs.create(); buf.writeInt(id); packet.write(buf); byte[] uncompressed = new byte[buf.readableBytes()]; @@ -83,7 +83,7 @@ public void sendPacket(C2CPacket packet, PlayerListEntry recipient) throws Comma if (commandString.length() >= 256) { throw MESSAGE_TOO_LONG_EXCEPTION.create(commandString.length()); } - MinecraftClient.getInstance().getNetworkHandler().sendChatCommand(commandString); + Minecraft.getInstance().getConnection().sendCommand(commandString); OutgoingPacketFilter.addPacket(packetString); } @@ -91,12 +91,12 @@ public void sendPacket(C2CPacket packet, PlayerListEntry recipient) throws Comma public void onMessageC2CPacket(MessageC2CPacket packet) { String sender = packet.getSender(); String message = packet.getMessage(); - MutableText prefix = Text.empty(); - prefix.append(Text.literal("[").formatted(Formatting.DARK_GRAY)); - prefix.append(Text.literal("/cwe").formatted(Formatting.AQUA)); - prefix.append(Text.literal("]").formatted(Formatting.DARK_GRAY)); - prefix.append(Text.literal(" ")); - Text text = prefix.append(Text.translatable("ccpacket.messageC2CPacket.incoming", sender, message).formatted(Formatting.GRAY)); - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(text); + MutableComponent prefix = Component.empty(); + prefix.append(Component.literal("[").withStyle(ChatFormatting.DARK_GRAY)); + prefix.append(Component.literal("/cwe").withStyle(ChatFormatting.AQUA)); + prefix.append(Component.literal("]").withStyle(ChatFormatting.DARK_GRAY)); + prefix.append(Component.literal(" ")); + Component component = prefix.append(Component.translatable("ccpacket.messageC2CPacket.incoming", sender, message).withStyle(ChatFormatting.GRAY)); + Minecraft.getInstance().gui.getChat().addMessage(component); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/c2c/CCPacketHandler.java b/src/main/java/net/earthcomputer/clientcommands/c2c/CCPacketHandler.java index 7017c41f0..998b4a71b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/c2c/CCPacketHandler.java +++ b/src/main/java/net/earthcomputer/clientcommands/c2c/CCPacketHandler.java @@ -3,8 +3,8 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.earthcomputer.clientcommands.c2c.packets.MessageC2CPacket; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -14,13 +14,13 @@ public class CCPacketHandler { private static final Object2IntMap> packetIds = Util.make(new Object2IntOpenHashMap<>(), map -> map.defaultReturnValue(-1)); - private static final List> packetFactories = new ArrayList<>(); + private static final List> packetFactories = new ArrayList<>(); static { CCPacketHandler.register(MessageC2CPacket.class, MessageC2CPacket::new); } - public static

void register(Class

packet, Function packetFactory) { + public static

void register(Class

packet, Function packetFactory) { int id = packetFactories.size(); int i = packetIds.put(packet, id); if (i != -1) { @@ -37,8 +37,8 @@ public static

Integer getId(Class

packet) { } @Nullable - public static C2CPacket createPacket(int id, PacketByteBuf buf) { - Function function = packetFactories.get(id); + public static C2CPacket createPacket(int id, FriendlyByteBuf buf) { + Function function = packetFactories.get(id); return function == null ? null : function.apply(buf); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/c2c/packets/MessageC2CPacket.java b/src/main/java/net/earthcomputer/clientcommands/c2c/packets/MessageC2CPacket.java index 7b548eab5..b84792a58 100644 --- a/src/main/java/net/earthcomputer/clientcommands/c2c/packets/MessageC2CPacket.java +++ b/src/main/java/net/earthcomputer/clientcommands/c2c/packets/MessageC2CPacket.java @@ -2,7 +2,7 @@ import net.earthcomputer.clientcommands.c2c.C2CPacket; import net.earthcomputer.clientcommands.c2c.CCPacketListener; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; public class MessageC2CPacket implements C2CPacket { @@ -14,15 +14,15 @@ public MessageC2CPacket(String sender, String message) { this.message = message; } - public MessageC2CPacket(PacketByteBuf raw) { - this.sender = raw.readString(); - this.message = raw.readString(); + public MessageC2CPacket(FriendlyByteBuf raw) { + this.sender = raw.readUtf(); + this.message = raw.readUtf(); } @Override - public void write(PacketByteBuf buf) { - buf.writeString(this.sender); - buf.writeString(this.message); + public void write(FriendlyByteBuf buf) { + buf.writeUtf(this.sender); + buf.writeUtf(this.message); } @Override diff --git a/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java index 949ca3f59..e1d426714 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java @@ -15,10 +15,10 @@ import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.chat.Component; import org.slf4j.Logger; import java.io.IOException; @@ -39,11 +39,11 @@ public class AliasCommand { private static final Path ALIAS_PATH = FabricLoader.getInstance().getConfigDir().resolve("clientcommands").resolve("alias_list.json"); - private static final SimpleCommandExceptionType ILLEGAL_FORMAT_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.calias.illegalFormatException")); + private static final SimpleCommandExceptionType ILLEGAL_FORMAT_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.calias.illegalFormatException")); - private static final DynamicCommandExceptionType ALIAS_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.calias.addAlias.aliasAlreadyExists", arg)); - private static final DynamicCommandExceptionType COMMAND_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.calias.addAlias.commandAlreadyExists", arg)); - private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.calias.notFound", arg)); + private static final DynamicCommandExceptionType ALIAS_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.calias.addAlias.aliasAlreadyExists", arg)); + private static final DynamicCommandExceptionType COMMAND_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.calias.addAlias.commandAlreadyExists", arg)); + private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.calias.notFound", arg)); private static final HashMap aliasMap = loadAliases(); @@ -92,15 +92,15 @@ private static int executeAliasCommand(FabricClientCommandSource source, String } else if (arguments != null) { cmd += " " + arguments; } - ClientPlayNetworkHandler networkHandler = MinecraftClient.getInstance().getNetworkHandler(); - if (networkHandler == null) { + ClientPacketListener packetListener = Minecraft.getInstance().getConnection(); + if (packetListener == null) { return Command.SINGLE_SUCCESS; } if (cmd.startsWith("/")) { cmd = cmd.substring(1); - networkHandler.sendChatCommand(cmd); + packetListener.sendCommand(cmd); } else { - networkHandler.sendChatMessage(cmd); + packetListener.sendChat(cmd); } return Command.SINGLE_SUCCESS; @@ -118,7 +118,7 @@ private static int addAlias(FabricClientCommandSource source, String key, String command = "/" + command; } - for (CommandDispatcher dispatcher : new CommandDispatcher[] { ClientCommandManager.getActiveDispatcher(), MinecraftClient.getInstance().getNetworkHandler().getCommandDispatcher() }) { + for (CommandDispatcher dispatcher : new CommandDispatcher[] { ClientCommandManager.getActiveDispatcher(), Minecraft.getInstance().getConnection().getCommands() }) { dispatcher.register(literal(key) .executes(ctx -> executeAliasCommand(source, key, null)) .then(argument("arguments", greedyString()) @@ -128,17 +128,17 @@ private static int addAlias(FabricClientCommandSource source, String key, String aliasMap.put(key, command); saveAliases(); - source.sendFeedback(Text.translatable("commands.calias.addAlias.success", key)); + source.sendFeedback(Component.translatable("commands.calias.addAlias.success", key)); return Command.SINGLE_SUCCESS; } private static int listAliases(FabricClientCommandSource source) { if (aliasMap.isEmpty()) { - source.sendFeedback(Text.translatable("commands.calias.listAliases.noAliasesRegistered")); + source.sendFeedback(Component.translatable("commands.calias.listAliases.noAliasesRegistered")); } else { - source.sendFeedback(Text.translatable("commands.calias.listAliases.success", aliasMap.size())); + source.sendFeedback(Component.translatable("commands.calias.listAliases.success", aliasMap.size())); for (String key : aliasMap.keySet()) { - source.sendFeedback(Text.of(Formatting.BOLD + key + Formatting.RESET + ": " + aliasMap.get(key).replace("%","%%"))); + source.sendFeedback(Component.literal(ChatFormatting.BOLD + key + ChatFormatting.RESET + ": " + aliasMap.get(key).replace("%","%%"))); } } return Command.SINGLE_SUCCESS; @@ -147,14 +147,14 @@ private static int listAliases(FabricClientCommandSource source) { private static int removeAlias(FabricClientCommandSource source, String key) throws CommandSyntaxException { if (aliasMap.containsKey(key)) { BrigadierRemover.of(ClientCommandManager.getActiveDispatcher()).get(key).remove(); - BrigadierRemover.of(MinecraftClient.getInstance().getNetworkHandler().getCommandDispatcher()).get(key).remove(); + BrigadierRemover.of(Minecraft.getInstance().getConnection().getCommands()).get(key).remove(); aliasMap.remove(key); } else { throw NOT_FOUND_EXCEPTION.create(key); } saveAliases(); - source.sendFeedback(Text.translatable("commands.calias.removeAlias.success", key)); + source.sendFeedback(Component.translatable("commands.calias.removeAlias.success", key)); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java index 3c0a94e17..639a19662 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java @@ -7,45 +7,45 @@ import com.mojang.brigadier.tree.LiteralCommandNode; import net.earthcomputer.clientcommands.render.RenderQueue; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.world.chunk.ChunkManager; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.level.chunk.ChunkSource; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.phys.AABB; import static dev.xpple.clientarguments.arguments.CBlockPosArgumentType.*; -import static net.earthcomputer.clientcommands.command.arguments.ListArgumentType.*; import static net.earthcomputer.clientcommands.command.arguments.ClientBlockPredicateArgumentType.*; +import static net.earthcomputer.clientcommands.command.arguments.ListArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class AreaStatsCommand { - private static final SimpleCommandExceptionType NOT_LOADED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.careastats.notLoaded")); + private static final SimpleCommandExceptionType NOT_LOADED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.careastats.notLoaded")); - private static ChunkManager chunkManager; + private static ChunkSource chunkSource; - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { LiteralCommandNode careastats = dispatcher.register(literal("careastats")); dispatcher.register(literal("careastats") .then(argument("pos1", blockPos()) .then(argument("pos2", blockPos()) - .then(argument("predicates", list(blockPredicate(registryAccess).disallowNbt(), 1)) + .then(argument("predicates", list(blockPredicate(context).disallowNbt(), 1)) .executes(ctx -> areaStats(ctx.getSource(), getCBlockPos(ctx, "pos1"), getCBlockPos(ctx, "pos2"), getBlockPredicateList(ctx, "predicates")))) .executes(ctx -> areaStats(ctx.getSource(), getCBlockPos(ctx, "pos1"), getCBlockPos(ctx, "pos2"), ClientBlockPredicate.simple(state -> !state.isAir())))))); } private static int areaStats(FabricClientCommandSource source, BlockPos pos1, BlockPos pos2, ClientBlockPredicate blockPredicate) throws CommandSyntaxException { - final ClientWorld world = source.getWorld(); - chunkManager = world.getChunkManager(); + final ClientLevel level = source.getWorld(); + chunkSource = level.getChunkSource(); assertChunkIsLoaded(pos1.getX() >> 4, pos1.getZ() >> 4); assertChunkIsLoaded(pos2.getX() >> 4, pos2.getZ() >> 4); final long startTime = System.nanoTime(); - final WorldChunk chunk1 = world.getWorldChunk(pos1); - final WorldChunk chunk2 = world.getWorldChunk(pos2); + final LevelChunk chunk1 = level.getChunkAt(pos1); + final LevelChunk chunk2 = level.getChunkAt(pos2); final int minX, maxX, minZ, maxZ, minY, maxY; minX = Math.min(pos1.getX(), pos2.getX()); @@ -61,7 +61,7 @@ private static int areaStats(FabricClientCommandSource source, BlockPos pos1, Bl minZShifted = minZ >> 4; maxZShifted = maxZ >> 4; - final BlockPos.Mutable mutablePos = new BlockPos.Mutable(); + final BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos(); int blocks = 0; int chunks; @@ -71,43 +71,43 @@ private static int areaStats(FabricClientCommandSource source, BlockPos pos1, Bl blocks += loop(minX, maxX, minZ, maxZ, minY, maxY, blockPredicate, chunk1, mutablePos); } else if (chunk1.getPos().x == chunk2.getPos().x) { chunks = 2; - final WorldChunk minMinChunk = world.getChunk(minXShifted, minZShifted); + final LevelChunk minMinChunk = level.getChunk(minXShifted, minZShifted); blocks += loop(minX, maxX, minZ, minZShifted * 16 + 15, minY, maxY, blockPredicate, minMinChunk, mutablePos); - final WorldChunk minMaxChunk = world.getChunk(minXShifted, maxZShifted); + final LevelChunk minMaxChunk = level.getChunk(minXShifted, maxZShifted); blocks += loop(minX, maxX, maxZShifted * 16, maxZ, minY, maxY, blockPredicate, minMaxChunk, mutablePos); for (int chunkZ = minMinChunk.getPos().z + 1; chunkZ < minMaxChunk.getPos().z; chunkZ++) { assertChunkIsLoaded(minMinChunk.getPos().x, chunkZ); chunks++; - final WorldChunk chunk = world.getChunk(minMinChunk.getPos().x, chunkZ); + final LevelChunk chunk = level.getChunk(minMinChunk.getPos().x, chunkZ); blocks += loop(minX, maxX, 16 * chunkZ, 16 * chunkZ + 15, minY, maxY, blockPredicate, chunk, mutablePos); } } else if (chunk1.getPos().z == chunk2.getPos().z) { chunks = 2; - final WorldChunk minMinChunk = world.getChunk(minXShifted, minZShifted); + final LevelChunk minMinChunk = level.getChunk(minXShifted, minZShifted); blocks += loop(minX, minXShifted * 16 + 15, minZ, maxZ, minY, maxY, blockPredicate, minMinChunk, mutablePos); - final WorldChunk maxMinChunk = world.getChunk(maxXShifted, minZShifted); + final LevelChunk maxMinChunk = level.getChunk(maxXShifted, minZShifted); blocks += loop(maxXShifted * 16, maxX, minZ, maxZ, minY, maxY, blockPredicate, maxMinChunk, mutablePos); for (int chunkX = minMinChunk.getPos().x + 1; chunkX < maxMinChunk.getPos().x; chunkX++) { assertChunkIsLoaded(chunkX, minMinChunk.getPos().z); chunks++; - final WorldChunk chunk = world.getChunk(chunkX, minMinChunk.getPos().z); + final LevelChunk chunk = level.getChunk(chunkX, minMinChunk.getPos().z); blocks += loop(16 * chunkX, 16 * chunkX + 15, minZ, maxZ, minY, maxY, blockPredicate, chunk, mutablePos); } } else { chunks = 4; - final WorldChunk minMinChunk, minMaxChunk, maxMinChunk, maxMaxChunk; + final LevelChunk minMinChunk, minMaxChunk, maxMinChunk, maxMaxChunk; assertChunkIsLoaded(minXShifted, minZShifted); assertChunkIsLoaded(minXShifted, maxZShifted); assertChunkIsLoaded(maxXShifted, minZShifted); assertChunkIsLoaded(maxXShifted, maxZShifted); - minMinChunk = world.getChunk(minXShifted, minZShifted); - minMaxChunk = world.getChunk(minXShifted, maxZShifted); - maxMinChunk = world.getChunk(maxXShifted, minZShifted); - maxMaxChunk = world.getChunk(maxXShifted, maxZShifted); + minMinChunk = level.getChunk(minXShifted, minZShifted); + minMaxChunk = level.getChunk(minXShifted, maxZShifted); + maxMinChunk = level.getChunk(maxXShifted, minZShifted); + maxMaxChunk = level.getChunk(maxXShifted, maxZShifted); blocks += loop(minX, minXShifted * 16 + 15, minZ, minZShifted * 16 + 15, minY, maxY, blockPredicate, minMinChunk, mutablePos); @@ -120,57 +120,57 @@ private static int areaStats(FabricClientCommandSource source, BlockPos pos1, Bl for (int minMinMaxMin = minMinChunk.getPos().x + 1; minMinMaxMin < maxMinChunk.getPos().x; minMinMaxMin++) { assertChunkIsLoaded(minMinMaxMin, minMinChunk.getPos().z); chunks++; - final WorldChunk chunk = world.getChunk(minMinMaxMin, minMinChunk.getPos().z); + final LevelChunk chunk = level.getChunk(minMinMaxMin, minMinChunk.getPos().z); blocks += loop(16 * minMinMaxMin, 16 * minMinMaxMin + 15, minZ, minZShifted * 16 + 15, minY, maxY, blockPredicate, chunk, mutablePos); } for (int minMinMinMax = minMinChunk.getPos().z + 1; minMinMinMax < minMaxChunk.getPos().z; minMinMinMax++) { assertChunkIsLoaded(minMinChunk.getPos().x, minMinMinMax); chunks++; - final WorldChunk chunk = world.getChunk(minMinChunk.getPos().x, minMinMinMax); + final LevelChunk chunk = level.getChunk(minMinChunk.getPos().x, minMinMinMax); blocks += loop(minX, minXShifted * 16 + 15, 16 * minMinMinMax, 16 * minMinMinMax + 15, minY, maxY, blockPredicate, chunk, mutablePos); } for (int minMaxMaxMax = minMaxChunk.getPos().x + 1; minMaxMaxMax < maxMaxChunk.getPos().x; minMaxMaxMax++) { assertChunkIsLoaded(minMaxMaxMax, minMaxChunk.getPos().z); chunks++; - final WorldChunk chunk = world.getChunk(minMaxMaxMax, minMaxChunk.getPos().z); + final LevelChunk chunk = level.getChunk(minMaxMaxMax, minMaxChunk.getPos().z); blocks += loop(16 * minMaxMaxMax, 16 * minMaxMaxMax + 15, maxZShifted * 16, maxZ, minY, maxY, blockPredicate, chunk, mutablePos); } for (int maxMinMaxMax = maxMinChunk.getPos().z + 1; maxMinMaxMax < maxMaxChunk.getPos().z; maxMinMaxMax++) { assertChunkIsLoaded(maxMinChunk.getPos().x, maxMinMaxMax); chunks++; - final WorldChunk chunk = world.getChunk(maxMinChunk.getPos().x, maxMinMaxMax); + final LevelChunk chunk = level.getChunk(maxMinChunk.getPos().x, maxMinMaxMax); blocks += loop(maxXShifted * 16, maxX, 16 * maxMinMaxMax, 16 * maxMinMaxMax + 15, minY, maxY, blockPredicate, chunk, mutablePos); } for (int chunkX = minMinChunk.getPos().x + 1; chunkX < maxMinChunk.getPos().x; chunkX++) { for (int chunkZ = minMinChunk.getPos().z + 1; chunkZ < minMaxChunk.getPos().z; chunkZ++) { assertChunkIsLoaded(chunkX, chunkZ); chunks++; - final WorldChunk chunk = world.getChunk(chunkX, chunkZ); + final LevelChunk chunk = level.getChunk(chunkX, chunkZ); blocks += loop(16 * chunkX, 16 * chunkX + 15, 16 * chunkZ, 16 * chunkZ + 15, minY, maxY, blockPredicate, chunk, mutablePos); } } } - final long entities = Streams.stream(world.getEntities()) + final long entities = Streams.stream(level.entitiesForRendering()) .filter(entity -> entity.getX() >= minX && entity.getX() <= maxX && entity.getZ() >= minZ && entity.getZ() <= maxZ && entity.getY() >= minY && entity.getY() <= maxY) .count(); - Box box = new Box(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1); + AABB box = new AABB(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1); RenderQueue.addCuboid(RenderQueue.Layer.ON_TOP, box, box, 0xFFFF0000, 60 * 20); long endTime = System.nanoTime(); - source.sendFeedback(Text.translatable("commands.careastats.output.chunksScanned", chunks, endTime - startTime, (endTime - startTime) / 1000000)); - source.sendFeedback(Text.translatable("commands.careastats.output.blocksMatched", blocks, (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1))); - source.sendFeedback(Text.translatable("commands.careastats.output.entitiesFound", entities)); + source.sendFeedback(Component.translatable("commands.careastats.output.chunksScanned", chunks, endTime - startTime, (endTime - startTime) / 1000000)); + source.sendFeedback(Component.translatable("commands.careastats.output.blocksMatched", blocks, (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1))); + source.sendFeedback(Component.translatable("commands.careastats.output.entitiesFound", entities)); return blocks; } - private static int loop(int start1, int end1, int start2, int end2, int start3, int end3, ClientBlockPredicate predicate, WorldChunk chunk, BlockPos.Mutable mutablePos) { + private static int loop(int start1, int end1, int start2, int end2, int start3, int end3, ClientBlockPredicate predicate, LevelChunk chunk, BlockPos.MutableBlockPos mutablePos) { int counter = 0; for (int x = start1; x <= end1; x++) { mutablePos.setX(x); @@ -188,7 +188,7 @@ private static int loop(int start1, int end1, int start2, int end2, int start3, } private static void assertChunkIsLoaded(int x, int z) throws CommandSyntaxException { - if (chunkManager.isChunkLoaded(x, z)) { + if (chunkSource.hasChunk(x, z)) { return; } throw NOT_LOADED_EXCEPTION.create(); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java index 5adfb7557..2881383c9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java @@ -6,16 +6,16 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.earthcomputer.clientcommands.MultiVersionCompat; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.item.WrittenBookItem; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtString; -import net.minecraft.network.packet.c2s.play.BookUpdateC2SPacket; -import net.minecraft.text.Text; -import net.minecraft.util.Hand; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ServerboundEditBookPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.WrittenBookItem; import java.util.ArrayList; import java.util.List; @@ -29,7 +29,7 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class BookCommand { - private static final SimpleCommandExceptionType NO_BOOK = new SimpleCommandExceptionType(Text.translatable("commands.cbook.commandException")); + private static final SimpleCommandExceptionType NO_BOOK = new SimpleCommandExceptionType(Component.translatable("commands.cbook.commandException")); private static final int MAX_LIMIT = WrittenBookItem.MAX_PAGES; private static final int DEFAULT_LIMIT = 50; @@ -71,35 +71,35 @@ private static IntStream ascii(Random rand) { } private static int fillBook(FabricClientCommandSource source, IntStream characterGenerator, int limit) throws CommandSyntaxException { - ClientPlayerEntity player = source.getPlayer(); + LocalPlayer player = source.getPlayer(); assert player != null; - ItemStack heldItem = player.getMainHandStack(); - Hand hand = Hand.MAIN_HAND; + ItemStack heldItem = player.getMainHandItem(); + InteractionHand hand = InteractionHand.MAIN_HAND; if (heldItem.getItem() != Items.WRITABLE_BOOK) { - heldItem = player.getOffHandStack(); - hand = Hand.OFF_HAND; + heldItem = player.getOffhandItem(); + hand = InteractionHand.OFF_HAND; if (heldItem.getItem() != Items.WRITABLE_BOOK) { throw NO_BOOK.create(); } } - int slot = hand == Hand.MAIN_HAND ? player.getInventory().selectedSlot : PlayerInventory.OFF_HAND_SLOT; + int slot = hand == InteractionHand.MAIN_HAND ? player.getInventory().selected : Inventory.SLOT_OFFHAND; String joinedPages = characterGenerator.limit(MAX_LIMIT * 210).mapToObj(i -> String.valueOf((char) i)).collect(Collectors.joining()); List pages = new ArrayList<>(limit); - NbtList pagesNbt = new NbtList(); + ListTag pagesNbt = new ListTag(); for (int pageIndex = 0; pageIndex < limit; pageIndex++) { String page = joinedPages.substring(pageIndex * 210, (pageIndex + 1) * 210); pages.add(page); - pagesNbt.add(NbtString.of(page)); + pagesNbt.add(StringTag.valueOf(page)); } - heldItem.setSubNbt("pages", pagesNbt); - player.networkHandler.sendPacket(new BookUpdateC2SPacket(slot, pages, Optional.empty())); + heldItem.addTagElement("pages", pagesNbt); + player.connection.send(new ServerboundEditBookPacket(slot, pages, Optional.empty())); - source.sendFeedback(Text.translatable("commands.cbook.success")); + source.sendFeedback(Component.translatable("commands.cbook.success")); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java index 48ff6ce21..3a33761d2 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java @@ -3,17 +3,16 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.earthcomputer.clientcommands.Configs; -import net.earthcomputer.clientcommands.command.arguments.ItemAndEnchantmentsPredicateArgumentType.ItemAndEnchantmentsPredicate; import net.earthcomputer.clientcommands.features.EnchantmentCracker; import net.earthcomputer.clientcommands.features.PlayerRandCracker; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.enchantment.EnchantmentLevelEntry; -import net.minecraft.item.Item; -import net.minecraft.item.Items; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.EnchantmentInstance; import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.earthcomputer.clientcommands.command.arguments.ItemAndEnchantmentsPredicateArgumentType.*; @@ -31,24 +30,24 @@ public static void register(CommandDispatcher dispatc } private static boolean enchantmentPredicate(Item item, Enchantment ench) { - return !ench.isTreasure() && ench.isAvailableForRandomSelection() && (item == Items.BOOK || ench.target.isAcceptableItem(item)); + return !ench.isTreasureOnly() && ench.isDiscoverable() && (item == Items.BOOK || ench.category.canEnchant(item)); } private static int cenchant(FabricClientCommandSource source, ItemAndEnchantmentsPredicate itemAndEnchantmentsPredicate) { if (!Configs.getEnchantingPrediction()) { - Text text = Text.translatable("commands.cenchant.needEnchantingPrediction") - .formatted(Formatting.RED) + Component component = Component.translatable("commands.cenchant.needEnchantingPrediction") + .withStyle(ChatFormatting.RED) .append(" ") .append(getCommandTextComponent("commands.client.enable", "/cconfig clientcommands enchantingPrediction set true")); - source.sendFeedback(text); + source.sendFeedback(component); return Command.SINGLE_SUCCESS; } if (!Configs.playerCrackState.knowsSeed() && Configs.enchCrackState != EnchantmentCracker.CrackState.CRACKED) { - Text text = Text.translatable("commands.cenchant.uncracked") - .formatted(Formatting.RED) + Component component = Component.translatable("commands.cenchant.uncracked") + .withStyle(ChatFormatting.RED) .append(" ") .append(getCommandTextComponent("commands.client.crack", "/ccrackrng")); - source.sendFeedback(text); + source.sendFeedback(component); return Command.SINGLE_SUCCESS; } @@ -60,27 +59,27 @@ private static int cenchant(FabricClientCommandSource source, ItemAndEnchantment simulate ); if (result == null) { - source.sendFeedback(Text.translatable("commands.cenchant.failed")); + source.sendFeedback(Component.translatable("commands.cenchant.failed")); if (Configs.playerCrackState != PlayerRandCracker.CrackState.CRACKED) { - MutableText help = Text.translatable("commands.cenchant.help.uncrackedPlayerSeed") + MutableComponent help = Component.translatable("commands.cenchant.help.uncrackedPlayerSeed") .append(" ") .append(getCommandTextComponent("commands.client.crack", "/ccrackrng")); sendHelp(help); } } else { if (result.itemThrows() < 0) { - source.sendFeedback(Text.translatable("enchCrack.insn.itemThrows.noDummy")); + source.sendFeedback(Component.translatable("enchCrack.insn.itemThrows.noDummy")); } else { - source.sendFeedback(Text.translatable("enchCrack.insn.itemThrows", result.itemThrows(), (float)result.itemThrows() / 20f)); + source.sendFeedback(Component.translatable("enchCrack.insn.itemThrows", result.itemThrows(), (float)result.itemThrows() / 20f)); } - source.sendFeedback(Text.translatable("enchCrack.insn.bookshelves", result.bookshelves())); - source.sendFeedback(Text.translatable("enchCrack.insn.slot", result.slot() + 1)); - source.sendFeedback(Text.translatable("enchCrack.insn.enchantments")); - for (EnchantmentLevelEntry ench : result.enchantments()) { - source.sendFeedback(Text.literal("- ").append(ench.enchantment.getName(ench.level))); + source.sendFeedback(Component.translatable("enchCrack.insn.bookshelves", result.bookshelves())); + source.sendFeedback(Component.translatable("enchCrack.insn.slot", result.slot() + 1)); + source.sendFeedback(Component.translatable("enchCrack.insn.enchantments")); + for (EnchantmentInstance ench : result.enchantments()) { + source.sendFeedback(Component.literal("- ").append(ench.enchantment.getFullname(ench.level))); } if (!simulate) { - source.sendFeedback(Text.translatable("commands.cenchant.success")); + source.sendFeedback(Component.translatable("commands.cenchant.success")); } } return Command.SINGLE_SUCCESS; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CFunctionCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CFunctionCommand.java index 24fd4886f..5ffef7eaa 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CFunctionCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CFunctionCommand.java @@ -5,8 +5,8 @@ import net.earthcomputer.clientcommands.features.ClientCommandFunctions; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.command.CommandSource; -import net.minecraft.text.Text; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.network.chat.Component; import static com.mojang.brigadier.arguments.StringArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -15,11 +15,11 @@ public class CFunctionCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cfunction") .then(argument("function", greedyString()) - .suggests((context, builder) -> CommandSource.suggestMatching(ClientCommandFunctions.allFunctions(), builder)) + .suggests((context, builder) -> SharedSuggestionProvider.suggest(ClientCommandFunctions.allFunctions(), builder)) .executes(ctx -> run(ctx.getSource(), getString(ctx, "function"))))); } private static int run(FabricClientCommandSource source, String function) throws CommandSyntaxException { - return ClientCommandFunctions.executeFunction(ClientCommandManager.getActiveDispatcher(), source, function, result -> source.sendFeedback(Text.translatable("commands.cfunction.success", result, function))); + return ClientCommandFunctions.executeFunction(ClientCommandManager.getActiveDispatcher(), source, function, result -> source.sendFeedback(Component.translatable("commands.cfunction.success", result, function))); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java index a2660cb0c..5c9c1e442 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java @@ -5,10 +5,10 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.command.argument.ItemStackArgument; -import net.minecraft.item.ItemStack; -import net.minecraft.text.Text; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.arguments.item.ItemInput; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; @@ -16,26 +16,26 @@ public class CGiveCommand { - private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cgive.notCreative")); + private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cgive.notCreative")); - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("cgive") - .then(argument("item", itemStack(registryAccess)) + .then(argument("item", itemStack(context)) .executes(ctx -> give(ctx.getSource(), getCItemStackArgument(ctx, "item"), 1)) .then(argument("count", integer(1)) .executes(ctx -> give(ctx.getSource(), getCItemStackArgument(ctx, "item"), getInteger(ctx, "count")))))); } - private static int give(FabricClientCommandSource source, ItemStackArgument itemArgument, int count) throws CommandSyntaxException { - if (!source.getPlayer().getAbilities().creativeMode) { + private static int give(FabricClientCommandSource source, ItemInput itemInput, int count) throws CommandSyntaxException { + if (!source.getPlayer().getAbilities().instabuild) { throw NOT_CREATIVE_EXCEPTION.create(); } - ItemStack stack = itemArgument.createStack(Math.min(count, itemArgument.getItem().getMaxCount()), false); - source.getClient().interactionManager.clickCreativeStack(stack, 36 + source.getPlayer().getInventory().selectedSlot); - source.getPlayer().playerScreenHandler.sendContentUpdates(); + ItemStack stack = itemInput.createItemStack(Math.min(count, itemInput.getItem().getMaxStackSize()), false); + source.getClient().gameMode.handleCreativeModeItemAdd(stack, 36 + source.getPlayer().getInventory().selected); + source.getPlayer().inventoryMenu.broadcastChanges(); - source.sendFeedback(Text.translatable("commands.cgive.success", count, stack.toHoverableText())); + source.sendFeedback(Component.translatable("commands.cgive.success", count, stack.getDisplayName())); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java index 8f134868d..8cac55499 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java @@ -5,12 +5,12 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.particle.ParticleEffect; -import net.minecraft.particle.ParticleTypes; -import net.minecraft.registry.Registries; -import net.minecraft.text.Text; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.random.Random; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.chat.Component; +import net.minecraft.util.RandomSource; +import net.minecraft.world.phys.Vec3; import static com.mojang.brigadier.arguments.FloatArgumentType.*; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; @@ -20,14 +20,14 @@ public class CParticleCommand { - private static final SimpleCommandExceptionType UNSUITABLE_PARTICLE_OPTION_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cparticle.unsuitableParticleOption")); + private static final SimpleCommandExceptionType UNSUITABLE_PARTICLE_OPTION_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cparticle.unsuitableParticleOption")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cparticle") .then(argument("name", particleEffect()) - .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), ctx.getSource().getPlayer().getPos(), Vec3d.ZERO, 1, 1, false)) + .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), ctx.getSource().getPlayer().position(), Vec3.ZERO, 1, 1, false)) .then(argument("pos", vec3()) - .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), getCVec3(ctx, "pos"), Vec3d.ZERO, 1, 1, false)) + .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), getCVec3(ctx, "pos"), Vec3.ZERO, 1, 1, false)) .then(argument("delta", vec3(false)) .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), getCVec3(ctx, "pos"), getCVec3(ctx, "delta"), 1, 1, false)) .then(argument("speed", floatArg(0)) @@ -40,8 +40,8 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), getCVec3(ctx, "pos"), getCVec3(ctx, "delta"), getFloat(ctx, "speed"), getInteger(ctx, "count"), true))))))))); } - private static int spawnParticle(FabricClientCommandSource source, ParticleEffect parameters, Vec3d pos, Vec3d delta, float speed, int count, boolean force) throws CommandSyntaxException { - switch (source.getClient().options.getParticles().getValue()) { + private static int spawnParticle(FabricClientCommandSource source, ParticleOptions parameters, Vec3 pos, Vec3 delta, float speed, int count, boolean force) throws CommandSyntaxException { + switch (source.getClient().options.particles().get()) { case MINIMAL: if (!force) { throw UNSUITABLE_PARTICLE_OPTION_EXCEPTION.create(); @@ -54,13 +54,13 @@ private static int spawnParticle(FabricClientCommandSource source, ParticleEffec if (count == 0) { source.getWorld().addParticle(parameters, force, pos.x, pos.y, pos.z, delta.x * speed, delta.y * speed, delta.z * speed); } else { - final Random random = source.getClient().getNetworkHandler().getWorld().random; + final RandomSource random = source.getClient().getConnection().getLevel().random; for (int i = 0; i < count; i++) { source.getWorld().addParticle(parameters, force, pos.x + delta.x * random.nextGaussian(), pos.y + delta.y * random.nextGaussian(), pos.z + delta.z * random.nextGaussian(), speed * random.nextGaussian(), speed * random.nextGaussian(), speed * random.nextGaussian()); } } - source.sendFeedback(Text.translatable("commands.cparticle.success", - Registries.PARTICLE_TYPE.getId(parameters.getType()).toString())); + source.sendFeedback(Component.translatable("commands.cparticle.success", + BuiltInRegistries.PARTICLE_TYPE.getKey(parameters.getType()).toString())); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java index bb067dbbc..f496b4958 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java @@ -5,13 +5,13 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import dev.xpple.clientarguments.arguments.CSuggestionProviders; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.sound.PositionedSoundInstance; -import net.minecraft.client.sound.SoundInstance; -import net.minecraft.sound.SoundCategory; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.random.Random; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.world.phys.Vec3; import static com.mojang.brigadier.arguments.FloatArgumentType.*; import static dev.xpple.clientarguments.arguments.CIdentifierArgumentType.*; @@ -24,29 +24,29 @@ public static void register(CommandDispatcher dispatc var builder = argument("sound", identifier()) .suggests(CSuggestionProviders.AVAILABLE_SOUNDS); - for (SoundCategory category : SoundCategory.values()) { - builder.then(buildArguments(category)); + for (SoundSource source : SoundSource.values()) { + builder.then(buildArguments(source)); } dispatcher.register(literal("cplaysound").then(builder)); } - private static LiteralArgumentBuilder buildArguments(SoundCategory category) { - return literal(category.getName()) - .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, ctx.getSource().getPlayer().getPos(), 1, 1)) + private static LiteralArgumentBuilder buildArguments(SoundSource source) { + return literal(source.getName()) + .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), source, ctx.getSource().getPlayer().position(), 1, 1)) .then(argument("pos", vec3()) - .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, getCVec3(ctx, "pos"), 1, 1)) + .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), source, getCVec3(ctx, "pos"), 1, 1)) .then(argument("volume", floatArg(0)) - .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, getCVec3(ctx, "pos"), getFloat(ctx, "volume"), 1)) + .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), source, getCVec3(ctx, "pos"), getFloat(ctx, "volume"), 1)) .then(argument("pitch", floatArg(0, 2))) - .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, getCVec3(ctx, "pos"), getFloat(ctx, "volume"), getFloat(ctx, "pitch"))))); + .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), source, getCVec3(ctx, "pos"), getFloat(ctx, "volume"), getFloat(ctx, "pitch"))))); } - private static int playSound(FabricClientCommandSource source, Identifier sound, SoundCategory category, Vec3d pos, float volume, float pitch) { - SoundInstance soundInstance = new PositionedSoundInstance(sound, category, volume, pitch, Random.create(), false, 0, SoundInstance.AttenuationType.LINEAR, pos.getX(), pos.getY(), pos.getZ(), false); + private static int playSound(FabricClientCommandSource source, ResourceLocation sound, SoundSource soundSource, Vec3 pos, float volume, float pitch) { + SoundInstance soundInstance = new SimpleSoundInstance(sound, soundSource, volume, pitch, RandomSource.create(), false, 0, SoundInstance.Attenuation.LINEAR, pos.x(), pos.y(), pos.z(), false); source.getClient().getSoundManager().play(soundInstance); - source.sendFeedback(Text.translatable("commands.cplaysound.success", sound)); + source.sendFeedback(Component.translatable("commands.cplaysound.success", sound)); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java index c3566fae9..e7f726f1d 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java @@ -5,9 +5,9 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import dev.xpple.clientarguments.arguments.CSuggestionProviders; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.sound.SoundCategory; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundSource; import static dev.xpple.clientarguments.arguments.CIdentifierArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -17,33 +17,33 @@ public class CStopSoundCommand { public static void register(CommandDispatcher dispatcher) { var builder = literal("cstopsound"); - for (SoundCategory category : SoundCategory.values()) { - builder.then(buildArguments(category, category.getName())); + for (SoundSource source : SoundSource.values()) { + builder.then(buildArguments(source, source.getName())); } builder.then(buildArguments(null, "*")); dispatcher.register(builder); } - private static LiteralArgumentBuilder buildArguments(SoundCategory category, String literal) { + private static LiteralArgumentBuilder buildArguments(SoundSource source, String literal) { return literal(literal) - .executes(ctx -> stopSound(ctx.getSource(), category, null)) + .executes(ctx -> stopSound(ctx.getSource(), source, null)) .then(argument("sound", identifier()) .suggests(CSuggestionProviders.AVAILABLE_SOUNDS) - .executes(ctx -> stopSound(ctx.getSource(), category, getCIdentifier(ctx, "sound")))); + .executes(ctx -> stopSound(ctx.getSource(), source, getCIdentifier(ctx, "sound")))); } - private static int stopSound(FabricClientCommandSource source, SoundCategory category, Identifier sound) { - source.getClient().getSoundManager().stopSounds(sound, category); + private static int stopSound(FabricClientCommandSource source, SoundSource soundSource, ResourceLocation sound) { + source.getClient().getSoundManager().stop(sound, soundSource); - if (category == null && sound == null) { - source.sendFeedback(Text.translatable("commands.cstopsound.success.sourceless.any")); - } else if (category == null) { - source.sendFeedback(Text.translatable("commands.cstopsound.success.sourceless.sound", sound)); + if (soundSource == null && sound == null) { + source.sendFeedback(Component.translatable("commands.cstopsound.success.sourceless.any")); + } else if (soundSource == null) { + source.sendFeedback(Component.translatable("commands.cstopsound.success.sourceless.sound", sound)); } else if (sound == null) { - source.sendFeedback(Text.translatable("commands.cstopsound.success.source.any", category.getName())); + source.sendFeedback(Component.translatable("commands.cstopsound.success.source.any", soundSource.getName())); } else { - source.sendFeedback(Text.translatable("commands.cstopsound.success.source.sound", sound, category.getName())); + source.sendFeedback(Component.translatable("commands.cstopsound.success.source.sound", sound, soundSource.getName())); } return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java index 4650ad5a6..a5c74d115 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java @@ -5,10 +5,10 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.network.packet.c2s.play.SpectatorTeleportC2SPacket; -import net.minecraft.text.Text; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ServerboundTeleportToEntityPacket; import java.util.UUID; @@ -16,7 +16,7 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class CTeleportCommand { - private static final SimpleCommandExceptionType NOT_SPECTATOR_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.ctp.notSpectator")); + private static final SimpleCommandExceptionType NOT_SPECTATOR_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.ctp.notSpectator")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ctp") @@ -29,20 +29,20 @@ private static int teleport(FabricClientCommandSource source, UUID uuid) throws throw NOT_SPECTATOR_EXCEPTION.create(); } - ClientPlayNetworkHandler networkHandler = source.getClient().getNetworkHandler(); - assert networkHandler != null; + ClientPacketListener packetListener = source.getClient().getConnection(); + assert packetListener != null; - networkHandler.sendPacket(new SpectatorTeleportC2SPacket(uuid)); + packetListener.send(new ServerboundTeleportToEntityPacket(uuid)); - PlayerListEntry playerListEntry = networkHandler.getPlayerListEntry(uuid); + PlayerInfo playerInfo = packetListener.getPlayerInfo(uuid); String name; - if (playerListEntry != null) { - name = playerListEntry.getProfile().getName(); + if (playerInfo != null) { + name = playerInfo.getProfile().getName(); } else { name = uuid.toString(); } - source.sendFeedback(Text.translatable("commands.ctp.success", name)); + source.sendFeedback(Component.translatable("commands.ctp.success", name)); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java index ffa2019b0..c89d82e35 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java @@ -3,8 +3,8 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.MutableText; -import net.minecraft.text.Texts; +import net.minecraft.network.chat.ComponentUtils; +import net.minecraft.network.chat.MutableComponent; import static dev.xpple.clientarguments.arguments.CTextArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -15,8 +15,8 @@ public static void register(CommandDispatcher dispatc dispatcher.register(literal("ctellraw") .then(argument("message", text()) .executes(ctx -> { - MutableText text = Texts.parse(new FakeCommandSource(ctx.getSource().getPlayer()), getCTextArgument(ctx, "message"), ctx.getSource().getPlayer(), 0); - ctx.getSource().getClient().inGameHud.getChatHud().addMessage(text); + MutableComponent component = ComponentUtils.updateForEntity(new FakeCommandSource(ctx.getSource().getPlayer()), getCTextArgument(ctx, "message"), ctx.getSource().getPlayer(), 0); + ctx.getSource().getClient().gui.getChat().addMessage(component); return Command.SINGLE_SUCCESS; }) ) diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java index 8599ce44e..8a3126a1d 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java @@ -5,10 +5,9 @@ import net.earthcomputer.clientcommands.features.ClientTimeModifier; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.minecraft.SharedConstants; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; -import static dev.xpple.clientarguments.arguments.CTimeArgumentType.getCTime; -import static dev.xpple.clientarguments.arguments.CTimeArgumentType.time; +import static dev.xpple.clientarguments.arguments.CTimeArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class CTimeCommand { @@ -39,30 +38,30 @@ public static void register(CommandDispatcher dispatc } private static int executeQueryDay(FabricClientCommandSource source) { - return executeQuery(source, (int) (source.getWorld().getTimeOfDay() / SharedConstants.TICKS_PER_IN_GAME_DAY % 2147483647L)); + return executeQuery(source, (int) (source.getWorld().getDayTime() / SharedConstants.TICKS_PER_GAME_DAY % 2147483647L)); } private static int executeQueryDayTime(FabricClientCommandSource source) { - return executeQuery(source, (int) (source.getWorld().getTimeOfDay() % SharedConstants.TICKS_PER_IN_GAME_DAY)); + return executeQuery(source, (int) (source.getWorld().getDayTime() % SharedConstants.TICKS_PER_GAME_DAY)); } private static int executeQueryGameTime(FabricClientCommandSource source) { - return executeQuery(source, (int) (source.getWorld().getTime() % 2147483647L)); + return executeQuery(source, (int) (source.getWorld().getGameTime() % 2147483647L)); } private static int executeQuery(FabricClientCommandSource source, int time) { - source.sendFeedback(Text.translatable("commands.time.query", time)); + source.sendFeedback(Component.translatable("commands.time.query", time)); return time; } - + private static int executeSetTime(FabricClientCommandSource source, int time) { ClientTimeModifier.lock(time); return executeQueryDayTime(source); } - + private static int executeResetTime(FabricClientCommandSource source) { ClientTimeModifier.none(); - source.sendFeedback(Text.translatable("commands.ctime.reset.success")); + source.sendFeedback(Component.translatable("commands.ctime.reset.success")); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTitleCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTitleCommand.java index 1e5c1d735..43631150d 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTitleCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTitleCommand.java @@ -3,7 +3,7 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static dev.xpple.clientarguments.arguments.CTextArgumentType.*; @@ -35,45 +35,45 @@ public static void register(CommandDispatcher dispatc } private static int executeClear(FabricClientCommandSource source) { - source.getClient().inGameHud.clearTitle(); + source.getClient().gui.clear(); - source.sendFeedback(Text.translatable("commands.ctitle.cleared")); + source.sendFeedback(Component.translatable("commands.ctitle.cleared")); return Command.SINGLE_SUCCESS; } private static int executeReset(FabricClientCommandSource source) { - source.getClient().inGameHud.clearTitle(); - source.getClient().inGameHud.setDefaultTitleFade(); - - source.sendFeedback(Text.translatable("commands.ctitle.reset")); + source.getClient().gui.clear(); + source.getClient().gui.resetTitleTimes(); + + source.sendFeedback(Component.translatable("commands.ctitle.reset")); return Command.SINGLE_SUCCESS; } - private static int executeTitle(FabricClientCommandSource source, Text title) { - source.getClient().inGameHud.setTitle(title); + private static int executeTitle(FabricClientCommandSource source, Component title) { + source.getClient().gui.setTitle(title); - sendFeedback(Text.translatable("commands.ctitle.show.title")); + sendFeedback(Component.translatable("commands.ctitle.show.title")); return Command.SINGLE_SUCCESS; } - private static int executeSubtitle(FabricClientCommandSource source, Text title) { - source.getClient().inGameHud.setSubtitle(title); + private static int executeSubtitle(FabricClientCommandSource source, Component title) { + source.getClient().gui.setSubtitle(title); - sendFeedback(Text.translatable("commands.ctitle.show.subtitle")); + sendFeedback(Component.translatable("commands.ctitle.show.subtitle")); return Command.SINGLE_SUCCESS; } - private static int executeActionBar(FabricClientCommandSource source, Text title) { - source.getClient().inGameHud.setOverlayMessage(title, false); + private static int executeActionBar(FabricClientCommandSource source, Component title) { + source.getClient().gui.setOverlayMessage(title, false); - sendFeedback(Text.translatable("commands.ctitle.show.actionbar")); + sendFeedback(Component.translatable("commands.ctitle.show.actionbar")); return Command.SINGLE_SUCCESS; } private static int executeTimes(FabricClientCommandSource source, int fadeIn, int stay, int fadeOut) { - source.getClient().inGameHud.setTitleTicks(fadeIn, stay, fadeOut); + source.getClient().gui.setTimes(fadeIn, stay, fadeOut); - sendFeedback(Text.translatable("commands.ctitle.times")); + sendFeedback(Component.translatable("commands.ctitle.times")); return Command.SINGLE_SUCCESS; } } \ No newline at end of file diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java index 5514ba302..b1c61414c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java @@ -3,12 +3,12 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; - import net.earthcomputer.clientcommands.Configs; import net.earthcomputer.clientcommands.command.arguments.ExpressionArgumentType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.*; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.earthcomputer.clientcommands.command.arguments.ExpressionArgumentType.*; @@ -16,7 +16,7 @@ public class CalcCommand { - private static final SimpleCommandExceptionType TOO_DEEPLY_NESTED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.ccalc.tooDeeplyNested")); + private static final SimpleCommandExceptionType TOO_DEEPLY_NESTED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.ccalc.tooDeeplyNested")); private static final Flag FLAG_PARSE = Flag.ofFlag("parse").build(); @@ -29,13 +29,13 @@ public static void register(CommandDispatcher dispatc private static int evaluateExpression(FabricClientCommandSource source, ExpressionArgumentType.Expression expression) throws CommandSyntaxException { if (getFlag(source, FLAG_PARSE)) { - Text parsedTree; + Component parsedTree; try { parsedTree = expression.getParsedTree(0); } catch (StackOverflowError e) { throw TOO_DEEPLY_NESTED_EXCEPTION.create(); } - source.sendFeedback(Text.translatable("commands.ccalc.parse", parsedTree)); + source.sendFeedback(Component.translatable("commands.ccalc.parse", parsedTree)); } double result; @@ -47,11 +47,11 @@ private static int evaluateExpression(FabricClientCommandSource source, Expressi Configs.calcAnswer = result; int iresult = 0; - MutableText feedback = Text.literal(expression.strVal + " = "); + MutableComponent feedback = Component.literal(expression.strVal + " = "); if (Math.round(result) == result) { String strResult = String.valueOf(result); - feedback.append(Text.literal(strResult.contains("E") ? strResult : strResult.substring(0, strResult.length() - 2)).formatted(Formatting.BOLD)); + feedback.append(Component.literal(strResult.contains("E") ? strResult : strResult.substring(0, strResult.length() - 2)).withStyle(ChatFormatting.BOLD)); iresult = (int) result; if (iresult == result && iresult > 0) { int stacks = iresult / 64; @@ -59,7 +59,7 @@ private static int evaluateExpression(FabricClientCommandSource source, Expressi feedback.append(" = " + stacks + " * 64 + " + remainder); } } else { - feedback.append(Text.literal(String.valueOf(result)).formatted(Formatting.BOLD)); + feedback.append(Component.literal(String.valueOf(result)).withStyle(ChatFormatting.BOLD)); } source.sendFeedback(feedback); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java index 0064e3a5b..0d6fd1b2a 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java @@ -2,46 +2,45 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.item.ItemStack; -import net.minecraft.text.Text; -import net.minecraft.util.Hand; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.network.chat.Component; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; -import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; +import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class CalcStackCommand { - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccalcstack") .then(argument("count", integer(0)) - .then(argument("item", itemStack(registryAccess)) + .then(argument("item", itemStack(context)) .executes(ctx -> { - ItemStack stack = getCItemStackArgument(ctx, "item").createStack(1, false); + ItemStack stack = getCItemStackArgument(ctx, "item").createItemStack(1, false); return getStackSize(ctx.getSource(), stack, getInteger(ctx, "count")); })) .executes(ctx -> getStackSize(ctx.getSource(), getInteger(ctx, "count"))))); } private static int getStackSize(FabricClientCommandSource source, ItemStack stack, int count) { - int stacks = count / stack.getMaxCount(); - int remainder = count % stack.getMaxCount(); + int stacks = count / stack.getMaxStackSize(); + int remainder = count % stack.getMaxStackSize(); if (stack.isEmpty()) { if (remainder == 0) { - source.sendFeedback(Text.translatable("commands.ccalcstack.success.empty.exact", count, stacks)); + source.sendFeedback(Component.translatable("commands.ccalcstack.success.empty.exact", count, stacks)); } else { - source.sendFeedback(Text.translatable("commands.ccalcstack.success.empty", count, stacks, remainder)); + source.sendFeedback(Component.translatable("commands.ccalcstack.success.empty", count, stacks, remainder)); } } else { - Text itemText = stack.toHoverableText(); + Component itemText = stack.getDisplayName(); if (remainder == 0) { - source.sendFeedback(Text.translatable("commands.ccalcstack.success.exact", count, itemText, stacks)); + source.sendFeedback(Component.translatable("commands.ccalcstack.success.exact", count, itemText, stacks)); } else { - source.sendFeedback(Text.translatable("commands.ccalcstack.success", count, itemText, stacks, remainder)); + source.sendFeedback(Component.translatable("commands.ccalcstack.success", count, itemText, stacks, remainder)); } } @@ -49,7 +48,7 @@ private static int getStackSize(FabricClientCommandSource source, ItemStack stac } private static int getStackSize(FabricClientCommandSource source, int count) { - ItemStack heldStack = source.getPlayer().getStackInHand(Hand.MAIN_HAND).copy(); + ItemStack heldStack = source.getPlayer().getItemInHand(InteractionHand.MAIN_HAND).copy(); return getStackSize(source, heldStack, count); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ChatCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ChatCommand.java index a7b484048..b1cfd9fd9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ChatCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ChatCommand.java @@ -3,7 +3,7 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -14,8 +14,8 @@ public static void register(CommandDispatcher dispatc } private static int execute() { - MinecraftClient.getInstance().send(() -> { - MinecraftClient.getInstance().openChatScreen(""); + Minecraft.getInstance().tell(() -> { + Minecraft.getInstance().openChatScreen(""); sendFeedback("commands.chat.success"); }); return Command.SINGLE_SUCCESS; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ChorusCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ChorusCommand.java index 2f686f94f..bffd2f563 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ChorusCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ChorusCommand.java @@ -5,7 +5,7 @@ import dev.xpple.clientarguments.arguments.CPosArgument; import net.earthcomputer.clientcommands.features.ChorusManipulation; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; import java.util.EnumSet; @@ -38,11 +38,11 @@ public static RequiredArgumentBuilder a public static RequiredArgumentBuilder blockThen(boolean relative) { return argument("posGoal", vec3()) .executes(ctx -> ChorusManipulation.setGoal( - getCVec3(ctx, "posGoal").floorAlongAxes(EnumSet.allOf(Direction.Axis.class)).add(-0.2, 0, -0.2), - getCVec3(ctx, "posGoal").floorAlongAxes(EnumSet.allOf(Direction.Axis.class)).add(1.2, 1, 1.2), relative)) + getCVec3(ctx, "posGoal").align(EnumSet.allOf(Direction.Axis.class)).add(-0.2, 0, -0.2), + getCVec3(ctx, "posGoal").align(EnumSet.allOf(Direction.Axis.class)).add(1.2, 1, 1.2), relative)) .then(literal("--perfectly") .executes(ctx -> ChorusManipulation.setGoal( - getCVec3(ctx, "posGoal").floorAlongAxes(EnumSet.allOf(Direction.Axis.class)).add(0.3, 0, 0.3), - getCVec3(ctx, "posGoal").floorAlongAxes(EnumSet.allOf(Direction.Axis.class)).add(0.7, 1, 0.7), relative))); + getCVec3(ctx, "posGoal").align(EnumSet.allOf(Direction.Axis.class)).add(0.3, 0, 0.3), + getCVec3(ctx, "posGoal").align(EnumSet.allOf(Direction.Axis.class)).add(0.7, 1, 0.7), relative))); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java b/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java index 207c3e644..c20b4306c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java @@ -2,14 +2,17 @@ import com.demonwav.mcdev.annotations.Translatable; import com.mojang.brigadier.context.CommandContext; -import net.earthcomputer.clientcommands.interfaces.IClientCommandSource; -import net.earthcomputer.clientcommands.mixin.InGameHudAccessor; +import net.earthcomputer.clientcommands.interfaces.IClientSuggestionsProvider; +import net.earthcomputer.clientcommands.mixin.GuiAccessor; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.hud.InGameHud; -import net.minecraft.text.*; -import net.minecraft.util.Formatting; -import net.minecraft.util.math.BlockPos; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.MutableComponent; public class ClientCommandHelper { @@ -18,65 +21,65 @@ public static T getFlag(CommandContext ctx, Flag< } public static T getFlag(FabricClientCommandSource source, Flag flag) { - return ((IClientCommandSource) source).clientcommands_getFlag(flag); + return ((IClientSuggestionsProvider) source).clientcommands_getFlag(flag); } public static FabricClientCommandSource withFlag(FabricClientCommandSource source, Flag flag, T value) { - return (FabricClientCommandSource) ((IClientCommandSource) source).clientcommands_withFlag(flag, value); + return (FabricClientCommandSource) ((IClientSuggestionsProvider) source).clientcommands_withFlag(flag, value); } - public static void sendError(Text error) { - sendFeedback(Text.literal("").append(error).formatted(Formatting.RED)); + public static void sendError(Component error) { + sendFeedback(Component.literal("").append(error).withStyle(ChatFormatting.RED)); } - public static void sendHelp(Text help) { - sendFeedback(Text.literal("").append(help).formatted(Formatting.AQUA)); + public static void sendHelp(Component help) { + sendFeedback(Component.literal("").append(help).withStyle(ChatFormatting.AQUA)); } public static void sendFeedback(@Translatable String message, Object... args) { - sendFeedback(Text.translatable(message, args)); + sendFeedback(Component.translatable(message, args)); } - public static void sendFeedback(Text message) { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(message); + public static void sendFeedback(Component message) { + Minecraft.getInstance().gui.getChat().addMessage(message); } public static void sendRequiresRestart() { - sendFeedback(Text.translatable("commands.client.requiresRestart").formatted(Formatting.YELLOW)); + sendFeedback(Component.translatable("commands.client.requiresRestart").withStyle(ChatFormatting.YELLOW)); } - public static void addOverlayMessage(Text message, int time) { - InGameHud inGameHud = MinecraftClient.getInstance().inGameHud; - inGameHud.setOverlayMessage(message, false); - ((InGameHudAccessor) inGameHud).setOverlayRemaining(time); + public static void addOverlayMessage(Component message, int time) { + Gui gui = Minecraft.getInstance().gui; + gui.setOverlayMessage(message, false); + ((GuiAccessor) gui).setOverlayMessageTime(time); } - public static Text getLookCoordsTextComponent(BlockPos pos) { - return getCommandTextComponent(Text.translatable("commands.client.blockpos", pos.getX(), pos.getY(), pos.getZ()), + public static Component getLookCoordsTextComponent(BlockPos pos) { + return getCommandTextComponent(Component.translatable("commands.client.blockpos", pos.getX(), pos.getY(), pos.getZ()), String.format("/clook block %d %d %d", pos.getX(), pos.getY(), pos.getZ())); } - public static Text getLookCoordsTextComponent(MutableText translatableText, BlockPos pos) { - return getCommandTextComponent(translatableText, String.format("/clook block %d %d %d", pos.getX(), pos.getY(), pos.getZ())); + public static Component getLookCoordsTextComponent(MutableComponent component, BlockPos pos) { + return getCommandTextComponent(component, String.format("/clook block %d %d %d", pos.getX(), pos.getY(), pos.getZ())); } - public static Text getGlowCoordsTextComponent(BlockPos pos) { - return getCommandTextComponent(Text.translatable("commands.client.blockpos", pos.getX(), pos.getY(), pos.getZ()), + public static Component getGlowCoordsTextComponent(BlockPos pos) { + return getCommandTextComponent(Component.translatable("commands.client.blockpos", pos.getX(), pos.getY(), pos.getZ()), String.format("/cglow block %d %d %d 10", pos.getX(), pos.getY(), pos.getZ())); } - public static Text getGlowCoordsTextComponent(MutableText translatableText, BlockPos pos) { - return getCommandTextComponent(translatableText, String.format("/cglow block %d %d %d 10", pos.getX(), pos.getY(), pos.getZ())); + public static Component getGlowCoordsTextComponent(MutableComponent component, BlockPos pos) { + return getCommandTextComponent(component, String.format("/cglow block %d %d %d 10", pos.getX(), pos.getY(), pos.getZ())); } - public static Text getCommandTextComponent(@Translatable String translationKey, String command) { - return getCommandTextComponent(Text.translatable(translationKey), command); + public static Component getCommandTextComponent(@Translatable String translationKey, String command) { + return getCommandTextComponent(Component.translatable(translationKey), command); } - public static Text getCommandTextComponent(MutableText translatableText, String command) { - return translatableText.styled(style -> style.withFormatting(Formatting.UNDERLINE) + public static Component getCommandTextComponent(MutableComponent component, String command) { + return component.withStyle(style -> style.applyFormat(ChatFormatting.UNDERLINE) .withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command)) - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(command)))); + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(command)))); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ClientEntitySelector.java b/src/main/java/net/earthcomputer/clientcommands/command/ClientEntitySelector.java index daf76e5cb..c91415eda 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ClientEntitySelector.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ClientEntitySelector.java @@ -1,11 +1,11 @@ package net.earthcomputer.clientcommands.command; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.client.MinecraftClient; -import net.minecraft.command.argument.EntityArgumentType; -import net.minecraft.entity.Entity; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.Minecraft; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.Collections; @@ -15,15 +15,15 @@ public class ClientEntitySelector { - private final BiPredicate filter; - private final BiConsumer> sorter; + private final BiPredicate filter; + private final BiConsumer> sorter; private final int limit; private final boolean senderOnly; private final Double originX; private final Double originY; private final Double originZ; - public ClientEntitySelector(BiPredicate filter, BiConsumer> sorter, int limit, boolean senderOnly, Double originX, Double originY, Double originZ) { + public ClientEntitySelector(BiPredicate filter, BiConsumer> sorter, int limit, boolean senderOnly, Double originX, Double originY, Double originZ) { this.filter = filter; this.sorter = sorter; this.limit = limit; @@ -33,27 +33,27 @@ public ClientEntitySelector(BiPredicate filter, BiConsumer entities = getEntities(source); if (entities.isEmpty()) { - throw EntityArgumentType.ENTITY_NOT_FOUND_EXCEPTION.create(); + throw EntityArgument.NO_ENTITIES_FOUND.create(); } if (entities.size() > 1) { - throw EntityArgumentType.TOO_MANY_ENTITIES_EXCEPTION.create(); + throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.create(); } return entities.get(0); } - public List getEntities(ServerCommandSource source) { - Vec3d origin = source.getPosition(); - origin = new Vec3d(originX == null ? origin.x : originX, originY == null ? origin.y : originY, originZ == null ? origin.z : originZ); + public List getEntities(CommandSourceStack source) { + Vec3 origin = source.getPosition(); + origin = new Vec3(originX == null ? origin.x : originX, originY == null ? origin.y : originY, originZ == null ? origin.z : originZ); if (senderOnly) { return filter.test(origin, source.getEntity()) ? Collections.singletonList(source.getEntity()) : Collections.emptyList(); } List entities = new ArrayList<>(); - for (Entity entity : MinecraftClient.getInstance().world.getEntities()) { + for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) { if (filter.test(origin, entity)) { entities.add(entity); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java index 7f0f0db66..16e4fbcab 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java @@ -3,11 +3,11 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.cortex.clientAddon.cracker.SeedCracker; -import net.earthcomputer.clientcommands.ServerBrandManager; import net.earthcomputer.clientcommands.Configs; +import net.earthcomputer.clientcommands.ServerBrandManager; import net.earthcomputer.clientcommands.features.PlayerRandCracker; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -21,7 +21,7 @@ public static void register(CommandDispatcher dispatc private static int crackPlayerRNG(FabricClientCommandSource source) { ServerBrandManager.rngWarning(); SeedCracker.crack(seed -> { - source.sendFeedback(Text.translatable("commands.ccrackrng.success", Long.toHexString(seed))); + source.sendFeedback(Component.translatable("commands.ccrackrng.success", Long.toHexString(seed))); PlayerRandCracker.setSeed(seed); Configs.playerCrackState = PlayerRandCracker.CrackState.CRACKED; }); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java b/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java index f91ab0d40..423c77675 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java @@ -1,26 +1,29 @@ package net.earthcomputer.clientcommands.command; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.registry.DynamicRegistryManager; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.RegistryAccess; +import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.stream.Collectors; -public class FakeCommandSource extends ServerCommandSource { - public FakeCommandSource(ClientPlayerEntity player) { - super(player, player.getPos(), player.getRotationClient(), null, 314159265, player.getNameForScoreboard(), player.getName(), null, player); +public class FakeCommandSource extends CommandSourceStack { + public FakeCommandSource(LocalPlayer player) { + super(player, player.position(), player.getRotationVector(), null, 314159265, player.getScoreboardName(), player.getName(), null, player); } + @NotNull @Override - public Collection getPlayerNames() { - return MinecraftClient.getInstance().getNetworkHandler().getPlayerList() + public Collection getOnlinePlayerNames() { + return Minecraft.getInstance().getConnection().getOnlinePlayers() .stream().map(e -> e.getProfile().getName()).collect(Collectors.toList()); } + @NotNull @Override - public DynamicRegistryManager getRegistryManager() { - return MinecraftClient.getInstance().getNetworkHandler().getRegistryManager(); + public RegistryAccess registryAccess() { + return Minecraft.getInstance().getConnection().registryAccess(); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java index e959fe015..0a983cf3d 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java @@ -6,15 +6,15 @@ import net.earthcomputer.clientcommands.task.RenderDistanceScanTask; import net.earthcomputer.clientcommands.task.TaskManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.entity.Entity; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import java.util.Objects; @@ -25,16 +25,16 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class FindBlockCommand { - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("cfindblock") - .then(argument("block", withString(blockPredicate(registryAccess))) + .then(argument("block", withString(blockPredicate(context))) .executes(ctx -> { var blockWithString = getWithString(ctx, "block", ClientBlockPredicateArgumentType.ParseResult.class); - return findBlock(Text.translatable("commands.cfindblock.starting", blockWithString.getLeft()), getBlockPredicate(blockWithString.getRight())); + return findBlock(Component.translatable("commands.cfindblock.starting", blockWithString.getLeft()), getBlockPredicate(blockWithString.getRight())); }))); } - public static int findBlock(Text startingMessage, ClientBlockPredicate block) { + public static int findBlock(Component startingMessage, ClientBlockPredicate block) { sendFeedback(startingMessage); TaskManager.addTask("cfindblock", new FindBlockTask(block)); return Command.SINGLE_SUCCESS; @@ -53,38 +53,38 @@ private static final class FindBlockTask extends RenderDistanceScanTask { @Override protected void scanBlock(Entity cameraEntity, BlockPos pos) { - ClientWorld world = MinecraftClient.getInstance().world; - assert world != null; - Vec3d cameraPos = cameraEntity.getCameraPosVec(0); - if ((closestBlock == null || pos.getSquaredDistance(cameraPos) < closestBlock.getSquaredDistance(cameraPos)) && predicate.test(world, pos)) { - closestBlock = pos.toImmutable(); + ClientLevel level = Minecraft.getInstance().level; + assert level != null; + Vec3 cameraPos = cameraEntity.getEyePosition(0); + if ((closestBlock == null || pos.distToCenterSqr(cameraPos) < closestBlock.distToCenterSqr(cameraPos)) && predicate.test(level, pos)) { + closestBlock = pos.immutable(); } } @Override protected boolean canScanChunk(Entity cameraEntity, ChunkPos pos) { - return (closestBlock == null || hasAnyBlockCloserThan(cameraEntity, pos, closestBlock.getSquaredDistance(cameraEntity.getCameraPosVec(0)))) + return (closestBlock == null || hasAnyBlockCloserThan(cameraEntity, pos, closestBlock.distToCenterSqr(cameraEntity.getEyePosition(0)))) && super.canScanChunk(cameraEntity, pos); } @Override - protected boolean canScanChunkSection(Entity cameraEntity, ChunkSectionPos pos) { + protected boolean canScanChunkSection(Entity cameraEntity, SectionPos pos) { return hasBlockState(pos, predicate::canEverMatch) && super.canScanChunkSection(cameraEntity, pos); } @Override public void onCompleted() { if (closestBlock == null) { - sendError(Text.translatable("commands.cfindblock.notFound")); + sendError(Component.translatable("commands.cfindblock.notFound")); } else { - Entity cameraEntity = Objects.requireNonNullElse(MinecraftClient.getInstance().cameraEntity, MinecraftClient.getInstance().player); + Entity cameraEntity = Objects.requireNonNullElse(Minecraft.getInstance().cameraEntity, Minecraft.getInstance().player); - String foundRadius = "%.2f".formatted(Math.sqrt(closestBlock.getSquaredDistance(cameraEntity.getCameraPosVec(0)))); - sendFeedback(Text.translatable("commands.cfindblock.success.left", foundRadius) + String foundRadius = "%.2f".formatted(Math.sqrt(closestBlock.distToCenterSqr(cameraEntity.getEyePosition(0)))); + sendFeedback(Component.translatable("commands.cfindblock.success.left", foundRadius) .append(getLookCoordsTextComponent(closestBlock)) .append(" ") - .append(getGlowCoordsTextComponent(Text.translatable("commands.cfindblock.success.glow"), closestBlock)) - .append(Text.translatable("commands.cfindblock.success.right", foundRadius))); + .append(getGlowCoordsTextComponent(Component.translatable("commands.cfindblock.success.glow"), closestBlock)) + .append(Component.translatable("commands.cfindblock.success.right", foundRadius))); } } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java index 46ff0ee63..91bd0b07b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java @@ -3,16 +3,15 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; - import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import dev.xpple.clientarguments.arguments.CEntitySelector; import net.earthcomputer.clientcommands.task.LongTask; import net.earthcomputer.clientcommands.task.TaskManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.entity.Entity; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.Entity; import java.util.HashSet; import java.util.List; @@ -27,7 +26,7 @@ public class FindCommand { private static final Flag FLAG_KEEP_SEARCHING = Flag.ofFlag("keep-searching").build(); - private static final SimpleCommandExceptionType NO_MATCH_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cfind.noMatch")); + private static final SimpleCommandExceptionType NO_MATCH_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cfind.noMatch")); public static void register(CommandDispatcher dispatcher) { var cfind = dispatcher.register(literal("cfind") @@ -41,7 +40,7 @@ private static int listEntities(FabricClientCommandSource source, CEntitySelecto if (keepSearching) { String taskName = TaskManager.addTask("cfind", new FindTask(source, selector)); - source.sendFeedback(Text.translatable("commands.cfind.keepSearching.success") + source.sendFeedback(Component.translatable("commands.cfind.keepSearching.success") .append(" ") .append(getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName))); @@ -53,7 +52,7 @@ private static int listEntities(FabricClientCommandSource source, CEntitySelecto throw NO_MATCH_EXCEPTION.create(); } - source.sendFeedback(Text.translatable("commands.cfind.success", entities.size()).formatted(Formatting.BOLD)); + source.sendFeedback(Component.translatable("commands.cfind.success", entities.size()).withStyle(ChatFormatting.BOLD)); for (Entity entity : entities) { sendEntityFoundMessage(source, entity); } @@ -63,10 +62,10 @@ private static int listEntities(FabricClientCommandSource source, CEntitySelecto } private static void sendEntityFoundMessage(FabricClientCommandSource source, Entity entity) { - String distance = "%.2f".formatted(Math.sqrt(entity.squaredDistanceTo(source.getPosition()))); - source.sendFeedback(Text.translatable("commands.cfind.found.left", entity.getName(), distance) - .append(getLookCoordsTextComponent(entity.getBlockPos())) - .append(Text.translatable("commands.cfind.found.right", entity.getName(), distance))); + String distance = "%.2f".formatted(Math.sqrt(entity.distanceToSqr(source.getPosition()))); + source.sendFeedback(Component.translatable("commands.cfind.found.left", entity.getName(), distance) + .append(getLookCoordsTextComponent(entity.blockPosition())) + .append(Component.translatable("commands.cfind.found.right", entity.getName(), distance))); } private static class FindTask extends LongTask { @@ -85,7 +84,7 @@ public void initialize() { @Override public boolean condition() { - return MinecraftClient.getInstance().player != null; + return Minecraft.getInstance().player != null; } @Override @@ -96,7 +95,7 @@ public void increment() { public void body() { try { for (Entity entity : selector.getEntities(this.source)) { - if (foundEntities.add(entity.getUuid())) { + if (foundEntities.add(entity.getUUID())) { sendEntityFoundMessage(source, entity); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java index 3048fc194..f18f058ec 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java @@ -6,47 +6,47 @@ import net.earthcomputer.clientcommands.ClientcommandsDataQueryHandler; import net.earthcomputer.clientcommands.GuiBlocker; import net.earthcomputer.clientcommands.MathUtil; -import net.earthcomputer.clientcommands.mixin.ScreenHandlerAccessor; +import net.earthcomputer.clientcommands.mixin.AbstractContainerMenuAccessor; import net.earthcomputer.clientcommands.task.SimpleTask; import net.earthcomputer.clientcommands.task.TaskManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.ChestBlock; -import net.minecraft.block.ShulkerBoxBlock; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.enums.ChestType; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.screen.ingame.ScreenHandlerProvider; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.network.ClientPlayerInteractionManager; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; -import net.minecraft.nbt.NbtList; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.slot.Slot; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.chunk.ChunkStatus; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.Container; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.level.block.ShulkerBoxBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.ChestType; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; @@ -66,9 +66,9 @@ public class FindItemCommand { private static final Flag FLAG_KEEP_SEARCHING = Flag.ofFlag("keep-searching").build(); @SuppressWarnings("unchecked") - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { var cfinditem = dispatcher.register(literal("cfinditem") - .then(argument("item", withString(itemPredicate(registryAccess))) + .then(argument("item", withString(itemPredicate(context))) .executes(ctx -> findItem(ctx, getFlag(ctx, FLAG_NO_SEARCH_SHULKER_BOX), @@ -81,20 +81,20 @@ public static void register(CommandDispatcher dispatc private static int findItem(CommandContext ctx, boolean noSearchShulkerBox, boolean keepSearching, Pair> item) { String taskName = TaskManager.addTask("cfinditem", makeFindItemsTask(item.getLeft(), item.getRight(), !noSearchShulkerBox, keepSearching)); if (keepSearching) { - ctx.getSource().sendFeedback(Text.translatable("commands.cfinditem.starting.keepSearching", item.getLeft()) + ctx.getSource().sendFeedback(Component.translatable("commands.cfinditem.starting.keepSearching", item.getLeft()) .append(" ") .append(getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName))); } else { - ctx.getSource().sendFeedback(Text.translatable("commands.cfinditem.starting", item.getLeft())); + ctx.getSource().sendFeedback(Component.translatable("commands.cfinditem.starting", item.getLeft())); } return Command.SINGLE_SUCCESS; } private static SimpleTask makeFindItemsTask(String searchingForName, Predicate searchingFor, boolean searchShulkerBoxes, boolean keepSearching) { - ClientPlayerEntity player = MinecraftClient.getInstance().player; + LocalPlayer player = Minecraft.getInstance().player; assert player != null; - if (player.hasPermissionLevel(2)) { + if (player.hasPermissions(2)) { return new NbtQueryFindItemsTask(searchingForName, searchingFor, searchShulkerBoxes, keepSearching); } else { return new ClickInventoriesFindItemsTask(searchingForName, searchingFor, searchShulkerBoxes, keepSearching); @@ -116,18 +116,18 @@ private AbstractFindItemsTask(String searchingForName, Predicate sear this.keepSearching = keepSearching; } - protected int countItems(NbtList inventory) { + protected int countItems(ListTag inventory) { int result = 0; for (int i = 0; i < inventory.size(); i++) { - NbtCompound compound = inventory.getCompound(i); - ItemStack stack = ItemStack.fromNbt(compound); + CompoundTag compound = inventory.getCompound(i); + ItemStack stack = ItemStack.of(compound); if (searchingFor.test(stack)) { result += stack.getCount(); } if (searchShulkerBoxes && stack.getItem() instanceof BlockItem block && block.getBlock() instanceof ShulkerBoxBlock) { - NbtCompound blockEntityNbt = BlockItem.getBlockEntityNbt(stack); - if (blockEntityNbt != null && blockEntityNbt.contains("Items", NbtElement.LIST_TYPE)) { - result += countItems(blockEntityNbt.getList("Items", NbtElement.COMPOUND_TYPE)); + CompoundTag blockEntityNbt = BlockItem.getBlockEntityData(stack); + if (blockEntityNbt != null && blockEntityNbt.contains("Items", Tag.TAG_LIST)) { + result += countItems(blockEntityNbt.getList("Items", Tag.TAG_COMPOUND)); } } } @@ -135,16 +135,16 @@ protected int countItems(NbtList inventory) { } protected void printLocation(BlockPos pos, int count) { - sendFeedback(Text.translatable("commands.cfinditem.match.left", count, searchingForName) + sendFeedback(Component.translatable("commands.cfinditem.match.left", count, searchingForName) .append(getLookCoordsTextComponent(pos)) .append(" ") - .append(getGlowCoordsTextComponent(Text.translatable("commands.cfindblock.success.glow"), pos)) - .append(Text.translatable("commands.cfinditem.match.right", count, searchingForName))); + .append(getGlowCoordsTextComponent(Component.translatable("commands.cfindblock.success.glow"), pos)) + .append(Component.translatable("commands.cfinditem.match.right", count, searchingForName))); } @Override public void onCompleted() { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable("commands.cfinditem.total", totalFound, searchingForName).formatted(Formatting.BOLD)); + Minecraft.getInstance().gui.getChat().addMessage(Component.translatable("commands.cfinditem.total", totalFound, searchingForName).withStyle(ChatFormatting.BOLD)); } } @@ -165,45 +165,45 @@ public boolean condition() { @Override protected void onTick() { - Entity entity = MinecraftClient.getInstance().cameraEntity; + Entity entity = Minecraft.getInstance().cameraEntity; if (entity == null) { _break(); return; } - World world = MinecraftClient.getInstance().world; - assert world != null; - ClientPlayerEntity player = MinecraftClient.getInstance().player; + Level level = Minecraft.getInstance().level; + assert level != null; + LocalPlayer player = Minecraft.getInstance().player; assert player != null; - ClientPlayerInteractionManager interactionManager = MinecraftClient.getInstance().interactionManager; - assert interactionManager != null; + MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode; + assert gameMode != null; if (currentlySearchingTimeout > 0) { currentlySearchingTimeout--; return; } - if (player.isSneaking()) { + if (player.isShiftKeyDown()) { return; } - Vec3d origin = entity.getCameraPosVec(0); - float reachDistance = interactionManager.getReachDistance(); - int minX = MathHelper.floor(origin.x - reachDistance); - int minY = MathHelper.floor(origin.y - reachDistance); - int minZ = MathHelper.floor(origin.z - reachDistance); - int maxX = MathHelper.floor(origin.x + reachDistance); - int maxY = MathHelper.floor(origin.y + reachDistance); - int maxZ = MathHelper.floor(origin.z + reachDistance); + Vec3 origin = entity.getEyePosition(0); + float reachDistance = gameMode.getPickRange(); + int minX = Mth.floor(origin.x - reachDistance); + int minY = Mth.floor(origin.y - reachDistance); + int minZ = Mth.floor(origin.z - reachDistance); + int maxX = Mth.floor(origin.x + reachDistance); + int maxY = Mth.floor(origin.y + reachDistance); + int maxZ = Mth.floor(origin.z + reachDistance); for (int x = minX; x <= maxX; x++) { for (int y = minY; y <= maxY; y++) { for (int z = minZ; z <= maxZ; z++) { BlockPos pos = new BlockPos(x, y, z); - if (!canSearch(world, pos)) { + if (!canSearch(level, pos)) { continue; } if (searchedBlocks.contains(pos)) { continue; } - BlockState state = world.getBlockState(pos); - Vec3d closestPos = MathUtil.getClosestPoint(pos, state.getOutlineShape(world, pos), origin); - if (closestPos.squaredDistanceTo(origin) > reachDistance * reachDistance) { + BlockState state = level.getBlockState(pos); + Vec3 closestPos = MathUtil.getClosestPoint(pos, state.getShape(level, pos), origin); + if (closestPos.distanceToSqr(origin) > reachDistance * reachDistance) { continue; } searchedBlocks.add(pos); @@ -212,9 +212,9 @@ protected void onTick() { continue; } hasSearchedEnderChest = true; - } else if (state.getBlock() instanceof ChestBlock && state.get(ChestBlock.CHEST_TYPE) != ChestType.SINGLE) { - BlockPos offsetPos = pos.offset(ChestBlock.getFacing(state)); - if (world.getBlockState(offsetPos).getBlock() == state.getBlock()) { + } else if (state.getBlock() instanceof ChestBlock && state.getValue(ChestBlock.TYPE) != ChestType.SINGLE) { + BlockPos offsetPos = pos.relative(ChestBlock.getConnectedDirection(state)); + if (level.getBlockState(offsetPos).getBlock() == state.getBlock()) { searchedBlocks.add(offsetPos); } } @@ -229,55 +229,55 @@ protected void onTick() { } } - private boolean canSearch(World world, BlockPos pos) { - BlockState state = world.getBlockState(pos); - BlockEntity blockEntity = world.getBlockEntity(pos); - if (!(blockEntity instanceof Inventory) && state.getBlock() != Blocks.ENDER_CHEST) { + private boolean canSearch(Level level, BlockPos pos) { + BlockState state = level.getBlockState(pos); + BlockEntity blockEntity = level.getBlockEntity(pos); + if (!(blockEntity instanceof Container) && state.getBlock() != Blocks.ENDER_CHEST) { return false; } if (state.getBlock() instanceof ChestBlock || state.getBlock() == Blocks.ENDER_CHEST) { - if (ChestBlock.isChestBlocked(world, pos)) { + if (ChestBlock.isChestBlockedAt(level, pos)) { return false; } - if (state.getBlock() instanceof ChestBlock && state.get(ChestBlock.CHEST_TYPE) != ChestType.SINGLE) { - BlockPos offsetPos = pos.offset(ChestBlock.getFacing(state)); - return world.getBlockState(offsetPos).getBlock() != state.getBlock() || !ChestBlock.isChestBlocked(world, offsetPos); + if (state.getBlock() instanceof ChestBlock && state.getValue(ChestBlock.TYPE) != ChestType.SINGLE) { + BlockPos offsetPos = pos.relative(ChestBlock.getConnectedDirection(state)); + return level.getBlockState(offsetPos).getBlock() != state.getBlock() || !ChestBlock.isChestBlockedAt(level, offsetPos); } } return true; } - private void startSearch(BlockPos pos, Vec3d cameraPos, Vec3d clickPos) { - MinecraftClient mc = MinecraftClient.getInstance(); + private void startSearch(BlockPos pos, Vec3 cameraPos, Vec3 clickPos) { + Minecraft mc = Minecraft.getInstance(); currentlySearching = pos; currentlySearchingTimeout = 100; GuiBlocker.addBlocker(new GuiBlocker() { @Override public boolean accept(Screen screen) { - if (!(screen instanceof ScreenHandlerProvider handlerProvider)) { + if (!(screen instanceof MenuAccess menuAccess)) { return true; } assert mc.player != null; - ScreenHandler container = handlerProvider.getScreenHandler(); + AbstractContainerMenu container = menuAccess.getMenu(); Set playerInvSlots = new HashSet<>(); for (Slot slot : container.slots) { - if (slot.inventory instanceof PlayerInventory) { - playerInvSlots.add(slot.id); + if (slot.container instanceof Inventory) { + playerInvSlots.add(slot.index); } } - mc.player.currentScreenHandler = new ScreenHandler(((ScreenHandlerAccessor) container).getNullableType(), container.syncId) { + mc.player.containerMenu = new AbstractContainerMenu(((AbstractContainerMenuAccessor) container).getNullableType(), container.containerId) { @Override - public boolean canUse(PlayerEntity var1) { + public boolean stillValid(Player var1) { return true; } @Override - public ItemStack quickMove(PlayerEntity player, int index) { + public ItemStack quickMoveStack(Player player, int index) { return ItemStack.EMPTY; } @Override - public void updateSlotStacks(int revision, List stacks, ItemStack cursorStack) { + public void initializeContents(int revision, List stacks, ItemStack cursorStack) { int matchingItems = 0; for (int slot = 0; slot < stacks.size(); slot++) { if (playerInvSlots.contains(slot)) { @@ -288,9 +288,9 @@ public void updateSlotStacks(int revision, List stacks, ItemStack cur matchingItems += stack.getCount(); } if (searchShulkerBoxes && stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock() instanceof ShulkerBoxBlock) { - NbtCompound blockEntityTag = BlockItem.getBlockEntityNbt(stack); - if (blockEntityTag != null && blockEntityTag.contains("Items", NbtElement.LIST_TYPE)) { - matchingItems += countItems(blockEntityTag.getList("Items", NbtElement.COMPOUND_TYPE)); + CompoundTag blockEntityTag = BlockItem.getBlockEntityData(stack); + if (blockEntityTag != null && blockEntityTag.contains("Items", Tag.TAG_LIST)) { + matchingItems += countItems(blockEntityTag.getList("Items", Tag.TAG_COMPOUND)); } } } @@ -300,16 +300,16 @@ public void updateSlotStacks(int revision, List stacks, ItemStack cur } currentlySearching = null; currentlySearchingTimeout = 0; - mc.player.closeHandledScreen(); + mc.player.closeContainer(); } }; return false; } }); - assert mc.interactionManager != null; - mc.interactionManager.interactBlock(mc.player, Hand.MAIN_HAND, + assert mc.gameMode != null; + mc.gameMode.useItemOn(mc.player, InteractionHand.MAIN_HAND, new BlockHitResult(clickPos, - Direction.getFacing((float) (clickPos.x - cameraPos.x), (float) (clickPos.y - cameraPos.y), (float) (clickPos.z - cameraPos.z)), + Direction.getNearest((float) (clickPos.x - cameraPos.x), (float) (clickPos.y - cameraPos.y), (float) (clickPos.z - cameraPos.z)), pos, false)); } } @@ -321,7 +321,7 @@ private static class NbtQueryFindItemsTask extends AbstractFindItemsTask { private final Set searchedBlocks = new HashSet<>(); private boolean isScanning = true; - private Iterator scanningIterator; + private Iterator scanningIterator; private final Set waitingOnBlocks = new HashSet<>(); private int currentlySearchingTimeout; @Nullable @@ -341,23 +341,23 @@ public boolean condition() { @Override protected void onTick() { - Entity cameraEntity = MinecraftClient.getInstance().cameraEntity; + Entity cameraEntity = Minecraft.getInstance().cameraEntity; if (cameraEntity == null) { _break(); return; } - ClientWorld world = MinecraftClient.getInstance().world; - assert world != null; + ClientLevel level = Minecraft.getInstance().level; + assert level != null; if (isScanning) { long startTime = System.nanoTime(); if (scanningIterator == null) { - Vec3d cameraPos = cameraEntity.getCameraPosVec(0); - scanningIterator = BlockPos.iterateInSquare(new BlockPos(MathHelper.floor(cameraPos.x) >> 4, 0, MathHelper.floor(cameraPos.z) >> 4), MinecraftClient.getInstance().options.getViewDistance().getValue(), Direction.EAST, Direction.SOUTH).iterator(); + Vec3 cameraPos = cameraEntity.getEyePosition(0); + scanningIterator = BlockPos.spiralAround(new BlockPos(Mth.floor(cameraPos.x) >> 4, 0, Mth.floor(cameraPos.z) >> 4), Minecraft.getInstance().options.renderDistance().get(), Direction.EAST, Direction.SOUTH).iterator(); } while (scanningIterator.hasNext()) { BlockPos chunkPosAsBlockPos = scanningIterator.next(); - if (world.getChunk(chunkPosAsBlockPos.getX(), chunkPosAsBlockPos.getZ(), ChunkStatus.FULL, false) != null) { + if (level.getChunk(chunkPosAsBlockPos.getX(), chunkPosAsBlockPos.getZ(), ChunkStatus.FULL, false) != null) { scanChunk(new ChunkPos(chunkPosAsBlockPos.getX(), chunkPosAsBlockPos.getZ()), cameraEntity); } @@ -387,19 +387,19 @@ protected void onTick() { } private void scanChunk(ChunkPos chunkToScan, Entity cameraEntity) { - ClientPlayerEntity player = MinecraftClient.getInstance().player; + LocalPlayer player = Minecraft.getInstance().player; assert player != null; - ClientWorld world = MinecraftClient.getInstance().world; - assert world != null; - ClientPlayNetworkHandler networkHandler = MinecraftClient.getInstance().getNetworkHandler(); - assert networkHandler != null; + ClientLevel level = Minecraft.getInstance().level; + assert level != null; + ClientPacketListener packetListener = Minecraft.getInstance().getConnection(); + assert packetListener != null; // check if we can possibly find a closer ender chest if (enderChestPosition != null && numItemsInEnderChest != null && !hasPrintedEnderChest) { - Vec3d cameraPos = cameraEntity.getCameraPosVec(0); - double enderChestDistanceSq = enderChestPosition.getSquaredDistance(cameraPos); - int cameraChunkX = MathHelper.floor(cameraPos.x) >> 4; - int cameraChunkZ = MathHelper.floor(cameraPos.z) >> 4; + Vec3 cameraPos = cameraEntity.getEyePosition(0); + double enderChestDistanceSq = enderChestPosition.distToCenterSqr(cameraPos); + int cameraChunkX = Mth.floor(cameraPos.x) >> 4; + int cameraChunkZ = Mth.floor(cameraPos.z) >> 4; int currentChunkRadius = Math.max(Math.abs(cameraChunkX - chunkToScan.x), Math.abs(cameraChunkZ - chunkToScan.z)); double closestPossibleDistance = ((currentChunkRadius - 1) << 4) + Math.min( Math.min(cameraPos.x - (cameraChunkX << 4), cameraPos.z - (cameraChunkZ << 4)), @@ -412,53 +412,53 @@ private void scanChunk(ChunkPos chunkToScan, Entity cameraEntity) { } } - WorldChunk chunk = world.getChunk(chunkToScan.x, chunkToScan.z); + LevelChunk chunk = level.getChunk(chunkToScan.x, chunkToScan.z); - int minSection = chunk.getBottomSectionCoord(); - int maxSection = chunk.getTopSectionCoord(); + int minSection = chunk.getMinSection(); + int maxSection = chunk.getMaxSection(); for (int sectionY = minSection; sectionY < maxSection; sectionY++) { - if (!chunk.getSection(chunk.sectionCoordToIndex(sectionY)).hasAny(state -> state.isOf(Blocks.ENDER_CHEST) || state.hasBlockEntity())) { + if (!chunk.getSection(chunk.getSectionIndexFromSectionY(sectionY)).maybeHas(state -> state.is(Blocks.ENDER_CHEST) || state.hasBlockEntity())) { continue; } - for (BlockPos pos : BlockPos.iterate(chunkToScan.getStartX(), sectionY << 4, chunkToScan.getStartZ(), chunkToScan.getEndX(), (sectionY << 4) + 15, chunkToScan.getEndZ())) { + for (BlockPos pos : BlockPos.betweenClosed(chunkToScan.getMinBlockX(), sectionY << 4, chunkToScan.getMinBlockZ(), chunkToScan.getMaxBlockX(), (sectionY << 4) + 15, chunkToScan.getMaxBlockZ())) { if (searchedBlocks.contains(pos)) { continue; } BlockState state = chunk.getBlockState(pos); - if (state.isOf(Blocks.ENDER_CHEST)) { - BlockPos currentPos = pos.toImmutable(); + if (state.is(Blocks.ENDER_CHEST)) { + BlockPos currentPos = pos.immutable(); searchedBlocks.add(currentPos); if (enderChestPosition == null) { enderChestPosition = currentPos; currentlySearchingTimeout = NO_RESPONSE_TIMEOUT; - ClientcommandsDataQueryHandler.get(networkHandler).queryEntityNbt(player.getId(), playerNbt -> { + ClientcommandsDataQueryHandler.get(packetListener).queryEntityNbt(player.getId(), playerNbt -> { int numItemsInEnderChest = 0; - if (playerNbt != null && playerNbt.contains("EnderItems", NbtElement.LIST_TYPE)) { - numItemsInEnderChest = countItems(playerNbt.getList("EnderItems", NbtElement.COMPOUND_TYPE)); + if (playerNbt != null && playerNbt.contains("EnderItems", Tag.TAG_LIST)) { + numItemsInEnderChest = countItems(playerNbt.getList("EnderItems", Tag.TAG_COMPOUND)); } this.numItemsInEnderChest = numItemsInEnderChest; totalFound += numItemsInEnderChest; currentlySearchingTimeout = NO_RESPONSE_TIMEOUT; }); } else if (!hasPrintedEnderChest) { - Vec3d cameraPos = cameraEntity.getCameraPosVec(0); - double currentDistanceSq = enderChestPosition.getSquaredDistance(cameraPos); - double newDistanceSq = currentPos.getSquaredDistance(cameraPos); + Vec3 cameraPos = cameraEntity.getEyePosition(0); + double currentDistanceSq = enderChestPosition.distToCenterSqr(cameraPos); + double newDistanceSq = currentPos.distToCenterSqr(cameraPos); if (newDistanceSq < currentDistanceSq) { enderChestPosition = currentPos; } } - } else if (chunk.getBlockEntity(pos) instanceof Inventory) { - BlockPos currentPos = pos.toImmutable(); + } else if (chunk.getBlockEntity(pos) instanceof Container) { + BlockPos currentPos = pos.immutable(); searchedBlocks.add(currentPos); waitingOnBlocks.add(currentPos); currentlySearchingTimeout = NO_RESPONSE_TIMEOUT; - ClientcommandsDataQueryHandler.get(networkHandler).queryBlockNbt(currentPos, blockNbt -> { + ClientcommandsDataQueryHandler.get(packetListener).queryBlockNbt(currentPos, blockNbt -> { waitingOnBlocks.remove(currentPos); - if (blockNbt != null && blockNbt.contains("Items", NbtElement.LIST_TYPE)) { - int count = countItems(blockNbt.getList("Items", NbtElement.COMPOUND_TYPE)); + if (blockNbt != null && blockNbt.contains("Items", Tag.TAG_LIST)) { + int count = countItems(blockNbt.getList("Items", Tag.TAG_COMPOUND)); if (count > 0) { totalFound += count; printLocation(currentPos, count); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java index 170958999..ab6756372 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java @@ -9,11 +9,11 @@ import net.earthcomputer.clientcommands.command.arguments.ClientItemPredicateArgumentType; import net.earthcomputer.clientcommands.features.FishingCracker; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.item.Item; -import net.minecraft.item.Items; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; import org.apache.commons.lang3.tuple.Pair; import java.util.Set; @@ -30,12 +30,12 @@ public class FishCommand { private static final Set ENCHANTABLE_ITEMS = ImmutableSet.of(Items.BOOK, Items.FISHING_ROD, Items.BOW); private static final SimpleCommandExceptionType NEED_FISHING_MANIPULATION_EXCEPTION = new SimpleCommandExceptionType( - Text.translatable("commands.cfish.needFishingManipulation") - .styled(style -> style.withColor(Formatting.RED)) + Component.translatable("commands.cfish.needFishingManipulation") + .withStyle(style -> style.withColor(ChatFormatting.RED)) .append(" ") .append(getCommandTextComponent("commands.client.enable", "/cconfig clientcommands fishingManipulation set MANUAL"))); - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { if (MultiVersionCompat.INSTANCE.getProtocolVersion() >= MultiVersionCompat.V1_20) { return; // fishing manipulation patched in 1.20 } @@ -44,10 +44,10 @@ public static void register(CommandDispatcher dispatc .then(literal("list-goals") .executes(ctx -> listGoals(ctx.getSource()))) .then(literal("add-goal") - .then(argument("goal", clientItemPredicate(registryAccess)) + .then(argument("goal", clientItemPredicate(context)) .executes(ctx -> addGoal(ctx.getSource(), getClientItemPredicate(ctx, "goal"))))) .then(literal("add-enchanted-goal") - .then(argument("goal", withString(itemAndEnchantmentsPredicate().withItemPredicate(ENCHANTABLE_ITEMS::contains).withEnchantmentPredicate((item, ench) -> ench.isAvailableForRandomSelection()).constrainMaxLevel())) + .then(argument("goal", withString(itemAndEnchantmentsPredicate().withItemPredicate(ENCHANTABLE_ITEMS::contains).withEnchantmentPredicate((item, ench) -> ench.isDiscoverable()).constrainMaxLevel())) .executes(ctx -> addEnchantedGoal(ctx.getSource(), getWithString(ctx, "goal", ItemAndEnchantmentsPredicate.class))))) .then(literal("remove-goal") .then(argument("index", integer(1)) @@ -60,11 +60,11 @@ private static int listGoals(FabricClientCommandSource source) throws CommandSyn } if (FishingCracker.goals.isEmpty()) { - source.sendFeedback(Text.translatable("commands.cfish.listGoals.noGoals").styled(style -> style.withColor(Formatting.RED))); + source.sendFeedback(Component.translatable("commands.cfish.listGoals.noGoals").withStyle(style -> style.withColor(ChatFormatting.RED))); } else { - source.sendFeedback(Text.translatable("commands.cfish.listGoals.success", FishingCracker.goals.size())); + source.sendFeedback(Component.translatable("commands.cfish.listGoals.success", FishingCracker.goals.size())); for (int i = 0; i < FishingCracker.goals.size(); i++) { - source.sendFeedback(Text.of((i + 1) + ": " + FishingCracker.goals.get(i).getPrettyString())); + source.sendFeedback(Component.literal((i + 1) + ": " + FishingCracker.goals.get(i).getPrettyString())); } } @@ -78,7 +78,7 @@ private static int addGoal(FabricClientCommandSource source, ClientItemPredicate FishingCracker.goals.add(goal); - source.sendFeedback(Text.translatable("commands.cfish.addGoal.success", goal.getPrettyString())); + source.sendFeedback(Component.translatable("commands.cfish.addGoal.success", goal.getPrettyString())); return FishingCracker.goals.size(); } @@ -95,7 +95,7 @@ private static int addEnchantedGoal(FabricClientCommandSource source, Pair S getActualSource(ParseResults parse) { @SuppressWarnings("unchecked") public static S getActualSource(CommandContext ctx) { - if (ctx.getRootNode() == Objects.requireNonNull(MinecraftClient.getInstance().getNetworkHandler()).getCommandDispatcher().getRoot()) { + if (ctx.getRootNode() == Objects.requireNonNull(Minecraft.getInstance().getConnection()).getCommands().getRoot()) { // we're in the completion dispatcher, reparse using the real dispatcher to get the redirects return (S) getActualSource(Objects.requireNonNull(ClientCommandManager.getActiveDispatcher()).parse( StringRange.encompassing(ctx.getRange(), ctx.getLastChild().getRange()).get(ctx.getInput()), diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java index f10b1792b..c9790ec98 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java @@ -2,10 +2,9 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - -import net.earthcomputer.clientcommands.mixin.SimpleOptionAccessor; +import net.earthcomputer.clientcommands.mixin.OptionInstanceAccessor; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -23,9 +22,9 @@ public static void register(CommandDispatcher dispatc } private static int setFov(FabricClientCommandSource source, int fov) { - ((SimpleOptionAccessor) (Object) source.getClient().options.getFov()).forceSetValue(fov); + ((OptionInstanceAccessor) (Object) source.getClient().options.fov()).forceSetValue(fov); - Text feedback = Text.translatable("commands.cfov.success", fov); + Component feedback = Component.translatable("commands.cfov.success", fov); source.sendFeedback(feedback); return Command.SINGLE_SUCCESS; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java index f06f656dd..21bfff9b5 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java @@ -2,10 +2,9 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - -import net.earthcomputer.clientcommands.mixin.SimpleOptionAccessor; +import net.earthcomputer.clientcommands.mixin.OptionInstanceAccessor; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static com.mojang.brigadier.arguments.DoubleArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -19,9 +18,9 @@ public static void register(CommandDispatcher dispatc } private static int setGamma(FabricClientCommandSource source, double gamma) { - ((SimpleOptionAccessor) (Object) source.getClient().options.getGamma()).forceSetValue(gamma); + ((OptionInstanceAccessor) (Object) source.getClient().options.gamma()).forceSetValue(gamma); - Text feedback = Text.translatable("commands.cgamma.success", gamma); + Component feedback = Component.translatable("commands.cgamma.success", gamma); source.sendFeedback(feedback); return Command.SINGLE_SUCCESS; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java index 68e8dab55..8467515b6 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java @@ -10,15 +10,19 @@ import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.client.MinecraftClient; -import net.minecraft.command.BlockDataObject; -import net.minecraft.command.DataCommandObject; -import net.minecraft.command.EntityDataObject; -import net.minecraft.nbt.*; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CollectionTag; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.server.commands.data.BlockDataAccessor; +import net.minecraft.server.commands.data.DataAccessor; +import net.minecraft.server.commands.data.EntityDataAccessor; +import net.minecraft.util.Mth; +import net.minecraft.world.level.block.entity.BlockEntity; import java.util.Collection; import java.util.Iterator; @@ -32,14 +36,14 @@ public class GetDataCommand { - private static final DynamicCommandExceptionType GET_UNKNOWN_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.data.get.unknown", arg)); - private static final SimpleCommandExceptionType GET_MULTIPLE_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.data.get.multiple")); - private static final SimpleCommandExceptionType INVALID_BLOCK_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.data.block.invalid")); + private static final DynamicCommandExceptionType GET_UNKNOWN_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.data.get.unknown", arg)); + private static final SimpleCommandExceptionType GET_MULTIPLE_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.data.get.multiple")); + private static final SimpleCommandExceptionType INVALID_BLOCK_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.data.block.invalid")); - public static final Function CLIENT_ENTITY_DATA_OBJECT = argName -> new ObjectType() { + public static final Function CLIENT_ENTITY_DATA_ACCESSOR = argName -> new AccessorType() { @Override - public DataCommandObject getObject(CommandContext ctx) throws CommandSyntaxException { - return new EntityDataObject(getCEntity(ctx, argName)); + public DataAccessor getAccessor(CommandContext ctx) throws CommandSyntaxException { + return new EntityDataAccessor(getCEntity(ctx, argName)); } @Override @@ -48,14 +52,14 @@ public DataCommandObject getObject(CommandContext ctx } }; - public static final Function CLIENT_TILE_ENTITY_DATA_OBJECT = argName -> new ObjectType() { - public DataCommandObject getObject(CommandContext ctx) throws CommandSyntaxException { + public static final Function CLIENT_TILE_ENTITY_DATA_OBJECT = argName -> new AccessorType() { + public DataAccessor getAccessor(CommandContext ctx) throws CommandSyntaxException { BlockPos pos = getCBlockPos(ctx, argName + "Pos"); - BlockEntity blockEntity = MinecraftClient.getInstance().world.getBlockEntity(pos); + BlockEntity blockEntity = Minecraft.getInstance().level.getBlockEntity(pos); if (blockEntity == null) { throw INVALID_BLOCK_EXCEPTION.create(); } else { - return new BlockDataObject(blockEntity, pos); + return new BlockDataAccessor(blockEntity, pos); } } @@ -64,47 +68,47 @@ public DataCommandObject getObject(CommandContext ctx } }; - public static List> OBJECT_TYPES = ImmutableList.of(CLIENT_ENTITY_DATA_OBJECT, CLIENT_TILE_ENTITY_DATA_OBJECT); - public static List TARGET_OBJECT_TYPES = OBJECT_TYPES.stream().map(it -> it.apply("target")).collect(ImmutableList.toImmutableList()); + public static List> OBJECT_TYPES = ImmutableList.of(CLIENT_ENTITY_DATA_ACCESSOR, CLIENT_TILE_ENTITY_DATA_OBJECT); + public static List TARGET_OBJECT_TYPES = OBJECT_TYPES.stream().map(it -> it.apply("target")).collect(ImmutableList.toImmutableList()); public static void register(CommandDispatcher dispatcher) { - for (ObjectType objType : TARGET_OBJECT_TYPES) { + for (AccessorType objType : TARGET_OBJECT_TYPES) { //noinspection unchecked dispatcher.register((LiteralArgumentBuilder) objType.addArgumentsToBuilder(literal("cgetdata"), builder -> - builder.executes(ctx -> getData(ctx.getSource(), objType.getObject(ctx))) + builder.executes(ctx -> getData(ctx.getSource(), objType.getAccessor(ctx))) .then(argument("path", nbtPath()) - .executes(ctx -> getData(ctx.getSource(), objType.getObject(ctx), getCNbtPath(ctx, "path")))))); + .executes(ctx -> getData(ctx.getSource(), objType.getAccessor(ctx), getCNbtPath(ctx, "path")))))); } } - private static int getData(FabricClientCommandSource source, DataCommandObject dataObj) throws CommandSyntaxException { - source.sendFeedback(dataObj.feedbackQuery(dataObj.getNbt())); + private static int getData(FabricClientCommandSource source, DataAccessor accessor) throws CommandSyntaxException { + source.sendFeedback(accessor.getPrintSuccess(accessor.getData())); return Command.SINGLE_SUCCESS; } - private static int getData(FabricClientCommandSource source, DataCommandObject dataObj, NbtPath path) throws CommandSyntaxException { - NbtElement tag = getNbt(path, dataObj); + private static int getData(FabricClientCommandSource source, DataAccessor accessor, NbtPath path) throws CommandSyntaxException { + Tag tag = getNbt(path, accessor); int ret; - if (tag instanceof AbstractNbtNumber) { - ret = MathHelper.floor(((AbstractNbtNumber) tag).doubleValue()); - } else if (tag instanceof AbstractNbtList) { - ret = ((AbstractNbtList) tag).size(); - } else if (tag instanceof NbtCompound) { - ret = ((NbtCompound) tag).getSize(); - } else if (tag instanceof NbtString) { - ret = tag.asString().length(); + if (tag instanceof NumericTag) { + ret = Mth.floor(((NumericTag) tag).getAsDouble()); + } else if (tag instanceof CollectionTag) { + ret = ((CollectionTag) tag).size(); + } else if (tag instanceof CompoundTag) { + ret = ((CompoundTag) tag).size(); + } else if (tag instanceof StringTag) { + ret = tag.getAsString().length(); } else { throw GET_UNKNOWN_EXCEPTION.create(path.toString()); } - source.sendFeedback(dataObj.feedbackQuery(tag)); + source.sendFeedback(accessor.getPrintSuccess(tag)); return ret; } - private static NbtElement getNbt(NbtPath path, DataCommandObject dataObj) throws CommandSyntaxException { - Collection tags = path.get(dataObj.getNbt()); - Iterator tagItr = tags.iterator(); - NbtElement firstTag = tagItr.next(); + private static Tag getNbt(NbtPath path, DataAccessor accessor) throws CommandSyntaxException { + Collection tags = path.get(accessor.getData()); + Iterator tagItr = tags.iterator(); + Tag firstTag = tagItr.next(); if (tagItr.hasNext()) { throw GET_MULTIPLE_EXCEPTION.create(); } else { @@ -112,8 +116,8 @@ private static NbtElement getNbt(NbtPath path, DataCommandObject dataObj) throws } } - private interface ObjectType { - DataCommandObject getObject(CommandContext ctx) throws CommandSyntaxException; + private interface AccessorType { + DataAccessor getAccessor(CommandContext ctx) throws CommandSyntaxException; ArgumentBuilder addArgumentsToBuilder(ArgumentBuilder builder, Function, ArgumentBuilder> subcommandAdder); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java index a0c67707b..922d8f944 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java @@ -5,13 +5,13 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.block.BlockState; -import net.minecraft.block.pattern.CachedBlockPosition; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockBox; -import net.minecraft.util.math.BlockPos; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.pattern.BlockInWorld; +import net.minecraft.world.level.levelgen.structure.BoundingBox; import java.util.function.Predicate; @@ -22,52 +22,52 @@ public class GhostBlockCommand { - private static final SimpleCommandExceptionType SET_FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.setblock.failed")); - private static final SimpleCommandExceptionType FILL_FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.fill.failed")); + private static final SimpleCommandExceptionType SET_FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.setblock.failed")); + private static final SimpleCommandExceptionType FILL_FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.fill.failed")); - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("cghostblock") .then(literal("set") .then(argument("pos", blockPos()) - .then(argument("block", blockState(registryAccess)) + .then(argument("block", blockState(context)) .executes(ctx -> setGhostBlock(ctx.getSource(), getCBlockPos(ctx, "pos"), getCBlockState(ctx, "block").getBlockState()))))) .then(literal("fill") .then(argument("from", blockPos()) .then(argument("to", blockPos()) - .then(argument("block", blockState(registryAccess)) + .then(argument("block", blockState(context)) .executes(ctx -> fillGhostBlocks(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getCBlockState(ctx, "block").getBlockState(), pos -> true)) .then(literal("replace") - .then(argument("filter", blockPredicate(registryAccess)) + .then(argument("filter", blockPredicate(context)) .executes(ctx -> fillGhostBlocks(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getCBlockState(ctx, "block").getBlockState(), getCBlockPredicate(ctx, "filter")))))))))); } private static int setGhostBlock(FabricClientCommandSource source, BlockPos pos, BlockState state) throws CommandSyntaxException { - ClientWorld world = source.getWorld(); - assert world != null; + ClientLevel level = source.getWorld(); + assert level != null; - checkLoaded(world, pos); + checkLoaded(level, pos); - boolean result = world.setBlockState(pos, state, 18); + boolean result = level.setBlock(pos, state, 18); if (result) { - source.sendFeedback(Text.translatable("commands.cghostblock.set.success")); + source.sendFeedback(Component.translatable("commands.cghostblock.set.success")); return Command.SINGLE_SUCCESS; } else { throw SET_FAILED_EXCEPTION.create(); } } - private static int fillGhostBlocks(FabricClientCommandSource source, BlockPos from, BlockPos to, BlockState state, Predicate filter) throws CommandSyntaxException { - ClientWorld world = source.getWorld(); - assert world != null; + private static int fillGhostBlocks(FabricClientCommandSource source, BlockPos from, BlockPos to, BlockState state, Predicate filter) throws CommandSyntaxException { + ClientLevel level = source.getWorld(); + assert level != null; - checkLoaded(world, from); - checkLoaded(world, to); + checkLoaded(level, from); + checkLoaded(level, to); - BlockBox range = BlockBox.create(from, to); + BoundingBox range = BoundingBox.fromCorners(from, to); int successCount = 0; - for (BlockPos pos : BlockPos.iterate(range.getMinX(), range.getMinY(), range.getMinZ(), range.getMaxX(), range.getMaxY(), range.getMaxZ())) { - if (filter.test(new CachedBlockPosition(world, pos, true))) { - if (world.setBlockState(pos, state, 18)) { + for (BlockPos pos : BlockPos.betweenClosed(range.minX(), range.minY(), range.minZ(), range.maxX(), range.maxY(), range.maxZ())) { + if (filter.test(new BlockInWorld(level, pos, true))) { + if (level.setBlock(pos, state, 18)) { successCount++; } } @@ -77,15 +77,15 @@ private static int fillGhostBlocks(FabricClientCommandSource source, BlockPos fr throw FILL_FAILED_EXCEPTION.create(); } - source.sendFeedback(Text.translatable("commands.cghostblock.fill.success", successCount)); + source.sendFeedback(Component.translatable("commands.cghostblock.fill.success", successCount)); return successCount; } - private static void checkLoaded(ClientWorld world, BlockPos pos) throws CommandSyntaxException { - if (!world.isChunkLoaded(pos)) { + private static void checkLoaded(ClientLevel level, BlockPos pos) throws CommandSyntaxException { + if (!level.hasChunkAt(pos)) { throw UNLOADED_EXCEPTION.create(); - } else if (!world.isInBuildLimit(pos)) { + } else if (!level.isInWorldBounds(pos)) { throw OUT_OF_WORLD_EXCEPTION.create(); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java index 6b3b74208..084023a41 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java @@ -10,12 +10,12 @@ import net.earthcomputer.clientcommands.task.SimpleTask; import net.earthcomputer.clientcommands.task.TaskManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.entity.Entity; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.AABB; import java.util.ArrayList; import java.util.List; @@ -30,7 +30,7 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class GlowCommand { - private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cglow.entity.failed")); + private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cglow.entity.failed")); private static final Flag FLAG_KEEP_SEARCHING = Flag.ofFlag("keep-searching").build(); @@ -43,7 +43,7 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> glowEntities(ctx.getSource(), ctx.getArgument("targets", CEntitySelector.class), getInteger(ctx, "seconds"), 0xffffff)) .then(literal("color") .then(argument("color", color()) - .executes(ctx -> glowEntities(ctx.getSource(), ctx.getArgument("targets", CEntitySelector.class), getInteger(ctx, "seconds"), Optional.ofNullable(getCColor(ctx, "color").getColorValue()).orElse(0xffffff))))) + .executes(ctx -> glowEntities(ctx.getSource(), ctx.getArgument("targets", CEntitySelector.class), getInteger(ctx, "seconds"), Optional.ofNullable(getCColor(ctx, "color").getColor()).orElse(0xffffff))))) .then(literal("colorCode") .then(argument("color", multibaseInteger(0, 0xffffff)) .executes(ctx -> glowEntities(ctx.getSource(), ctx.getArgument("targets", CEntitySelector.class), getInteger(ctx, "seconds"), getMultibaseInteger(ctx, "color")))))))) @@ -55,7 +55,7 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getInteger(ctx, "seconds"), 0xffffff)) .then(literal("color") .then(argument("color", color()) - .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getInteger(ctx, "seconds"), Optional.ofNullable(getCColor(ctx, "color").getColorValue()).orElse(0xffffff))))) + .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getInteger(ctx, "seconds"), Optional.ofNullable(getCColor(ctx, "color").getColor()).orElse(0xffffff))))) .then(literal("colorCode") .then(argument("color", multibaseInteger(0, 0xffffff)) .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getInteger(ctx, "seconds"), getMultibaseInteger(ctx, "color"))))))))) @@ -66,7 +66,7 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "block"), null, getInteger(ctx, "seconds"), 0xffffff)) .then(literal("color") .then(argument("color", color()) - .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "block"), null, getInteger(ctx, "seconds"), Optional.ofNullable(getCColor(ctx, "color").getColorValue()).orElse(0xffffff))))) + .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "block"), null, getInteger(ctx, "seconds"), Optional.ofNullable(getCColor(ctx, "color").getColor()).orElse(0xffffff))))) .then(literal("colorCode") .then(argument("color", multibaseInteger(0, 0xffffff)) .executes(ctx -> glowBlock(ctx.getSource(), getCBlockPos(ctx, "block"), null, getInteger(ctx, "seconds"), getMultibaseInteger(ctx, "color"))))))))); @@ -79,12 +79,12 @@ private static int glowEntities(FabricClientCommandSource source, CEntitySelecto String taskName = TaskManager.addTask("cglow", new SimpleTask() { @Override public boolean condition() { - return MinecraftClient.getInstance().player != null; + return Minecraft.getInstance().player != null; } @Override protected void onTick() { - ClientPlayerEntity player = MinecraftClient.getInstance().player; + LocalPlayer player = Minecraft.getInstance().player; assert player != null; try { @@ -97,7 +97,7 @@ protected void onTick() { } }); - source.sendFeedback(Text.translatable("commands.cglow.entity.keepSearching.success") + source.sendFeedback(Component.translatable("commands.cglow.entity.keepSearching.success") .append(" ") .append(getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName))); @@ -112,31 +112,31 @@ protected void onTick() { ((IEntity) entity).addGlowingTicket(seconds * 20, color); } - source.sendFeedback(Text.translatable("commands.cglow.entity.success", entities.size())); + source.sendFeedback(Component.translatable("commands.cglow.entity.success", entities.size())); return entities.size(); } } private static int glowBlock(FabricClientCommandSource source, BlockPos pos1, BlockPos pos2, int seconds, int color) { - List boundingBoxes = new ArrayList<>(); + List boundingBoxes = new ArrayList<>(); if (pos2 == null) { - boundingBoxes.addAll(MinecraftClient.getInstance().world.getBlockState(pos1).getOutlineShape(source.getWorld(), pos1).getBoundingBoxes()); + boundingBoxes.addAll(Minecraft.getInstance().level.getBlockState(pos1).getShape(source.getWorld(), pos1).toAabbs()); if (boundingBoxes.isEmpty()) { - boundingBoxes.add(new Box(pos1)); + boundingBoxes.add(new AABB(pos1)); } else { - boundingBoxes.replaceAll((box) -> box.offset(pos1)); + boundingBoxes.replaceAll((box) -> box.move(pos1)); } } else { - boundingBoxes.add(Box.enclosing(pos1, pos2)); + boundingBoxes.add(AABB.encapsulatingFullBlocks(pos1, pos2)); } - for (Box box : boundingBoxes) { + for (AABB box : boundingBoxes) { RenderQueue.addCuboid(RenderQueue.Layer.ON_TOP, box, box, color, seconds * 20); } - source.sendFeedback(Text.translatable("commands.cglow.area.success", boundingBoxes.size())); + source.sendFeedback(Component.translatable("commands.cglow.area.success", boundingBoxes.size())); return boundingBoxes.size(); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java index 25b37edb7..5384b14e7 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java @@ -5,20 +5,20 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.option.HotbarStorage; -import net.minecraft.client.option.HotbarStorageEntry; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.text.Text; +import net.minecraft.client.HotbarManager; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.player.inventory.Hotbar; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.item.ItemStack; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class HotbarCommand { - private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.chotbar.notCreative")); + private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.chotbar.notCreative")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("chotbar") @@ -32,44 +32,44 @@ public static void register(CommandDispatcher dispatc } private static int save(FabricClientCommandSource source, int index) { - MinecraftClient client = source.getClient(); + Minecraft minecraft = source.getClient(); - HotbarStorage storage = client.getCreativeHotbarStorage(); - HotbarStorageEntry entry = storage.getSavedHotbar(index - 1); + HotbarManager manager = minecraft.getHotbarManager(); + Hotbar hotbar = manager.get(index - 1); - for (int slot = 0; slot < PlayerInventory.getHotbarSize(); slot++) { - entry.set(slot, source.getPlayer().getInventory().getStack(slot).copy()); + for (int slot = 0; slot < Inventory.getSelectionSize(); slot++) { + hotbar.set(slot, source.getPlayer().getInventory().getItem(slot).copy()); } - storage.save(); + manager.save(); - Text loadKey = client.options.loadToolbarActivatorKey.getBoundKeyLocalizedText(); - Text hotbarKey = client.options.hotbarKeys[index - 1].getBoundKeyLocalizedText(); + Component loadKey = minecraft.options.keyLoadHotbarActivator.getTranslatedKeyMessage(); + Component hotbarKey = minecraft.options.keyHotbarSlots[index - 1].getTranslatedKeyMessage(); - source.sendFeedback(Text.translatable("inventory.hotbarSaved", loadKey, hotbarKey)); + source.sendFeedback(Component.translatable("inventory.hotbarSaved", loadKey, hotbarKey)); return Command.SINGLE_SUCCESS; } private static int restore(FabricClientCommandSource source, int index) throws CommandSyntaxException { - MinecraftClient client = source.getClient(); + Minecraft minecraft = source.getClient(); - ClientPlayerEntity player = source.getPlayer(); - if (!player.getAbilities().creativeMode) { + LocalPlayer player = source.getPlayer(); + if (!player.getAbilities().instabuild) { throw NOT_CREATIVE_EXCEPTION.create(); } - HotbarStorage storage = client.getCreativeHotbarStorage(); - HotbarStorageEntry entry = storage.getSavedHotbar(index - 1); + HotbarManager manager = minecraft.getHotbarManager(); + Hotbar hotbar = manager.get(index - 1); - for (int slot = 0; slot < PlayerInventory.getHotbarSize(); slot++) { - ItemStack stack = entry.get(slot).copy(); + for (int slot = 0; slot < Inventory.getSelectionSize(); slot++) { + ItemStack stack = hotbar.get(slot).copy(); - player.getInventory().setStack(slot, stack); - client.interactionManager.clickCreativeStack(stack, 36 + slot); + player.getInventory().setItem(slot, stack); + minecraft.gameMode.handleCreativeModeItemAdd(stack, 36 + slot); } - player.playerScreenHandler.sendContentUpdates(); + player.inventoryMenu.broadcastChanges(); - source.sendFeedback(Text.translatable("commands.chotbar.restoredHotbar", index)); + source.sendFeedback(Component.translatable("commands.chotbar.restoredHotbar", index)); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java index c7073084d..ac012e900 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java @@ -12,17 +12,21 @@ import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.SharedConstants; -import net.minecraft.client.MinecraftClient; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.datafixer.TypeReferences; -import net.minecraft.item.ItemStack; -import net.minecraft.item.ItemStackSet; -import net.minecraft.nbt.*; -import net.minecraft.registry.Registries; -import net.minecraft.registry.Registry; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.datafix.fixes.References; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.ItemStackLinkedSet; import org.slf4j.Logger; import java.io.File; @@ -36,18 +40,18 @@ import static com.mojang.brigadier.arguments.StringArgumentType.*; import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; -import static net.minecraft.command.CommandSource.*; +import static net.minecraft.commands.SharedSuggestionProvider.*; public class ItemGroupCommand { private static final Logger LOGGER = LogUtils.getLogger(); - private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.citemgroup.notFound", arg)); - private static final DynamicCommandExceptionType OUT_OF_BOUNDS_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.citemgroup.outOfBounds", arg)); + private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.citemgroup.notFound", arg)); + private static final DynamicCommandExceptionType OUT_OF_BOUNDS_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.citemgroup.outOfBounds", arg)); - private static final SimpleCommandExceptionType SAVE_FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.citemgroup.saveFile.failed")); - private static final DynamicCommandExceptionType ILLEGAL_CHARACTER_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.citemgroup.addGroup.illegalCharacter", arg)); - private static final DynamicCommandExceptionType ALREADY_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.citemgroup.addGroup.alreadyExists", arg)); + private static final SimpleCommandExceptionType SAVE_FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.citemgroup.saveFile.failed")); + private static final DynamicCommandExceptionType ILLEGAL_CHARACTER_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.citemgroup.addGroup.illegalCharacter", arg)); + private static final DynamicCommandExceptionType ALREADY_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.citemgroup.addGroup.alreadyExists", arg)); private static final Path configPath = FabricLoader.getInstance().getConfigDir().resolve("clientcommands"); @@ -62,38 +66,38 @@ public static void registerItemGroups() { groups.forEach((key, group) -> group.registerItemGroup(key)); } - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("citemgroup") .then(literal("modify") .then(argument("group", string()) - .suggests((ctx, builder) -> suggestMatching(groups.keySet(), builder)) + .suggests((ctx, builder) -> suggest(groups.keySet(), builder)) .then(literal("add") - .then(argument("itemstack", itemStack(registryAccess)) + .then(argument("itemstack", itemStack(context)) .then(argument("count", integer(1)) - .executes(ctx -> addStack(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "itemstack").createStack(getInteger(ctx, "count"), false)))) - .executes(ctx -> addStack(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "itemstack").createStack(1, false))))) + .executes(ctx -> addStack(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "itemstack").createItemStack(getInteger(ctx, "count"), false)))) + .executes(ctx -> addStack(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "itemstack").createItemStack(1, false))))) .then(literal("remove") .then(argument("index", integer(0)) .executes(ctx -> removeStack(ctx.getSource(), getString(ctx, "group"), getInteger(ctx, "index"))))) .then(literal("set") .then(argument("index", integer(0)) - .then(argument("itemstack", itemStack(registryAccess)) + .then(argument("itemstack", itemStack(context)) .then(argument("count", integer(1)) - .executes(ctx -> setStack(ctx.getSource(), getString(ctx, "group"), getInteger(ctx, "index"), getCItemStackArgument(ctx, "itemstack").createStack(getInteger(ctx, "count"), false)))) - .executes(ctx -> setStack(ctx.getSource(), getString(ctx, "group"), getInteger(ctx, "index"), getCItemStackArgument(ctx, "itemstack").createStack(1, false)))))) + .executes(ctx -> setStack(ctx.getSource(), getString(ctx, "group"), getInteger(ctx, "index"), getCItemStackArgument(ctx, "itemstack").createItemStack(getInteger(ctx, "count"), false)))) + .executes(ctx -> setStack(ctx.getSource(), getString(ctx, "group"), getInteger(ctx, "index"), getCItemStackArgument(ctx, "itemstack").createItemStack(1, false)))))) .then(literal("icon") - .then(argument("icon", itemStack(registryAccess)) - .executes(ctx -> changeIcon(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "icon").createStack(1, false))))) + .then(argument("icon", itemStack(context)) + .executes(ctx -> changeIcon(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "icon").createItemStack(1, false))))) .then(literal("rename") .then(argument("new", string()) .executes(ctx -> renameGroup(ctx.getSource(), getString(ctx, "group"), getString(ctx, "new"))))))) .then(literal("add") .then(argument("group", string()) - .then(argument("icon", itemStack(registryAccess)) - .executes(ctx -> addGroup(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "icon").createStack(1, false)))))) + .then(argument("icon", itemStack(context)) + .executes(ctx -> addGroup(ctx.getSource(), getString(ctx, "group"), getCItemStackArgument(ctx, "icon").createItemStack(1, false)))))) .then(literal("remove") .then(argument("group", string()) - .suggests((ctx, builder) -> suggestMatching(groups.keySet(), builder)) + .suggests((ctx, builder) -> suggest(groups.keySet(), builder)) .executes(ctx -> removeGroup(ctx.getSource(), getString(ctx, "group")))))); } @@ -102,14 +106,14 @@ private static int addGroup(FabricClientCommandSource source, String name, ItemS throw ALREADY_EXISTS_EXCEPTION.create(name); } - final Identifier identifier = Identifier.tryParse("clientcommands:" + name); + final ResourceLocation identifier = ResourceLocation.tryParse("clientcommands:" + name); if (identifier == null) { throw ILLEGAL_CHARACTER_EXCEPTION.create(name); } - groups.put(name, new Group(icon, new NbtList())); + groups.put(name, new Group(icon, new ListTag())); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.addGroup.success", name)); + source.sendFeedback(Component.translatable("commands.citemgroup.addGroup.success", name)); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } @@ -122,7 +126,7 @@ private static int removeGroup(FabricClientCommandSource source, String name) th groups.remove(name); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.removeGroup.success", name)); + source.sendFeedback(Component.translatable("commands.citemgroup.removeGroup.success", name)); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } @@ -133,11 +137,11 @@ private static int addStack(FabricClientCommandSource source, String name, ItemS } Group group = groups.get(name); - NbtList items = group.items(); - items.add(itemStack.writeNbt(new NbtCompound())); + ListTag items = group.items(); + items.add(itemStack.save(new CompoundTag())); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.addStack.success", itemStack.getItem().getName(), name)); + source.sendFeedback(Component.translatable("commands.citemgroup.addStack.success", itemStack.getItem().getDescription(), name)); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } @@ -148,14 +152,14 @@ private static int removeStack(FabricClientCommandSource source, String name, in } Group group = groups.get(name); - NbtList items = group.items(); + ListTag items = group.items(); if (index < 0 || index >= items.size()) { throw OUT_OF_BOUNDS_EXCEPTION.create(index); } items.remove(index); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.removeStack.success", name, index)); + source.sendFeedback(Component.translatable("commands.citemgroup.removeStack.success", name, index)); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } @@ -166,14 +170,14 @@ private static int setStack(FabricClientCommandSource source, String name, int i } Group group = groups.get(name); - NbtList items = group.items(); + ListTag items = group.items(); if ((index < 0) || (index >= items.size())) { throw OUT_OF_BOUNDS_EXCEPTION.create(index); } - items.set(index, itemStack.writeNbt(new NbtCompound())); + items.set(index, itemStack.save(new CompoundTag())); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.setStack.success", name, index, itemStack.getItem().getName())); + source.sendFeedback(Component.translatable("commands.citemgroup.setStack.success", name, index, itemStack.getItem().getDescription())); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } @@ -184,13 +188,13 @@ private static int changeIcon(FabricClientCommandSource source, String name, Ite } Group group = groups.get(name); - NbtList items = group.items(); + ListTag items = group.items(); ItemStack old = group.icon(); groups.put(name, new Group(icon, items)); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.changeIcon.success", name, old.getItem().getName(), icon.getItem().getName())); + source.sendFeedback(Component.translatable("commands.citemgroup.changeIcon.success", name, old.getItem().getDescription(), icon.getItem().getDescription())); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } @@ -200,7 +204,7 @@ private static int renameGroup(FabricClientCommandSource source, String name, St throw NOT_FOUND_EXCEPTION.create(name); } - Identifier identifier = Identifier.tryParse("clientcommands:" + _new); + ResourceLocation identifier = ResourceLocation.tryParse("clientcommands:" + _new); if (identifier == null) { throw ILLEGAL_CHARACTER_EXCEPTION.create(_new); } @@ -208,28 +212,28 @@ private static int renameGroup(FabricClientCommandSource source, String name, St groups.put(_new, group); saveFile(); - source.sendFeedback(Text.translatable("commands.citemgroup.renameGroup.success", name, _new)); + source.sendFeedback(Component.translatable("commands.citemgroup.renameGroup.success", name, _new)); ClientCommandHelper.sendRequiresRestart(); return Command.SINGLE_SUCCESS; } private static void saveFile() throws CommandSyntaxException { try { - NbtCompound rootTag = new NbtCompound(); - NbtCompound compoundTag = new NbtCompound(); + CompoundTag rootTag = new CompoundTag(); + CompoundTag compoundTag = new CompoundTag(); groups.forEach((key, value) -> { - NbtCompound group = new NbtCompound(); - group.put("icon", value.icon().writeNbt(new NbtCompound())); + CompoundTag group = new CompoundTag(); + group.put("icon", value.icon().save(new CompoundTag())); group.put("items", value.items()); compoundTag.put(key, group); }); - rootTag.putInt("DataVersion", SharedConstants.getGameVersion().getSaveVersion().getId()); + rootTag.putInt("DataVersion", SharedConstants.getCurrentVersion().getDataVersion().getVersion()); rootTag.put("Groups", compoundTag); Path newFile = File.createTempFile("groups", ".dat", configPath.toFile()).toPath(); NbtIo.write(rootTag, newFile); Path backupFile = configPath.resolve("groups.dat_old"); Path currentFile = configPath.resolve("groups.dat"); - Util.backupAndReplace(currentFile, newFile, backupFile); + Util.safeReplaceFile(currentFile, newFile, backupFile); } catch (IOException e) { e.printStackTrace(); throw SAVE_FAILED_EXCEPTION.create(); @@ -238,42 +242,42 @@ private static void saveFile() throws CommandSyntaxException { private static void loadFile() throws IOException { groups.clear(); - NbtCompound rootTag = NbtIo.read(configPath.resolve("groups.dat")); + CompoundTag rootTag = NbtIo.read(configPath.resolve("groups.dat")); if (rootTag == null) { return; } - final int currentVersion = SharedConstants.getGameVersion().getSaveVersion().getId(); + final int currentVersion = SharedConstants.getCurrentVersion().getDataVersion().getVersion(); final int fileVersion = rootTag.getInt("DataVersion"); - NbtCompound compoundTag = rootTag.getCompound("Groups"); - DataFixer dataFixer = MinecraftClient.getInstance().getDataFixer(); + CompoundTag compoundTag = rootTag.getCompound("Groups"); + DataFixer dataFixer = Minecraft.getInstance().getFixerUpper(); if (fileVersion >= currentVersion) { - compoundTag.getKeys().forEach(key -> { - if (Identifier.tryParse("clientcommands:" + key) == null) { + compoundTag.getAllKeys().forEach(key -> { + if (ResourceLocation.tryParse("clientcommands:" + key) == null) { LOGGER.warn("Skipping item group with invalid name {}", key); return; } - NbtCompound group = compoundTag.getCompound(key); + CompoundTag group = compoundTag.getCompound(key); ItemStack icon = singleItemFromNbt(group.getCompound("icon")); - NbtList items = group.getList("items", NbtElement.COMPOUND_TYPE); + ListTag items = group.getList("items", Tag.TAG_COMPOUND); groups.put(key, new Group(icon, items)); }); } else { - compoundTag.getKeys().forEach(key -> { - if (Identifier.tryParse("clientcommands:" + key) == null) { + compoundTag.getAllKeys().forEach(key -> { + if (ResourceLocation.tryParse("clientcommands:" + key) == null) { LOGGER.warn("Skipping item group with invalid name {}", key); return; } - NbtCompound group = compoundTag.getCompound(key); - Dynamic oldStackDynamic = new Dynamic<>(NbtOps.INSTANCE, group.getCompound("icon")); - Dynamic newStackDynamic = dataFixer.update(TypeReferences.ITEM_STACK, oldStackDynamic, fileVersion, currentVersion); - ItemStack icon = singleItemFromNbt((NbtCompound) newStackDynamic.getValue()); + CompoundTag group = compoundTag.getCompound(key); + Dynamic oldStackDynamic = new Dynamic<>(NbtOps.INSTANCE, group.getCompound("icon")); + Dynamic newStackDynamic = dataFixer.update(References.ITEM_STACK, oldStackDynamic, fileVersion, currentVersion); + ItemStack icon = singleItemFromNbt((CompoundTag) newStackDynamic.getValue()); - NbtList updatedListTag = new NbtList(); - group.getList("items", NbtElement.COMPOUND_TYPE).forEach(tag -> { - Dynamic oldTagDynamic = new Dynamic<>(NbtOps.INSTANCE, tag); - Dynamic newTagDynamic = dataFixer.update(TypeReferences.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); + ListTag updatedListTag = new ListTag(); + group.getList("items", Tag.TAG_COMPOUND).forEach(tag -> { + Dynamic oldTagDynamic = new Dynamic<>(NbtOps.INSTANCE, tag); + Dynamic newTagDynamic = dataFixer.update(References.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); updatedListTag.add(newTagDynamic.getValue()); }); groups.put(key, new Group(icon, updatedListTag)); @@ -281,21 +285,21 @@ private static void loadFile() throws IOException { } } - private static ItemStack singleItemFromNbt(NbtCompound nbt) { - ItemStack stack = ItemStack.fromNbt(nbt); + private static ItemStack singleItemFromNbt(CompoundTag nbt) { + ItemStack stack = ItemStack.of(nbt); if (!stack.isEmpty()) { stack.setCount(1); } return stack; } - private record Group(ItemStack icon, NbtList items) { + private record Group(ItemStack icon, ListTag items) { void registerItemGroup(String key) { - Registry.register(Registries.ITEM_GROUP, new Identifier("clientcommands", key), FabricItemGroup.builder() - .displayName(Text.literal(key)) + Registry.register(BuiltInRegistries.CREATIVE_MODE_TAB, new ResourceLocation("clientcommands", key), FabricItemGroup.builder() + .title(Component.literal(key)) .icon(() -> icon) - .entries((displayContext, entries) -> { - Set existingStacks = ItemStackSet.create(); + .displayItems((displayContext, entries) -> { + Set existingStacks = ItemStackLinkedSet.createTypeAndTagSet(); for (int i = 0; i < items.size(); i++) { ItemStack stack = singleItemFromNbt(items.getCompound(i)); if (stack.isEmpty()) { @@ -303,7 +307,7 @@ void registerItemGroup(String key) { } stack.setCount(1); if (existingStacks.add(stack)) { - entries.add(stack); + entries.accept(stack); } } }) diff --git a/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java index 98abd46b4..2d9b4e58b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java @@ -10,19 +10,23 @@ import com.mojang.serialization.Dynamic; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.ChatFormatting; import net.minecraft.SharedConstants; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.ingame.AbstractInventoryScreen; -import net.minecraft.datafixer.TypeReferences; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.*; -import net.minecraft.screen.PlayerScreenHandler; -import net.minecraft.screen.slot.Slot; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.util.datafix.fixes.References; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import org.slf4j.Logger; import java.io.File; @@ -34,22 +38,22 @@ import static com.mojang.brigadier.arguments.StringArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; -import static net.minecraft.command.CommandSource.*; +import static net.minecraft.commands.SharedSuggestionProvider.*; public class KitCommand { private static final Logger LOGGER = LogUtils.getLogger(); - private static final SimpleCommandExceptionType SAVE_FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.ckit.saveFile.failed")); + private static final SimpleCommandExceptionType SAVE_FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.ckit.saveFile.failed")); - private static final DynamicCommandExceptionType ALREADY_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.ckit.create.alreadyExists", arg)); + private static final DynamicCommandExceptionType ALREADY_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.ckit.create.alreadyExists", arg)); - private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.ckit.load.notCreative")); - private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.ckit.notFound", arg)); + private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.ckit.load.notCreative")); + private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.ckit.notFound", arg)); private static final Path configPath = FabricLoader.getInstance().getConfigDir().resolve("clientcommands"); - private static final Map kits = new HashMap<>(); + private static final Map kits = new HashMap<>(); static { try { @@ -66,15 +70,15 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> create(ctx.getSource(), getString(ctx, "name"))))) .then(literal("delete") .then(argument("name", string()) - .suggests((ctx, builder) -> suggestMatching(kits.keySet(), builder)) + .suggests((ctx, builder) -> suggest(kits.keySet(), builder)) .executes(ctx -> delete(ctx.getSource(), getString(ctx, "name"))))) .then(literal("edit") .then(argument("name", string()) - .suggests((ctx, builder) -> suggestMatching(kits.keySet(), builder)) + .suggests((ctx, builder) -> suggest(kits.keySet(), builder)) .executes(ctx -> edit(ctx.getSource(), getString(ctx, "name"))))) .then(literal("load") .then(argument("name", string()) - .suggests((ctx, builder) -> suggestMatching(kits.keySet(), builder)) + .suggests((ctx, builder) -> suggest(kits.keySet(), builder)) .then(literal("--override") .executes(ctx -> load(ctx.getSource(), getString(ctx, "name"), true))) .executes(ctx -> load(ctx.getSource(), getString(ctx, "name"), false)))) @@ -82,7 +86,7 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> list(ctx.getSource()))) .then(literal("preview") .then(argument("name", string()) - .suggests((ctx, builder) -> suggestMatching(kits.keySet(), builder)) + .suggests((ctx, builder) -> suggest(kits.keySet(), builder)) .executes(ctx -> preview(ctx.getSource(), getString(ctx, "name")))))); } @@ -90,9 +94,9 @@ private static int create(FabricClientCommandSource source, String name) throws if (kits.containsKey(name)) { throw ALREADY_EXISTS_EXCEPTION.create(name); } - kits.put(name, source.getPlayer().getInventory().writeNbt(new NbtList())); + kits.put(name, source.getPlayer().getInventory().save(new ListTag())); saveFile(); - source.sendFeedback(Text.translatable("commands.ckit.create.success", name)); + source.sendFeedback(Component.translatable("commands.ckit.create.success", name)); return Command.SINGLE_SUCCESS; } @@ -101,7 +105,7 @@ private static int delete(FabricClientCommandSource source, String name) throws throw NOT_FOUND_EXCEPTION.create(name); } saveFile(); - source.sendFeedback(Text.translatable("commands.ckit.delete.success", name)); + source.sendFeedback(Component.translatable("commands.ckit.delete.success", name)); return Command.SINGLE_SUCCESS; } @@ -109,79 +113,79 @@ private static int edit(FabricClientCommandSource source, String name) throws Co if (!kits.containsKey(name)) { throw NOT_FOUND_EXCEPTION.create(name); } - kits.put(name, source.getPlayer().getInventory().writeNbt(new NbtList())); + kits.put(name, source.getPlayer().getInventory().save(new ListTag())); saveFile(); - source.sendFeedback(Text.translatable("commands.ckit.edit.success", name)); + source.sendFeedback(Component.translatable("commands.ckit.edit.success", name)); return Command.SINGLE_SUCCESS; } private static int load(FabricClientCommandSource source, String name, boolean override) throws CommandSyntaxException { - if (!source.getPlayer().getAbilities().creativeMode) { + if (!source.getPlayer().getAbilities().instabuild) { throw NOT_CREATIVE_EXCEPTION.create(); } - NbtList kit = kits.get(name); + ListTag kit = kits.get(name); if (kit == null) { throw NOT_FOUND_EXCEPTION.create(name); } - PlayerInventory tempInv = new PlayerInventory(source.getPlayer()); - tempInv.readNbt(kit); - List slots = source.getPlayer().playerScreenHandler.slots; + Inventory tempInv = new Inventory(source.getPlayer()); + tempInv.load(kit); + List slots = source.getPlayer().inventoryMenu.slots; for (int i = 0; i < slots.size(); i++) { - if (slots.get(i).inventory == source.getPlayer().getInventory()) { - ItemStack itemStack = tempInv.getStack(slots.get(i).getIndex()); + if (slots.get(i).container == source.getPlayer().getInventory()) { + ItemStack itemStack = tempInv.getItem(slots.get(i).getContainerSlot()); if (!itemStack.isEmpty() || override) { - source.getClient().interactionManager.clickCreativeStack(itemStack, i); + source.getClient().gameMode.handleCreativeModeItemAdd(itemStack, i); } } } - source.getPlayer().playerScreenHandler.sendContentUpdates(); - source.sendFeedback(Text.translatable("commands.ckit.load.success", name)); + source.getPlayer().inventoryMenu.broadcastChanges(); + source.sendFeedback(Component.translatable("commands.ckit.load.success", name)); return Command.SINGLE_SUCCESS; } private static int list(FabricClientCommandSource source) { if (kits.isEmpty()) { - source.sendFeedback(Text.translatable("commands.ckit.list.empty")); + source.sendFeedback(Component.translatable("commands.ckit.list.empty")); } else { String list = String.join(", ", kits.keySet()); - source.sendFeedback(Text.translatable("commands.ckit.list", list)); + source.sendFeedback(Component.translatable("commands.ckit.list", list)); } return kits.size(); } private static int preview(FabricClientCommandSource source, String name) throws CommandSyntaxException { - NbtList kit = kits.get(name); + ListTag kit = kits.get(name); if (kit == null) { throw NOT_FOUND_EXCEPTION.create(name); } - PlayerInventory tempInv = new PlayerInventory(source.getPlayer()); - tempInv.readNbt(kit); + Inventory tempInv = new Inventory(source.getPlayer()); + tempInv.load(kit); /* After executing a command, the current screen will be closed (the chat hud). And if you open a new screen in a command, that new screen will be closed instantly along with the chat hud. Slightly delaying the opening of the screen fixes this issue. */ - source.getClient().send(() -> source.getClient().setScreen(new PreviewScreen(new PlayerScreenHandler(tempInv, true, source.getPlayer()), tempInv, name))); + source.getClient().tell(() -> source.getClient().setScreen(new PreviewScreen(new InventoryMenu(tempInv, true, source.getPlayer()), tempInv, name))); return Command.SINGLE_SUCCESS; } private static void saveFile() throws CommandSyntaxException { try { - NbtCompound rootTag = new NbtCompound(); - NbtCompound compoundTag = new NbtCompound(); + CompoundTag rootTag = new CompoundTag(); + CompoundTag compoundTag = new CompoundTag(); kits.forEach(compoundTag::put); - rootTag.putInt("DataVersion", SharedConstants.getGameVersion().getSaveVersion().getId()); + rootTag.putInt("DataVersion", SharedConstants.getCurrentVersion().getDataVersion().getVersion()); rootTag.put("Kits", compoundTag); Path newFile = File.createTempFile("kits", ".dat", configPath.toFile()).toPath(); NbtIo.write(rootTag, newFile); Path backupFile = configPath.resolve("kits.dat_old"); Path currentFile = configPath.resolve("kits.dat");; - Util.backupAndReplace(currentFile, newFile, backupFile); + Util.safeReplaceFile(currentFile, newFile, backupFile); } catch (IOException e) { throw SAVE_FAILED_EXCEPTION.create(); } @@ -189,22 +193,22 @@ private static void saveFile() throws CommandSyntaxException { private static void loadFile() throws IOException { kits.clear(); - NbtCompound rootTag = NbtIo.read(configPath.resolve("kits.dat")); + CompoundTag rootTag = NbtIo.read(configPath.resolve("kits.dat")); if (rootTag == null) { return; } - final int currentVersion = SharedConstants.getGameVersion().getSaveVersion().getId(); + final int currentVersion = SharedConstants.getCurrentVersion().getDataVersion().getVersion(); final int fileVersion = rootTag.getInt("DataVersion"); - NbtCompound compoundTag = rootTag.getCompound("Kits"); - DataFixer dataFixer = MinecraftClient.getInstance().getDataFixer(); + CompoundTag compoundTag = rootTag.getCompound("Kits"); + DataFixer dataFixer = Minecraft.getInstance().getFixerUpper(); if (fileVersion >= currentVersion) { - compoundTag.getKeys().forEach(key -> kits.put(key, compoundTag.getList(key, NbtElement.COMPOUND_TYPE))); + compoundTag.getAllKeys().forEach(key -> kits.put(key, compoundTag.getList(key, Tag.TAG_COMPOUND))); } else { - compoundTag.getKeys().forEach(key -> { - NbtList updatedListTag = new NbtList(); - compoundTag.getList(key, NbtElement.COMPOUND_TYPE).forEach(tag -> { - Dynamic oldTagDynamic = new Dynamic<>(NbtOps.INSTANCE, tag); - Dynamic newTagDynamic = dataFixer.update(TypeReferences.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); + compoundTag.getAllKeys().forEach(key -> { + ListTag updatedListTag = new ListTag(); + compoundTag.getList(key, Tag.TAG_COMPOUND).forEach(tag -> { + Dynamic oldTagDynamic = new Dynamic<>(NbtOps.INSTANCE, tag); + Dynamic newTagDynamic = dataFixer.update(References.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); updatedListTag.add(newTagDynamic.getValue()); }); kits.put(key, updatedListTag); @@ -213,34 +217,34 @@ private static void loadFile() throws IOException { } } -class PreviewScreen extends AbstractInventoryScreen { +class PreviewScreen extends EffectRenderingInventoryScreen { - public PreviewScreen(PlayerScreenHandler playerScreenHandler, PlayerInventory inventory, String name) { - super(playerScreenHandler, inventory, Text.literal(name).styled(style -> style.withColor(Formatting.RED))); - this.titleX = 80; + public PreviewScreen(InventoryMenu menu, Inventory inventory, String name) { + super(menu, inventory, Component.literal(name).withStyle(style -> style.withColor(ChatFormatting.RED))); + this.titleLabelX = 80; } @Override - protected void drawForeground(DrawContext context, int mouseX, int mouseY) { - context.drawText(this.textRenderer, this.title, this.titleX, this.titleY, 0x404040, false); + protected void renderLabels(GuiGraphics graphics, int mouseX, int mouseY) { + graphics.drawString(this.font, this.title, this.titleLabelX, this.titleLabelY, 0x404040, false); } @Override - public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) { - this.renderBackground(drawContext, mouseX, mouseY, delta); - super.render(drawContext, mouseX, mouseY, delta); + public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + this.renderBackground(graphics, mouseX, mouseY, delta); + super.render(graphics, mouseX, mouseY, delta); - this.drawMouseoverTooltip(drawContext, mouseX, mouseY); + this.renderTooltip(graphics, mouseX, mouseY); } @Override - protected void drawStatusEffects(DrawContext context, int mouseX, int mouseY) { + protected void renderEffects(GuiGraphics graphics, int mouseX, int mouseY) { // nop } @Override - protected void drawBackground(DrawContext context, float delta, int mouseX, int mouseY) { - context.drawTexture(BACKGROUND_TEXTURE, this.x, this.y, 0, 0, this.backgroundWidth, this.backgroundHeight); + protected void renderBg(GuiGraphics graphics, float delta, int mouseX, int mouseY) { + graphics.blit(INVENTORY_LOCATION, this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight); } @Override diff --git a/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java index 89287cf88..d6063d3b1 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java @@ -4,9 +4,9 @@ import com.mojang.brigadier.CommandDispatcher; import dev.xpple.clientarguments.arguments.CPosArgument; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec2f; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.Vec2; import static dev.xpple.clientarguments.arguments.CBlockPosArgumentType.*; import static dev.xpple.clientarguments.arguments.CRotationArgumentType.*; @@ -38,9 +38,9 @@ public static void register(CommandDispatcher dispatc } private static int lookBlock(FabricClientCommandSource source, BlockPos pos) { - ClientPlayerEntity player = source.getPlayer(); + LocalPlayer player = source.getPlayer(); double dx = (pos.getX() + 0.5) - player.getX(); - double dy = (pos.getY() + 0.5) - (player.getY() + player.getStandingEyeHeight()); + double dy = (pos.getY() + 0.5) - (player.getY() + player.getEyeHeight()); double dz = (pos.getZ() + 0.5) - player.getZ(); double dh = Math.sqrt(dx * dx + dz * dz); float yaw = (float) Math.toDegrees(Math.atan2(dz, dx)) - 90; @@ -49,7 +49,7 @@ private static int lookBlock(FabricClientCommandSource source, BlockPos pos) { } private static int lookAngles(FabricClientCommandSource source, CPosArgument rotation) { - Vec2f rot = rotation.toAbsoluteRotation(source); + Vec2 rot = rotation.toAbsoluteRotation(source); return doLook(source.getPlayer(), rot.y, rot.x); } @@ -61,8 +61,8 @@ private static int lookCardinal(FabricClientCommandSource source, float pitch) { return lookCardinal(source, source.getRotation().y, pitch); } - private static int doLook(ClientPlayerEntity player, float yaw, float pitch) { - player.refreshPositionAndAngles(player.getX(), player.getY(), player.getZ(), yaw, pitch); + private static int doLook(LocalPlayer player, float yaw, float pitch) { + player.moveTo(player.getX(), player.getY(), player.getZ(), yaw, pitch); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/MoteCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/MoteCommand.java index ec2228b40..693654c40 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/MoteCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/MoteCommand.java @@ -3,7 +3,7 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -103,7 +103,7 @@ public static void register(CommandDispatcher dispatc } private static int sendEmoticon(String emoticon) { - MinecraftClient.getInstance().getNetworkHandler().sendChatMessage(emoticon); + Minecraft.getInstance().getConnection().sendChat(emoticon); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java index 7b63f6edf..fd49d65ff 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java @@ -3,21 +3,21 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.MutableText; +import net.minecraft.network.chat.MutableComponent; -import static net.earthcomputer.clientcommands.command.arguments.FormattedTextArgumentType.*; +import static net.earthcomputer.clientcommands.command.arguments.FormattedComponentArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class NoteCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cnote") - .then(argument("message", formattedText()) - .executes(ctx -> note(ctx.getSource(), getFormattedText(ctx, "message"))))); + .then(argument("message", formattedComponent()) + .executes(ctx -> note(ctx.getSource(), getFormattedComponent(ctx, "message"))))); } - private static int note(FabricClientCommandSource source, MutableText message) { - source.getClient().inGameHud.getChatHud().addMessage(message); + private static int note(FabricClientCommandSource source, MutableComponent message) { + source.getClient().gui.getChat().addMessage(message); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java index e2768058d..257a32d99 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java @@ -3,7 +3,7 @@ import com.mojang.brigadier.CommandDispatcher; import net.earthcomputer.clientcommands.interfaces.IEntity; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -16,7 +16,7 @@ public static void register(CommandDispatcher dispatc private static int getPermissionLevel(FabricClientCommandSource source) { int permissionLevel = ((IEntity) source.getPlayer()).callGetPermissionLevel(); - source.sendFeedback(Text.translatable("commands.cpermissionlevel.success", permissionLevel)); + source.sendFeedback(Component.translatable("commands.cpermissionlevel.success", permissionLevel)); return permissionLevel; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java index d1a47a523..6fef0c697 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java @@ -6,10 +6,10 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.text.Text; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.network.chat.Component; import java.util.Collection; @@ -18,9 +18,9 @@ public class PingCommand { - private static final SimpleCommandExceptionType PLAYER_IN_SINGLEPLAYER_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cping.singleplayer")); - private static final SimpleCommandExceptionType PLAYER_NOT_FOUND_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cping.playerNotFound")); - private static final SimpleCommandExceptionType TOO_MANY_PLAYERS_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cping.tooManyPlayers")); + private static final SimpleCommandExceptionType PLAYER_IN_SINGLEPLAYER_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cping.singleplayer")); + private static final SimpleCommandExceptionType PLAYER_NOT_FOUND_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cping.playerNotFound")); + private static final SimpleCommandExceptionType TOO_MANY_PLAYERS_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cping.tooManyPlayers")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cping") @@ -31,7 +31,7 @@ public static void register(CommandDispatcher dispatc } private static int printPing(FabricClientCommandSource source) throws CommandSyntaxException { - if (source.getClient().isInSingleplayer()) { + if (source.getClient().isLocalServer()) { throw PLAYER_IN_SINGLEPLAYER_EXCEPTION.create(); } @@ -40,12 +40,12 @@ private static int printPing(FabricClientCommandSource source) throws CommandSyn throw PLAYER_IN_SINGLEPLAYER_EXCEPTION.create(); } - source.sendFeedback(Text.translatable("commands.cping.success", ping)); + source.sendFeedback(Component.translatable("commands.cping.success", ping)); return Command.SINGLE_SUCCESS; } private static int printPing(FabricClientCommandSource source, Collection profiles) throws CommandSyntaxException { - if (source.getClient().isInSingleplayer()) { + if (source.getClient().isLocalServer()) { throw PLAYER_IN_SINGLEPLAYER_EXCEPTION.create(); } @@ -57,25 +57,25 @@ private static int printPing(FabricClientCommandSource source, Collection { String plugins = packet.getSuggestions().getList().stream() .map(Suggestion::getText) @@ -45,26 +45,26 @@ private static int getPlugins(FabricClientCommandSource source, String partial) .distinct() .collect(Collectors.joining(", ")); - source.sendFeedback(Text.translatable("commands.cplugins.found")); - source.sendFeedback(Text.literal(plugins)); + source.sendFeedback(Component.translatable("commands.cplugins.found")); + source.sendFeedback(Component.literal(plugins)); }; return Command.SINGLE_SUCCESS; } private static int getPluginsFromDispatcher(FabricClientCommandSource source) { - String plugins = source.getClient().getNetworkHandler().getCommandDispatcher().getRoot().getChildren().stream() + String plugins = source.getClient().getConnection().getCommands().getRoot().getChildren().stream() .map(CommandNode::getName) .filter(name -> name.contains(":")) .map(name -> name.substring(0, name.indexOf(":"))) .distinct() .collect(Collectors.joining(", ")); - source.sendFeedback(Text.translatable("commands.cplugins.found")); - source.sendFeedback(Text.literal(plugins)); + source.sendFeedback(Component.translatable("commands.cplugins.found")); + source.sendFeedback(Component.literal(plugins)); return Command.SINGLE_SUCCESS; } - public static void onCommandSuggestions(CommandSuggestionsS2CPacket packet) { + public static void onCommandSuggestions(ClientboundCommandSuggestionsPacket packet) { if (!awaitingSuggestionsPacket) { return; } @@ -75,5 +75,5 @@ public static void onCommandSuggestions(CommandSuggestionsS2CPacket packet) { @FunctionalInterface interface SuggestionsCallback { - void apply(CommandSuggestionsS2CPacket packet); + void apply(ClientboundCommandSuggestionsPacket packet); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/PosCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/PosCommand.java index 582d9292a..4fd450230 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/PosCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/PosCommand.java @@ -4,12 +4,12 @@ import com.mojang.brigadier.CommandDispatcher; import dev.xpple.clientarguments.arguments.CDimensionArgumentType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.resource.language.I18n; -import net.minecraft.registry.RegistryKey; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.client.resources.language.I18n; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.Level; import static dev.xpple.clientarguments.arguments.CBlockPosArgumentType.*; import static dev.xpple.clientarguments.arguments.CDimensionArgumentType.*; @@ -33,9 +33,9 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> convertCoords(ctx.getSource(), getCBlockPos(ctx, "pos"), getCDimensionArgument(ctx, "sourceDimension"), getCDimensionArgument(ctx, "targetDimension")))) .executes(ctx -> convertCoords(ctx.getSource(), - ctx.getSource().getPlayer().getBlockPos(), getCDimensionArgument(ctx, "sourceDimension"), getCDimensionArgument(ctx, "targetDimension"))))) + ctx.getSource().getPlayer().blockPosition(), getCDimensionArgument(ctx, "sourceDimension"), getCDimensionArgument(ctx, "targetDimension"))))) .executes(ctx -> convertCoords(ctx.getSource(), - ctx.getSource().getPlayer().getBlockPos(), null, getCDimensionArgument(ctx, "targetDimension"))))) + ctx.getSource().getPlayer().blockPosition(), null, getCDimensionArgument(ctx, "targetDimension"))))) .then(literal("from").then(argument("sourceDimension", dimension()) .then(argument("pos", blockPos()) .executes(ctx -> convertCoords(ctx.getSource(), @@ -45,69 +45,69 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> convertCoords(ctx.getSource(), getCBlockPos(ctx, "pos"), getCDimensionArgument(ctx, "sourceDimension"), getCDimensionArgument(ctx, "targetDimension")))) .executes(ctx -> convertCoords(ctx.getSource(), - ctx.getSource().getPlayer().getBlockPos(), getCDimensionArgument(ctx, "sourceDimension"), getCDimensionArgument(ctx, "targetDimension"))))) + ctx.getSource().getPlayer().blockPosition(), getCDimensionArgument(ctx, "sourceDimension"), getCDimensionArgument(ctx, "targetDimension"))))) .executes(ctx -> convertCoords(ctx.getSource(), - ctx.getSource().getPlayer().getBlockPos(), getCDimensionArgument(ctx, "sourceDimension"), null)))) + ctx.getSource().getPlayer().blockPosition(), getCDimensionArgument(ctx, "sourceDimension"), null)))) .executes(ctx -> convertCoords(ctx.getSource(), - ctx.getSource().getPlayer().getBlockPos(), null, null))); + ctx.getSource().getPlayer().blockPosition(), null, null))); } private static int convertCoords(FabricClientCommandSource source, BlockPos pos, CDimensionArgumentType.DimensionArgument sourceDim, CDimensionArgumentType.DimensionArgument targetDim) { - RegistryKey sourceWorld; - RegistryKey targetWorld; + ResourceKey sourceLevel; + ResourceKey targetLevel; if (sourceDim == null && targetDim == null) { // If neither argument is given, set current dimension as source and "opposite" as target - sourceWorld = source.getPlayer().getWorld().getRegistryKey(); - targetWorld = getOppositeWorld(sourceWorld); + sourceLevel = source.getPlayer().level().dimension(); + targetLevel = getOppositeLevel(sourceLevel); } else if (targetDim == null) { // If only source dimension is given, set the target to "opposite" - sourceWorld = sourceDim.getRegistryKey(); - targetWorld = getOppositeWorld(sourceWorld); + sourceLevel = sourceDim.getRegistryKey(); + targetLevel = getOppositeLevel(sourceLevel); } else if (sourceDim == null) { // If only target dimension is given, set the source to "opposite" - targetWorld = targetDim.getRegistryKey(); - sourceWorld = getOppositeWorld(targetWorld); + targetLevel = targetDim.getRegistryKey(); + sourceLevel = getOppositeLevel(targetLevel); } else { // Both dimensions are specified by the user - sourceWorld = sourceDim.getRegistryKey(); - targetWorld = targetDim.getRegistryKey(); + sourceLevel = sourceDim.getRegistryKey(); + targetLevel = targetDim.getRegistryKey(); } - double scaleFactor = (double) getCoordinateScale(sourceWorld) / getCoordinateScale(targetWorld); - BlockPos targetPos = BlockPos.ofFloored(pos.getX() * scaleFactor, pos.getY(), pos.getZ() * scaleFactor); - String sourceWorldName = getWorldName(sourceWorld); - String targetWorldName = getWorldName(targetWorld); + double scaleFactor = (double) getCoordinateScale(sourceLevel) / getCoordinateScale(targetLevel); + BlockPos targetPos = BlockPos.containing(pos.getX() * scaleFactor, pos.getY(), pos.getZ() * scaleFactor); + String sourceWorldName = getLevelName(sourceLevel); + String targetWorldName = getLevelName(targetLevel); source.sendFeedback(getCoordsTextComponent(pos) - .append(Text.translatable("commands.cpos.coords.left", sourceWorldName, targetWorldName)) + .append(Component.translatable("commands.cpos.coords.left", sourceWorldName, targetWorldName)) .append(getLookCoordsTextComponent(targetPos)) - .append(Text.translatable("commands.cpos.coords.right", sourceWorldName, targetWorldName))); + .append(Component.translatable("commands.cpos.coords.right", sourceWorldName, targetWorldName))); return Command.SINGLE_SUCCESS; } /** - * Return the "opposite" world; that is the Nether when given anything else than the Nether, + * Return the "opposite" level; that is the Nether when given anything else than the Nether, * and the Overworld, if given the Nether. */ - private static RegistryKey getOppositeWorld(RegistryKey world) { - if (world == World.NETHER) { - return World.OVERWORLD; + private static ResourceKey getOppositeLevel(ResourceKey level) { + if (level == Level.NETHER) { + return Level.OVERWORLD; } else { - return World.NETHER; + return Level.NETHER; } } /** - * Return the scale factor of the given world. + * Return the scale factor of the given level. */ - private static int getCoordinateScale(RegistryKey world) { + private static int getCoordinateScale(ResourceKey level) { // This is supposed to mimick the value from DimensionType.coordinateScale(), // which unfortunately is not available to us at this time, so we hard-code // the known values of Vanilla. - if (world == World.NETHER) { + if (level == Level.NETHER) { return 8; } else { return 1; @@ -115,19 +115,19 @@ private static int getCoordinateScale(RegistryKey world) { } /** - * Return a translated string describing the given world, or the built-in ID + * Return a translated string describing the given level, or the built-in ID * if that fails. */ - private static String getWorldName(RegistryKey world) { - String worldNameKey = "commands.cpos.world." + world.getValue().getPath(); - if (I18n.hasTranslation(worldNameKey)) { - return I18n.translate(worldNameKey); + private static String getLevelName(ResourceKey level) { + String levelNameKey = "commands.cpos.level." + level.location().getPath(); + if (I18n.exists(levelNameKey)) { + return I18n.get(levelNameKey); } else { - return world.getValue().getPath(); + return level.location().getPath(); } } - private static MutableText getCoordsTextComponent(BlockPos pos) { - return Text.translatable("commands.client.blockpos", pos.getX(), pos.getY(), pos.getZ()); + private static MutableComponent getCoordsTextComponent(BlockPos pos) { + return Component.translatable("commands.client.blockpos", pos.getX(), pos.getY(), pos.getZ()); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/RelogCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/RelogCommand.java index fd522ac61..b6b42c7b7 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/RelogCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/RelogCommand.java @@ -6,12 +6,12 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.earthcomputer.clientcommands.features.Relogger; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class RelogCommand { - private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.crelog.failed")); + private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.crelog.failed")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("crelog") diff --git a/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java index a867f95bf..9f5f82945 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java @@ -5,7 +5,7 @@ import dev.xpple.clientarguments.arguments.CEntitySelector; import net.earthcomputer.clientcommands.features.RenderSettings; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static dev.xpple.clientarguments.arguments.CEntityArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -26,7 +26,7 @@ public static void register(CommandDispatcher dispatc private static int enableEntityRendering(FabricClientCommandSource source, CEntitySelector selector, boolean enable) { RenderSettings.addEntityRenderSelector(selector, enable); - source.sendFeedback(Text.translatable("commands.crender.entities.success")); + source.sendFeedback(Component.translatable("commands.crender.entities.success")); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java index bebf4a0fd..5245c4310 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java @@ -3,8 +3,8 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayNetworkHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -16,9 +16,9 @@ public static void register(CommandDispatcher dispatc } private static int shrug(FabricClientCommandSource source) { - ClientPlayNetworkHandler networkHandler = MinecraftClient.getInstance().getNetworkHandler(); - if (networkHandler != null) { - networkHandler.sendChatMessage("¯\\_(ツ)_/¯"); + ClientPacketListener packetListener = Minecraft.getInstance().getConnection(); + if (packetListener != null) { + packetListener.sendChat("¯\\_(ツ)_/¯"); } return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/SignSearchCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/SignSearchCommand.java index 4a54ac9e6..da9b533f5 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/SignSearchCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/SignSearchCommand.java @@ -3,15 +3,15 @@ import com.mojang.brigadier.CommandDispatcher; import net.earthcomputer.clientcommands.command.arguments.ClientBlockPredicateArgumentType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.block.AbstractSignBlock; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.block.entity.SignText; -import net.minecraft.client.MinecraftClient; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.SignBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.level.block.entity.SignText; +import net.minecraft.world.level.block.state.BlockState; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -26,10 +26,10 @@ public static void register(CommandDispatcher dispatc dispatcher.register(literal("csignsearch") .then(literal("text") .then(argument("query", greedyString()) - .executes(ctx -> FindBlockCommand.findBlock(Text.translatable("commands.csignsearch.starting"), predicate(getString(ctx, "query")))))) + .executes(ctx -> FindBlockCommand.findBlock(Component.translatable("commands.csignsearch.starting"), predicate(getString(ctx, "query")))))) .then(literal("regex") .then(argument("query", greedyRegex()) - .executes(ctx -> FindBlockCommand.findBlock(Text.translatable("commands.csignsearch.starting"), predicate(getRegex(ctx, "query"))))))); + .executes(ctx -> FindBlockCommand.findBlock(Component.translatable("commands.csignsearch.starting"), predicate(getRegex(ctx, "query"))))))); } private static ClientBlockPredicateArgumentType.ClientBlockPredicate predicate(String query) { @@ -43,23 +43,23 @@ private static ClientBlockPredicateArgumentType.ClientBlockPredicate predicate(P private static ClientBlockPredicateArgumentType.ClientBlockPredicate signPredicateFromLinePredicate(Predicate linePredicate) { return new ClientBlockPredicateArgumentType.ClientBlockPredicate() { @Override - public boolean test(BlockView blockView, BlockPos pos) { - if (!(blockView.getBlockState(pos).getBlock() instanceof AbstractSignBlock)) { + public boolean test(BlockGetter blockGetter, BlockPos pos) { + if (!(blockGetter.getBlockState(pos).getBlock() instanceof SignBlock)) { return false; } - BlockEntity be = blockView.getBlockEntity(pos); + BlockEntity be = blockGetter.getBlockEntity(pos); if (!(be instanceof SignBlockEntity sign)) { return false; } SignText frontText = sign.getFrontText(); SignText backText = sign.getBackText(); - for (int i = 0; i < SignText.field_43299; i++) { - String line = frontText.getMessage(i, MinecraftClient.getInstance().shouldFilterText()).getString(); + for (int i = 0; i < SignText.LINES; i++) { + String line = frontText.getMessage(i, Minecraft.getInstance().isTextFilteringEnabled()).getString(); if (linePredicate.test(line)) { return true; } - line = backText.getMessage(i, MinecraftClient.getInstance().shouldFilterText()).getString(); + line = backText.getMessage(i, Minecraft.getInstance().isTextFilteringEnabled()).getString(); if (linePredicate.test(line)) { return true; } @@ -70,7 +70,7 @@ public boolean test(BlockView blockView, BlockPos pos) { @Override public boolean canEverMatch(BlockState state) { - return state.getBlock() instanceof AbstractSignBlock; + return state.getBlock() instanceof SignBlock; } }; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/SnakeCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/SnakeCommand.java index d9698c668..6e876b9d6 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/SnakeCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/SnakeCommand.java @@ -3,15 +3,15 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.sound.PositionedSoundInstance; -import net.minecraft.sound.SoundEvents; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Direction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.core.Direction; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundEvents; import org.joml.Vector2i; import org.lwjgl.glfw.GLFW; @@ -34,16 +34,16 @@ After executing a command, the current screen will be closed (the chat hud). instantly along with the chat hud. Slightly delaying the opening of the screen fixes this issue. */ - source.getClient().send(() -> source.getClient().setScreen(new SnakeGameScreen())); + source.getClient().tell(() -> source.getClient().setScreen(new SnakeGameScreen())); return Command.SINGLE_SUCCESS; } } class SnakeGameScreen extends Screen { - private static final MinecraftClient client = MinecraftClient.getInstance(); + private static final Minecraft minecraft = Minecraft.getInstance(); - private static final Identifier GRID_TEXTURE = new Identifier("clientcommands:textures/snake_grid.png"); + private static final ResourceLocation GRID_TEXTURE = new ResourceLocation("clientcommands:textures/snake_grid.png"); private static final Random random = new Random(); @@ -57,7 +57,7 @@ class SnakeGameScreen extends Screen { private Vector2i apple; SnakeGameScreen() { - super(Text.translatable("snakeGame.title")); + super(Component.translatable("snakeGame.title")); this.snake.add(new Vector2i(6, 8)); this.snake.add(new Vector2i(5, 8)); this.snake.add(new Vector2i(4, 8)); @@ -75,39 +75,39 @@ public void tick() { } @Override - public void render(DrawContext context, int mouseX, int mouseY, float delta) { - this.renderBackground(context, mouseX, mouseY, delta); - super.render(context, mouseX, mouseY, delta); + public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + this.renderBackground(graphics, mouseX, mouseY, delta); + super.render(graphics, mouseX, mouseY, delta); } @Override - public void renderBackground(DrawContext context, int mouseX, int mouseY, float delta) { - super.renderBackground(context, mouseX, mouseY, delta); + public void renderBackground(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + super.renderBackground(graphics, mouseX, mouseY, delta); int startX = (this.width - 289) / 2; int startY = (this.height - 289) / 2; - context.drawTextWithShadow(client.textRenderer, this.title, startX, startY - 10, 0xff_ffffff); - MutableText score = Text.translatable("snakeGame.score", this.snake.size()); - context.drawCenteredTextWithShadow(client.textRenderer, score, this.width / 2, startY - 10, 0xff_ffffff); + graphics.drawString(minecraft.font, this.title, startX, startY - 10, 0xff_ffffff); + MutableComponent score = Component.translatable("snakeGame.score", this.snake.size()); + graphics.drawCenteredString(minecraft.font, score, this.width / 2, startY - 10, 0xff_ffffff); - context.drawTexture(GRID_TEXTURE, startX, startY, 0, 0, 289, 289, 289, 289); + graphics.blit(GRID_TEXTURE, startX, startY, 0, 0, 289, 289, 289, 289); int scaleX = MAX_X + 1; int scaleY = MAX_Y + 1; - context.fill(startX + this.apple.x() * scaleX, startY + this.apple.y() * scaleY, startX + this.apple.x() * scaleX + scaleX, startY + this.apple.y() * scaleY + scaleY, 0xff_f52559); + graphics.fill(startX + this.apple.x() * scaleX, startY + this.apple.y() * scaleY, startX + this.apple.x() * scaleX + scaleX, startY + this.apple.y() * scaleY + scaleY, 0xff_f52559); for (Vector2i vec : this.snake) { - context.fill(startX + vec.x() * scaleX, startY + vec.y() * scaleY, startX + vec.x() * scaleX + scaleX, startY + vec.y() * scaleY + scaleY, 0xff_1f2df6); + graphics.fill(startX + vec.x() * scaleX, startY + vec.y() * scaleY, startX + vec.x() * scaleX + scaleX, startY + vec.y() * scaleY + scaleY, 0xff_1f2df6); } } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if (client.options.forwardKey.matchesKey(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_UP) { + if (minecraft.options.keyUp.matches(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_UP) { return this.setDirection(Direction.NORTH); - } else if (client.options.leftKey.matchesKey(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_LEFT) { + } else if (minecraft.options.keyLeft.matches(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_LEFT) { return this.setDirection(Direction.WEST); - } else if (client.options.backKey.matchesKey(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_DOWN) { + } else if (minecraft.options.keyDown.matches(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_DOWN) { return this.setDirection(Direction.SOUTH); - } else if (client.options.rightKey.matchesKey(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_RIGHT) { + } else if (minecraft.options.keyRight.matches(keyCode, scanCode) || keyCode == GLFW.GLFW_KEY_RIGHT) { return this.setDirection(Direction.EAST); } return super.keyPressed(keyCode, scanCode, modifiers); @@ -115,11 +115,11 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { private void move() { Vector2i head = this.snake.getFirst(); - this.snake.addFirst(new Vector2i(head.x() + this.direction.getOffsetX(), head.y() + this.direction.getOffsetZ())); + this.snake.addFirst(new Vector2i(head.x() + this.direction.getStepX(), head.y() + this.direction.getStepZ())); this.lastMoved = this.direction; if (this.checkGameOver()) { - client.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.ENTITY_OCELOT_DEATH, 1)); - this.close(); + minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.OCELOT_DEATH, 1)); + this.onClose(); return; } this.checkApple(); @@ -142,7 +142,7 @@ private boolean checkGameOver() { private void checkApple() { Vector2i head = this.snake.getFirst(); if (head.equals(this.apple)) { - client.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.ENTITY_GENERIC_EAT, 1)); + minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.GENERIC_EAT, 1)); do { this.apple = new Vector2i(random.nextInt(MAX_X + 1), random.nextInt(MAX_Y + 1)); } while (this.snake.contains(this.apple)); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/StartupCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/StartupCommand.java index 173a2fc54..a06a2acc3 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/StartupCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/StartupCommand.java @@ -7,8 +7,8 @@ import com.mojang.logging.LogUtils; import net.earthcomputer.clientcommands.features.ClientCommandFunctions; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.network.chat.Component; import org.slf4j.Logger; import java.io.IOException; @@ -22,8 +22,8 @@ public class StartupCommand { private static final Logger LOGGER = LogUtils.getLogger(); - private static final SimpleCommandExceptionType COULD_NOT_CREATE_FILE_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cstartup.couldNotCreateFile")); - private static final SimpleCommandExceptionType COULD_NOT_EDIT_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cstartup.couldNotEdit")); + private static final SimpleCommandExceptionType COULD_NOT_CREATE_FILE_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cstartup.couldNotCreateFile")); + private static final SimpleCommandExceptionType COULD_NOT_EDIT_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cstartup.couldNotEdit")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cstartup") @@ -56,7 +56,7 @@ private static int addStartupCommand(FabricClientCommandSource source, boolean g throw COULD_NOT_EDIT_EXCEPTION.create(); } - source.sendFeedback(Text.translatable("commands.cstartup.add.success")); + source.sendFeedback(Component.translatable("commands.cstartup.add.success")); return Command.SINGLE_SUCCESS; } @@ -68,7 +68,7 @@ private static int editStartupCommand(boolean global) throws CommandSyntaxExcept if (file == null) { throw COULD_NOT_CREATE_FILE_EXCEPTION.create(); } - Util.getOperatingSystem().open(file.toFile()); + Util.getPlatform().openFile(file.toFile()); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java index 04d6bfd17..27b59ad58 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java @@ -5,8 +5,8 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.earthcomputer.clientcommands.task.TaskManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; import java.util.ArrayList; import java.util.List; @@ -16,7 +16,7 @@ public class TaskCommand { - private static final SimpleCommandExceptionType NO_MATCH_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.ctask.stop.noMatch")); + private static final SimpleCommandExceptionType NO_MATCH_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.ctask.stop.noMatch")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ctask") @@ -34,11 +34,11 @@ private static int listTasks(FabricClientCommandSource source) { int taskCount = TaskManager.getTaskCount(); if (taskCount == 0) { - source.sendFeedback(Text.translatable("commands.ctask.list.noTasks")); + source.sendFeedback(Component.translatable("commands.ctask.list.noTasks")); } else { - source.sendFeedback(Text.translatable("commands.ctask.list.success", taskCount).formatted(Formatting.BOLD)); + source.sendFeedback(Component.translatable("commands.ctask.list.success", taskCount).withStyle(ChatFormatting.BOLD)); for (String task : tasks) { - source.sendFeedback(Text.literal("- " + task)); + source.sendFeedback(Component.literal("- " + task)); } } @@ -58,12 +58,12 @@ private static int stopTasks(FabricClientCommandSource source, String pattern) t if (tasksToStop.isEmpty()) { if (pattern.isEmpty()) { - source.sendFeedback(Text.translatable("commands.ctask.list.noTasks")); + source.sendFeedback(Component.translatable("commands.ctask.list.noTasks")); } else { throw NO_MATCH_EXCEPTION.create(); } } else { - source.sendFeedback(Text.translatable("commands.ctask.stop.success", tasksToStop.size())); + source.sendFeedback(Component.translatable("commands.ctask.stop.success", tasksToStop.size())); } return tasksToStop.size(); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/TooltipCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/TooltipCommand.java index 0eccdbd7f..b17260fab 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/TooltipCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/TooltipCommand.java @@ -2,10 +2,10 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.item.ItemStack; -import net.minecraft.text.Text; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; import java.util.List; @@ -17,23 +17,23 @@ public class TooltipCommand { private static final Flag FLAG_ADVANCED = Flag.ofFlag("advanced").build(); - public static void register(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { var ctooltip = dispatcher.register(literal("ctooltip") .then(literal("held") - .executes(ctx -> showTooltip(ctx.getSource(), ctx.getSource().getPlayer().getMainHandStack(), "held"))) + .executes(ctx -> showTooltip(ctx.getSource(), ctx.getSource().getPlayer().getMainHandItem(), "held"))) .then(literal("stack") - .then(argument("stack", itemStack(registryAccess)) - .executes(ctx -> showTooltip(ctx.getSource(), getCItemStackArgument(ctx, "stack").createStack(1, false), "stack"))))); + .then(argument("stack", itemStack(context)) + .executes(ctx -> showTooltip(ctx.getSource(), getCItemStackArgument(ctx, "stack").createItemStack(1, false), "stack"))))); FLAG_ADVANCED.addToCommand(dispatcher, ctooltip, ctx -> true); } private static int showTooltip(FabricClientCommandSource source, ItemStack stack, String type) { - source.sendFeedback(Text.translatable("commands.ctooltip.header." + type)); + source.sendFeedback(Component.translatable("commands.ctooltip.header." + type)); - TooltipContext context = getFlag(source, FLAG_ADVANCED) ? TooltipContext.ADVANCED : TooltipContext.BASIC; + TooltipFlag context = getFlag(source, FLAG_ADVANCED) ? TooltipFlag.ADVANCED : TooltipFlag.NORMAL; - List tooltip = stack.getTooltip(source.getPlayer(), context); - for (Text line : tooltip) { + List tooltip = stack.getTooltipLines(source.getPlayer(), context); + for (Component line : tooltip) { source.sendFeedback(line); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/TranslateCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/TranslateCommand.java index f271daa89..1644ea742 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/TranslateCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/TranslateCommand.java @@ -8,9 +8,9 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.earthcomputer.clientcommands.command.arguments.TranslationQueryArgumentType; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.ClickEvent; -import net.minecraft.text.HoverEvent; -import net.minecraft.text.Text; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; import org.apache.http.client.utils.URIBuilder; import java.net.URI; @@ -26,7 +26,7 @@ public class TranslateCommand { - private static final SimpleCommandExceptionType UNKNOWN_ERROR_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.ctranslate.unknownError")); + private static final SimpleCommandExceptionType UNKNOWN_ERROR_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.ctranslate.unknownError")); private static final String URL = "https://translate.googleapis.com/translate_a/single?client=gtx&dt=t"; @@ -48,7 +48,7 @@ private static int translate(FabricClientCommandSource source, TranslationQueryA .build(); httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) - .thenAccept(response -> source.getClient().send(() -> { + .thenAccept(response -> source.getClient().tell(() -> { JsonArray result = JsonParser.parseString(response).getAsJsonArray(); source.sendFeedback(createText(result.get(0).getAsJsonArray().get(0).getAsJsonArray().get(0).getAsString())); })); @@ -66,12 +66,12 @@ private static URI createUri(String from, String to, String query) throws URISyn return builder.build(); } - private static Text createText(String translation) { - return Text.literal(translation).styled(s -> s - .withUnderline(true) + private static Component createText(String translation) { + return Component.literal(translation).withStyle(s -> s + .withUnderlined(true) .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, translation)) .withInsertion(translation) - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.translatable("commands.ctranslate.hoverText"))) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("commands.ctranslate.hoverText"))) ); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java index 6f42f350b..e78942c59 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java @@ -6,10 +6,10 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.tree.CommandNode; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.command.CommandSource; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.network.chat.Component; import java.util.ArrayList; import java.util.List; @@ -21,7 +21,7 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class UsageTreeCommand { - private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.help.failed")); + private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.help.failed")); @SuppressWarnings("unchecked") private static final Flag>> FLAG_DISPATCHER = @@ -35,7 +35,7 @@ public static void register(CommandDispatcher dispatc .then( argument("command", greedyString()) .suggests((ctx, builder) -> - CommandSource.suggestMatching(getFlag(ctx, FLAG_DISPATCHER).apply(dispatcher).getRoot() + SharedSuggestionProvider.suggest(getFlag(ctx, FLAG_DISPATCHER).apply(dispatcher).getRoot() .getChildren() .stream() .map(CommandNode::getUsageText) @@ -44,12 +44,12 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> usageCommand(ctx.getSource(), getString(ctx, "command"), getFlag(ctx, FLAG_DISPATCHER).apply(dispatcher))) ) ); - FLAG_DISPATCHER.addToCommand(dispatcher, cusagetree, ctx -> d -> (CommandDispatcher) (CommandDispatcher) Objects.requireNonNull(MinecraftClient.getInstance().getNetworkHandler()).getCommandDispatcher()); + FLAG_DISPATCHER.addToCommand(dispatcher, cusagetree, ctx -> d -> (CommandDispatcher) (CommandDispatcher) Objects.requireNonNull(Minecraft.getInstance().getConnection()).getCommands()); } private static int usage(FabricClientCommandSource source, CommandDispatcher dispatcher) { var content = tree(dispatcher.getRoot()); - source.sendFeedback(Text.literal("/")); + source.sendFeedback(Component.literal("/")); for (var line : content) { source.sendFeedback(line); } @@ -63,30 +63,30 @@ private static int usageCommand(FabricClientCommandSource source, String cmdName } var node = Iterables.getLast(parseResults.getContext().getNodes()).getNode(); var content = tree(node); - source.sendFeedback(Text.literal("/" + cmdName).styled(s -> s.withColor(node.getCommand() != null ? Formatting.GREEN : Formatting.WHITE))); + source.sendFeedback(Component.literal("/" + cmdName).withStyle(s -> s.withColor(node.getCommand() != null ? ChatFormatting.GREEN : ChatFormatting.WHITE))); for (var line : content) { source.sendFeedback(line); } return content.size(); } - private static List tree(CommandNode root) { - List lines = new ArrayList<>(); + private static List tree(CommandNode root) { + List lines = new ArrayList<>(); var children = List.copyOf(root.getChildren()); for (int i = 0; i < children.size(); i++) { var child = children.get(i); - var childName = Text.literal(child.getUsageText()).styled(s -> - s.withColor(child.getCommand() != null ? Formatting.GREEN : Formatting.WHITE) + var childName = Component.literal(child.getUsageText()).withStyle(s -> + s.withColor(child.getCommand() != null ? ChatFormatting.GREEN : ChatFormatting.WHITE) ); var childLines = tree(child); if (i + 1 < children.size()) { - lines.add(Text.literal("├─ ").styled(s -> s.withColor(Formatting.GRAY)).append(childName)); + lines.add(Component.literal("├─ ").withStyle(s -> s.withColor(ChatFormatting.GRAY)).append(childName)); lines.addAll(childLines.stream() - .map(line -> Text.literal("│ ").styled(s -> s.withColor(Formatting.GRAY)).append(line)) + .map(line -> Component.literal("│ ").withStyle(s -> s.withColor(ChatFormatting.GRAY)).append(line)) .toList()); } else { - lines.add(Text.literal("└─ ").styled(s -> s.withColor(Formatting.GRAY)).append(childName)); - lines.addAll(childLines.stream().map(line -> Text.literal(" ").append(line)).toList()); + lines.add(Component.literal("└─ ").withStyle(s -> s.withColor(ChatFormatting.GRAY)).append(childName)); + lines.addAll(childLines.stream().map(line -> Component.literal(" ").append(line)).toList()); } } return lines; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java index 0166f6b0a..19fd770e5 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java @@ -3,11 +3,11 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.text.ClickEvent; -import net.minecraft.text.HoverEvent; -import net.minecraft.text.Text; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.HoverEvent; import java.util.UUID; @@ -24,22 +24,22 @@ public static void register(CommandDispatcher dispatc private static int getUuid(FabricClientCommandSource source, UUID entity) { String uuid = entity.toString(); - Text uuidText = Text.literal(uuid).styled(style -> style - .withUnderline(true) - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.translatable("chat.copy.click"))) + Component uuidComponent = Component.literal(uuid).withStyle(style -> style + .withUnderlined(true) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("chat.copy.click"))) .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, uuid)) ); - ClientPlayNetworkHandler networkHandler = source.getClient().getNetworkHandler(); - assert networkHandler != null; + ClientPacketListener packetListener = source.getClient().getConnection(); + assert packetListener != null; - PlayerListEntry player = networkHandler.getPlayerListEntry(entity); + PlayerInfo player = packetListener.getPlayerInfo(entity); if (player == null) { - source.sendFeedback(Text.translatable("commands.cuuid.success.nameless", uuidText)); + source.sendFeedback(Component.translatable("commands.cuuid.success.nameless", uuidComponent)); return Command.SINGLE_SUCCESS; } String name = player.getProfile().getName(); - source.sendFeedback(Text.translatable("commands.cuuid.success", name, uuidText)); + source.sendFeedback(Component.translatable("commands.cuuid.success", name, uuidComponent)); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/VarCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/VarCommand.java index 14ca40c14..3378a71f9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/VarCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/VarCommand.java @@ -8,10 +8,10 @@ import com.mojang.logging.LogUtils; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.Util; +import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; -import net.minecraft.text.Text; -import net.minecraft.util.Util; +import net.minecraft.network.chat.Component; import org.slf4j.Logger; import java.io.File; @@ -24,7 +24,7 @@ import static com.mojang.brigadier.arguments.StringArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; -import static net.minecraft.command.CommandSource.*; +import static net.minecraft.commands.SharedSuggestionProvider.*; public class VarCommand { @@ -32,9 +32,9 @@ public class VarCommand { private static final Logger LOGGER = LogUtils.getLogger(); - private static final SimpleCommandExceptionType SAVE_FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cvar.saveFile.failed")); - private static final DynamicCommandExceptionType ALREADY_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.cvar.add.alreadyExists", arg)); - private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Text.translatable("commands.cvar.notFound", arg)); + private static final SimpleCommandExceptionType SAVE_FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cvar.saveFile.failed")); + private static final DynamicCommandExceptionType ALREADY_EXISTS_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.cvar.add.alreadyExists", arg)); + private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(arg -> Component.translatable("commands.cvar.notFound", arg)); private static final Path configPath = FabricLoader.getInstance().getConfigDir().resolve("clientcommands"); @@ -56,16 +56,16 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> addVariable(ctx.getSource(), getString(ctx, "variable"), getString(ctx, "value")))))) .then(literal("remove") .then(argument("variable", word()) - .suggests((ctx, builder) -> suggestMatching(variables.keySet(), builder)) + .suggests((ctx, builder) -> suggest(variables.keySet(), builder)) .executes(ctx -> removeVariable(ctx.getSource(), getString(ctx, "variable"))))) .then(literal("edit") .then(argument("variable", word()) - .suggests((ctx, builder) -> suggestMatching(variables.keySet(), builder)) + .suggests((ctx, builder) -> suggest(variables.keySet(), builder)) .then(argument("value", greedyString()) .executes(ctx -> editVariable(ctx.getSource(), getString(ctx, "variable"), getString(ctx, "value")))))) .then(literal("parse") .then(argument("variable", word()) - .suggests((ctx, builder) -> suggestMatching(variables.keySet(), builder)) + .suggests((ctx, builder) -> suggest(variables.keySet(), builder)) .executes(ctx -> parseVariable(ctx.getSource(), getString(ctx, "variable"))))) .then(literal("list") .executes(ctx -> listVariables(ctx.getSource())))); @@ -77,7 +77,7 @@ private static int addVariable(FabricClientCommandSource source, String variable } variables.put(variable, value); saveFile(); - source.sendFeedback(Text.translatable("commands.cvar.add.success", variable)); + source.sendFeedback(Component.translatable("commands.cvar.add.success", variable)); return Command.SINGLE_SUCCESS; } @@ -86,7 +86,7 @@ private static int removeVariable(FabricClientCommandSource source, String varia throw NOT_FOUND_EXCEPTION.create(variable); } saveFile(); - source.sendFeedback(Text.translatable("commands.cvar.remove.success", variable)); + source.sendFeedback(Component.translatable("commands.cvar.remove.success", variable)); return Command.SINGLE_SUCCESS; } @@ -96,7 +96,7 @@ private static int editVariable(FabricClientCommandSource source, String variabl } variables.put(variable, value); saveFile(); - source.sendFeedback(Text.translatable("commands.cvar.edit.success", variable)); + source.sendFeedback(Component.translatable("commands.cvar.edit.success", variable)); return Command.SINGLE_SUCCESS; } @@ -105,29 +105,29 @@ private static int parseVariable(FabricClientCommandSource source, String variab if (value == null) { throw NOT_FOUND_EXCEPTION.create(variable); } - source.sendFeedback(Text.translatable("commands.cvar.parse.success", variable, value)); + source.sendFeedback(Component.translatable("commands.cvar.parse.success", variable, value)); return Command.SINGLE_SUCCESS; } private static int listVariables(FabricClientCommandSource source) { if (variables.isEmpty()) { - source.sendFeedback(Text.translatable("commands.cvar.list.empty")); + source.sendFeedback(Component.translatable("commands.cvar.list.empty")); } else { String list = "%" + String.join("%, %", variables.keySet()) + "%"; - source.sendFeedback(Text.translatable("commands.cvar.list", list)); + source.sendFeedback(Component.translatable("commands.cvar.list", list)); } return variables.size(); } private static void saveFile() throws CommandSyntaxException { try { - NbtCompound rootTag = new NbtCompound(); + CompoundTag rootTag = new CompoundTag(); variables.forEach(rootTag::putString); Path newFile = File.createTempFile("vars", ".dat", configPath.toFile()).toPath(); NbtIo.write(rootTag, newFile); Path backupFile = configPath.resolve("vars.dat_old"); Path currentFile = configPath.resolve("vars.dat"); - Util.backupAndReplace(currentFile, newFile, backupFile); + Util.safeReplaceFile(currentFile, newFile, backupFile); } catch (IOException e) { throw SAVE_FAILED_EXCEPTION.create(); } @@ -135,11 +135,11 @@ private static void saveFile() throws CommandSyntaxException { private static void loadFile() throws IOException { variables.clear(); - NbtCompound rootTag = NbtIo.read(configPath.resolve("vars.dat")); + CompoundTag rootTag = NbtIo.read(configPath.resolve("vars.dat")); if (rootTag == null) { return; } - rootTag.getKeys().forEach(key -> variables.put(key, rootTag.getString(key))); + rootTag.getAllKeys().forEach(key -> variables.put(key, rootTag.getString(key))); } public static String replaceVariables(String originalString) { diff --git a/src/main/java/net/earthcomputer/clientcommands/command/WeatherCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/WeatherCommand.java index c9965b3b8..993b18bf2 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/WeatherCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/WeatherCommand.java @@ -2,10 +2,9 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - import net.earthcomputer.clientcommands.features.ClientWeather; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; @@ -23,7 +22,7 @@ public static void register(CommandDispatcher dispatc private static int executeWeatherClear(FabricClientCommandSource source) { ClientWeather.setRain(0); ClientWeather.setThunder(0); - Text feedback = Text.translatable("commands.weather.set.clear"); + Component feedback = Component.translatable("commands.weather.set.clear"); source.sendFeedback(feedback); return Command.SINGLE_SUCCESS; } @@ -31,7 +30,7 @@ private static int executeWeatherClear(FabricClientCommandSource source) { private static int executeWeatherRain(FabricClientCommandSource source) { ClientWeather.setRain(1); ClientWeather.setThunder(0); - Text feedback = Text.translatable("commands.weather.set.rain"); + Component feedback = Component.translatable("commands.weather.set.rain"); source.sendFeedback(feedback); return Command.SINGLE_SUCCESS; } @@ -39,7 +38,7 @@ private static int executeWeatherRain(FabricClientCommandSource source) { private static int executeWeatherThunder(FabricClientCommandSource source) { ClientWeather.setRain(1); ClientWeather.setThunder(1); - Text feedback = Text.translatable("commands.weather.set.thunder"); + Component feedback = Component.translatable("commands.weather.set.thunder"); source.sendFeedback(feedback); return Command.SINGLE_SUCCESS; } @@ -47,7 +46,7 @@ private static int executeWeatherThunder(FabricClientCommandSource source) { private static int executeWeatherReset(FabricClientCommandSource source) { ClientWeather.setRain(-1); ClientWeather.setThunder(-1); - Text feedback = Text.translatable("commands.cweather.reset"); + Component feedback = Component.translatable("commands.cweather.reset"); source.sendFeedback(feedback); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/WhisperEncryptedCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/WhisperEncryptedCommand.java index 5218063c0..defd880ef 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/WhisperEncryptedCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/WhisperEncryptedCommand.java @@ -8,10 +8,10 @@ import net.earthcomputer.clientcommands.c2c.CCNetworkHandler; import net.earthcomputer.clientcommands.c2c.packets.MessageC2CPacket; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; import java.util.Collection; @@ -21,7 +21,7 @@ public class WhisperEncryptedCommand { - private static final SimpleCommandExceptionType PLAYER_NOT_FOUND_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cwe.playerNotFound")); + private static final SimpleCommandExceptionType PLAYER_NOT_FOUND_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cwe.playerNotFound")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cwe") @@ -31,24 +31,24 @@ public static void register(CommandDispatcher dispatc } private static int whisper(FabricClientCommandSource source, Collection profiles, String message) throws CommandSyntaxException { - assert source.getClient().getNetworkHandler() != null; + assert source.getClient().getConnection() != null; if (profiles.size() != 1) { throw PLAYER_NOT_FOUND_EXCEPTION.create(); } - PlayerListEntry recipient = source.getClient().getNetworkHandler().getPlayerList().stream() + PlayerInfo recipient = source.getClient().getConnection().getOnlinePlayers().stream() .filter(p -> p.getProfile().getName().equalsIgnoreCase(profiles.iterator().next().getName())) .findFirst() .orElseThrow(PLAYER_NOT_FOUND_EXCEPTION::create); - MessageC2CPacket packet = new MessageC2CPacket(source.getClient().getNetworkHandler().getProfile().getName(), message); + MessageC2CPacket packet = new MessageC2CPacket(source.getClient().getConnection().getLocalGameProfile().getName(), message); CCNetworkHandler.getInstance().sendPacket(packet, recipient); - MutableText prefix = Text.empty(); - prefix.append(Text.literal("[").formatted(Formatting.DARK_GRAY)); - prefix.append(Text.literal("/cwe").formatted(Formatting.AQUA)); - prefix.append(Text.literal("]").formatted(Formatting.DARK_GRAY)); - prefix.append(Text.literal(" ")); - Text text = prefix.append(Text.translatable("ccpacket.messageC2CPacket.outgoing", recipient.getProfile().getName(), message).formatted(Formatting.GRAY)); - source.sendFeedback(text); + MutableComponent prefix = Component.empty(); + prefix.append(Component.literal("[").withStyle(ChatFormatting.DARK_GRAY)); + prefix.append(Component.literal("/cwe").withStyle(ChatFormatting.AQUA)); + prefix.append(Component.literal("]").withStyle(ChatFormatting.DARK_GRAY)); + prefix.append(Component.literal(" ")); + Component component = prefix.append(Component.translatable("ccpacket.messageC2CPacket.outgoing", recipient.getProfile().getName(), message).withStyle(ChatFormatting.GRAY)); + source.sendFeedback(component); return Command.SINGLE_SUCCESS; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java index 4e8d75e0d..5d6df37e9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java @@ -5,13 +5,13 @@ import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.earthcomputer.clientcommands.features.WikiRetriever; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; import static com.mojang.brigadier.arguments.StringArgumentType.*; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.*; public class WikiCommand { - private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Text.translatable("commands.cwiki.failed")); + private static final SimpleCommandExceptionType FAILED_EXCEPTION = new SimpleCommandExceptionType(Component.translatable("commands.cwiki.failed")); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cwiki") @@ -28,7 +28,7 @@ private static int displayWikiPage(FabricClientCommandSource source, String page content = content.trim(); for (String line : content.split("\n")) { - source.sendFeedback(Text.literal(line)); + source.sendFeedback(Component.literal(line)); } return content.length(); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientBlockPredicateArgumentType.java b/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientBlockPredicateArgumentType.java index ae6285dff..ed367c522 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientBlockPredicateArgumentType.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientBlockPredicateArgumentType.java @@ -8,19 +8,19 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.datafixers.util.Either; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.command.argument.BlockArgumentParser; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtHelper; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.RegistryWrapper; -import net.minecraft.registry.entry.RegistryEntryList; -import net.minecraft.state.property.Property; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; import org.apache.commons.lang3.tuple.Pair; import java.util.ArrayList; @@ -33,16 +33,16 @@ import java.util.function.Predicate; public class ClientBlockPredicateArgumentType implements ArgumentType { - private final RegistryWrapper registryWrapper; + private final HolderLookup holderLookup; private boolean allowNbt = true; private boolean allowTags = true; - private ClientBlockPredicateArgumentType(CommandRegistryAccess registryAccess) { - registryWrapper = registryAccess.createWrapper(RegistryKeys.BLOCK); + private ClientBlockPredicateArgumentType(CommandBuildContext context) { + holderLookup = context.holderLookup(Registries.BLOCK); } - public static ClientBlockPredicateArgumentType blockPredicate(CommandRegistryAccess registryAccess) { - return new ClientBlockPredicateArgumentType(registryAccess); + public static ClientBlockPredicateArgumentType blockPredicate(CommandBuildContext context) { + return new ClientBlockPredicateArgumentType(context); } public ClientBlockPredicateArgumentType disallowNbt() { @@ -57,13 +57,13 @@ public ClientBlockPredicateArgumentType disallowTags() { @Override public ParseResult parse(StringReader stringReader) throws CommandSyntaxException { - var result = BlockArgumentParser.blockOrTag(registryWrapper, stringReader, allowNbt); - return new ParseResult(result, registryWrapper); + var result = BlockStateParser.parseForTesting(holderLookup, stringReader, allowNbt); + return new ParseResult(result, holderLookup); } @Override public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { - return BlockArgumentParser.getSuggestions(registryWrapper, builder, allowTags, allowNbt); + return BlockStateParser.fillSuggestions(holderLookup, builder, allowTags, allowNbt); } public static ClientBlockPredicate getBlockPredicate(CommandContext context, String arg) throws CommandSyntaxException { @@ -72,19 +72,19 @@ public static ClientBlockPredicate getBlockPredicate(CommandContext predicate = getPredicateForListWithoutNbt(Collections.singletonList(result.result)); - NbtCompound nbtData = result.result.map(BlockArgumentParser.BlockResult::nbt, BlockArgumentParser.TagResult::nbt); + CompoundTag nbtData = result.result.map(BlockStateParser.BlockResult::nbt, BlockStateParser.TagResult::nbt); if (nbtData == null) { return ClientBlockPredicate.simple(predicate); } return new ClientBlockPredicate() { @Override - public boolean test(BlockView blockView, BlockPos pos) { - if (!predicate.test(blockView.getBlockState(pos))) { + public boolean test(BlockGetter blockGetter, BlockPos pos) { + if (!predicate.test(blockGetter.getBlockState(pos))) { return false; } - BlockEntity be = blockView.getBlockEntity(pos); - return be != null && NbtHelper.matches(nbtData, be.createNbt(), true); + BlockEntity be = blockGetter.getBlockEntity(pos); + return be != null && NbtUtils.compareNbt(nbtData, be.saveWithoutMetadata(), true); } @Override @@ -98,10 +98,10 @@ public static ClientBlockPredicate getBlockPredicateList(CommandContext results = ListArgumentType.getList(context, arg); Predicate predicate = getPredicateForListWithoutNbt(results.stream().map(ParseResult::result).toList()); - List, NbtCompound>> nbtPredicates = new ArrayList<>(results.size()); + List, CompoundTag>> nbtPredicates = new ArrayList<>(results.size()); boolean nbtSensitive = false; for (ParseResult result : results) { - NbtCompound nbtData = result.result.map(BlockArgumentParser.BlockResult::nbt, BlockArgumentParser.TagResult::nbt); + CompoundTag nbtData = result.result.map(BlockStateParser.BlockResult::nbt, BlockStateParser.TagResult::nbt); if (nbtData != null) { nbtSensitive = true; } @@ -117,28 +117,28 @@ public static ClientBlockPredicate getBlockPredicateList(CommandContext, NbtCompound> nbtPredicate : nbtPredicates) { + CompoundTag actualNbt = null; + for (Pair, CompoundTag> nbtPredicate : nbtPredicates) { if (nbtPredicate.getLeft().test(state)) { - NbtCompound nbt = nbtPredicate.getRight(); + CompoundTag nbt = nbtPredicate.getRight(); if (nbt == null) { return true; } if (actualNbt == null) { - BlockEntity be = blockView.getBlockEntity(pos); + BlockEntity be = blockGetter.getBlockEntity(pos); if (be == null) { // from this point we would always require a block entity return false; } - actualNbt = be.createNbt(); + actualNbt = be.saveWithoutMetadata(); } - if (NbtHelper.matches(nbt, actualNbt, true)) { + if (NbtUtils.compareNbt(nbt, actualNbt, true)) { return true; } } @@ -154,7 +154,7 @@ public boolean canEverMatch(BlockState state) { }; } - private static Predicate getPredicateForListWithoutNbt(List> results) throws CommandSyntaxException { + private static Predicate getPredicateForListWithoutNbt(List> results) throws CommandSyntaxException { List> predicates = new ArrayList<>(results.size()); for (var result : results) { predicates.add(getPredicateWithoutNbt(result)); @@ -163,7 +163,7 @@ private static Predicate getPredicateForListWithoutNbt(List predicate : predicates) { if (predicate.test(state)) { mask.set(id); @@ -172,19 +172,19 @@ private static Predicate getPredicateForListWithoutNbt(List mask.get(Block.STATE_IDS.getRawId(blockState)); + return blockState -> mask.get(Block.BLOCK_STATE_REGISTRY.getId(blockState)); } - private static Predicate getPredicateWithoutNbt(Either result) throws CommandSyntaxException { + private static Predicate getPredicateWithoutNbt(Either result) throws CommandSyntaxException { return result.map( blockResult -> { Map, Comparable> props = blockResult.properties(); return state -> { - if (!state.isOf(blockResult.blockState().getBlock())) { + if (!state.is(blockResult.blockState().getBlock())) { return false; } for (Map.Entry, Comparable> entry : props.entrySet()) { - if (state.get(entry.getKey()) != entry.getValue()) { + if (state.getValue(entry.getKey()) != entry.getValue()) { return false; } } @@ -192,23 +192,23 @@ private static Predicate getPredicateWithoutNbt(Either { - RegistryEntryList myTag = tagResult.tag(); + HolderSet myTag = tagResult.tag(); Map props = tagResult.vagueProperties(); return state -> { - if (!state.isIn(myTag)) { + if (!state.is(myTag)) { return false; } for (Map.Entry entry : props.entrySet()) { - Property prop = state.getBlock().getStateManager().getProperty(entry.getKey()); + Property prop = state.getBlock().getStateDefinition().getProperty(entry.getKey()); if (prop == null) { return false; } - Comparable expectedValue = prop.parse(entry.getValue()).orElse(null); + Comparable expectedValue = prop.getValue(entry.getValue()).orElse(null); if (expectedValue == null) { return false; } - if (state.get(prop) != expectedValue) { + if (state.getValue(prop) != expectedValue) { return false; } } @@ -219,20 +219,20 @@ private static Predicate getPredicateWithoutNbt(Either result, - RegistryWrapper registryWrapper + Either result, + HolderLookup holderLookup ) { } public interface ClientBlockPredicate { - boolean test(BlockView blockView, BlockPos pos); + boolean test(BlockGetter blockGetter, BlockPos pos); boolean canEverMatch(BlockState state); static ClientBlockPredicate simple(Predicate delegate) { return new ClientBlockPredicate() { @Override - public boolean test(BlockView blockView, BlockPos pos) { - return delegate.test(blockView.getBlockState(pos)); + public boolean test(BlockGetter blockGetter, BlockPos pos) { + return delegate.test(blockGetter.getBlockState(pos)); } @Override diff --git a/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientItemPredicateArgumentType.java b/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientItemPredicateArgumentType.java index b772c1f1b..1eb005bcd 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientItemPredicateArgumentType.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/arguments/ClientItemPredicateArgumentType.java @@ -7,19 +7,19 @@ import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.command.CommandRegistryAccess; -import net.minecraft.command.argument.ItemPredicateArgumentType; -import net.minecraft.command.argument.ItemStringReader; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtHelper; -import net.minecraft.registry.Registries; -import net.minecraft.registry.RegistryKeys; -import net.minecraft.registry.RegistryWrapper; -import net.minecraft.registry.entry.RegistryEntry; -import net.minecraft.registry.entry.RegistryEntryList; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.arguments.item.ItemParser; +import net.minecraft.commands.arguments.item.ItemPredicateArgument; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import java.util.Arrays; import java.util.Collection; @@ -29,22 +29,22 @@ public class ClientItemPredicateArgumentType implements ArgumentType { - private final RegistryWrapper registryWrapper; + private final HolderLookup holderLookup; - private ClientItemPredicateArgumentType(CommandRegistryAccess registryAccess) { - registryWrapper = registryAccess.createWrapper(RegistryKeys.ITEM); + private ClientItemPredicateArgumentType(CommandBuildContext context) { + holderLookup = context.holderLookup(Registries.ITEM); } /** - * @deprecated Use {@link #clientItemPredicate(CommandRegistryAccess)} instead + * @deprecated Use {@link #clientItemPredicate(CommandBuildContext)} instead */ @Deprecated - public static ItemPredicateArgumentType itemPredicate(CommandRegistryAccess registryAccess) { - return ItemPredicateArgumentType.itemPredicate(registryAccess); + public static ItemPredicateArgument itemPredicate(CommandBuildContext context) { + return ItemPredicateArgument.itemPredicate(context); } - public static ClientItemPredicateArgumentType clientItemPredicate(CommandRegistryAccess registryAccess) { - return new ClientItemPredicateArgumentType(registryAccess); + public static ClientItemPredicateArgumentType clientItemPredicate(CommandBuildContext context) { + return new ClientItemPredicateArgumentType(context); } public static ClientItemPredicate getClientItemPredicate(CommandContext ctx, String name) { @@ -54,7 +54,7 @@ public static ClientItemPredicate getClientItemPredicate(CommandContext new ItemPredicate(itemResult.item(), itemResult.nbt()), tagResult -> new TagPredicate(reader.getString().substring(start, reader.getCursor()), tagResult.tag(), tagResult.nbt()) @@ -63,7 +63,7 @@ public ClientItemPredicate parse(StringReader reader) throws CommandSyntaxExcept @Override public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { - return ItemStringReader.getSuggestions(registryWrapper, builder, true); + return ItemParser.fillSuggestions(holderLookup, builder, true); } public sealed interface ClientItemPredicate extends Predicate { @@ -71,15 +71,15 @@ public sealed interface ClientItemPredicate extends Predicate { Collection getPossibleItems(); } - record TagPredicate(String id, RegistryEntryList tag, NbtCompound compound) implements ClientItemPredicate { + record TagPredicate(String id, HolderSet tag, CompoundTag compound) implements ClientItemPredicate { @Override public boolean test(ItemStack stack) { - return tag.contains(stack.getRegistryEntry()) && NbtHelper.matches(this.compound, stack.getNbt(), true); + return tag.contains(stack.getItemHolder()) && NbtUtils.compareNbt(this.compound, stack.getTag(), true); } @Override public Collection getPossibleItems() { - return tag.stream().map(RegistryEntry::value).toList(); + return tag.stream().map(Holder::value).toList(); } @Override @@ -92,10 +92,10 @@ public String getPrettyString() { } } - record ItemPredicate(RegistryEntry item, NbtCompound compound) implements ClientItemPredicate { + record ItemPredicate(Holder item, CompoundTag compound) implements ClientItemPredicate { @Override public boolean test(ItemStack stack) { - return stack.itemMatches(item) && NbtHelper.matches(this.compound, stack.getNbt(), true); + return stack.is(item) && NbtUtils.compareNbt(this.compound, stack.getTag(), true); } @Override @@ -105,7 +105,7 @@ public Collection getPossibleItems() { @Override public String getPrettyString() { - String ret = String.valueOf(Registries.ITEM.getId(item.value())); + String ret = String.valueOf(BuiltInRegistries.ITEM.getKey(item.value())); if (compound != null) { ret += compound; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/arguments/EntityUUIDArgumentType.java b/src/main/java/net/earthcomputer/clientcommands/command/arguments/EntityUUIDArgumentType.java index 6d311ad9a..567f4d110 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/arguments/EntityUUIDArgumentType.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/arguments/EntityUUIDArgumentType.java @@ -11,8 +11,8 @@ import dev.xpple.clientarguments.arguments.CEntitySelector; import dev.xpple.clientarguments.arguments.CEntitySelectorReader; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.command.CommandSource; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.commands.SharedSuggestionProvider; import java.util.Arrays; import java.util.Collection; @@ -55,7 +55,7 @@ public EntityUUIDArgument parse(StringReader reader) throws CommandSyntaxExcepti @Override public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { - if (context.getSource() instanceof CommandSource commandSource) { + if (context.getSource() instanceof SharedSuggestionProvider commandSource) { StringReader stringReader = new StringReader(builder.getInput()); stringReader.setCursor(builder.getStart()); CEntitySelectorReader entitySelectorReader = new CEntitySelectorReader(stringReader, true); @@ -66,9 +66,9 @@ public CompletableFuture listSuggestions(CommandContext cont } return entitySelectorReader.listSuggestions(builder, (builderx) -> { - Collection collection = commandSource.getPlayerNames(); - Iterable iterable = Iterables.concat(collection, commandSource.getEntitySuggestions()); - CommandSource.suggestMatching(iterable, builderx); + Collection collection = commandSource.getOnlinePlayerNames(); + Iterable iterable = Iterables.concat(collection, commandSource.getSelectedEntities()); + SharedSuggestionProvider.suggest(iterable, builderx); }); } return Suggestions.empty(); @@ -86,7 +86,7 @@ sealed interface EntityUUIDArgument { private record NameBacked(String name) implements EntityUUIDArgument { @Override public UUID getUUID(FabricClientCommandSource source) throws CommandSyntaxException { - PlayerListEntry entry = source.getClient().getNetworkHandler().getPlayerListEntry(name); + PlayerInfo entry = source.getClient().getConnection().getPlayerInfo(name); if (entry == null) { throw CEntityArgumentType.ENTITY_NOT_FOUND_EXCEPTION.create(); } @@ -104,7 +104,7 @@ public UUID getUUID(FabricClientCommandSource source) { private record SelectorBacked(CEntitySelector selector) implements EntityUUIDArgument { @Override public UUID getUUID(FabricClientCommandSource source) throws CommandSyntaxException { - return selector.getEntity(source).getUuid(); + return selector.getEntity(source).getUUID(); } } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/arguments/ExpressionArgumentType.java b/src/main/java/net/earthcomputer/clientcommands/command/arguments/ExpressionArgumentType.java index b24ae4852..af2c7cbb9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/arguments/ExpressionArgumentType.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/arguments/ExpressionArgumentType.java @@ -11,14 +11,19 @@ import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.earthcomputer.clientcommands.Configs; -import net.earthcomputer.clientcommands.mixin.ChatInputSuggestorAccessor; +import net.earthcomputer.clientcommands.mixin.CommandSuggestionsAccessor; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.command.CommandSource; -import net.minecraft.text.MutableText; -import net.minecraft.text.Style; -import net.minecraft.text.Text; - -import java.util.*; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.DoubleBinaryOperator; @@ -28,9 +33,9 @@ public class ExpressionArgumentType implements ArgumentType EXAMPLES = Arrays.asList("123", "ans", "(1+2)", "1*3"); - private static final DynamicCommandExceptionType EXPECTED_EXCEPTION = new DynamicCommandExceptionType(obj -> Text.translatable("commands.ccalc.expected", obj)); - private static final Dynamic2CommandExceptionType INVALID_ARGUMENT_COUNT = new Dynamic2CommandExceptionType((func, count) -> Text.translatable("commands.ccalc.invalidArgumentCount", func, count)); - private static final SimpleCommandExceptionType TOO_DEEPLY_NESTED = new SimpleCommandExceptionType(Text.translatable("commands.ccalc.tooDeeplyNested")); + private static final DynamicCommandExceptionType EXPECTED_EXCEPTION = new DynamicCommandExceptionType(obj -> Component.translatable("commands.ccalc.expected", obj)); + private static final Dynamic2CommandExceptionType INVALID_ARGUMENT_COUNT = new Dynamic2CommandExceptionType((func, count) -> Component.translatable("commands.ccalc.invalidArgumentCount", func, count)); + private static final SimpleCommandExceptionType TOO_DEEPLY_NESTED = new SimpleCommandExceptionType(Component.translatable("commands.ccalc.tooDeeplyNested")); private ExpressionArgumentType() {} @@ -190,8 +195,8 @@ private Expression parseConstantOrFunction() throws CommandSyntaxException { int cursor = reader.getCursor(); suggestor = builder -> { SuggestionsBuilder newBuilder = builder.createOffset(cursor); - CommandSource.suggestMatching(ConstantExpression.CONSTANTS.keySet(), newBuilder); - CommandSource.suggestMatching(FunctionExpression.FUNCTIONS.keySet(), newBuilder); + SharedSuggestionProvider.suggest(ConstantExpression.CONSTANTS.keySet(), newBuilder); + SharedSuggestionProvider.suggest(FunctionExpression.FUNCTIONS.keySet(), newBuilder); builder.add(newBuilder); }; @@ -291,10 +296,10 @@ private static boolean isAllowedNumber(char c) { public static abstract class Expression { public String strVal; public abstract double eval() throws StackOverflowError; - public abstract Text getParsedTree(int depth) throws StackOverflowError; + public abstract Component getParsedTree(int depth) throws StackOverflowError; - protected static Text getDepthStyled(int depth, MutableText text) { - List