From b1ce44cd8cb05714e96772c0fb09ccfc3530d587 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Wed, 4 Jun 2025 19:52:28 +0800 Subject: [PATCH 01/14] =?UTF-8?q?perf(entity):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=AE=B6=E5=85=B7=E5=AE=9E=E4=BD=93=E7=BD=91=E7=BB=9C=E5=8C=85?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../entity/furniture/BukkitFurniture.java | 21 +++++++++++++++++++ .../furniture/BukkitFurnitureManager.java | 3 +++ .../furniture/FurnitureEventListener.java | 3 +++ .../plugin/network/BukkitNetworkManager.java | 1 - .../plugin/network/PacketConsumers.java | 13 ------------ .../FurnitureCollisionPacketHandler.java | 14 ------------- .../handler/FurniturePacketHandler.java | 7 ------- .../reflection/minecraft/CoreReflections.java | 6 ++++++ 8 files changed, 33 insertions(+), 35 deletions(-) delete mode 100644 bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurnitureCollisionPacketHandler.java diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java index 7002c5216..2404edb9d 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java @@ -28,6 +28,7 @@ import org.joml.Vector3f; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.*; +import java.util.function.Consumer; public class BukkitFurniture implements Furniture { private final Key id; @@ -130,6 +131,7 @@ public class BukkitFurniture implements Furniture { Object world = FastNMS.INSTANCE.field$CraftWorld$ServerLevel(this.location.getWorld()); for (Collider entity : this.colliderEntities) { FastNMS.INSTANCE.method$LevelWriter$addFreshEntity(world, entity.handle()); + injectFurnitureEntity(entity.handle()); Entity bukkitEntity = FastNMS.INSTANCE.method$Entity$getBukkitEntity(entity.handle()); bukkitEntity.getPersistentDataContainer().set(BukkitFurnitureManager.FURNITURE_COLLISION, PersistentDataType.BYTE, (byte) 1); } @@ -359,4 +361,23 @@ public class BukkitFurniture implements Furniture { newLocation.add(offset.x, offset.y + 0.6, -offset.z); return newLocation; } + + public static void injectFurnitureEntity(Object nmsEntity) { + try { + Object trackedEntity = FastNMS.INSTANCE.field$Entity$trackedEntity(nmsEntity); + Object serverEntity = FastNMS.INSTANCE.filed$ChunkMap$TrackedEntity$serverEntity(trackedEntity); + CoreReflections.field$ServerEntity$broadcast.set(serverEntity, Handlers.DO_NOTHING); + } catch (Exception e) { + CraftEngine.instance().logger().warn("Failed to inject collider", e); + } + } + + @FunctionalInterface + public interface Handlers extends Consumer { + Handlers DO_NOTHING = doNothing(); + + static Handlers doNothing() { + return (packet) -> {}; + } + } } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurnitureManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurnitureManager.java index 04e74f456..f4ed4f698 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurnitureManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurnitureManager.java @@ -86,6 +86,7 @@ public class BukkitFurnitureManager extends AbstractFurnitureManager { SoundData data = furniture.settings().sounds().placeSound(); location.getWorld().playSound(location, data.id().toString(), SoundCategory.BLOCKS, data.volume(), data.pitch()); } + BukkitFurniture.injectFurnitureEntity(FastNMS.INSTANCE.method$CraftEntity$getHandle(furnitureEntity)); return loadedFurnitureByRealEntityId(furnitureEntity.getEntityId()); } @@ -101,6 +102,7 @@ public class BukkitFurnitureManager extends AbstractFurnitureManager { for (Entity entity : entities) { if (entity instanceof ItemDisplay display) { handleBaseEntityLoadEarly(display); + BukkitFurniture.injectFurnitureEntity(FastNMS.INSTANCE.method$CraftEntity$getHandle(display)); } else if (entity instanceof Interaction interaction) { handleCollisionEntityLoadOnEntitiesLoad(interaction); } else if (entity instanceof Boat boat) { @@ -208,6 +210,7 @@ public class BukkitFurnitureManager extends AbstractFurnitureManager { furniture.initializeColliders(); } } + BukkitFurniture.injectFurnitureEntity(FastNMS.INSTANCE.method$CraftEntity$getHandle(display)); if (depth > 2) return; this.plugin.scheduler().sync().runLater(() -> handleBaseEntityLoadLate(display, depth + 1), 1, location.getWorld(), location.getBlockX() >> 4, location.getBlockZ() >> 4); } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/FurnitureEventListener.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/FurnitureEventListener.java index f9c526233..b5a38be5c 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/FurnitureEventListener.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/FurnitureEventListener.java @@ -2,6 +2,7 @@ package net.momirealms.craftengine.bukkit.entity.furniture; import com.destroystokyo.paper.event.entity.EntityAddToWorldEvent; import com.destroystokyo.paper.event.entity.EntityRemoveFromWorldEvent; +import net.momirealms.craftengine.bukkit.nms.FastNMS; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.ItemDisplay; @@ -36,6 +37,7 @@ public class FurnitureEventListener implements Listener { for (Entity entity : entities) { if (entity instanceof ItemDisplay itemDisplay) { this.manager.handleBaseEntityLoadEarly(itemDisplay); + BukkitFurniture.injectFurnitureEntity(FastNMS.INSTANCE.method$CraftEntity$getHandle(itemDisplay)); } else if (BukkitFurnitureManager.COLLISION_ENTITY_CLASS.isInstance(entity)) { this.manager.handleCollisionEntityLoadOnEntitiesLoad(entity); } @@ -48,6 +50,7 @@ public class FurnitureEventListener implements Listener { for (Entity entity : entities) { if (entity instanceof ItemDisplay itemDisplay) { this.manager.handleBaseEntityLoadEarly(itemDisplay); + BukkitFurniture.injectFurnitureEntity(FastNMS.INSTANCE.method$CraftEntity$getHandle(itemDisplay)); } else if (BukkitFurnitureManager.COLLISION_ENTITY_CLASS.isInstance(entity)) { this.manager.handleCollisionEntityLoadOnEntitiesLoad(entity); } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java index 0e6a33c6e..5f72e032e 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java @@ -149,7 +149,6 @@ public class BukkitNetworkManager implements NetworkManager, Listener, PluginMes registerNMSPacketConsumer(PacketConsumers.RESPAWN, NetworkReflections.clazz$ClientboundRespawnPacket); registerNMSPacketConsumer(PacketConsumers.INTERACT_ENTITY, NetworkReflections.clazz$ServerboundInteractPacket); registerNMSPacketConsumer(PacketConsumers.SYNC_ENTITY_POSITION, NetworkReflections.clazz$ClientboundEntityPositionSyncPacket); - registerNMSPacketConsumer(PacketConsumers.MOVE_POS_ENTITY, NetworkReflections.clazz$ClientboundMoveEntityPacket$Pos); registerNMSPacketConsumer(PacketConsumers.PICK_ITEM_FROM_ENTITY, NetworkReflections.clazz$ServerboundPickItemFromEntityPacket); registerNMSPacketConsumer(PacketConsumers.RENAME_ITEM, NetworkReflections.clazz$ServerboundRenameItemPacket); registerNMSPacketConsumer(PacketConsumers.SIGN_UPDATE, NetworkReflections.clazz$ServerboundSignUpdatePacket); diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java index 4e9c0a759..a6c00a87c 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java @@ -163,7 +163,6 @@ public class PacketConsumers { BukkitFurniture furniture = BukkitFurnitureManager.instance().loadedFurnitureByRealEntityId(id); if (furniture != null) { event.setCancelled(true); - user.entityPacketHandlers().put(id, FurnitureCollisionPacketHandler.INSTANCE); } }; ADD_ENTITY_HANDLERS[MEntityTypes.instance$EntityType$OAK_BOAT$registryId] = (user, event) -> { @@ -174,7 +173,6 @@ public class PacketConsumers { BukkitFurniture furniture = BukkitFurnitureManager.instance().loadedFurnitureByRealEntityId(id); if (furniture != null) { event.setCancelled(true); - user.entityPacketHandlers().put(id, FurnitureCollisionPacketHandler.INSTANCE); } }; } @@ -2287,17 +2285,6 @@ public class PacketConsumers { } }; - public static final TriConsumer MOVE_POS_ENTITY = (user, event, packet) -> { - try { - int entityId = ProtectedFieldVisitor.get().field$ClientboundMoveEntityPacket$entityId(packet); - if (BukkitFurnitureManager.instance().isFurnitureRealEntity(entityId)) { - event.setCancelled(true); - } - } catch (Exception e) { - CraftEngine.instance().logger().warn("Failed to handle ClientboundMoveEntityPacket", e); - } - }; - public static final TriConsumer MOVE_POS_AND_ROTATE_ENTITY = (user, event, packet) -> { try { int entityId = ProtectedFieldVisitor.get().field$ClientboundMoveEntityPacket$entityId(packet); diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurnitureCollisionPacketHandler.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurnitureCollisionPacketHandler.java deleted file mode 100644 index 70121b19b..000000000 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurnitureCollisionPacketHandler.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.momirealms.craftengine.bukkit.plugin.network.handler; - -import net.momirealms.craftengine.core.plugin.network.EntityPacketHandler; -import net.momirealms.craftengine.core.plugin.network.NMSPacketEvent; -import net.momirealms.craftengine.core.plugin.network.NetWorkUser; - -public class FurnitureCollisionPacketHandler implements EntityPacketHandler { - public static final FurnitureCollisionPacketHandler INSTANCE = new FurnitureCollisionPacketHandler(); - - @Override - public void handleSyncEntityPosition(NetWorkUser user, NMSPacketEvent event, Object packet) { - event.setCancelled(true); - } -} diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurniturePacketHandler.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurniturePacketHandler.java index f9f0134a6..70c0d6778 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurniturePacketHandler.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/FurniturePacketHandler.java @@ -2,8 +2,6 @@ package net.momirealms.craftengine.bukkit.plugin.network.handler; import it.unimi.dsi.fastutil.ints.IntList; import net.momirealms.craftengine.core.plugin.network.EntityPacketHandler; -import net.momirealms.craftengine.core.plugin.network.NMSPacketEvent; -import net.momirealms.craftengine.core.plugin.network.NetWorkUser; import java.util.List; @@ -19,9 +17,4 @@ public class FurniturePacketHandler implements EntityPacketHandler { entityIds.addAll(this.fakeEntities); return true; } - - @Override - public void handleSyncEntityPosition(NetWorkUser user, NMSPacketEvent event, Object packet) { - event.setCancelled(true); - } } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java index a89afddbf..755c7f191 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java @@ -3265,4 +3265,10 @@ public final class CoreReflections { public static final Method method$Registry$asLookup = ReflectionUtils.getMethod( clazz$Registry, clazz$HolderLookup$RegistryLookup, new String[]{"asLookup", "p"} ); + + public static final Field field$ServerEntity$broadcast = requireNonNull( + ReflectionUtils.getDeclaredField( + clazz$ServerEntity, Consumer.class, 0 + ) + ); } From 3d64db54be13177bfe16fac75aea5a7070e518d5 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Thu, 5 Jun 2025 21:06:43 +0800 Subject: [PATCH 02/14] =?UTF-8?q?perf(entity):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=8F=8D=E5=B0=84=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../entity/furniture/BukkitFurniture.java | 5 +- .../plugin/network/PacketConsumers.java | 107 +++++++++--------- .../reflection/minecraft/CoreReflections.java | 13 +++ .../minecraft/NetworkReflections.java | 102 +++++++++++++++++ .../core/util/ReflectionUtils.java | 21 +++- 5 files changed, 190 insertions(+), 58 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java index 2404edb9d..8bd6ccf01 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java @@ -366,8 +366,9 @@ public class BukkitFurniture implements Furniture { try { Object trackedEntity = FastNMS.INSTANCE.field$Entity$trackedEntity(nmsEntity); Object serverEntity = FastNMS.INSTANCE.filed$ChunkMap$TrackedEntity$serverEntity(trackedEntity); - CoreReflections.field$ServerEntity$broadcast.set(serverEntity, Handlers.DO_NOTHING); - } catch (Exception e) { + CoreReflections.handle$ServerEntity$broadcastSetter.invoke(serverEntity, Handlers.DO_NOTHING); + CoreReflections.handle$ServerEntity$updateIntervalSetter.invoke(serverEntity, Integer.MAX_VALUE); + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to inject collider", e); } } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java index a6c00a87c..0bf9daee7 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java @@ -70,7 +70,6 @@ import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.BiConsumer; @@ -1170,21 +1169,21 @@ public class PacketConsumers { public static final TriConsumer HELLO_C2S = (user, event, packet) -> { try { BukkitServerPlayer player = (BukkitServerPlayer) user; - String name = (String) NetworkReflections.field$ServerboundHelloPacket$name.get(packet); + String name = (String) NetworkReflections.handle$ServerboundHelloPacket$nameGetter.invoke(packet); player.setName(name); if (VersionHelper.isOrAbove1_20_2()) { - UUID uuid = (UUID) NetworkReflections.field$ServerboundHelloPacket$uuid.get(packet); + UUID uuid = (UUID) NetworkReflections.handle$ServerboundHelloPacket$uuidGetter.invoke(packet); player.setUUID(uuid); } else { @SuppressWarnings("unchecked") - Optional uuid = (Optional) NetworkReflections.field$ServerboundHelloPacket$uuid.get(packet); + Optional uuid = (Optional) NetworkReflections.handle$ServerboundHelloPacket$uuidGetter.invoke(packet); if (uuid.isPresent()) { player.setUUID(uuid.get()); } else { player.setUUID(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8))); } } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundHelloPacket", e); } }; @@ -1221,10 +1220,10 @@ public class PacketConsumers { player.clearView(); Object dimensionKey; if (!VersionHelper.isOrAbove1_20_2()) { - dimensionKey = NetworkReflections.field$ClientboundRespawnPacket$dimension.get(packet); + dimensionKey = NetworkReflections.handle$ClientboundRespawnPacket$dimensionGetter.invoke(packet); } else { - Object commonInfo = NetworkReflections.field$ClientboundRespawnPacket$commonPlayerSpawnInfo.get(packet); - dimensionKey = NetworkReflections.field$CommonPlayerSpawnInfo$dimension.get(commonInfo); + Object commonInfo = NetworkReflections.handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter.invoke(packet); + dimensionKey = NetworkReflections.handle$CommonPlayerSpawnInfo$dimensionGetter.invoke(commonInfo); } Object location = FastNMS.INSTANCE.field$ResourceKey$location(dimensionKey); World world = Bukkit.getWorld(Objects.requireNonNull(NamespacedKey.fromString(location.toString()))); @@ -1235,7 +1234,7 @@ public class PacketConsumers { } else { CraftEngine.instance().logger().warn("Failed to handle ClientboundRespawnPacket: World " + location + " does not exist"); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ClientboundRespawnPacket", e); } }; @@ -1249,10 +1248,10 @@ public class PacketConsumers { if (BukkitNetworkManager.hasViaVersion()) { user.setProtocolVersion(CraftEngine.instance().compatibilityManager().getPlayerProtocolVersion(player.uuid())); } - dimensionKey = NetworkReflections.field$ClientboundLoginPacket$dimension.get(packet); + dimensionKey = NetworkReflections.handle$ClientboundLoginPacket$dimensionGetter.invoke(packet); } else { - Object commonInfo = NetworkReflections.field$ClientboundLoginPacket$commonPlayerSpawnInfo.get(packet); - dimensionKey = NetworkReflections.field$CommonPlayerSpawnInfo$dimension.get(commonInfo); + Object commonInfo = NetworkReflections.handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter.invoke(packet); + dimensionKey = NetworkReflections.handle$CommonPlayerSpawnInfo$dimensionGetter.invoke(commonInfo); } Object location = FastNMS.INSTANCE.field$ResourceKey$location(dimensionKey); World world = Bukkit.getWorld(Objects.requireNonNull(NamespacedKey.fromString(location.toString()))); @@ -1263,7 +1262,7 @@ public class PacketConsumers { } else { CraftEngine.instance().logger().warn("Failed to handle ClientboundLoginPacket: World " + location + " does not exist"); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ClientboundLoginPacket", e); } }; @@ -1280,25 +1279,25 @@ public class PacketConsumers { player.platformPlayer().getScheduler().run(BukkitCraftEngine.instance().javaPlugin(), (t) -> { try { handleSetCreativeSlotPacketOnMainThread(player, packet); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundSetCreativeModeSlotPacket", e); } }, () -> {}); } else { handleSetCreativeSlotPacketOnMainThread(player, packet); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundSetCreativeModeSlotPacket", e); } }; - private static void handleSetCreativeSlotPacketOnMainThread(BukkitServerPlayer player, Object packet) throws Exception { + private static void handleSetCreativeSlotPacketOnMainThread(BukkitServerPlayer player, Object packet) throws Throwable { Player bukkitPlayer = player.platformPlayer(); if (bukkitPlayer == null) return; if (bukkitPlayer.getGameMode() != GameMode.CREATIVE) return; - int slot = VersionHelper.isOrAbove1_20_5() ? NetworkReflections.field$ServerboundSetCreativeModeSlotPacket$slotNum.getShort(packet) : NetworkReflections.field$ServerboundSetCreativeModeSlotPacket$slotNum.getInt(packet); + int slot = (int) NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter.invoke(packet); if (slot < 36 || slot > 44) return; - ItemStack item = FastNMS.INSTANCE.method$CraftItemStack$asCraftMirror(NetworkReflections.field$ServerboundSetCreativeModeSlotPacket$itemStack.get(packet)); + ItemStack item = FastNMS.INSTANCE.method$CraftItemStack$asCraftMirror(NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter.invoke(packet)); if (ItemUtils.isEmpty(item)) return; if (slot - 36 != bukkitPlayer.getInventory().getHeldItemSlot()) { return; @@ -1371,14 +1370,14 @@ public class PacketConsumers { if (!user.isOnline()) return; Player player = (Player) user.platformPlayer(); if (player == null) return; - Object pos = NetworkReflections.field$ServerboundPickItemFromBlockPacket$pos.get(packet); + Object pos = NetworkReflections.handle$ServerboundPickItemFromBlockPacket$posGetter.invoke(packet); if (VersionHelper.isFolia()) { int x = FastNMS.INSTANCE.field$Vec3i$x(pos); int z = FastNMS.INSTANCE.field$Vec3i$z(pos); BukkitCraftEngine.instance().scheduler().sync().run(() -> { try { handlePickItemFromBlockPacketOnMainThread(player, pos); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundPickItemFromBlockPacket", e); } }, player.getWorld(), x >> 4, z >> 4); @@ -1386,17 +1385,17 @@ public class PacketConsumers { BukkitCraftEngine.instance().scheduler().sync().run(() -> { try { handlePickItemFromBlockPacketOnMainThread(player, pos); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundPickItemFromBlockPacket", e); } }); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundPickItemFromBlockPacket", e); } }; - private static void handlePickItemFromBlockPacketOnMainThread(Player player, Object pos) throws Exception { + private static void handlePickItemFromBlockPacketOnMainThread(Player player, Object pos) throws Throwable { Object serverLevel = FastNMS.INSTANCE.field$CraftWorld$ServerLevel(player.getWorld()); Object blockState = FastNMS.INSTANCE.method$BlockGetter$getBlockState(serverLevel, pos); ImmutableBlockState state = BukkitBlockManager.instance().getImmutableBlockState(BlockStateUtils.blockStateToId(blockState)); @@ -1409,7 +1408,7 @@ public class PacketConsumers { // 1.21.4+ public static final TriConsumer PICK_ITEM_FROM_ENTITY = (user, event, packet) -> { try { - int entityId = (int) NetworkReflections.field$ServerboundPickItemFromEntityPacket$id.get(packet); + int entityId = (int) NetworkReflections.handle$ServerboundPickItemFromEntityPacket$idGetter.invoke(packet); BukkitFurniture furniture = BukkitFurnitureManager.instance().loadedFurnitureByEntityId(entityId); if (furniture == null) return; Player player = (Player) user.platformPlayer(); @@ -1418,7 +1417,7 @@ public class PacketConsumers { player.getScheduler().run(BukkitCraftEngine.instance().javaPlugin(), (t) -> { try { handlePickItemFromEntityOnMainThread(player, furniture); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundPickItemFromEntityPacket", e); } }, () -> {}); @@ -1426,23 +1425,23 @@ public class PacketConsumers { BukkitCraftEngine.instance().scheduler().sync().run(() -> { try { handlePickItemFromEntityOnMainThread(player, furniture); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundPickItemFromEntityPacket", e); } }); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundPickItemFromEntityPacket", e); } }; - private static void handlePickItemFromEntityOnMainThread(Player player, BukkitFurniture furniture) throws Exception { + private static void handlePickItemFromEntityOnMainThread(Player player, BukkitFurniture furniture) throws Throwable { Key itemId = furniture.config().settings().itemId(); if (itemId == null) return; pickItem(player, itemId, null, FastNMS.INSTANCE.method$CraftEntity$getHandle(furniture.baseEntity())); } - private static void pickItem(Player player, Key itemId, @Nullable Object blockPos, @Nullable Object entity) throws IllegalAccessException, InvocationTargetException { + private static void pickItem(Player player, Key itemId, @Nullable Object blockPos, @Nullable Object entity) throws Throwable { ItemStack itemStack = BukkitCraftEngine.instance().itemManager().buildCustomItemStack(itemId, BukkitCraftEngine.instance().adapt(player)); if (itemStack == null) { CraftEngine.instance().logger().warn("Item: " + itemId + " is not a valid item"); @@ -1451,11 +1450,11 @@ public class PacketConsumers { assert CoreReflections.method$ServerGamePacketListenerImpl$tryPickItem != null; if (VersionHelper.isOrAbove1_21_5()) { CoreReflections.method$ServerGamePacketListenerImpl$tryPickItem.invoke( - CoreReflections.field$ServerPlayer$connection.get(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), + CoreReflections.handle$ServerPlayer$connectionGetter.invoke(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), FastNMS.INSTANCE.method$CraftItemStack$asNMSCopy(itemStack), blockPos, entity, true); } else { CoreReflections.method$ServerGamePacketListenerImpl$tryPickItem.invoke( - CoreReflections.field$ServerPlayer$connection.get(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), FastNMS.INSTANCE.method$CraftItemStack$asNMSCopy(itemStack)); + CoreReflections.handle$ServerPlayer$connectionGetter.invoke(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), FastNMS.INSTANCE.method$CraftItemStack$asNMSCopy(itemStack)); } } @@ -1520,7 +1519,7 @@ public class PacketConsumers { } BukkitFurniture furniture = BukkitFurnitureManager.instance().loadedFurnitureByEntityId(entityId); if (furniture == null) return; - Object action = NetworkReflections.field$ServerboundInteractPacket$action.get(packet); + Object action = NetworkReflections.handle$ServerboundInteractPacket$actionGetter.invoke(packet); Object actionType = NetworkReflections.method$ServerboundInteractPacket$Action$getType.invoke(action); if (actionType == null) return; Location location = furniture.baseEntity().getLocation(); @@ -1553,15 +1552,15 @@ public class PacketConsumers { InteractionHand hand; Location interactionPoint; try { - Object interactionHand = NetworkReflections.field$ServerboundInteractPacket$InteractionAtLocationAction$hand.get(action); + Object interactionHand = NetworkReflections.handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter.invoke(action); hand = interactionHand == CoreReflections.instance$InteractionHand$MAIN_HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; - Object vec3 = NetworkReflections.field$ServerboundInteractPacket$InteractionAtLocationAction$location.get(action); + Object vec3 = NetworkReflections.handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter.invoke(action); double x = FastNMS.INSTANCE.field$Vec3$x(vec3); double y = FastNMS.INSTANCE.field$Vec3$y(vec3); double z = FastNMS.INSTANCE.field$Vec3$z(vec3); interactionPoint = new Location(location.getWorld(), x, y, z); - } catch (ReflectiveOperationException e) { + } catch (Throwable e) { throw new RuntimeException("Failed to get interaction hand from interact packet", e); } FurnitureInteractEvent interactEvent = new FurnitureInteractEvent(serverPlayer.platformPlayer(), furniture, hand, interactionPoint); @@ -1612,7 +1611,7 @@ public class PacketConsumers { } } }, player.getWorld(), location.getBlockX() >> 4, location.getBlockZ() >> 4); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundInteractPacket", e); } }; @@ -1697,20 +1696,20 @@ public class PacketConsumers { if (((BukkitServerPlayer) user).hasPermission(FontManager.BYPASS_ANVIL)) { return; } - String message = (String) NetworkReflections.field$ServerboundRenameItemPacket$name.get(packet); + String message = (String) NetworkReflections.handle$ServerboundRenameItemPacket$nameGetter.invoke(packet); if (message != null && !message.isEmpty()) { // check bypass FontManager manager = CraftEngine.instance().fontManager(); IllegalCharacterProcessResult result = manager.processIllegalCharacters(message); if (result.has()) { try { - NetworkReflections.field$ServerboundRenameItemPacket$name.set(packet, result.text()); + NetworkReflections.handle$ServerboundRenameItemPacket$nameSetter.invoke(packet, result.text()); } catch (ReflectiveOperationException e) { CraftEngine.instance().logger().warn("Failed to replace chat", e); } } } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundRenameItemPacket", e); } }; @@ -1723,7 +1722,7 @@ public class PacketConsumers { if (((BukkitServerPlayer) user).hasPermission(FontManager.BYPASS_SIGN)) { return; } - String[] lines = (String[]) NetworkReflections.field$ServerboundSignUpdatePacket$lines.get(packet); + String[] lines = (String[]) NetworkReflections.handle$ServerboundSignUpdatePacket$linesGetter.invoke(packet); FontManager manager = CraftEngine.instance().fontManager(); if (!manager.isDefaultFontInUse()) return; for (int i = 0; i < lines.length; i++) { @@ -1735,7 +1734,7 @@ public class PacketConsumers { } } } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundSignUpdatePacket", e); } }; @@ -1754,9 +1753,9 @@ public class PacketConsumers { boolean changed = false; - List pages = (List) NetworkReflections.field$ServerboundEditBookPacket$pages.get(packet); + List pages = (List) NetworkReflections.handleServerboundEditBookPacket$pagesGetter.invoke(packet); List newPages = new ArrayList<>(pages.size()); - Optional title = (Optional) NetworkReflections.field$ServerboundEditBookPacket$title.get(packet); + Optional title = (Optional) NetworkReflections.handle$ServerboundEditBookPacket$titleGetter.invoke(packet); Optional newTitle; if (title.isPresent()) { @@ -1780,13 +1779,13 @@ public class PacketConsumers { if (changed) { Object newPacket = NetworkReflections.constructor$ServerboundEditBookPacket.newInstance( - NetworkReflections.field$ServerboundEditBookPacket$slot.get(packet), + NetworkReflections.handle$ServerboundEditBookPacket$slotGetter.invoke(packet), newPages, newTitle ); event.replacePacket(newPacket); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundEditBookPacket", e); } }; @@ -1813,7 +1812,7 @@ public class PacketConsumers { public static final TriConsumer CUSTOM_PAYLOAD = (user, event, packet) -> { try { if (!VersionHelper.isOrAbove1_20_5()) return; - Object payload = NetworkReflections.field$ServerboundCustomPayloadPacket$payload.get(packet); + Object payload = NetworkReflections.handle$ServerboundCustomPayloadPacket$payloadGetter.invoke(packet); if (NetworkReflections.clazz$DiscardedPayload.isInstance(payload)) { Payload discardedPayload = DiscardedPayload.from(payload); if (discardedPayload == null || !discardedPayload.channel().equals(NetworkManager.MOD_CHANNEL_KEY)) @@ -1842,7 +1841,7 @@ public class PacketConsumers { } } } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundCustomPayloadPacket", e); } }; @@ -2232,9 +2231,9 @@ public class PacketConsumers { public static final TriConsumer HANDSHAKE_C2S = (user, event, packet) -> { try { if (BukkitNetworkManager.hasViaVersion()) return; - int protocolVersion = NetworkReflections.field$ClientIntentionPacket$protocolVersion.getInt(packet); + int protocolVersion = (int) NetworkReflections.handle$ClientIntentionPacket$protocolVersionGetter.invoke(packet); user.setProtocolVersion(protocolVersion); - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ClientIntentionPacket", e); } }; @@ -2252,7 +2251,7 @@ public class PacketConsumers { public static final TriConsumer RESOURCE_PACK_RESPONSE = (user, event, packet) -> { try { if (user.sentResourcePack() || !Config.sendPackOnJoin() || !Config.kickOnDeclined()) return; - Object action = NetworkReflections.field$ServerboundResourcePackPacket$action.get(packet); + Object action = NetworkReflections.handle$ServerboundResourcePackPacket$actionGetter.invoke(packet); if (action == null) return; if (action == NetworkReflections.instance$ServerboundResourcePackPacket$Action$DECLINED || action == NetworkReflections.instance$ServerboundResourcePackPacket$Action$FAILED_DOWNLOAD) { @@ -2265,7 +2264,7 @@ public class PacketConsumers { if (action == NetworkReflections.instance$ServerboundResourcePackPacket$Action$SUCCESSFULLY_LOADED) { user.setSentResourcePack(true); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ServerboundResourcePackPacket", e); } }; @@ -2274,13 +2273,13 @@ public class PacketConsumers { try { Object player = user.serverPlayer(); if (player == null) return; - int entityId = NetworkReflections.field$ClientboundEntityEventPacket$entityId.getInt(packet); + int entityId = (int) NetworkReflections.handle$ClientboundEntityEventPacket$entityIdGetter.invoke(packet); if (entityId != FastNMS.INSTANCE.method$Entity$getId(player)) return; - byte eventId = NetworkReflections.field$ClientboundEntityEventPacket$eventId.getByte(packet); + byte eventId = (byte) NetworkReflections.handle$ClientboundEntityEventPacket$eventIdGetter.invoke(packet); if (eventId >= 24 && eventId <= 28) { CraftEngine.instance().fontManager().refreshEmojiSuggestions(user.uuid()); } - } catch (Exception e) { + } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ClientboundEntityEventPacket", e); } }; diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java index 755c7f191..6bfc980cb 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java @@ -11,6 +11,7 @@ import net.momirealms.craftengine.core.util.ReflectionUtils; import net.momirealms.craftengine.core.util.VersionHelper; import java.io.BufferedReader; +import java.lang.invoke.MethodHandle; import java.lang.invoke.VarHandle; import java.lang.reflect.*; import java.util.*; @@ -3271,4 +3272,16 @@ public final class CoreReflections { clazz$ServerEntity, Consumer.class, 0 ) ); + + public static final MethodHandle handle$ServerEntity$broadcastSetter = requireNonNull( + ReflectionUtils.unreflectSetter(field$ServerEntity$broadcast) + ); + + public static final MethodHandle handle$ServerEntity$updateIntervalSetter = requireNonNull( + ReflectionUtils.unreflectSetter(field$ServerEntity$updateInterval) + ); + + public static final MethodHandle handle$ServerPlayer$connectionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerPlayer$connection) + ); } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java index c031447eb..c2dc38105 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java @@ -5,6 +5,7 @@ import net.momirealms.craftengine.bukkit.util.BukkitReflectionUtils; import net.momirealms.craftengine.core.util.ReflectionUtils; import net.momirealms.craftengine.core.util.VersionHelper; +import java.lang.invoke.MethodHandle; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -1293,4 +1294,105 @@ public final class NetworkReflections { public static final Constructor constructor$ClientboundTickingStatePacket = Optional.ofNullable(clazz$ClientboundTickingStatePacket) .map(it -> ReflectionUtils.getConstructor(it, float.class, boolean.class)) .orElse(null); + + public static final MethodHandle handle$ServerboundRenameItemPacket$nameGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundRenameItemPacket$name) + ); + + public static final MethodHandle handle$ServerboundRenameItemPacket$nameSetter = requireNonNull( + ReflectionUtils.unreflectSetter(field$ServerboundRenameItemPacket$name) + ); + + public static final MethodHandle handle$ServerboundHelloPacket$nameGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$name) + ); + + public static final MethodHandle handle$ServerboundHelloPacket$uuidGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$uuid) + ); + + public static final MethodHandle handle$ClientboundRespawnPacket$dimensionGetter = Optional.ofNullable(field$ClientboundRespawnPacket$dimension) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundRespawnPacket$commonPlayerSpawnInfo) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$CommonPlayerSpawnInfo$dimensionGetter = Optional.ofNullable(field$CommonPlayerSpawnInfo$dimension) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ClientboundLoginPacket$dimensionGetter = Optional.ofNullable(field$ClientboundLoginPacket$dimension) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundLoginPacket$commonPlayerSpawnInfo) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$itemStack) + ); + + public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$slotNum) + ); + + public static final MethodHandle handle$ServerboundPickItemFromBlockPacket$posGetter = Optional.ofNullable(field$ServerboundPickItemFromBlockPacket$pos) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ServerboundPickItemFromEntityPacket$idGetter = Optional.ofNullable(field$ServerboundPickItemFromEntityPacket$id) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ServerboundInteractPacket$actionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$action) + ); + + public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$hand) + ); + + public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$location) + ); + + public static final MethodHandle handle$ServerboundSignUpdatePacket$linesGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundSignUpdatePacket$lines) + ); + + public static final MethodHandle handleServerboundEditBookPacket$pagesGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$pages) + ); + + public static final MethodHandle handle$ServerboundEditBookPacket$titleGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$title) + ); + + public static final MethodHandle handle$ServerboundEditBookPacket$slotGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$slot) + ); + + public static final MethodHandle handle$ServerboundCustomPayloadPacket$payloadGetter = Optional.ofNullable(field$ServerboundCustomPayloadPacket$payload) + .map(ReflectionUtils::unreflectGetter) + .orElse(null); + + public static final MethodHandle handle$ServerboundResourcePackPacket$actionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundResourcePackPacket$action) + ); + + public static final MethodHandle handle$ClientboundEntityEventPacket$entityIdGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$entityId) + ); + + public static final MethodHandle handle$ClientboundEntityEventPacket$eventIdGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$eventId) + ); + + public static final MethodHandle handle$ClientIntentionPacket$protocolVersionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientIntentionPacket$protocolVersion) + ); + } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java b/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java index 12a92f3f0..8f901f12e 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java @@ -485,12 +485,16 @@ public class ReflectionUtils { return constructors[0]; } - public static MethodHandle unreflectGetter(Field field) throws IllegalAccessException { + public static MethodHandle unreflectGetter(Field field) { try { return LOOKUP.unreflectGetter(field); } catch (IllegalAccessException e) { field.setAccessible(true); - return LOOKUP.unreflectGetter(field); + try { + return LOOKUP.unreflectGetter(field); + } catch (IllegalAccessException ex) { + return null; + } } } @@ -520,4 +524,17 @@ public class ReflectionUtils { return null; } } + + public static MethodHandle unreflectSetter(Field field) { + try { + return LOOKUP.unreflectSetter(field); + } catch (IllegalAccessException e) { + field.setAccessible(true); + try { + return LOOKUP.unreflectSetter(field); + } catch (IllegalAccessException ex) { + return null; + } + } + } } From e4196cf5592c0932a7f1915ad691ccaa2b712c7e Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Thu, 5 Jun 2025 22:22:19 +0800 Subject: [PATCH 03/14] =?UTF-8?q?perf(entity):=20=E6=9C=80=E7=BB=88?= =?UTF-8?q?=E7=9A=84=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 已测试 1.20.1 1.20.4 1.21.4 --- .../entity/furniture/BukkitFurniture.java | 6 +- .../plugin/network/PacketConsumers.java | 58 +++++++++---------- .../reflection/minecraft/CoreReflections.java | 4 ++ .../minecraft/NetworkReflections.java | 36 +++++++++--- 4 files changed, 63 insertions(+), 41 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java index 8bd6ccf01..8f4df2e9c 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/furniture/BukkitFurniture.java @@ -366,8 +366,8 @@ public class BukkitFurniture implements Furniture { try { Object trackedEntity = FastNMS.INSTANCE.field$Entity$trackedEntity(nmsEntity); Object serverEntity = FastNMS.INSTANCE.filed$ChunkMap$TrackedEntity$serverEntity(trackedEntity); - CoreReflections.handle$ServerEntity$broadcastSetter.invoke(serverEntity, Handlers.DO_NOTHING); - CoreReflections.handle$ServerEntity$updateIntervalSetter.invoke(serverEntity, Integer.MAX_VALUE); + CoreReflections.handle$ServerEntity$broadcastSetter.invokeExact(serverEntity, Handlers.DO_NOTHING); + CoreReflections.handle$ServerEntity$updateIntervalSetter.invokeExact(serverEntity, Integer.MAX_VALUE); } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to inject collider", e); } @@ -375,7 +375,7 @@ public class BukkitFurniture implements Furniture { @FunctionalInterface public interface Handlers extends Consumer { - Handlers DO_NOTHING = doNothing(); + Consumer DO_NOTHING = doNothing(); static Handlers doNothing() { return (packet) -> {}; diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java index 0bf9daee7..a11ce2e94 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java @@ -1169,14 +1169,14 @@ public class PacketConsumers { public static final TriConsumer HELLO_C2S = (user, event, packet) -> { try { BukkitServerPlayer player = (BukkitServerPlayer) user; - String name = (String) NetworkReflections.handle$ServerboundHelloPacket$nameGetter.invoke(packet); + String name = (String) NetworkReflections.handle$ServerboundHelloPacket$nameGetter.invokeExact(packet); player.setName(name); if (VersionHelper.isOrAbove1_20_2()) { - UUID uuid = (UUID) NetworkReflections.handle$ServerboundHelloPacket$uuidGetter.invoke(packet); + UUID uuid = (UUID) NetworkReflections.handle$ServerboundHelloPacket$uuidGetter.invokeExact(packet); player.setUUID(uuid); } else { @SuppressWarnings("unchecked") - Optional uuid = (Optional) NetworkReflections.handle$ServerboundHelloPacket$uuidGetter.invoke(packet); + Optional uuid = (Optional) NetworkReflections.handle$ServerboundHelloPacket$uuidGetter.invokeExact(packet); if (uuid.isPresent()) { player.setUUID(uuid.get()); } else { @@ -1220,10 +1220,10 @@ public class PacketConsumers { player.clearView(); Object dimensionKey; if (!VersionHelper.isOrAbove1_20_2()) { - dimensionKey = NetworkReflections.handle$ClientboundRespawnPacket$dimensionGetter.invoke(packet); + dimensionKey = NetworkReflections.handle$ClientboundRespawnPacket$dimensionGetter.invokeExact(packet); } else { - Object commonInfo = NetworkReflections.handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter.invoke(packet); - dimensionKey = NetworkReflections.handle$CommonPlayerSpawnInfo$dimensionGetter.invoke(commonInfo); + Object commonInfo = NetworkReflections.handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter.invokeExact(packet); + dimensionKey = NetworkReflections.handle$CommonPlayerSpawnInfo$dimensionGetter.invokeExact(commonInfo); } Object location = FastNMS.INSTANCE.field$ResourceKey$location(dimensionKey); World world = Bukkit.getWorld(Objects.requireNonNull(NamespacedKey.fromString(location.toString()))); @@ -1248,10 +1248,10 @@ public class PacketConsumers { if (BukkitNetworkManager.hasViaVersion()) { user.setProtocolVersion(CraftEngine.instance().compatibilityManager().getPlayerProtocolVersion(player.uuid())); } - dimensionKey = NetworkReflections.handle$ClientboundLoginPacket$dimensionGetter.invoke(packet); + dimensionKey = NetworkReflections.handle$ClientboundLoginPacket$dimensionGetter.invokeExact(packet); } else { - Object commonInfo = NetworkReflections.handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter.invoke(packet); - dimensionKey = NetworkReflections.handle$CommonPlayerSpawnInfo$dimensionGetter.invoke(commonInfo); + Object commonInfo = NetworkReflections.handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter.invokeExact(packet); + dimensionKey = NetworkReflections.handle$CommonPlayerSpawnInfo$dimensionGetter.invokeExact(commonInfo); } Object location = FastNMS.INSTANCE.field$ResourceKey$location(dimensionKey); World world = Bukkit.getWorld(Objects.requireNonNull(NamespacedKey.fromString(location.toString()))); @@ -1295,9 +1295,9 @@ public class PacketConsumers { Player bukkitPlayer = player.platformPlayer(); if (bukkitPlayer == null) return; if (bukkitPlayer.getGameMode() != GameMode.CREATIVE) return; - int slot = (int) NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter.invoke(packet); + int slot = VersionHelper.isOrAbove1_20_5() ? (short) NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter.invokeExact(packet) : (int) NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter.invokeExact(packet); if (slot < 36 || slot > 44) return; - ItemStack item = FastNMS.INSTANCE.method$CraftItemStack$asCraftMirror(NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter.invoke(packet)); + ItemStack item = FastNMS.INSTANCE.method$CraftItemStack$asCraftMirror(NetworkReflections.handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter.invokeExact(packet)); if (ItemUtils.isEmpty(item)) return; if (slot - 36 != bukkitPlayer.getInventory().getHeldItemSlot()) { return; @@ -1370,7 +1370,7 @@ public class PacketConsumers { if (!user.isOnline()) return; Player player = (Player) user.platformPlayer(); if (player == null) return; - Object pos = NetworkReflections.handle$ServerboundPickItemFromBlockPacket$posGetter.invoke(packet); + Object pos = NetworkReflections.handle$ServerboundPickItemFromBlockPacket$posGetter.invokeExact(packet); if (VersionHelper.isFolia()) { int x = FastNMS.INSTANCE.field$Vec3i$x(pos); int z = FastNMS.INSTANCE.field$Vec3i$z(pos); @@ -1408,7 +1408,7 @@ public class PacketConsumers { // 1.21.4+ public static final TriConsumer PICK_ITEM_FROM_ENTITY = (user, event, packet) -> { try { - int entityId = (int) NetworkReflections.handle$ServerboundPickItemFromEntityPacket$idGetter.invoke(packet); + int entityId = (int) NetworkReflections.handle$ServerboundPickItemFromEntityPacket$idGetter.invokeExact(packet); BukkitFurniture furniture = BukkitFurnitureManager.instance().loadedFurnitureByEntityId(entityId); if (furniture == null) return; Player player = (Player) user.platformPlayer(); @@ -1450,11 +1450,11 @@ public class PacketConsumers { assert CoreReflections.method$ServerGamePacketListenerImpl$tryPickItem != null; if (VersionHelper.isOrAbove1_21_5()) { CoreReflections.method$ServerGamePacketListenerImpl$tryPickItem.invoke( - CoreReflections.handle$ServerPlayer$connectionGetter.invoke(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), + CoreReflections.handle$ServerPlayer$connectionGetter.invokeExact(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), FastNMS.INSTANCE.method$CraftItemStack$asNMSCopy(itemStack), blockPos, entity, true); } else { CoreReflections.method$ServerGamePacketListenerImpl$tryPickItem.invoke( - CoreReflections.handle$ServerPlayer$connectionGetter.invoke(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), FastNMS.INSTANCE.method$CraftItemStack$asNMSCopy(itemStack)); + CoreReflections.handle$ServerPlayer$connectionGetter.invokeExact(FastNMS.INSTANCE.method$CraftPlayer$getHandle(player)), FastNMS.INSTANCE.method$CraftItemStack$asNMSCopy(itemStack)); } } @@ -1519,7 +1519,7 @@ public class PacketConsumers { } BukkitFurniture furniture = BukkitFurnitureManager.instance().loadedFurnitureByEntityId(entityId); if (furniture == null) return; - Object action = NetworkReflections.handle$ServerboundInteractPacket$actionGetter.invoke(packet); + Object action = NetworkReflections.handle$ServerboundInteractPacket$actionGetter.invokeExact(packet); Object actionType = NetworkReflections.method$ServerboundInteractPacket$Action$getType.invoke(action); if (actionType == null) return; Location location = furniture.baseEntity().getLocation(); @@ -1552,9 +1552,9 @@ public class PacketConsumers { InteractionHand hand; Location interactionPoint; try { - Object interactionHand = NetworkReflections.handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter.invoke(action); + Object interactionHand = NetworkReflections.handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter.invokeExact(action); hand = interactionHand == CoreReflections.instance$InteractionHand$MAIN_HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; - Object vec3 = NetworkReflections.handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter.invoke(action); + Object vec3 = NetworkReflections.handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter.invokeExact(action); double x = FastNMS.INSTANCE.field$Vec3$x(vec3); double y = FastNMS.INSTANCE.field$Vec3$y(vec3); @@ -1696,14 +1696,14 @@ public class PacketConsumers { if (((BukkitServerPlayer) user).hasPermission(FontManager.BYPASS_ANVIL)) { return; } - String message = (String) NetworkReflections.handle$ServerboundRenameItemPacket$nameGetter.invoke(packet); + String message = (String) NetworkReflections.handle$ServerboundRenameItemPacket$nameGetter.invokeExact(packet); if (message != null && !message.isEmpty()) { // check bypass FontManager manager = CraftEngine.instance().fontManager(); IllegalCharacterProcessResult result = manager.processIllegalCharacters(message); if (result.has()) { try { - NetworkReflections.handle$ServerboundRenameItemPacket$nameSetter.invoke(packet, result.text()); + NetworkReflections.handle$ServerboundRenameItemPacket$nameSetter.invokeExact(packet, result.text()); } catch (ReflectiveOperationException e) { CraftEngine.instance().logger().warn("Failed to replace chat", e); } @@ -1722,7 +1722,7 @@ public class PacketConsumers { if (((BukkitServerPlayer) user).hasPermission(FontManager.BYPASS_SIGN)) { return; } - String[] lines = (String[]) NetworkReflections.handle$ServerboundSignUpdatePacket$linesGetter.invoke(packet); + String[] lines = (String[]) NetworkReflections.handle$ServerboundSignUpdatePacket$linesGetter.invokeExact(packet); FontManager manager = CraftEngine.instance().fontManager(); if (!manager.isDefaultFontInUse()) return; for (int i = 0; i < lines.length; i++) { @@ -1753,9 +1753,9 @@ public class PacketConsumers { boolean changed = false; - List pages = (List) NetworkReflections.handleServerboundEditBookPacket$pagesGetter.invoke(packet); + List pages = (List) NetworkReflections.handleServerboundEditBookPacket$pagesGetter.invokeExact(packet); List newPages = new ArrayList<>(pages.size()); - Optional title = (Optional) NetworkReflections.handle$ServerboundEditBookPacket$titleGetter.invoke(packet); + Optional title = (Optional) NetworkReflections.handle$ServerboundEditBookPacket$titleGetter.invokeExact(packet); Optional newTitle; if (title.isPresent()) { @@ -1779,7 +1779,7 @@ public class PacketConsumers { if (changed) { Object newPacket = NetworkReflections.constructor$ServerboundEditBookPacket.newInstance( - NetworkReflections.handle$ServerboundEditBookPacket$slotGetter.invoke(packet), + (int) NetworkReflections.handle$ServerboundEditBookPacket$slotGetter.invokeExact(packet), newPages, newTitle ); @@ -1812,7 +1812,7 @@ public class PacketConsumers { public static final TriConsumer CUSTOM_PAYLOAD = (user, event, packet) -> { try { if (!VersionHelper.isOrAbove1_20_5()) return; - Object payload = NetworkReflections.handle$ServerboundCustomPayloadPacket$payloadGetter.invoke(packet); + Object payload = NetworkReflections.handle$ServerboundCustomPayloadPacket$payloadGetter.invokeExact(packet); if (NetworkReflections.clazz$DiscardedPayload.isInstance(payload)) { Payload discardedPayload = DiscardedPayload.from(payload); if (discardedPayload == null || !discardedPayload.channel().equals(NetworkManager.MOD_CHANNEL_KEY)) @@ -2231,7 +2231,7 @@ public class PacketConsumers { public static final TriConsumer HANDSHAKE_C2S = (user, event, packet) -> { try { if (BukkitNetworkManager.hasViaVersion()) return; - int protocolVersion = (int) NetworkReflections.handle$ClientIntentionPacket$protocolVersionGetter.invoke(packet); + int protocolVersion = (int) NetworkReflections.handle$ClientIntentionPacket$protocolVersionGetter.invokeExact(packet); user.setProtocolVersion(protocolVersion); } catch (Throwable e) { CraftEngine.instance().logger().warn("Failed to handle ClientIntentionPacket", e); @@ -2251,7 +2251,7 @@ public class PacketConsumers { public static final TriConsumer RESOURCE_PACK_RESPONSE = (user, event, packet) -> { try { if (user.sentResourcePack() || !Config.sendPackOnJoin() || !Config.kickOnDeclined()) return; - Object action = NetworkReflections.handle$ServerboundResourcePackPacket$actionGetter.invoke(packet); + Object action = NetworkReflections.handle$ServerboundResourcePackPacket$actionGetter.invokeExact(packet); if (action == null) return; if (action == NetworkReflections.instance$ServerboundResourcePackPacket$Action$DECLINED || action == NetworkReflections.instance$ServerboundResourcePackPacket$Action$FAILED_DOWNLOAD) { @@ -2273,9 +2273,9 @@ public class PacketConsumers { try { Object player = user.serverPlayer(); if (player == null) return; - int entityId = (int) NetworkReflections.handle$ClientboundEntityEventPacket$entityIdGetter.invoke(packet); + int entityId = (int) NetworkReflections.handle$ClientboundEntityEventPacket$entityIdGetter.invokeExact(packet); if (entityId != FastNMS.INSTANCE.method$Entity$getId(player)) return; - byte eventId = (byte) NetworkReflections.handle$ClientboundEntityEventPacket$eventIdGetter.invoke(packet); + byte eventId = (byte) NetworkReflections.handle$ClientboundEntityEventPacket$eventIdGetter.invokeExact(packet); if (eventId >= 24 && eventId <= 28) { CraftEngine.instance().fontManager().refreshEmojiSuggestions(user.uuid()); } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java index 6bfc980cb..986c58c50 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java @@ -12,6 +12,7 @@ import net.momirealms.craftengine.core.util.VersionHelper; import java.io.BufferedReader; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodType; import java.lang.invoke.VarHandle; import java.lang.reflect.*; import java.util.*; @@ -3275,13 +3276,16 @@ public final class CoreReflections { public static final MethodHandle handle$ServerEntity$broadcastSetter = requireNonNull( ReflectionUtils.unreflectSetter(field$ServerEntity$broadcast) + .asType(MethodType.methodType(void.class, Object.class, Consumer.class)) ); public static final MethodHandle handle$ServerEntity$updateIntervalSetter = requireNonNull( ReflectionUtils.unreflectSetter(field$ServerEntity$updateInterval) + .asType(MethodType.methodType(void.class, Object.class, int.class)) ); public static final MethodHandle handle$ServerPlayer$connectionGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerPlayer$connection) + .asType(MethodType.methodType(Object.class, Object.class)) ); } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java index c2dc38105..83ff087e5 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java @@ -6,6 +6,7 @@ import net.momirealms.craftengine.core.util.ReflectionUtils; import net.momirealms.craftengine.core.util.VersionHelper; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -969,7 +970,7 @@ public final class NetworkReflections { ); public static final Field field$ServerboundEditBookPacket$slot = requireNonNull( - ReflectionUtils.getDeclaredField(clazz$ServerboundEditBookPacket, int.class, 0) + ReflectionUtils.getDeclaredField(clazz$ServerboundEditBookPacket, int.class, VersionHelper.isOrAbove1_20_5() ? 0 : 4) ); public static final Field field$ServerboundEditBookPacket$pages = requireNonNull( @@ -1297,102 +1298,119 @@ public final class NetworkReflections { public static final MethodHandle handle$ServerboundRenameItemPacket$nameGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundRenameItemPacket$name) + .asType(MethodType.methodType(String.class, Object.class)) ); public static final MethodHandle handle$ServerboundRenameItemPacket$nameSetter = requireNonNull( ReflectionUtils.unreflectSetter(field$ServerboundRenameItemPacket$name) + .asType(MethodType.methodType(void.class, Object.class, String.class)) ); public static final MethodHandle handle$ServerboundHelloPacket$nameGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$name) + .asType(MethodType.methodType(String.class, Object.class)) ); public static final MethodHandle handle$ServerboundHelloPacket$uuidGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$uuid) + .asType(MethodType.methodType(VersionHelper.isOrAbove1_20_2() ? UUID.class : Optional.class, Object.class)) ); public static final MethodHandle handle$ClientboundRespawnPacket$dimensionGetter = Optional.ofNullable(field$ClientboundRespawnPacket$dimension) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundRespawnPacket$commonPlayerSpawnInfo) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$CommonPlayerSpawnInfo$dimensionGetter = Optional.ofNullable(field$CommonPlayerSpawnInfo$dimension) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$ClientboundLoginPacket$dimensionGetter = Optional.ofNullable(field$ClientboundLoginPacket$dimension) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundLoginPacket$commonPlayerSpawnInfo) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$itemStack) + .asType(MethodType.methodType(Object.class, Object.class)) ); public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$slotNum) + .asType(MethodType.methodType(VersionHelper.isOrAbove1_20_5() ? short.class : int.class, Object.class)) ); public static final MethodHandle handle$ServerboundPickItemFromBlockPacket$posGetter = Optional.ofNullable(field$ServerboundPickItemFromBlockPacket$pos) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$ServerboundPickItemFromEntityPacket$idGetter = Optional.ofNullable(field$ServerboundPickItemFromEntityPacket$id) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(int.class, Object.class))) .orElse(null); public static final MethodHandle handle$ServerboundInteractPacket$actionGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$action) + .asType(MethodType.methodType(Object.class, Object.class)) ); public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$hand) + .asType(MethodType.methodType(Object.class, Object.class)) ); public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$location) + .asType(MethodType.methodType(Object.class, Object.class)) ); public static final MethodHandle handle$ServerboundSignUpdatePacket$linesGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundSignUpdatePacket$lines) + .asType(MethodType.methodType(String[].class, Object.class)) ); public static final MethodHandle handleServerboundEditBookPacket$pagesGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$pages) + .asType(MethodType.methodType(List.class, Object.class)) ); public static final MethodHandle handle$ServerboundEditBookPacket$titleGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$title) + .asType(MethodType.methodType(Optional.class, Object.class)) ); public static final MethodHandle handle$ServerboundEditBookPacket$slotGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$slot) + .asType(MethodType.methodType(int.class, Object.class)) ); public static final MethodHandle handle$ServerboundCustomPayloadPacket$payloadGetter = Optional.ofNullable(field$ServerboundCustomPayloadPacket$payload) - .map(ReflectionUtils::unreflectGetter) + .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) .orElse(null); public static final MethodHandle handle$ServerboundResourcePackPacket$actionGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ServerboundResourcePackPacket$action) + .asType(MethodType.methodType(Object.class, Object.class)) ); public static final MethodHandle handle$ClientboundEntityEventPacket$entityIdGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$entityId) + .asType(MethodType.methodType(int.class, Object.class)) ); public static final MethodHandle handle$ClientboundEntityEventPacket$eventIdGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$eventId) + .asType(MethodType.methodType(byte.class, Object.class)) ); public static final MethodHandle handle$ClientIntentionPacket$protocolVersionGetter = requireNonNull( ReflectionUtils.unreflectGetter(field$ClientIntentionPacket$protocolVersion) + .asType(MethodType.methodType(int.class, Object.class)) ); } From 8d6f8d6d663aef395fd74d04005986136d0fee22 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Thu, 5 Jun 2025 22:36:52 +0800 Subject: [PATCH 04/14] =?UTF-8?q?refactor(core):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=8F=8D=E5=B0=84=E5=B7=A5=E5=85=B7=E7=B1=BB=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../net/momirealms/craftengine/core/util/ReflectionUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java b/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java index 8f901f12e..5022cc141 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java @@ -493,7 +493,7 @@ public class ReflectionUtils { try { return LOOKUP.unreflectGetter(field); } catch (IllegalAccessException ex) { - return null; + throw new RuntimeException(ex); } } } @@ -533,7 +533,7 @@ public class ReflectionUtils { try { return LOOKUP.unreflectSetter(field); } catch (IllegalAccessException ex) { - return null; + throw new RuntimeException(ex); } } } From 95e0674af59a74ce05a6dc7e07e25a72430a254c Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Thu, 5 Jun 2025 22:49:08 +0800 Subject: [PATCH 05/14] =?UTF-8?q?refactor(bukkit):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=8F=8D=E5=B0=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reflection/minecraft/CoreReflections.java | 34 ++- .../minecraft/NetworkReflections.java | 238 +++++++++++------- .../core/util/ReflectionUtils.java | 30 +-- 3 files changed, 179 insertions(+), 123 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java index 986c58c50..eafbdc60e 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java @@ -3274,18 +3274,26 @@ public final class CoreReflections { ) ); - public static final MethodHandle handle$ServerEntity$broadcastSetter = requireNonNull( - ReflectionUtils.unreflectSetter(field$ServerEntity$broadcast) - .asType(MethodType.methodType(void.class, Object.class, Consumer.class)) - ); + public static final MethodHandle handle$ServerEntity$broadcastSetter; + public static final MethodHandle handle$ServerEntity$updateIntervalSetter; + public static final MethodHandle handle$ServerPlayer$connectionGetter; - public static final MethodHandle handle$ServerEntity$updateIntervalSetter = requireNonNull( - ReflectionUtils.unreflectSetter(field$ServerEntity$updateInterval) - .asType(MethodType.methodType(void.class, Object.class, int.class)) - ); - - public static final MethodHandle handle$ServerPlayer$connectionGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerPlayer$connection) - .asType(MethodType.methodType(Object.class, Object.class)) - ); + static { + try { + handle$ServerEntity$broadcastSetter = requireNonNull( + ReflectionUtils.unreflectSetter(field$ServerEntity$broadcast) + .asType(MethodType.methodType(void.class, Object.class, Consumer.class)) + ); + handle$ServerEntity$updateIntervalSetter = requireNonNull( + ReflectionUtils.unreflectSetter(field$ServerEntity$updateInterval) + .asType(MethodType.methodType(void.class, Object.class, int.class)) + ); + handle$ServerPlayer$connectionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerPlayer$connection) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java index 83ff087e5..bf3019c03 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java @@ -1296,121 +1296,177 @@ public final class NetworkReflections { .map(it -> ReflectionUtils.getConstructor(it, float.class, boolean.class)) .orElse(null); - public static final MethodHandle handle$ServerboundRenameItemPacket$nameGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundRenameItemPacket$name) - .asType(MethodType.methodType(String.class, Object.class)) - ); + public static final MethodHandle handle$ServerboundRenameItemPacket$nameGetter; + public static final MethodHandle handle$ServerboundRenameItemPacket$nameSetter; + public static final MethodHandle handle$ServerboundHelloPacket$nameGetter; + public static final MethodHandle handle$ServerboundHelloPacket$uuidGetter; + public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter; + public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter; + public static final MethodHandle handle$ServerboundInteractPacket$actionGetter; + public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter; + public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter; + public static final MethodHandle handle$ServerboundSignUpdatePacket$linesGetter; + public static final MethodHandle handleServerboundEditBookPacket$pagesGetter; + public static final MethodHandle handle$ServerboundEditBookPacket$titleGetter; + public static final MethodHandle handle$ServerboundEditBookPacket$slotGetter; + public static final MethodHandle handle$ServerboundResourcePackPacket$actionGetter; + public static final MethodHandle handle$ClientboundEntityEventPacket$entityIdGetter; + public static final MethodHandle handle$ClientboundEntityEventPacket$eventIdGetter; + public static final MethodHandle handle$ClientIntentionPacket$protocolVersionGetter; - public static final MethodHandle handle$ServerboundRenameItemPacket$nameSetter = requireNonNull( - ReflectionUtils.unreflectSetter(field$ServerboundRenameItemPacket$name) - .asType(MethodType.methodType(void.class, Object.class, String.class)) - ); - - public static final MethodHandle handle$ServerboundHelloPacket$nameGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$name) - .asType(MethodType.methodType(String.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundHelloPacket$uuidGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$uuid) - .asType(MethodType.methodType(VersionHelper.isOrAbove1_20_2() ? UUID.class : Optional.class, Object.class)) - ); + static { + try { + handle$ServerboundRenameItemPacket$nameGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundRenameItemPacket$name) + .asType(MethodType.methodType(String.class, Object.class)) + ); + handle$ServerboundRenameItemPacket$nameSetter = requireNonNull( + ReflectionUtils.unreflectSetter(field$ServerboundRenameItemPacket$name) + .asType(MethodType.methodType(void.class, Object.class, String.class)) + ); + handle$ServerboundHelloPacket$nameGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$name) + .asType(MethodType.methodType(String.class, Object.class)) + ); + handle$ServerboundHelloPacket$uuidGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundHelloPacket$uuid) + .asType(MethodType.methodType(VersionHelper.isOrAbove1_20_2() ? UUID.class : Optional.class, Object.class)) + ); + handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$itemStack) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$slotNum) + .asType(MethodType.methodType(VersionHelper.isOrAbove1_20_5() ? short.class : int.class, Object.class)) + ); + handle$ServerboundInteractPacket$actionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$action) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$hand) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$location) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + handle$ServerboundSignUpdatePacket$linesGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundSignUpdatePacket$lines) + .asType(MethodType.methodType(String[].class, Object.class)) + ); + handleServerboundEditBookPacket$pagesGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$pages) + .asType(MethodType.methodType(List.class, Object.class)) + ); + handle$ServerboundEditBookPacket$titleGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$title) + .asType(MethodType.methodType(Optional.class, Object.class)) + ); + handle$ServerboundEditBookPacket$slotGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$slot) + .asType(MethodType.methodType(int.class, Object.class)) + ); + handle$ServerboundResourcePackPacket$actionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundResourcePackPacket$action) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + handle$ClientboundEntityEventPacket$entityIdGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$entityId) + .asType(MethodType.methodType(int.class, Object.class)) + ); + handle$ClientboundEntityEventPacket$eventIdGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$eventId) + .asType(MethodType.methodType(byte.class, Object.class)) + ); + handle$ClientIntentionPacket$protocolVersionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientIntentionPacket$protocolVersion) + .asType(MethodType.methodType(int.class, Object.class)) + ); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } public static final MethodHandle handle$ClientboundRespawnPacket$dimensionGetter = Optional.ofNullable(field$ClientboundRespawnPacket$dimension) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); public static final MethodHandle handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundRespawnPacket$commonPlayerSpawnInfo) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); public static final MethodHandle handle$CommonPlayerSpawnInfo$dimensionGetter = Optional.ofNullable(field$CommonPlayerSpawnInfo$dimension) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); public static final MethodHandle handle$ClientboundLoginPacket$dimensionGetter = Optional.ofNullable(field$ClientboundLoginPacket$dimension) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); public static final MethodHandle handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundLoginPacket$commonPlayerSpawnInfo) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); - public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$itemStackGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$itemStack) - .asType(MethodType.methodType(Object.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundSetCreativeModeSlotPacket$slotNumGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundSetCreativeModeSlotPacket$slotNum) - .asType(MethodType.methodType(VersionHelper.isOrAbove1_20_5() ? short.class : int.class, Object.class)) - ); - public static final MethodHandle handle$ServerboundPickItemFromBlockPacket$posGetter = Optional.ofNullable(field$ServerboundPickItemFromBlockPacket$pos) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); public static final MethodHandle handle$ServerboundPickItemFromEntityPacket$idGetter = Optional.ofNullable(field$ServerboundPickItemFromEntityPacket$id) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(int.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(int.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); - public static final MethodHandle handle$ServerboundInteractPacket$actionGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$action) - .asType(MethodType.methodType(Object.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$handGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$hand) - .asType(MethodType.methodType(Object.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundInteractPacket$InteractionAtLocationAction$locationGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundInteractPacket$InteractionAtLocationAction$location) - .asType(MethodType.methodType(Object.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundSignUpdatePacket$linesGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundSignUpdatePacket$lines) - .asType(MethodType.methodType(String[].class, Object.class)) - ); - - public static final MethodHandle handleServerboundEditBookPacket$pagesGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$pages) - .asType(MethodType.methodType(List.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundEditBookPacket$titleGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$title) - .asType(MethodType.methodType(Optional.class, Object.class)) - ); - - public static final MethodHandle handle$ServerboundEditBookPacket$slotGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundEditBookPacket$slot) - .asType(MethodType.methodType(int.class, Object.class)) - ); - public static final MethodHandle handle$ServerboundCustomPayloadPacket$payloadGetter = Optional.ofNullable(field$ServerboundCustomPayloadPacket$payload) - .map(it -> ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class))) + .map(it -> { + try { + return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) .orElse(null); - public static final MethodHandle handle$ServerboundResourcePackPacket$actionGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ServerboundResourcePackPacket$action) - .asType(MethodType.methodType(Object.class, Object.class)) - ); - - public static final MethodHandle handle$ClientboundEntityEventPacket$entityIdGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$entityId) - .asType(MethodType.methodType(int.class, Object.class)) - ); - - public static final MethodHandle handle$ClientboundEntityEventPacket$eventIdGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ClientboundEntityEventPacket$eventId) - .asType(MethodType.methodType(byte.class, Object.class)) - ); - - public static final MethodHandle handle$ClientIntentionPacket$protocolVersionGetter = requireNonNull( - ReflectionUtils.unreflectGetter(field$ClientIntentionPacket$protocolVersion) - .asType(MethodType.methodType(int.class, Object.class)) - ); - } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java b/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java index 5022cc141..ea6759cfb 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/ReflectionUtils.java @@ -485,16 +485,21 @@ public class ReflectionUtils { return constructors[0]; } - public static MethodHandle unreflectGetter(Field field) { + public static MethodHandle unreflectGetter(Field field) throws IllegalAccessException { try { return LOOKUP.unreflectGetter(field); } catch (IllegalAccessException e) { field.setAccessible(true); - try { - return LOOKUP.unreflectGetter(field); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex); - } + return LOOKUP.unreflectGetter(field); + } + } + + public static MethodHandle unreflectSetter(Field field) throws IllegalAccessException { + try { + return LOOKUP.unreflectSetter(field); + } catch (IllegalAccessException e) { + field.setAccessible(true); + return LOOKUP.unreflectSetter(field); } } @@ -524,17 +529,4 @@ public class ReflectionUtils { return null; } } - - public static MethodHandle unreflectSetter(Field field) { - try { - return LOOKUP.unreflectSetter(field); - } catch (IllegalAccessException e) { - field.setAccessible(true); - try { - return LOOKUP.unreflectSetter(field); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex); - } - } - } } From 58c7751a69e8ffeaec7abe2c25c21d1fedde79a2 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Thu, 5 Jun 2025 23:02:37 +0800 Subject: [PATCH 06/14] =?UTF-8?q?refactor(bukkit):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=8F=8D=E5=B0=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reflection/minecraft/CoreReflections.java | 2 +- .../minecraft/NetworkReflections.java | 157 +++++++++--------- 2 files changed, 76 insertions(+), 83 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java index eafbdc60e..6371c5b08 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/CoreReflections.java @@ -3293,7 +3293,7 @@ public final class CoreReflections { .asType(MethodType.methodType(Object.class, Object.class)) ); } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new ReflectionInitException("Failed to initialize reflection", e); } } } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java index bf3019c03..27ceab131 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/reflection/minecraft/NetworkReflections.java @@ -1,6 +1,7 @@ package net.momirealms.craftengine.bukkit.plugin.reflection.minecraft; import io.netty.buffer.ByteBuf; +import net.momirealms.craftengine.bukkit.plugin.reflection.ReflectionInitException; import net.momirealms.craftengine.bukkit.util.BukkitReflectionUtils; import net.momirealms.craftengine.core.util.ReflectionUtils; import net.momirealms.craftengine.core.util.VersionHelper; @@ -1313,6 +1314,14 @@ public final class NetworkReflections { public static final MethodHandle handle$ClientboundEntityEventPacket$entityIdGetter; public static final MethodHandle handle$ClientboundEntityEventPacket$eventIdGetter; public static final MethodHandle handle$ClientIntentionPacket$protocolVersionGetter; + public static final MethodHandle handle$ClientboundRespawnPacket$dimensionGetter; + public static final MethodHandle handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter; + public static final MethodHandle handle$CommonPlayerSpawnInfo$dimensionGetter; + public static final MethodHandle handle$ClientboundLoginPacket$dimensionGetter; + public static final MethodHandle handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter; + public static final MethodHandle handle$ServerboundPickItemFromBlockPacket$posGetter; + public static final MethodHandle handle$ServerboundPickItemFromEntityPacket$idGetter; + public static final MethodHandle handle$ServerboundCustomPayloadPacket$payloadGetter; static { try { @@ -1384,89 +1393,73 @@ public final class NetworkReflections { ReflectionUtils.unreflectGetter(field$ClientIntentionPacket$protocolVersion) .asType(MethodType.methodType(int.class, Object.class)) ); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); + if (field$ServerboundCustomPayloadPacket$payload != null) { + handle$ServerboundCustomPayloadPacket$payloadGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundCustomPayloadPacket$payload) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$ServerboundCustomPayloadPacket$payloadGetter = null; + } + if (field$ServerboundPickItemFromEntityPacket$id != null) { + handle$ServerboundPickItemFromEntityPacket$idGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundPickItemFromEntityPacket$id) + .asType(MethodType.methodType(int.class, Object.class)) + ); + } else { + handle$ServerboundPickItemFromEntityPacket$idGetter = null; + } + if (field$ServerboundPickItemFromBlockPacket$pos != null) { + handle$ServerboundPickItemFromBlockPacket$posGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ServerboundPickItemFromBlockPacket$pos) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$ServerboundPickItemFromBlockPacket$posGetter = null; + } + if (field$ClientboundLoginPacket$commonPlayerSpawnInfo != null) { + handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundLoginPacket$commonPlayerSpawnInfo) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter = null; + } + if (field$ClientboundLoginPacket$dimension != null) { + handle$ClientboundLoginPacket$dimensionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundLoginPacket$dimension) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$ClientboundLoginPacket$dimensionGetter = null; + } + if (field$CommonPlayerSpawnInfo$dimension != null) { + handle$CommonPlayerSpawnInfo$dimensionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$CommonPlayerSpawnInfo$dimension) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$CommonPlayerSpawnInfo$dimensionGetter = null; + } + if (field$ClientboundRespawnPacket$commonPlayerSpawnInfo != null) { + handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundRespawnPacket$commonPlayerSpawnInfo) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter = null; + } + if (field$ClientboundRespawnPacket$dimension != null) { + handle$ClientboundRespawnPacket$dimensionGetter = requireNonNull( + ReflectionUtils.unreflectGetter(field$ClientboundRespawnPacket$dimension) + .asType(MethodType.methodType(Object.class, Object.class)) + ); + } else { + handle$ClientboundRespawnPacket$dimensionGetter = null; + } + } catch (Throwable e) { + throw new ReflectionInitException("Failed to initialize reflection", e); } } - public static final MethodHandle handle$ClientboundRespawnPacket$dimensionGetter = Optional.ofNullable(field$ClientboundRespawnPacket$dimension) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$ClientboundRespawnPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundRespawnPacket$commonPlayerSpawnInfo) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$CommonPlayerSpawnInfo$dimensionGetter = Optional.ofNullable(field$CommonPlayerSpawnInfo$dimension) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$ClientboundLoginPacket$dimensionGetter = Optional.ofNullable(field$ClientboundLoginPacket$dimension) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$ClientboundLoginPacket$commonPlayerSpawnInfoGetter = Optional.ofNullable(field$ClientboundLoginPacket$commonPlayerSpawnInfo) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$ServerboundPickItemFromBlockPacket$posGetter = Optional.ofNullable(field$ServerboundPickItemFromBlockPacket$pos) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$ServerboundPickItemFromEntityPacket$idGetter = Optional.ofNullable(field$ServerboundPickItemFromEntityPacket$id) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(int.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - - public static final MethodHandle handle$ServerboundCustomPayloadPacket$payloadGetter = Optional.ofNullable(field$ServerboundCustomPayloadPacket$payload) - .map(it -> { - try { - return ReflectionUtils.unreflectGetter(it).asType(MethodType.methodType(Object.class, Object.class)); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }) - .orElse(null); - } From b8483c00e8d2601b20ca96d4673b753604bcb2f9 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Fri, 6 Jun 2025 00:24:23 +0800 Subject: [PATCH 07/14] =?UTF-8?q?fix(item):=20=E6=B7=BB=E5=8A=A0=E6=9C=AA?= =?UTF-8?q?=E7=9F=A5=E7=89=A9=E5=93=81=E7=BB=84=E4=BB=B6=E8=AD=A6=E5=91=8A?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../craftengine/bukkit/item/ComponentItemWrapper.java | 5 +++++ common-files/src/main/resources/translations/en.yml | 1 + common-files/src/main/resources/translations/zh_cn.yml | 1 + gradle.properties | 2 +- 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/ComponentItemWrapper.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/ComponentItemWrapper.java index 892b88c35..f0f1b2ffd 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/ComponentItemWrapper.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/ComponentItemWrapper.java @@ -8,6 +8,7 @@ import net.momirealms.craftengine.bukkit.nms.FastNMS; import net.momirealms.craftengine.bukkit.plugin.reflection.minecraft.CoreReflections; import net.momirealms.craftengine.bukkit.plugin.reflection.minecraft.MRegistryOps; import net.momirealms.craftengine.core.item.ItemWrapper; +import net.momirealms.craftengine.core.plugin.locale.TranslationManager; import net.momirealms.craftengine.core.util.Key; import net.momirealms.sparrow.nbt.Tag; import org.bukkit.inventory.ItemStack; @@ -111,6 +112,10 @@ public class ComponentItemWrapper implements ItemWrapper { private void setComponentInternal(Object type, DynamicOps ops, Object value) { if (value == null) return; Object componentType = ensureDataComponentType(type); + if (componentType == null) { + TranslationManager.instance().log("warning.config.item.component_notfound", type.toString()); + return; + } Codec codec = FastNMS.INSTANCE.method$DataComponentType$codec(componentType); try { DataResult result = codec.parse(ops, value); diff --git a/common-files/src/main/resources/translations/en.yml b/common-files/src/main/resources/translations/en.yml index 4d46ce56c..42e9286ec 100644 --- a/common-files/src/main/resources/translations/en.yml +++ b/common-files/src/main/resources/translations/en.yml @@ -155,6 +155,7 @@ warning.config.item.invalid_material: "Issue found in file - The warning.config.item.invalid_custom_model_data: "Issue found in file - The item '' is using a negative custom model data '' which is invalid." warning.config.item.bad_custom_model_data: "Issue found in file - The item '' is using a custom model data '' that is too large. It's recommended to use a value lower than 16,777,216." warning.config.item.custom_model_data_conflict: "Issue found in file - The item '' is using a custom model data '' that has been occupied by item ''." +warning.config.item.component_notfound: "Issue found - Have item using a component '' that does not exist." warning.config.item.missing_model_id: "Issue found in file - The item '' is missing the required 'custom-model-data' or 'item-model' argument." warning.config.item.missing_model: "Issue found in file - The item '' is missing the required 'model' section for 1.21.4+ resource pack support." warning.config.item.behavior.missing_type: "Issue found in file - The item '' is missing the required 'type' argument for its item behavior." diff --git a/common-files/src/main/resources/translations/zh_cn.yml b/common-files/src/main/resources/translations/zh_cn.yml index 9280141c9..84b902036 100644 --- a/common-files/src/main/resources/translations/zh_cn.yml +++ b/common-files/src/main/resources/translations/zh_cn.yml @@ -155,6 +155,7 @@ warning.config.item.invalid_material: "在文件 发现问题 - warning.config.item.invalid_custom_model_data: "在文件 发现问题 - 物品 '' 使用了无效的负数模型值 ''." warning.config.item.bad_custom_model_data: "在文件 发现问题 - 物品 '' 使用的自定义模型数据 '' 数值过大 建议使用小于 16,777,216 的值" warning.config.item.custom_model_data_conflict: "在文件 发现问题 - 物品 '' 使用的自定义模型数据 '' 已被物品 '' 占用" +warning.config.item.component_notfound: "发现问题 - 有物品使用了未知的组件 ''" warning.config.item.missing_model_id: "在文件 发现问题 - 物品 '' 缺少必需的 'custom-model-data' 或 'item-model' 参数" warning.config.item.missing_model: "在文件 中发现问题 - 物品 '' 缺少支持 1.21.4+ 资源包必需的 'model' 配置项" warning.config.item.behavior.missing_type: "在文件 发现问题 - 物品 '' 的行为配置缺少必需的 'type' 参数" diff --git a/gradle.properties b/gradle.properties index 9952619bd..747826baf 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ org.gradle.jvmargs=-Xmx1G # Rule: [major update].[feature update].[bug fix] project_version=0.0.56.1 config_version=34 -lang_version=14 +lang_version=15 project_group=net.momirealms latest_supported_version=1.21.5 From 058b327612dd3cf7470f558f855c056dc6111eca Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Fri, 6 Jun 2025 18:32:25 +0800 Subject: [PATCH 08/14] =?UTF-8?q?feat(entity):=20=E4=B8=BA=20EntityData=20?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=B7=BB=E5=8A=A0=20entityDataAccessor=20?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=B9=B6=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../craftengine/bukkit/entity/data/EntityData.java | 1 + .../craftengine/bukkit/entity/data/SimpleEntityData.java | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java index 183a0578d..923211049 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java @@ -7,6 +7,7 @@ public interface EntityData { Object serializer(); int id(); T defaultValue(); + Object entityDataAccessor(); default Object createEntityDataIfNotDefaultValue(T value) { if (defaultValue().equals(value)) return null; diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/SimpleEntityData.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/SimpleEntityData.java index 7993ed163..ae96ccc3a 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/SimpleEntityData.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/SimpleEntityData.java @@ -1,14 +1,18 @@ package net.momirealms.craftengine.bukkit.entity.data; +import net.momirealms.craftengine.bukkit.nms.FastNMS; + public class SimpleEntityData implements EntityData { private final int id; private final Object serializer; private final T defaultValue; + private final Object entityDataAccessor; public SimpleEntityData(int id, Object serializer, T defaultValue) { this.id = id; this.serializer = serializer; this.defaultValue = defaultValue; + this.entityDataAccessor = FastNMS.INSTANCE.constructor$EntityDataAccessor(id, serializer); } @Override @@ -25,4 +29,9 @@ public class SimpleEntityData implements EntityData { public T defaultValue() { return defaultValue; } + + @Override + public Object entityDataAccessor() { + return entityDataAccessor; + } } From 2cd8088109ff653822f163ea8e9d6ed7d35f31b1 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Fri, 6 Jun 2025 18:37:35 +0800 Subject: [PATCH 09/14] =?UTF-8?q?perf(entity):=20=E5=87=8F=E5=B0=91?= =?UTF-8?q?=E4=B8=80=E6=AC=A1=E5=86=97=E4=BD=99=E7=9A=84=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../craftengine/bukkit/entity/data/EntityData.java | 6 +++--- .../craftengine/bukkit/entity/data/EntityDataValue.java | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java index 923211049..a40c5923e 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityData.java @@ -11,17 +11,17 @@ public interface EntityData { default Object createEntityDataIfNotDefaultValue(T value) { if (defaultValue().equals(value)) return null; - return EntityDataValue.create(id(), serializer(), value); + return EntityDataValue.create(id(), serializer(), entityDataAccessor(), value); } default void addEntityDataIfNotDefaultValue(T value, List list) { if (!defaultValue().equals(value)) { - list.add(EntityDataValue.create(id(), serializer(), value)); + list.add(EntityDataValue.create(id(), serializer(), entityDataAccessor(), value)); } } default void addEntityData(T value, List list) { - list.add(EntityDataValue.create(id(), serializer(), value)); + list.add(EntityDataValue.create(id(), serializer(), entityDataAccessor(), value)); } static EntityData of(int id, Object serializer, T defaultValue) { diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityDataValue.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityDataValue.java index 064983cdf..fee5d034f 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityDataValue.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/data/EntityDataValue.java @@ -98,8 +98,7 @@ public class EntityDataValue { throw new IllegalAccessError("Utility class"); } - public static Object create(int id, Object serializer, Object value) { - Object entityDataAccessor = FastNMS.INSTANCE.constructor$EntityDataAccessor(id, serializer); + public static Object create(int id, Object serializer, Object entityDataAccessor, Object value) { return FastNMS.INSTANCE.method$SynchedEntityData$DataValue$create(entityDataAccessor, value); } } From da5c6ad5c2b1b8550766f9178bc89625fea178e1 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Sat, 7 Jun 2025 14:48:04 +0800 Subject: [PATCH 10/14] =?UTF-8?q?fix(bukkit):=20=E5=A2=9E=E5=BC=BA?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E4=BB=A5=E5=85=8D=E5=87=BA=E7=8E=B0=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugin/network/handler/CommonItemPacketHandler.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java index 52359827c..a51598259 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java @@ -2,8 +2,10 @@ package net.momirealms.craftengine.bukkit.plugin.network.handler; import net.momirealms.craftengine.bukkit.item.BukkitItemManager; import net.momirealms.craftengine.bukkit.nms.FastNMS; +import net.momirealms.craftengine.bukkit.plugin.reflection.minecraft.CoreReflections; import net.momirealms.craftengine.bukkit.plugin.user.BukkitServerPlayer; import net.momirealms.craftengine.bukkit.util.EntityDataUtils; +import net.momirealms.craftengine.core.plugin.CraftEngine; import net.momirealms.craftengine.core.plugin.network.ByteBufPacketEvent; import net.momirealms.craftengine.core.plugin.network.EntityPacketHandler; import net.momirealms.craftengine.core.plugin.network.NetWorkUser; @@ -27,6 +29,10 @@ public class CommonItemPacketHandler implements EntityPacketHandler { int entityDataId = FastNMS.INSTANCE.field$SynchedEntityData$DataValue$id(packedItem); if (entityDataId == EntityDataUtils.ITEM_DATA_ID) { Object nmsItemStack = FastNMS.INSTANCE.field$SynchedEntityData$DataValue$value(packedItem); + if (!CoreReflections.clazz$ItemStack.isInstance(nmsItemStack)) { + CraftEngine.instance().logger().warn("Invalid item data for entity " + id); + continue; + } ItemStack itemStack = FastNMS.INSTANCE.method$CraftItemStack$asCraftMirror(nmsItemStack); Optional optional = BukkitItemManager.instance().s2c(itemStack, (BukkitServerPlayer) user); if (optional.isPresent()) { From 665924d1b1666563680b51a38630dcab8a1457fe Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Sat, 7 Jun 2025 15:39:34 +0800 Subject: [PATCH 11/14] =?UTF-8?q?perf(entity):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8A=95=E5=B0=84=E7=89=A9=E5=8F=91=E5=8C=85=E8=BF=87=E5=A4=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../projectile/BukkitProjectileManager.java | 47 ++++++++++++------- .../plugin/network/BukkitNetworkManager.java | 2 +- .../plugin/network/PacketConsumers.java | 2 +- .../projectile/AbstractCustomProjectile.java | 11 +++++ .../entity/projectile/CustomProjectile.java | 4 ++ 5 files changed, 47 insertions(+), 19 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java index b86c2324d..217775d55 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java @@ -161,6 +161,7 @@ public class BukkitProjectileManager implements Listener, ProjectileManager { public class ProjectileInjectTask implements Runnable { private final Projectile projectile; private final SchedulerTask task; + private Object cachedServerEntity; private boolean injected; public ProjectileInjectTask(Projectile projectile) { @@ -180,30 +181,42 @@ public class BukkitProjectileManager implements Listener, ProjectileManager { } Object nmsEntity = FastNMS.INSTANCE.method$CraftEntity$getHandle(this.projectile); if (!this.injected) { - Object trackedEntity = FastNMS.INSTANCE.field$Entity$trackedEntity(nmsEntity); - if (trackedEntity == null) { - return; - } - Object serverEntity = FastNMS.INSTANCE.filed$ChunkMap$TrackedEntity$serverEntity(trackedEntity); - if (serverEntity == null) { - return; - } - try { - CoreReflections.field$ServerEntity$updateInterval.set(serverEntity, 1); - this.injected = true; - } catch (ReflectiveOperationException e) { - plugin.logger().warn("Failed to update server entity tracking interval", e); - } + injectProjectile(nmsEntity, 1); + this.injected = true; } - if (canSpawnParticle(nmsEntity)) { + boolean inGround = FastNMS.INSTANCE.method$AbstractArrow$isInGround(nmsEntity); + if (canSpawnParticle(nmsEntity, inGround)) { this.projectile.getWorld().spawnParticle(ParticleUtils.BUBBLE, this.projectile.getLocation(), 3, 0.1, 0.1, 0.1, 0); } + projectileByEntityId(this.projectile.getEntityId()).ifPresent(customProjectile -> { + customProjectile.setInGroundTime(inGround ? customProjectile.inGroundTime() + 1 : 0); + if (customProjectile.inGroundTime() > 5) { + injectProjectile(nmsEntity, Integer.MAX_VALUE); + } else { + this.injected = false; + } + }); + } + + private void injectProjectile(Object entity, int updateInterval) { + if (this.cachedServerEntity == null) { + Object trackedEntity = FastNMS.INSTANCE.field$Entity$trackedEntity(entity); + if (trackedEntity == null) return; + Object serverEntity = FastNMS.INSTANCE.filed$ChunkMap$TrackedEntity$serverEntity(trackedEntity); + if (serverEntity == null) return; + this.cachedServerEntity = serverEntity; + } + try { + CoreReflections.handle$ServerEntity$updateIntervalSetter.invokeExact(this.cachedServerEntity, updateInterval); + } catch (Throwable e) { + plugin.logger().warn("Failed to update server entity tracking interval", e); + } } - private static boolean canSpawnParticle(Object nmsEntity) { + private static boolean canSpawnParticle(Object nmsEntity, boolean inGround) { if (!FastNMS.INSTANCE.field$Entity$wasTouchingWater(nmsEntity)) return false; if (CoreReflections.clazz$AbstractArrow.isInstance(nmsEntity)) { - return !FastNMS.INSTANCE.method$AbstractArrow$isInGround(nmsEntity); + return !inGround; } return true; } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java index 5f72e032e..7718ddde6 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/BukkitNetworkManager.java @@ -176,7 +176,7 @@ public class BukkitNetworkManager implements NetworkManager, Listener, PluginMes registerS2CByteBufPacketConsumer(VersionHelper.isOrAbove1_20_3() ? PacketConsumers.SET_OBJECTIVE_1_20_3 : PacketConsumers.SET_OBJECTIVE_1_20, this.packetIds.clientboundSetObjectivePacket()); registerS2CByteBufPacketConsumer(PacketConsumers.SET_SCORE_1_20_3, VersionHelper.isOrAbove1_20_3() ? this.packetIds.clientboundSetScorePacket() : -1); registerS2CByteBufPacketConsumer(PacketConsumers.REMOVE_ENTITY, this.packetIds.clientboundRemoveEntitiesPacket()); - registerS2CByteBufPacketConsumer(PacketConsumers.ADD_ENTITY_BYTEBUFFER, this.packetIds.clientboundAddEntityPacket()); + registerS2CByteBufPacketConsumer(PacketConsumers.ADD_ENTITY, this.packetIds.clientboundAddEntityPacket()); registerS2CByteBufPacketConsumer(PacketConsumers.SOUND, this.packetIds.clientboundSoundPacket()); registerS2CByteBufPacketConsumer(PacketConsumers.SET_ENTITY_DATA, this.packetIds.clientboundSetEntityDataPacket()); registerS2CByteBufPacketConsumer(PacketConsumers.CONTAINER_SET_CONTENT, this.packetIds.clientboundContainerSetContentPacket()); diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java index a11ce2e94..a34aa1c44 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/PacketConsumers.java @@ -1458,7 +1458,7 @@ public class PacketConsumers { } } - public static final BiConsumer ADD_ENTITY_BYTEBUFFER = (user, event) -> { + public static final BiConsumer ADD_ENTITY = (user, event) -> { try { FriendlyByteBuf buf = event.getBuffer(); buf.readVarInt(); diff --git a/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/AbstractCustomProjectile.java b/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/AbstractCustomProjectile.java index 117367a84..b61980d16 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/AbstractCustomProjectile.java +++ b/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/AbstractCustomProjectile.java @@ -6,6 +6,7 @@ public abstract class AbstractCustomProjectile implements CustomProjectile { protected final ProjectileMeta meta; protected final Projectile projectile; protected final Item item; + private int inGroundTime; protected AbstractCustomProjectile(ProjectileMeta meta, Projectile projectile, Item item) { this.meta = meta; @@ -27,4 +28,14 @@ public abstract class AbstractCustomProjectile implements CustomProjectile { public Item item() { return item; } + + @Override + public int inGroundTime() { + return inGroundTime; + } + + @Override + public void setInGroundTime(int inGroundTime) { + this.inGroundTime = inGroundTime; + } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/CustomProjectile.java b/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/CustomProjectile.java index 661f2d4ac..057c932ef 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/CustomProjectile.java +++ b/core/src/main/java/net/momirealms/craftengine/core/entity/projectile/CustomProjectile.java @@ -9,4 +9,8 @@ public interface CustomProjectile { Projectile projectile(); Item item(); + + int inGroundTime(); + + void setInGroundTime(int inGroundTime); } From b6023fba40e4c30fb8fe4e6b9302e925086170bf Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Sat, 7 Jun 2025 15:59:20 +0800 Subject: [PATCH 12/14] =?UTF-8?q?perf(entity):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=B3=A8=E5=85=A5=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../projectile/BukkitProjectileManager.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java index 217775d55..0bf5e8b2f 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/entity/projectile/BukkitProjectileManager.java @@ -163,6 +163,8 @@ public class BukkitProjectileManager implements Listener, ProjectileManager { private final SchedulerTask task; private Object cachedServerEntity; private boolean injected; + private int lastInjectedInterval = -1; + private boolean wasInGround; public ProjectileInjectTask(Projectile projectile) { this.projectile = projectile; @@ -183,6 +185,7 @@ public class BukkitProjectileManager implements Listener, ProjectileManager { if (!this.injected) { injectProjectile(nmsEntity, 1); this.injected = true; + this.lastInjectedInterval = 1; } boolean inGround = FastNMS.INSTANCE.method$AbstractArrow$isInGround(nmsEntity); if (canSpawnParticle(nmsEntity, inGround)) { @@ -191,10 +194,15 @@ public class BukkitProjectileManager implements Listener, ProjectileManager { projectileByEntityId(this.projectile.getEntityId()).ifPresent(customProjectile -> { customProjectile.setInGroundTime(inGround ? customProjectile.inGroundTime() + 1 : 0); if (customProjectile.inGroundTime() > 5) { - injectProjectile(nmsEntity, Integer.MAX_VALUE); - } else { - this.injected = false; + if (lastInjectedInterval != Integer.MAX_VALUE) { + injectProjectile(nmsEntity, Integer.MAX_VALUE); + } + } else if (!inGround && wasInGround) { + if (lastInjectedInterval != 1) { + injectProjectile(nmsEntity, 1); + } } + this.wasInGround = inGround; }); } @@ -208,6 +216,7 @@ public class BukkitProjectileManager implements Listener, ProjectileManager { } try { CoreReflections.handle$ServerEntity$updateIntervalSetter.invokeExact(this.cachedServerEntity, updateInterval); + this.lastInjectedInterval = updateInterval; } catch (Throwable e) { plugin.logger().warn("Failed to update server entity tracking interval", e); } From beb6465838792ac840b451b70557a1b8d7783cf8 Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Sun, 8 Jun 2025 00:39:30 +0800 Subject: [PATCH 13/14] =?UTF-8?q?fix(network):=20=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=E7=9E=8E=E6=90=9E=E5=AF=BC=E8=87=B4=E7=9A=84?= =?UTF-8?q?=E5=AE=9E=E4=BD=93=E7=89=A9=E5=93=81=E6=97=A0=E6=B3=95=E8=A2=AB?= =?UTF-8?q?=E6=AD=A3=E7=A1=AE=E5=A4=84=E7=90=86=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugin/network/handler/CommonItemPacketHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java index 8b89f725a..df172d479 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/network/handler/CommonItemPacketHandler.java @@ -27,9 +27,9 @@ public class CommonItemPacketHandler implements EntityPacketHandler { for (int i = 0; i < packedItems.size(); i++) { Object packedItem = packedItems.get(i); int entityDataId = FastNMS.INSTANCE.field$SynchedEntityData$DataValue$id(packedItem); - // TODO 检查为什么会导致问题,难道是其他插件乱发entity id? - if (entityDataId == EntityDataUtils.ITEM_DATA_ID && CoreReflections.clazz$ItemStack.isInstance(packedItem)) { + if (entityDataId == EntityDataUtils.ITEM_DATA_ID) { Object nmsItemStack = FastNMS.INSTANCE.field$SynchedEntityData$DataValue$value(packedItem); + // TODO 检查为什么会导致问题,难道是其他插件乱发entity id? if (!CoreReflections.clazz$ItemStack.isInstance(nmsItemStack)) { CraftEngine.instance().logger().warn("Invalid item data for entity " + id); continue; From 9f09c8f114a04676d342d561179758697dd355ae Mon Sep 17 00:00:00 2001 From: jhqwqmc <2110242767@qq.com> Date: Sun, 8 Jun 2025 01:10:23 +0800 Subject: [PATCH 14/14] =?UTF-8?q?feat(debug):=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=AE=9E=E4=BD=93id2uuid=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugin/command/BukkitCommandManager.java | 1 + .../feature/DebugEntityId2UUIDCommand.java | 59 +++++++++++++++++++ common-files/src/main/resources/commands.yml | 7 +++ gradle.properties | 2 +- 4 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/DebugEntityId2UUIDCommand.java diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/BukkitCommandManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/BukkitCommandManager.java index 6701320b9..ccc824bd9 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/BukkitCommandManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/BukkitCommandManager.java @@ -48,6 +48,7 @@ public class BukkitCommandManager extends AbstractCommandManager new DebugSpawnFurnitureCommand(this, plugin), new DebugTargetBlockCommand(this, plugin), new DebugIsSectionInjectedCommand(this, plugin), + new DebugEntityId2UUIDCommand(this, plugin), new TotemAnimationCommand(this, plugin), new EnableResourceCommand(this, plugin), new DisableResourceCommand(this, plugin), diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/DebugEntityId2UUIDCommand.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/DebugEntityId2UUIDCommand.java new file mode 100644 index 000000000..f5bacc952 --- /dev/null +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/DebugEntityId2UUIDCommand.java @@ -0,0 +1,59 @@ +package net.momirealms.craftengine.bukkit.plugin.command.feature; + +import net.momirealms.craftengine.bukkit.nms.FastNMS; +import net.momirealms.craftengine.bukkit.plugin.command.BukkitCommandFeature; +import net.momirealms.craftengine.core.plugin.CraftEngine; +import net.momirealms.craftengine.core.plugin.command.CraftEngineCommandManager; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.incendo.cloud.Command; +import org.incendo.cloud.CommandManager; +import org.incendo.cloud.bukkit.parser.WorldParser; +import org.incendo.cloud.parser.standard.IntegerParser; + +public class DebugEntityId2UUIDCommand extends BukkitCommandFeature { + + public DebugEntityId2UUIDCommand(CraftEngineCommandManager commandManager, CraftEngine plugin) { + super(commandManager, plugin); + } + + @Override + public Command.Builder assembleCommand(CommandManager manager, Command.Builder builder) { + return builder + .required("world", WorldParser.worldParser()) + .required("entityId", IntegerParser.integerParser()) + .handler(context -> { + World world = context.get("world"); + int entityId = context.get("entityId"); + Entity entity = FastNMS.INSTANCE.getBukkitEntityById(world, entityId); + if (entity == null) { + context.sender().sendMessage("entity not found"); + return; + } + Location location = entity.getLocation(); + context.sender().sendMessage( + String.format( + """ + =========================== + uuid: %s + name: %s + location: %s,%s,%s + type: %s + =========================== + """, + entity.getUniqueId(), + entity.getName(), + location.x(), location.y(), location.z(), + entity.getType() + ) + ); + }); + } + + @Override + public String getFeatureID() { + return "debug_entity_id_to_uuid"; + } +} diff --git a/common-files/src/main/resources/commands.yml b/common-files/src/main/resources/commands.yml index d600a8e7c..d7b499210 100644 --- a/common-files/src/main/resources/commands.yml +++ b/common-files/src/main/resources/commands.yml @@ -182,6 +182,13 @@ debug_clear_cooldown: - /craftengine debug clear-cooldown - /ce debug clear-cooldown +debug_entity_id_to_uuid: + enable: true + permission: ce.command.debug.entity_id_to_uuid + usage: + - /craftengine debug entity-id-to-uuid + - /ce debug entity-id-to-uuid + debug_test: enable: true permission: ce.command.debug.test diff --git a/gradle.properties b/gradle.properties index e1b0975d8..e9c2a415d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Project settings # Rule: [major update].[feature update].[bug fix] project_version=0.0.56.2 -config_version=34 +config_version=35 lang_version=15 project_group=net.momirealms latest_supported_version=1.21.5