diff --git a/docs/README.md b/docs/README.md index 0a5bffe1..106b5aa3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,8 +23,8 @@ Progress - [x] Rectify NeoForge([**91303b6970**](https://github.com/neoforged/NeoForge/commit/91303b6970)) - [ ] Start patch - * [x] Bukkit([**69fa4695**](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/69fa4695)) - * [ ] CraftBukkit([**661afb43c**](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/craftbukkit/commits/661afb43c)) + * [x] Bukkit([**8ec77750**](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/8ec77750)) + * [ ] CraftBukkit([**d50f50585**](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/craftbukkit/commits/d50f50585)) * [ ] Spigot ([**d2eba2c8**](https://hub.spigotmc.org/stash/projects/SPIGOT/repos/spigot/commits/d2eba2c8)) * [ ] Bukkit-Patches * [ ] CraftBukkit-Patches diff --git a/nms-patches/net/minecraft/core/cauldron/CauldronInteraction.patch b/nms-patches/net/minecraft/core/cauldron/CauldronInteraction.patch index d9fb2ed9..bf26224f 100644 --- a/nms-patches/net/minecraft/core/cauldron/CauldronInteraction.patch +++ b/nms-patches/net/minecraft/core/cauldron/CauldronInteraction.patch @@ -102,7 +102,7 @@ } @@ -210,12 +236,17 @@ - static EnumInteractionResult emptyBucket(World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, ItemStack itemstack, IBlockData iblockdata, SoundEffect soundeffect) { + static EnumInteractionResult emptyBucket(World world, BlockPos blockposition, EntityHuman entityhuman, EnumHand enumhand, ItemStack itemstack, IBlockData iblockdata, SoundEffect soundeffect) { if (!world.isClientSide) { + // CraftBukkit start + if (!LayeredCauldronBlock.changeLevel(iblockdata, world, blockposition, iblockdata, entityhuman, CauldronLevelChangeEvent.ChangeReason.BUCKET_EMPTY)) { diff --git a/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShears.patch b/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShears.patch index 6e092687..1d22573d 100644 --- a/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShears.patch +++ b/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShears.patch @@ -43,7 +43,7 @@ + // CraftBukkit end if (!worldserver.isClientSide()) { - BlockPosition blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + BlockPos blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); - this.setSuccess(tryShearBeehive(worldserver, blockposition) || tryShearLivingEntity(worldserver, blockposition, itemstack)); + this.setSuccess(tryShearBeehive(worldserver, blockposition) || tryShearLivingEntity(worldserver, blockposition, itemstack, bukkitBlock, craftItem)); // CraftBukkit @@ -54,8 +54,8 @@ return false; } -- private static boolean tryShearLivingEntity(WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack) { -+ private static boolean tryShearLivingEntity(WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, org.bukkit.block.Block bukkitBlock, CraftItemStack craftItem) { // CraftBukkit - add args +- private static boolean tryShearLivingEntity(WorldServer worldserver, BlockPos blockposition, ItemStack itemstack) { ++ private static boolean tryShearLivingEntity(WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, org.bukkit.block.Block bukkitBlock, CraftItemStack craftItem) { // CraftBukkit - add args List list = worldserver.getEntitiesOfClass(EntityLiving.class, new AxisAlignedBB(blockposition), IEntitySelector.NO_SPECTATORS); Iterator iterator = list.iterator(); diff --git a/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShulkerBox.patch b/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShulkerBox.patch index 4c4b2001..77bb3b25 100644 --- a/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShulkerBox.patch +++ b/nms-patches/net/minecraft/core/dispenser/DispenseBehaviorShulkerBox.patch @@ -14,7 +14,7 @@ private static final Logger LOGGER = LogUtils.getLogger(); @@ -26,6 +32,30 @@ - BlockPosition blockposition = sourceblock.pos().relative(enumdirection); + BlockPos blockposition = sourceblock.pos().relative(enumdirection); EnumDirection enumdirection1 = sourceblock.level().isEmptyBlock(blockposition.below()) ? enumdirection : EnumDirection.UP; + // CraftBukkit start diff --git a/nms-patches/net/minecraft/core/dispenser/IDispenseBehavior.patch b/nms-patches/net/minecraft/core/dispenser/IDispenseBehavior.patch index 502a05bc..5ca53ecf 100644 --- a/nms-patches/net/minecraft/core/dispenser/IDispenseBehavior.patch +++ b/nms-patches/net/minecraft/core/dispenser/IDispenseBehavior.patch @@ -70,7 +70,7 @@ } @@ -116,13 +160,41 @@ EnumDirection enumdirection = (EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING); - BlockPosition blockposition = sourceblock.pos().relative(enumdirection); + BlockPos blockposition = sourceblock.pos().relative(enumdirection); WorldServer worldserver = sourceblock.level(); + + // CraftBukkit start @@ -186,7 +186,7 @@ return itemstack; } @@ -202,6 +327,38 @@ - BlockPosition blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + BlockPos blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); WorldServer worldserver = sourceblock.level(); + // CraftBukkit start @@ -296,7 +296,7 @@ + this.setSuccess(true); EnumDirection enumdirection = (EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING); - BlockPosition blockposition = sourceblock.pos().relative(enumdirection); + BlockPos blockposition = sourceblock.pos().relative(enumdirection); IBlockData iblockdata = worldserver.getBlockState(blockposition); if (BlockFireAbstract.canBePlacedAt(worldserver, blockposition, enumdirection)) { @@ -317,7 +317,7 @@ @@ -283,12 +494,62 @@ this.setSuccess(true); WorldServer worldserver = sourceblock.level(); - BlockPosition blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + BlockPos blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + // CraftBukkit start + org.bukkit.block.Block block = CraftBlock.at(worldserver, sourceblock.pos()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack); @@ -380,7 +380,7 @@ @@ -298,12 +559,41 @@ protected ItemStack execute(SourceBlock sourceblock, ItemStack itemstack) { WorldServer worldserver = sourceblock.level(); - BlockPosition blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + BlockPos blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); - EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(worldserver, (double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, (EntityLiving) null); + // CraftBukkit start + // EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(worldserver, (double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, (EntityLiving) null); @@ -423,7 +423,7 @@ }); @@ -314,6 +604,30 @@ EnumDirection enumdirection = (EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING); - BlockPosition blockposition = sourceblock.pos().relative(enumdirection); + BlockPos blockposition = sourceblock.pos().relative(enumdirection); + // CraftBukkit start + org.bukkit.block.Block bukkitBlock = CraftBlock.at(worldserver, sourceblock.pos()); @@ -453,7 +453,7 @@ worldserver.setBlock(blockposition, (IBlockData) Blocks.WITHER_SKELETON_SKULL.defaultBlockState().setValue(BlockSkull.ROTATION, RotationSegment.convertToSegment(enumdirection)), 3); worldserver.gameEvent((Entity) null, (Holder) GameEvent.BLOCK_PLACE, blockposition); @@ -339,6 +653,30 @@ - BlockPosition blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + BlockPos blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); BlockPumpkinCarved blockpumpkincarved = (BlockPumpkinCarved) Blocks.CARVED_PUMPKIN; + // CraftBukkit start @@ -484,7 +484,7 @@ if (!worldserver.isClientSide) { worldserver.setBlock(blockposition, blockpumpkincarved.defaultBlockState(), 3); @@ -377,6 +715,30 @@ - BlockPosition blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); + BlockPos blockposition = sourceblock.pos().relative((EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING)); IBlockData iblockdata = worldserver.getBlockState(blockposition); + // CraftBukkit start diff --git a/nms-patches/net/minecraft/server/MinecraftServer.patch b/nms-patches/net/minecraft/server/MinecraftServer.patch index fd9dbabc..c6a54325 100644 --- a/nms-patches/net/minecraft/server/MinecraftServer.patch +++ b/nms-patches/net/minecraft/server/MinecraftServer.patch @@ -420,7 +420,7 @@ + if (spawn.getWorld() != worldserver.getWorld()) { + throw new IllegalStateException("Cannot set spawn point for " + iworlddataserver.getLevelName() + " to be in another world (" + spawn.getWorld().getName() + ")"); + } else { -+ iworlddataserver.setSpawn(new BlockPosition(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()), spawn.getYaw()); ++ iworlddataserver.setSpawn(new BlockPos(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()), spawn.getYaw()); + return; + } + } @@ -442,7 +442,7 @@ + // CraftBukkit end MinecraftServer.LOGGER.info("Preparing start region for dimension {}", worldserver.dimension().location()); - BlockPosition blockposition = worldserver.getSharedSpawnPos(); + BlockPos blockposition = worldserver.getSharedSpawnPos(); @@ -527,20 +778,22 @@ this.nextTickTimeNanos = SystemUtils.getNanos(); diff --git a/nms-patches/net/minecraft/server/commands/CommandSetWorldSpawn.patch b/nms-patches/net/minecraft/server/commands/CommandSetWorldSpawn.patch index be68ecb3..92eeac3e 100644 --- a/nms-patches/net/minecraft/server/commands/CommandSetWorldSpawn.patch +++ b/nms-patches/net/minecraft/server/commands/CommandSetWorldSpawn.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/server/commands/CommandSetWorldSpawn.java +++ b/net/minecraft/server/commands/CommandSetWorldSpawn.java @@ -30,7 +30,7 @@ - private static int setSpawn(CommandListenerWrapper commandlistenerwrapper, BlockPosition blockposition, float f) { + private static int setSpawn(CommandListenerWrapper commandlistenerwrapper, BlockPos blockposition, float f) { WorldServer worldserver = commandlistenerwrapper.getLevel(); - if (worldserver.dimension() != World.OVERWORLD) { diff --git a/nms-patches/net/minecraft/server/level/EntityPlayer.patch b/nms-patches/net/minecraft/server/level/EntityPlayer.patch index d2126ebd..9b78f149 100644 --- a/nms-patches/net/minecraft/server/level/EntityPlayer.patch +++ b/nms-patches/net/minecraft/server/level/EntityPlayer.patch @@ -110,8 +110,8 @@ + + // Yes, this doesn't match Vanilla, but it's the best we can do for now. + // If this is an issue, PRs are welcome -+ public final BlockPosition getSpawnPoint(WorldServer worldserver) { -+ BlockPosition blockposition = worldserver.getSharedSpawnPos(); ++ public final BlockPos getSpawnPoint(WorldServer worldserver) { ++ BlockPos blockposition = worldserver.getSharedSpawnPos(); + + if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) { + int i = Math.max(0, this.server.getSpawnRadius(worldserver)); @@ -135,7 +135,7 @@ + int i2 = (k1 + j1 * l1) % i1; + int j2 = i2 % (i * 2 + 1); + int k2 = i2 / (i * 2 + 1); -+ BlockPosition blockposition1 = WorldProviderNormal.getOverworldRespawnPos(worldserver, blockposition.getX() + j2 - i, blockposition.getZ() + k2 - i); ++ BlockPos blockposition1 = WorldProviderNormal.getOverworldRespawnPos(worldserver, blockposition.getX() + j2 - i, blockposition.getZ() + k2 - i); + + if (blockposition1 != null) { + return blockposition1; @@ -148,9 +148,9 @@ + // CraftBukkit end @Override - public BlockPosition adjustSpawnLocation(WorldServer worldserver, BlockPosition blockposition) { + public BlockPos adjustSpawnLocation(WorldServer worldserver, BlockPos blockposition) { AxisAlignedBB axisalignedbb = this.getDimensions(EntityPose.STANDING).makeBoundingBox(Vec3D.ZERO); - BlockPosition blockposition1 = blockposition; + BlockPos blockposition1 = blockposition; - if (worldserver.dimensionType().hasSkyLight() && worldserver.getServer().getWorldData().getGameType() != EnumGamemode.ADVENTURE) { + if (worldserver.dimensionType().hasSkyLight() && worldserver.serverLevelData.getGameType() != EnumGamemode.ADVENTURE) { // CraftBukkit @@ -208,7 +208,7 @@ + // CraftBukkit end + if (nbttagcompound.contains("SpawnX", 99) && nbttagcompound.contains("SpawnY", 99) && nbttagcompound.contains("SpawnZ", 99)) { - this.respawnPosition = new BlockPosition(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), nbttagcompound.getInt("SpawnZ")); + this.respawnPosition = new BlockPos(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), nbttagcompound.getInt("SpawnZ")); this.respawnForced = nbttagcompound.getBoolean("SpawnForced"); this.respawnAngle = nbttagcompound.getFloat("SpawnAngle"); if (nbttagcompound.contains("SpawnDimension")) { @@ -218,11 +218,11 @@ Objects.requireNonNull(logger1); @@ -484,7 +610,7 @@ - dataresult = BlockPosition.CODEC.parse(DynamicOpsNBT.INSTANCE, nbtbase); + dataresult = BlockPos.CODEC.parse(DynamicOpsNBT.INSTANCE, nbtbase); logger = EntityPlayer.LOGGER; Objects.requireNonNull(logger); - dataresult.resultOrPartial(logger::error).ifPresent((blockposition) -> { -+ ((DataResult) dataresult).resultOrPartial(logger::error).ifPresent((blockposition) -> { // CraftBukkit - decompile error ++ ((DataResult) dataresult).resultOrPartial(logger::error).ifPresent((blockposition) -> { // CraftBukkit - decompile error this.raidOmenPosition = blockposition; }); } @@ -516,7 +516,7 @@ + boolean isBedSpawn = false; + boolean isAnchorSpawn = false; + // CraftBukkit end - BlockPosition blockposition = this.getRespawnPosition(); + BlockPos blockposition = this.getRespawnPosition(); float f = this.getRespawnAngle(); boolean flag1 = this.isRespawnForced(); @@ -1116,13 +1358,32 @@ @@ -554,7 +554,7 @@ + // CraftBukkit end } - public static Optional findRespawnAndUseSpawnBlock(WorldServer worldserver, BlockPosition blockposition, float f, boolean flag, boolean flag1) { + public static Optional findRespawnAndUseSpawnBlock(WorldServer worldserver, BlockPos blockposition, float f, boolean flag, boolean flag1) { @@ -1137,11 +1398,11 @@ } @@ -722,11 +722,11 @@ } - @Override -- public Either startSleepInBed(BlockPosition blockposition) { +- public Either startSleepInBed(BlockPos blockposition) { - EnumDirection enumdirection = (EnumDirection) this.level().getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING); - + // CraftBukkit start - moved bed result checks from below into separate method -+ private Either getBedResult(BlockPosition blockposition, EnumDirection enumdirection) { ++ private Either getBedResult(BlockPos blockposition, EnumDirection enumdirection) { if (!this.isSleeping() && this.isAlive()) { - if (!this.level().dimensionType().natural()) { + if (!this.level().dimensionType().natural() || !this.level().dimensionType().bedWorks()) { @@ -755,7 +755,7 @@ + } + + @Override -+ public Either startSleepInBed(BlockPosition blockposition, boolean force) { ++ public Either startSleepInBed(BlockPos blockposition, boolean force) { + EnumDirection enumdirection = (EnumDirection) this.level().getBlockState(blockposition).getValue(BlockFacingHorizontal.FACING); + Either bedResult = this.getBedResult(blockposition, enumdirection); + @@ -797,7 +797,7 @@ + if (!this.isSleeping()) return; // CraftBukkit - Can't leave bed if not in one! + // CraftBukkit start - fire PlayerBedLeaveEvent + CraftPlayer player = this.getBukkitEntity(); -+ BlockPosition bedPosition = this.getSleepingPos().orElse(null); ++ BlockPos bedPosition = this.getSleepingPos().orElse(null); + + org.bukkit.block.Block bed; + if (bedPosition != null) { @@ -1032,7 +1032,7 @@ @Override - public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set set, float f, float f1, boolean flag) { + public boolean teleportTo(WorldServer worldserver, double d0, double d1, double d2, Set set, float f, float f1, boolean flag, TeleportCause cause) { // CraftBukkit - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(BlockPosition.containing(d0, d1, d2)); + ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(BlockPos.containing(d0, d1, d2)); worldserver.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, chunkcoordintpair, 1, this.getId()); @@ -1780,7 +2184,7 @@ @@ -1087,12 +1087,12 @@ @@ -2065,6 +2479,32 @@ } - public void setRespawnPosition(ResourceKey resourcekey, @Nullable BlockPosition blockposition, float f, boolean flag, boolean flag1) { + public void setRespawnPosition(ResourceKey resourcekey, @Nullable BlockPos blockposition, float f, boolean flag, boolean flag1) { + // CraftBukkit start + this.setRespawnPosition(resourcekey, blockposition, f, flag, flag1, PlayerSpawnChangeEvent.Cause.UNKNOWN); + } + -+ public void setRespawnPosition(ResourceKey resourcekey, @Nullable BlockPosition blockposition, float f, boolean flag, boolean flag1, PlayerSpawnChangeEvent.Cause cause) { ++ public void setRespawnPosition(ResourceKey resourcekey, @Nullable BlockPos blockposition, float f, boolean flag, boolean flag1, PlayerSpawnChangeEvent.Cause cause) { + WorldServer newWorld = this.server.getLevel(resourcekey); + Location newSpawn = (blockposition != null) ? CraftLocation.toBukkit(blockposition, newWorld.getWorld(), f, 0) : null; + @@ -1106,7 +1106,7 @@ + + if (newSpawn != null) { + resourcekey = ((CraftWorld) newSpawn.getWorld()).getHandle().dimension(); -+ blockposition = BlockPosition.containing(newSpawn.getX(), newSpawn.getY(), newSpawn.getZ()); ++ blockposition = BlockPos.containing(newSpawn.getX(), newSpawn.getY(), newSpawn.getZ()); + f = newSpawn.getYaw(); + } else { + resourcekey = World.OVERWORLD; @@ -1165,14 +1165,14 @@ + // CraftBukkit start + public static record RespawnPosAngle(Vec3D position, float yaw, boolean isBedSpawn, boolean isAnchorSpawn) { -- public static EntityPlayer.RespawnPosAngle of(Vec3D vec3d, BlockPosition blockposition) { +- public static EntityPlayer.RespawnPosAngle of(Vec3D vec3d, BlockPos blockposition) { - return new EntityPlayer.RespawnPosAngle(vec3d, calculateLookAtYaw(vec3d, blockposition)); -+ public static EntityPlayer.RespawnPosAngle of(Vec3D vec3d, BlockPosition blockposition, boolean isBedSpawn, boolean isAnchorSpawn) { ++ public static EntityPlayer.RespawnPosAngle of(Vec3D vec3d, BlockPos blockposition, boolean isBedSpawn, boolean isAnchorSpawn) { + return new EntityPlayer.RespawnPosAngle(vec3d, calculateLookAtYaw(vec3d, blockposition), isBedSpawn, isAnchorSpawn); + // CraftBukkit end } - private static float calculateLookAtYaw(Vec3D vec3d, BlockPosition blockposition) { + private static float calculateLookAtYaw(Vec3D vec3d, BlockPos blockposition) { @@ -2406,4 +2874,146 @@ return (float) MathHelper.wrapDegrees(MathHelper.atan2(vec3d1.z, vec3d1.x) * 57.2957763671875D - 90.0D); } diff --git a/nms-patches/net/minecraft/server/level/PlayerInteractManager.patch b/nms-patches/net/minecraft/server/level/PlayerInteractManager.patch index 5826f84b..84848dbf 100644 --- a/nms-patches/net/minecraft/server/level/PlayerInteractManager.patch +++ b/nms-patches/net/minecraft/server/level/PlayerInteractManager.patch @@ -156,7 +156,7 @@ } @@ -242,10 +326,65 @@ - public boolean destroyBlock(BlockPosition blockposition) { + public boolean destroyBlock(BlockPos blockposition) { IBlockData iblockdata = this.level.getBlockState(blockposition); + // CraftBukkit start - fire BlockBreakEvent + org.bukkit.block.Block bblock = CraftBlock.at(level, blockposition); @@ -275,11 +275,11 @@ + // CraftBukkit start - whole method + public boolean interactResult = false; + public boolean firedInteract = false; -+ public BlockPosition interactPosition; ++ public BlockPos interactPosition; + public EnumHand interactHand; + public ItemStack interactItemStack; public EnumInteractionResult useItemOn(EntityPlayer entityplayer, World world, ItemStack itemstack, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - BlockPosition blockposition = movingobjectpositionblock.getBlockPos(); + BlockPos blockposition = movingobjectpositionblock.getBlockPos(); IBlockData iblockdata = world.getBlockState(blockposition); + boolean cancelledBlock = false; diff --git a/nms-patches/net/minecraft/server/level/WorldServer.patch b/nms-patches/net/minecraft/server/level/WorldServer.patch index 170108a5..b78cc52d 100644 --- a/nms-patches/net/minecraft/server/level/WorldServer.patch +++ b/nms-patches/net/minecraft/server/level/WorldServer.patch @@ -23,7 +23,7 @@ + public class WorldServer extends World implements ServerEntityGetter, GeneratorAccessSeed { - public static final BlockPosition END_SPAWN_POINT = new BlockPosition(100, 50, 0); + public static final BlockPos END_SPAWN_POINT = new BlockPos(100, 50, 0); @@ -186,7 +203,7 @@ final List players = Lists.newArrayList(); private final ChunkProviderServer chunkSource; @@ -401,7 +401,7 @@ + // CraftBukkit end + @Override - public void destroyBlockProgress(int i, BlockPosition blockposition, int j) { + public void destroyBlockProgress(int i, BlockPos blockposition, int j) { Iterator iterator = this.server.getPlayerList().getPlayers().iterator(); + // CraftBukkit start @@ -517,7 +517,7 @@ @@ -1282,7 +1485,7 @@ @Nullable - public BlockPosition findNearestMapStructure(TagKey tagkey, BlockPosition blockposition, int i, boolean flag) { + public BlockPos findNearestMapStructure(TagKey tagkey, BlockPos blockposition, int i, boolean flag) { - if (!this.server.getWorldData().worldGenOptions().generateStructures()) { + if (!this.serverLevelData.worldGenOptions().generateStructures()) { // CraftBukkit return null; @@ -549,7 +549,7 @@ @@ -1639,6 +1853,11 @@ @Override - public void blockUpdated(BlockPosition blockposition, Block block) { + public void blockUpdated(BlockPos blockposition, Block block) { if (!this.isDebug()) { + // CraftBukkit start + if (populating) { diff --git a/nms-patches/net/minecraft/server/network/PlayerConnection.patch b/nms-patches/net/minecraft/server/network/PlayerConnection.patch index b11116f7..e5bfcf93 100644 --- a/nms-patches/net/minecraft/server/network/PlayerConnection.patch +++ b/nms-patches/net/minecraft/server/network/PlayerConnection.patch @@ -575,7 +575,7 @@ public void handlePlayerAction(PacketPlayInBlockDig packetplayinblockdig) { PlayerConnectionUtils.ensureRunningOnSameThread(packetplayinblockdig, this, this.player.serverLevel()); + if (this.player.isImmobile()) return; // CraftBukkit - BlockPosition blockposition = packetplayinblockdig.getPos(); + BlockPos blockposition = packetplayinblockdig.getPos(); this.player.resetLastActionTime(); @@ -1104,14 +1461,46 @@ @@ -1646,7 +1646,7 @@ + if (this.player.isImmobile()) return; // CraftBukkit this.player.resetLastActionTime(); WorldServer worldserver = this.player.serverLevel(); - BlockPosition blockposition = packetplayinupdatesign.getPos(); + BlockPos blockposition = packetplayinupdatesign.getPos(); @@ -1923,7 +2994,17 @@ @Override public void handlePlayerAbilities(PacketPlayInAbilities packetplayinabilities) { diff --git a/nms-patches/net/minecraft/server/players/PlayerList.patch b/nms-patches/net/minecraft/server/players/PlayerList.patch index f4b02439..ddd9392f 100644 --- a/nms-patches/net/minecraft/server/players/PlayerList.patch +++ b/nms-patches/net/minecraft/server/players/PlayerList.patch @@ -540,7 +540,7 @@ + } + // entityplayer1.initInventoryMenu(); entityplayer1.setHealth(entityplayer1.getHealth()); - BlockPosition blockposition = entityplayer1.getRespawnPosition(); + BlockPos blockposition = entityplayer1.getRespawnPosition(); WorldServer worldserver2 = this.server.getLevel(entityplayer1.getRespawnDimension()); @@ -496,6 +713,27 @@ entityplayer1.connection.send(new PacketPlayOutNamedSoundEffect(SoundEffects.RESPAWN_ANCHOR_DEPLETE, SoundCategory.BLOCKS, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), 1.0F, 1.0F, worldserver.getRandom().nextLong())); diff --git a/nms-patches/net/minecraft/util/SpawnUtil.patch b/nms-patches/net/minecraft/util/SpawnUtil.patch index 47da6b11..3470ba03 100644 --- a/nms-patches/net/minecraft/util/SpawnUtil.patch +++ b/nms-patches/net/minecraft/util/SpawnUtil.patch @@ -3,20 +3,20 @@ @@ -21,6 +21,12 @@ public SpawnUtil() {} - public static Optional trySpawnMob(EntityTypes entitytypes, EntitySpawnReason entityspawnreason, WorldServer worldserver, BlockPosition blockposition, int i, int j, int k, SpawnUtil.a spawnutil_a) { + public static Optional trySpawnMob(EntityTypes entitytypes, EntitySpawnReason entityspawnreason, WorldServer worldserver, BlockPos blockposition, int i, int j, int k, SpawnUtil.a spawnutil_a) { + // CraftBukkit start + return trySpawnMob(entitytypes, entityspawnreason, worldserver, blockposition, i, j, k, spawnutil_a, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT); + } + -+ public static Optional trySpawnMob(EntityTypes entitytypes, EntitySpawnReason entityspawnreason, WorldServer worldserver, BlockPosition blockposition, int i, int j, int k, SpawnUtil.a spawnutil_a, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) { ++ public static Optional trySpawnMob(EntityTypes entitytypes, EntitySpawnReason entityspawnreason, WorldServer worldserver, BlockPos blockposition, int i, int j, int k, SpawnUtil.a spawnutil_a, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) { + // CraftBukkit end - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = blockposition.mutable(); + BlockPos.MutableBlockPos blockposition_mutableblockposition = blockposition.mutable(); for (int l = 0; l < i; ++l) { @@ -29,15 +35,15 @@ blockposition_mutableblockposition.setWithOffset(blockposition, i1, k, j1); - if (worldserver.getWorldBorder().isWithinBounds((BlockPosition) blockposition_mutableblockposition) && moveToPossibleSpawnPosition(worldserver, k, blockposition_mutableblockposition, spawnutil_a)) { + if (worldserver.getWorldBorder().isWithinBounds((BlockPos) blockposition_mutableblockposition) && moveToPossibleSpawnPosition(worldserver, k, blockposition_mutableblockposition, spawnutil_a)) { - T t0 = (EntityInsentient) entitytypes.create(worldserver, (Consumer) null, blockposition_mutableblockposition, entityspawnreason, false, false); + T t0 = entitytypes.create(worldserver, (Consumer) null, blockposition_mutableblockposition, entityspawnreason, false, false); // CraftBukkit - decompile error diff --git a/nms-patches/net/minecraft/world/damagesource/DamageSource.patch b/nms-patches/net/minecraft/world/damagesource/DamageSource.patch index a76f2549..0d14cb09 100644 --- a/nms-patches/net/minecraft/world/damagesource/DamageSource.patch +++ b/nms-patches/net/minecraft/world/damagesource/DamageSource.patch @@ -76,7 +76,7 @@ + return this.directBlock; + } + -+ public DamageSource directBlock(net.minecraft.world.level.World world, net.minecraft.core.BlockPosition blockPosition) { ++ public DamageSource directBlock(net.minecraft.world.level.World world, net.minecraft.core.BlockPos blockPosition) { + if (blockPosition == null || world == null) { + return this; + } diff --git a/nms-patches/net/minecraft/world/entity/ConversionType.patch b/nms-patches/net/minecraft/world/entity/ConversionType.patch index 4aaf08e2..b53c2885 100644 --- a/nms-patches/net/minecraft/world/entity/ConversionType.patch +++ b/nms-patches/net/minecraft/world/entity/ConversionType.patch @@ -5,7 +5,7 @@ import net.minecraft.world.scores.Scoreboard; +// CraftBukkit start -+import net.minecraft.core.BlockPosition; ++import net.minecraft.core.BlockPos; +import org.bukkit.event.entity.EntityRemoveEvent; +// CraftBukkit end + @@ -26,7 +26,7 @@ entityinsentient1.yBodyRot = entityinsentient.yBodyRot; entityinsentient1.setOnGround(entityinsentient.onGround()); - Optional optional = entityinsentient.getSleepingPos(); -+ Optional optional = entityinsentient.getSleepingPos(); // CraftBukkit - decompile error ++ Optional optional = entityinsentient.getSleepingPos(); // CraftBukkit - decompile error Objects.requireNonNull(entityinsentient1); optional.ifPresent(entityinsentient1::setSleepingPos); diff --git a/nms-patches/net/minecraft/world/entity/Entity.patch b/nms-patches/net/minecraft/world/entity/Entity.patch index cf4d28c9..0670ddac 100644 --- a/nms-patches/net/minecraft/world/entity/Entity.patch +++ b/nms-patches/net/minecraft/world/entity/Entity.patch @@ -83,7 +83,7 @@ + public org.bukkit.projectiles.ProjectileSource projectileSource; // For projectiles only + public boolean lastDamageCancelled; // SPIGOT-5339, SPIGOT-6252, SPIGOT-6777: Keep track if the event was canceled + public boolean persistentInvisibility = false; -+ public BlockPosition lastLavaContact; ++ public BlockPos lastLavaContact; + // Marks an entity, that it was removed by a plugin via Entity#remove + // Main use case currently is for SPIGOT-7487, preventing dropping of leash when leash is removed + public boolean pluginRemoved = false; diff --git a/nms-patches/net/minecraft/world/entity/EntityInsentient.patch b/nms-patches/net/minecraft/world/entity/EntityInsentient.patch index a27e3229..e103c573 100644 --- a/nms-patches/net/minecraft/world/entity/EntityInsentient.patch +++ b/nms-patches/net/minecraft/world/entity/EntityInsentient.patch @@ -20,7 +20,7 @@ private static final DataWatcherObject DATA_MOB_FLAGS_ID = DataWatcher.defineId(EntityInsentient.class, DataWatcherRegistry.BYTE); @@ -136,6 +148,8 @@ - private BlockPosition restrictCenter; + private BlockPos restrictCenter; private float restrictRadius; + public boolean aware = true; // CraftBukkit diff --git a/nms-patches/net/minecraft/world/entity/EntityLightning.patch b/nms-patches/net/minecraft/world/entity/EntityLightning.patch index 04073819..3b80921b 100644 --- a/nms-patches/net/minecraft/world/entity/EntityLightning.patch +++ b/nms-patches/net/minecraft/world/entity/EntityLightning.patch @@ -64,7 +64,7 @@ iblockdata = world.getBlockState(blockposition1); } while (!(iblockdata.getBlock() instanceof WeatheringCopper)); -+ BlockPosition blockposition1Final = blockposition1; // CraftBukkit - decompile error ++ BlockPos blockposition1Final = blockposition1; // CraftBukkit - decompile error WeatheringCopper.getPrevious(iblockdata).ifPresent((iblockdata1) -> { - world.setBlockAndUpdate(blockposition1, iblockdata1); + world.setBlockAndUpdate(blockposition1Final, iblockdata1); // CraftBukkit - decompile error diff --git a/nms-patches/net/minecraft/world/entity/EntityLiving.patch b/nms-patches/net/minecraft/world/entity/EntityLiving.patch index 730ea72b..78ab87b7 100644 --- a/nms-patches/net/minecraft/world/entity/EntityLiving.patch +++ b/nms-patches/net/minecraft/world/entity/EntityLiving.patch @@ -689,7 +689,7 @@ + } + // CraftBukkit end + - public Optional getLastClimbablePos() { + public Optional getLastClimbablePos() { return this.lastClimbablePos; } @@ -1746,9 +2052,14 @@ @@ -1114,7 +1114,7 @@ public void stopSleeping() { - Optional optional = this.getSleepingPos(); -+ Optional optional = this.getSleepingPos(); // CraftBukkit - decompile error ++ Optional optional = this.getSleepingPos(); // CraftBukkit - decompile error World world = this.level(); java.util.Objects.requireNonNull(world); @@ -1122,8 +1122,8 @@ @Nullable public EnumDirection getBedOrientation() { -- BlockPosition blockposition = (BlockPosition) this.getSleepingPos().orElse((Object) null); -+ BlockPosition blockposition = (BlockPosition) this.getSleepingPos().orElse(null); // CraftBukkit - decompile error +- BlockPos blockposition = (BlockPos) this.getSleepingPos().orElse((Object) null); ++ BlockPos blockposition = (BlockPos) this.getSleepingPos().orElse(null); // CraftBukkit - decompile error return blockposition != null ? BlockBed.getBedOrientation(this.level(), blockposition) : null; } diff --git a/nms-patches/net/minecraft/world/entity/EntityTameableAnimal.patch b/nms-patches/net/minecraft/world/entity/EntityTameableAnimal.patch index c7f83229..f782a1e0 100644 --- a/nms-patches/net/minecraft/world/entity/EntityTameableAnimal.patch +++ b/nms-patches/net/minecraft/world/entity/EntityTameableAnimal.patch @@ -14,7 +14,7 @@ public static final int TELEPORT_WHEN_DISTANCE_IS_SQ = 144; @@ -292,7 +298,14 @@ - if (!this.canTeleportTo(new BlockPosition(i, j, k))) { + if (!this.canTeleportTo(new BlockPos(i, j, k))) { return false; } else { - this.moveTo((double) i + 0.5D, (double) j, (double) k + 0.5D, this.getYRot(), this.getXRot()); diff --git a/nms-patches/net/minecraft/world/entity/EntityTypes.patch b/nms-patches/net/minecraft/world/entity/EntityTypes.patch index a57f473f..288ad4a0 100644 --- a/nms-patches/net/minecraft/world/entity/EntityTypes.patch +++ b/nms-patches/net/minecraft/world/entity/EntityTypes.patch @@ -29,14 +29,14 @@ @@ -431,7 +432,14 @@ @Nullable - public T spawn(WorldServer worldserver, @Nullable ItemStack itemstack, @Nullable EntityHuman entityhuman, BlockPosition blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1) { + public T spawn(WorldServer worldserver, @Nullable ItemStack itemstack, @Nullable EntityHuman entityhuman, BlockPos blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1) { - Consumer consumer; + // CraftBukkit start + return this.spawn(worldserver, itemstack, entityhuman, blockposition, entityspawnreason, flag, flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER_EGG); + } + + @Nullable -+ public T spawn(WorldServer worldserver, @Nullable ItemStack itemstack, @Nullable EntityHuman entityhuman, BlockPosition blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { ++ public T spawn(WorldServer worldserver, @Nullable ItemStack itemstack, @Nullable EntityHuman entityhuman, BlockPos blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { + // CraftBukkit end + Consumer consumer; // CraftBukkit - decompile error @@ -61,26 +61,26 @@ } @Nullable - public T spawn(WorldServer worldserver, BlockPosition blockposition, EntitySpawnReason entityspawnreason) { + public T spawn(WorldServer worldserver, BlockPos blockposition, EntitySpawnReason entityspawnreason) { - return this.spawn(worldserver, (Consumer) null, blockposition, entityspawnreason, false, false); + // CraftBukkit start + return this.spawn(worldserver, blockposition, entityspawnreason, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT); + } + + @Nullable -+ public T spawn(WorldServer worldserver, BlockPosition blockposition, EntitySpawnReason entityspawnreason, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { ++ public T spawn(WorldServer worldserver, BlockPos blockposition, EntitySpawnReason entityspawnreason, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { + return this.spawn(worldserver, (Consumer) null, blockposition, entityspawnreason, false, false, spawnReason); // CraftBukkit - decompile error + // CraftBukkit end } @Nullable - public T spawn(WorldServer worldserver, @Nullable Consumer consumer, BlockPosition blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1) { + public T spawn(WorldServer worldserver, @Nullable Consumer consumer, BlockPos blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1) { + // CraftBukkit start + return this.spawn(worldserver, consumer, blockposition, entityspawnreason, flag, flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT); + } + + @Nullable -+ public T spawn(WorldServer worldserver, @Nullable Consumer consumer, BlockPosition blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { ++ public T spawn(WorldServer worldserver, @Nullable Consumer consumer, BlockPos blockposition, EntitySpawnReason entityspawnreason, boolean flag, boolean flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { + // CraftBukkit end T t0 = this.create(worldserver, consumer, blockposition, entityspawnreason, flag, flag1); diff --git a/nms-patches/net/minecraft/world/entity/Leashable.patch b/nms-patches/net/minecraft/world/entity/Leashable.patch index 770872a7..ea9ae148 100644 --- a/nms-patches/net/minecraft/world/entity/Leashable.patch +++ b/nms-patches/net/minecraft/world/entity/Leashable.patch @@ -25,14 +25,14 @@ return new Leashable.a(Either.left(nbttagcompound.getCompound("leash").getUUID("UUID"))); } else { if (nbttagcompound.contains("leash", 11)) { -- Either either = (Either) GameProfileSerializer.readBlockPos(nbttagcompound, "leash").map(Either::right).orElse((Object) null); -+ Either either = (Either) GameProfileSerializer.readBlockPos(nbttagcompound, "leash").map(Either::right).orElse(null); // CraftBukkit - decompile error +- Either either = (Either) GameProfileSerializer.readBlockPos(nbttagcompound, "leash").map(Either::right).orElse((Object) null); ++ Either either = (Either) GameProfileSerializer.readBlockPos(nbttagcompound, "leash").map(Either::right).orElse(null); // CraftBukkit - decompile error if (either != null) { return new Leashable.a(either); @@ -69,6 +74,11 @@ if (leashable_a != null) { - Either either = leashable_a.delayedLeashInfo; + Either either = leashable_a.delayedLeashInfo; Entity entity = leashable_a.leashHolder; + // CraftBukkit start - SPIGOT-7487: Don't save (and possible drop) leash, when the holder was removed by a plugin + if (entity != null && entity.pluginRemoved) { diff --git a/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorInteractDoor.patch b/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorInteractDoor.patch index 28e608f4..50a8be6d 100644 --- a/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorInteractDoor.patch +++ b/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorInteractDoor.patch @@ -31,7 +31,7 @@ @@ -129,7 +143,7 @@ } - private static boolean areOtherMobsComingThroughDoor(EntityLiving entityliving, BlockPosition blockposition, Optional> optional) { + private static boolean areOtherMobsComingThroughDoor(EntityLiving entityliving, BlockPos blockposition, Optional> optional) { - return optional.isEmpty() ? false : ((List) optional.get()).stream().filter((entityliving1) -> { + return optional.isEmpty() ? false : (optional.get()).stream().filter((entityliving1) -> { // CraftBukkit - decompile error return entityliving1.getType() == entityliving.getType(); diff --git a/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorMakeLove.patch b/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorMakeLove.patch index b8033a44..81216596 100644 --- a/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorMakeLove.patch +++ b/nms-patches/net/minecraft/world/entity/ai/behavior/BehaviorMakeLove.patch @@ -34,7 +34,7 @@ return Optional.of(entityvillager2); } @@ -127,6 +138,6 @@ - private void giveBedToChild(WorldServer worldserver, EntityVillager entityvillager, BlockPosition blockposition) { + private void giveBedToChild(WorldServer worldserver, EntityVillager entityvillager, BlockPos blockposition) { GlobalPos globalpos = GlobalPos.of(worldserver.dimension(), blockposition); - entityvillager.getBrain().setMemory(MemoryModuleType.HOME, (Object) globalpos); diff --git a/nms-patches/net/minecraft/world/entity/ai/behavior/PrepareRamNearestTarget.patch b/nms-patches/net/minecraft/world/entity/ai/behavior/PrepareRamNearestTarget.patch index eed68fa4..c0778116 100644 --- a/nms-patches/net/minecraft/world/entity/ai/behavior/PrepareRamNearestTarget.patch +++ b/nms-patches/net/minecraft/world/entity/ai/behavior/PrepareRamNearestTarget.patch @@ -62,7 +62,7 @@ NavigationAbstract navigationabstract = entitycreature.getNavigation(); - Stream stream = list.stream(); -+ Stream stream = list.stream(); // CraftBukkit - decompile error - BlockPosition blockposition1 = entitycreature.blockPosition(); ++ Stream stream = list.stream(); // CraftBukkit - decompile error + BlockPos blockposition1 = entitycreature.blockPosition(); Objects.requireNonNull(blockposition1); diff --git a/nms-patches/net/minecraft/world/entity/ai/goal/PathfinderGoalEatTile.patch b/nms-patches/net/minecraft/world/entity/ai/goal/PathfinderGoalEatTile.patch index 34b12bbc..3a0bd488 100644 --- a/nms-patches/net/minecraft/world/entity/ai/goal/PathfinderGoalEatTile.patch +++ b/nms-patches/net/minecraft/world/entity/ai/goal/PathfinderGoalEatTile.patch @@ -12,7 +12,7 @@ private static final int EAT_ANIMATION_TICKS = 40; @@ -64,7 +68,7 @@ - BlockPosition blockposition = this.mob.blockPosition(); + BlockPos blockposition = this.mob.blockPosition(); if (PathfinderGoalEatTile.IS_TALL_GRASS.test(this.level.getBlockState(blockposition))) { - if (getServerLevel(this.level).getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { @@ -21,7 +21,7 @@ } @@ -73,7 +77,7 @@ - BlockPosition blockposition1 = blockposition.below(); + BlockPos blockposition1 = blockposition.below(); if (this.level.getBlockState(blockposition1).is(Blocks.GRASS_BLOCK)) { - if (getServerLevel(this.level).getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { diff --git a/nms-patches/net/minecraft/world/entity/animal/EntityBee.patch b/nms-patches/net/minecraft/world/entity/animal/EntityBee.patch index 7ed8bcd2..d77d15ea 100644 --- a/nms-patches/net/minecraft/world/entity/animal/EntityBee.patch +++ b/nms-patches/net/minecraft/world/entity/animal/EntityBee.patch @@ -39,10 +39,10 @@ this.ticksWithoutNectarSinceExitingHive = nbttagcompound.getInt("TicksSincePollination"); this.stayOutOfHiveCountdown = nbttagcompound.getInt("CannotEnterHiveTicks"); this.numCropsGrownSincePollination = nbttagcompound.getInt("CropsGrownSincePollination"); -- this.hivePos = (BlockPosition) GameProfileSerializer.readBlockPos(nbttagcompound, "hive_pos").orElse((Object) null); -- this.savedFlowerPos = (BlockPosition) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse((Object) null); -+ this.hivePos = (BlockPosition) GameProfileSerializer.readBlockPos(nbttagcompound, "hive_pos").orElse(null); // CraftBukkit - decompile error -+ this.savedFlowerPos = (BlockPosition) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse(null); // CraftBukkit - decompile error +- this.hivePos = (BlockPos) GameProfileSerializer.readBlockPos(nbttagcompound, "hive_pos").orElse((Object) null); +- this.savedFlowerPos = (BlockPos) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse((Object) null); ++ this.hivePos = (BlockPos) GameProfileSerializer.readBlockPos(nbttagcompound, "hive_pos").orElse(null); // CraftBukkit - decompile error ++ this.savedFlowerPos = (BlockPos) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse(null); // CraftBukkit - decompile error this.readPersistentAngerSaveData(this.level(), nbttagcompound); } diff --git a/nms-patches/net/minecraft/world/entity/animal/EntityDolphin.patch b/nms-patches/net/minecraft/world/entity/animal/EntityDolphin.patch index 27264dec..38d33199 100644 --- a/nms-patches/net/minecraft/world/entity/animal/EntityDolphin.patch +++ b/nms-patches/net/minecraft/world/entity/animal/EntityDolphin.patch @@ -18,7 +18,7 @@ + return TOTAL_AIR_SUPPLY; + } + // CraftBukkit end - private static final DataWatcherObject TREASURE_POS = DataWatcher.defineId(EntityDolphin.class, DataWatcherRegistry.BLOCK_POS); + private static final DataWatcherObject TREASURE_POS = DataWatcher.defineId(EntityDolphin.class, DataWatcherRegistry.BLOCK_POS); private static final DataWatcherObject GOT_FISH = DataWatcher.defineId(EntityDolphin.class, DataWatcherRegistry.BOOLEAN); private static final DataWatcherObject MOISTNESS_LEVEL = DataWatcher.defineId(EntityDolphin.class, DataWatcherRegistry.INT); @@ -200,7 +212,7 @@ diff --git a/nms-patches/net/minecraft/world/entity/animal/EntitySnowman.patch b/nms-patches/net/minecraft/world/entity/animal/EntitySnowman.patch index f662758d..bb3f6e3b 100644 --- a/nms-patches/net/minecraft/world/entity/animal/EntitySnowman.patch +++ b/nms-patches/net/minecraft/world/entity/animal/EntitySnowman.patch @@ -21,7 +21,7 @@ if (!worldserver.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { @@ -116,7 +120,11 @@ - BlockPosition blockposition = new BlockPosition(j, k, l); + BlockPos blockposition = new BlockPos(j, k, l); if (this.level().getBlockState(blockposition).isAir() && iblockdata.canSurvive(this.level(), blockposition)) { - this.level().setBlockAndUpdate(blockposition, iblockdata); diff --git a/nms-patches/net/minecraft/world/entity/animal/EntityTurtle.patch b/nms-patches/net/minecraft/world/entity/animal/EntityTurtle.patch index 5484958b..8f04aeac 100644 --- a/nms-patches/net/minecraft/world/entity/animal/EntityTurtle.patch +++ b/nms-patches/net/minecraft/world/entity/animal/EntityTurtle.patch @@ -25,7 +25,7 @@ + if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.turtle, this.blockPos.above(), (IBlockData) Blocks.TURTLE_EGG.defaultBlockState().setValue(BlockTurtleEgg.EGGS, this.turtle.random.nextInt(4) + 1))) { // CraftBukkit world.playSound((EntityHuman) null, blockposition, SoundEffects.TURTLE_LAY_EGG, SoundCategory.BLOCKS, 0.3F, 0.9F + world.random.nextFloat() * 0.2F); - BlockPosition blockposition1 = this.blockPos.above(); + BlockPos blockposition1 = this.blockPos.above(); IBlockData iblockdata = (IBlockData) Blocks.TURTLE_EGG.defaultBlockState().setValue(BlockTurtleEgg.EGGS, this.turtle.random.nextInt(4) + 1); world.setBlock(blockposition1, iblockdata, 3); diff --git a/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderCrystal.patch b/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderCrystal.patch index 1bc0b773..4008d76f 100644 --- a/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderCrystal.patch +++ b/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderCrystal.patch @@ -12,9 +12,9 @@ + public class EntityEnderCrystal extends Entity { - private static final DataWatcherObject> DATA_BEAM_TARGET = DataWatcher.defineId(EntityEnderCrystal.class, DataWatcherRegistry.OPTIONAL_BLOCK_POS); + private static final DataWatcherObject> DATA_BEAM_TARGET = DataWatcher.defineId(EntityEnderCrystal.class, DataWatcherRegistry.OPTIONAL_BLOCK_POS); @@ -57,7 +63,11 @@ - BlockPosition blockposition = this.blockPosition(); + BlockPos blockposition = this.blockPosition(); if (((WorldServer) this.level()).getDragonFight() != null && this.level().getBlockState(blockposition).isAir()) { - this.level().setBlockAndUpdate(blockposition, BlockFireAbstract.getState(this.level(), blockposition)); diff --git a/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderDragon.patch b/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderDragon.patch index 6b683c7a..14f5026d 100644 --- a/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderDragon.patch +++ b/nms-patches/net/minecraft/world/entity/boss/enderdragon/EntityEnderDragon.patch @@ -105,7 +105,7 @@ + } else if (event.getYield() == 0F) { + // Yield zero ==> no drops + for (org.bukkit.block.Block block : event.blockList()) { -+ this.level().removeBlock(new BlockPosition(block.getX(), block.getY(), block.getZ()), false); ++ this.level().removeBlock(new BlockPos(block.getX(), block.getY(), block.getZ()), false); + } + } else { + for (org.bukkit.block.Block block : event.blockList()) { @@ -115,7 +115,7 @@ + } + + CraftBlock craftBlock = ((CraftBlock) block); -+ BlockPosition blockposition = craftBlock.getPosition(); ++ BlockPos blockposition = craftBlock.getPosition(); + + Block nmsBlock = craftBlock.getNMS().getBlock(); + if (nmsBlock.dropFromExplosion(explosionSource)) { @@ -135,7 +135,7 @@ + // CraftBukkit end + if (flag1) { - BlockPosition blockposition1 = new BlockPosition(i + this.random.nextInt(l - i + 1), j + this.random.nextInt(i1 - j + 1), k + this.random.nextInt(j1 - k + 1)); + BlockPos blockposition1 = new BlockPos(i + this.random.nextInt(l - i + 1), j + this.random.nextInt(i1 - j + 1), k + this.random.nextInt(j1 - k + 1)); @@ -531,7 +606,7 @@ diff --git a/nms-patches/net/minecraft/world/entity/boss/wither/EntityWither.patch b/nms-patches/net/minecraft/world/entity/boss/wither/EntityWither.patch index 27bbc62a..73ff18c9 100644 --- a/nms-patches/net/minecraft/world/entity/boss/wither/EntityWither.patch +++ b/nms-patches/net/minecraft/world/entity/boss/wither/EntityWither.patch @@ -37,7 +37,7 @@ if (!this.isSilent()) { - worldserver.globalLevelEvent(1023, this.blockPosition(), 0); + // CraftBukkit start - Use relative location for far away sounds -+ // worldserver.globalLevelEvent(1023, new BlockPosition(this), 0); ++ // worldserver.globalLevelEvent(1023, new BlockPos(this), 0); + int viewDistance = worldserver.getCraftServer().getViewDistance() * 16; + for (EntityPlayer player : (List) MinecraftServer.getServer().getPlayerList().players) { + double deltaX = this.getX() - player.getX(); @@ -47,7 +47,7 @@ + double deltaLength = Math.sqrt(distanceSquared); + double relativeX = player.getX() + (deltaX / deltaLength) * viewDistance; + double relativeZ = player.getZ() + (deltaZ / deltaLength) * viewDistance; -+ player.connection.send(new PacketPlayOutWorldEvent(1023, new BlockPosition((int) relativeX, (int) this.getY(), (int) relativeZ), 0, true)); ++ player.connection.send(new PacketPlayOutWorldEvent(1023, new BlockPos((int) relativeX, (int) this.getY(), (int) relativeZ), 0, true)); + } else { + player.connection.send(new PacketPlayOutWorldEvent(1023, this.blockPosition(), 0, true)); + } diff --git a/nms-patches/net/minecraft/world/entity/decoration/BlockAttachedEntity.patch b/nms-patches/net/minecraft/world/entity/decoration/BlockAttachedEntity.patch index 27d3b35b..c598887c 100644 --- a/nms-patches/net/minecraft/world/entity/decoration/BlockAttachedEntity.patch +++ b/nms-patches/net/minecraft/world/entity/decoration/BlockAttachedEntity.patch @@ -107,4 +107,4 @@ + @Override public void addAdditionalSaveData(NBTTagCompound nbttagcompound) { - BlockPosition blockposition = this.getPos(); + BlockPos blockposition = this.getPos(); diff --git a/nms-patches/net/minecraft/world/entity/decoration/EntityItemFrame.patch b/nms-patches/net/minecraft/world/entity/decoration/EntityItemFrame.patch index 26a8dd92..7294a44c 100644 --- a/nms-patches/net/minecraft/world/entity/decoration/EntityItemFrame.patch +++ b/nms-patches/net/minecraft/world/entity/decoration/EntityItemFrame.patch @@ -3,12 +3,12 @@ @@ -91,6 +91,12 @@ @Override - protected AxisAlignedBB calculateBoundingBox(BlockPosition blockposition, EnumDirection enumdirection) { + protected AxisAlignedBB calculateBoundingBox(BlockPos blockposition, EnumDirection enumdirection) { + // CraftBukkit start - break out BB calc into own method + return calculateBoundingBoxStatic(blockposition, enumdirection); + } + -+ public static AxisAlignedBB calculateBoundingBoxStatic(BlockPosition blockposition, EnumDirection enumdirection) { ++ public static AxisAlignedBB calculateBoundingBoxStatic(BlockPos blockposition, EnumDirection enumdirection) { + // CraftBukkit end float f = 0.46875F; Vec3D vec3d = Vec3D.atCenterOf(blockposition).relative(enumdirection, -0.46875D); diff --git a/nms-patches/net/minecraft/world/entity/decoration/EntityPainting.patch b/nms-patches/net/minecraft/world/entity/decoration/EntityPainting.patch index ac5b3f26..ab1c99d9 100644 --- a/nms-patches/net/minecraft/world/entity/decoration/EntityPainting.patch +++ b/nms-patches/net/minecraft/world/entity/decoration/EntityPainting.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/entity/decoration/EntityPainting.java +++ b/net/minecraft/world/entity/decoration/EntityPainting.java @@ -72,7 +72,7 @@ - public static Optional create(World world, BlockPosition blockposition, EnumDirection enumdirection) { + public static Optional create(World world, BlockPos blockposition, EnumDirection enumdirection) { EntityPainting entitypainting = new EntityPainting(world, blockposition); List> list = new ArrayList(); - Iterable iterable = world.registryAccess().lookupOrThrow(Registries.PAINTING_VARIANT).getTagOrEmpty(PaintingVariantTags.PLACEABLE); @@ -12,13 +12,13 @@ @@ -138,22 +138,32 @@ @Override - protected AxisAlignedBB calculateBoundingBox(BlockPosition blockposition, EnumDirection enumdirection) { + protected AxisAlignedBB calculateBoundingBox(BlockPos blockposition, EnumDirection enumdirection) { + // CraftBukkit start + PaintingVariant paintingvariant = (PaintingVariant) this.getVariant().value(); + return calculateBoundingBoxStatic(blockposition, enumdirection, paintingvariant.width(), paintingvariant.height()); + } + -+ public static AxisAlignedBB calculateBoundingBoxStatic(BlockPosition blockposition, EnumDirection enumdirection, int width, int height) { ++ public static AxisAlignedBB calculateBoundingBoxStatic(BlockPos blockposition, EnumDirection enumdirection, int width, int height) { + // CraftBukkit end float f = 0.46875F; Vec3D vec3d = Vec3D.atCenterOf(blockposition).relative(enumdirection, -0.46875D); diff --git a/nms-patches/net/minecraft/world/entity/item/EntityFallingBlock.patch b/nms-patches/net/minecraft/world/entity/item/EntityFallingBlock.patch index 183c3b95..0e13db3b 100644 --- a/nms-patches/net/minecraft/world/entity/item/EntityFallingBlock.patch +++ b/nms-patches/net/minecraft/world/entity/item/EntityFallingBlock.patch @@ -15,12 +15,12 @@ @@ -87,10 +92,17 @@ } - public static EntityFallingBlock fall(World world, BlockPosition blockposition, IBlockData iblockdata) { + public static EntityFallingBlock fall(World world, BlockPos blockposition, IBlockData iblockdata) { + // CraftBukkit start + return fall(world, blockposition, iblockdata, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT); + } + -+ public static EntityFallingBlock fall(World world, BlockPosition blockposition, IBlockData iblockdata, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { ++ public static EntityFallingBlock fall(World world, BlockPos blockposition, IBlockData iblockdata, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { + // CraftBukkit end EntityFallingBlock entityfallingblock = new EntityFallingBlock(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, iblockdata.hasProperty(BlockProperties.WATERLOGGED) ? (IBlockData) iblockdata.setValue(BlockProperties.WATERLOGGED, false) : iblockdata); + if (!CraftEventFactory.callEntityChangeBlockEvent(entityfallingblock, blockposition, iblockdata.getFluidState().createLegacyBlock())) return entityfallingblock; // CraftBukkit diff --git a/nms-patches/net/minecraft/world/entity/monster/EntityPigZombie.patch b/nms-patches/net/minecraft/world/entity/monster/EntityPigZombie.patch index f0a0fd53..26dcbfbc 100644 --- a/nms-patches/net/minecraft/world/entity/monster/EntityPigZombie.patch +++ b/nms-patches/net/minecraft/world/entity/monster/EntityPigZombie.patch @@ -41,4 +41,4 @@ + // CraftBukkit end } - public static boolean checkZombifiedPiglinSpawnRules(EntityTypes entitytypes, GeneratorAccess generatoraccess, EntitySpawnReason entityspawnreason, BlockPosition blockposition, RandomSource randomsource) { + public static boolean checkZombifiedPiglinSpawnRules(EntityTypes entitytypes, GeneratorAccess generatoraccess, EntitySpawnReason entityspawnreason, BlockPos blockposition, RandomSource randomsource) { diff --git a/nms-patches/net/minecraft/world/entity/monster/EntityShulker.patch b/nms-patches/net/minecraft/world/entity/monster/EntityShulker.patch index 611d16c8..da294eaf 100644 --- a/nms-patches/net/minecraft/world/entity/monster/EntityShulker.patch +++ b/nms-patches/net/minecraft/world/entity/monster/EntityShulker.patch @@ -22,7 +22,7 @@ + if (teleportEvent.isCancelled()) { + return false; + } else { -+ blockposition1 = CraftLocation.toBlockPosition(teleportEvent.getTo()); ++ blockposition1 = CraftLocation.toBlockPos(teleportEvent.getTo()); + } + // CraftBukkit end this.unRide(); diff --git a/nms-patches/net/minecraft/world/entity/monster/EntityZombie.patch b/nms-patches/net/minecraft/world/entity/monster/EntityZombie.patch index 1eed7427..a9b47bd9 100644 --- a/nms-patches/net/minecraft/world/entity/monster/EntityZombie.patch +++ b/nms-patches/net/minecraft/world/entity/monster/EntityZombie.patch @@ -74,7 +74,7 @@ + return convertVillagerToZombieVillager(worldserver, entityvillager, this.blockPosition(), this.isSilent(), EntityTransformEvent.TransformReason.INFECTION, CreatureSpawnEvent.SpawnReason.INFECTION) != null; + } + -+ public static EntityZombieVillager convertVillagerToZombieVillager(WorldServer worldserver, EntityVillager entityvillager, net.minecraft.core.BlockPosition blockPosition, boolean silent, EntityTransformEvent.TransformReason transformReason, CreatureSpawnEvent.SpawnReason spawnReason) { ++ public static EntityZombieVillager convertVillagerToZombieVillager(WorldServer worldserver, EntityVillager entityvillager, net.minecraft.core.BlockPos blockPosition, boolean silent, EntityTransformEvent.TransformReason transformReason, CreatureSpawnEvent.SpawnReason spawnReason) { + // CraftBukkit end EntityZombieVillager entityzombievillager = (EntityZombieVillager) entityvillager.convertTo(EntityTypes.ZOMBIE_VILLAGER, ConversionParams.single(entityvillager, true, true), (entityzombievillager1) -> { entityzombievillager1.finalizeSpawn(worldserver, worldserver.getCurrentDifficultyAt(entityzombievillager1.blockPosition()), EntitySpawnReason.CONVERSION, new EntityZombie.GroupDataZombie(false, true)); diff --git a/nms-patches/net/minecraft/world/entity/npc/EntityVillager.patch b/nms-patches/net/minecraft/world/entity/npc/EntityVillager.patch index 0f03f2ba..96558f1c 100644 --- a/nms-patches/net/minecraft/world/entity/npc/EntityVillager.patch +++ b/nms-patches/net/minecraft/world/entity/npc/EntityVillager.patch @@ -102,7 +102,7 @@ } @@ -963,7 +984,7 @@ @Override - public void startSleeping(BlockPosition blockposition) { + public void startSleeping(BlockPos blockposition) { super.startSleeping(blockposition); - this.brain.setMemory(MemoryModuleType.LAST_SLEPT, (Object) this.level().getGameTime()); + this.brain.setMemory(MemoryModuleType.LAST_SLEPT, this.level().getGameTime()); // CraftBukkit - decompile error diff --git a/nms-patches/net/minecraft/world/entity/npc/MobSpawnerTrader.patch b/nms-patches/net/minecraft/world/entity/npc/MobSpawnerTrader.patch index e4987a51..babc734a 100644 --- a/nms-patches/net/minecraft/world/entity/npc/MobSpawnerTrader.patch +++ b/nms-patches/net/minecraft/world/entity/npc/MobSpawnerTrader.patch @@ -19,7 +19,7 @@ entityvillagertrader.restrictTo(blockposition1, 16); return true; @@ -133,7 +133,7 @@ - BlockPosition blockposition = this.findSpawnPositionNear(worldserver, entityvillagertrader.blockPosition(), i); + BlockPos blockposition = this.findSpawnPositionNear(worldserver, entityvillagertrader.blockPosition(), i); if (blockposition != null) { - EntityLlamaTrader entityllamatrader = (EntityLlamaTrader) EntityTypes.TRADER_LLAMA.spawn(worldserver, blockposition, EntitySpawnReason.EVENT); diff --git a/nms-patches/net/minecraft/world/entity/player/EntityHuman.patch b/nms-patches/net/minecraft/world/entity/player/EntityHuman.patch index a09799fd..26d2e662 100644 --- a/nms-patches/net/minecraft/world/entity/player/EntityHuman.patch +++ b/nms-patches/net/minecraft/world/entity/player/EntityHuman.patch @@ -53,7 +53,7 @@ + } + // CraftBukkit end + - public EntityHuman(World world, BlockPosition blockposition, float f, GameProfile gameprofile) { + public EntityHuman(World world, BlockPos blockposition, float f, GameProfile gameprofile) { super(EntityTypes.PLAYER, world); this.lastItemInMainHand = ItemStack.EMPTY; @@ -350,7 +374,7 @@ @@ -310,12 +310,12 @@ @@ -1388,6 +1495,12 @@ } - public Either startSleepInBed(BlockPosition blockposition) { + public Either startSleepInBed(BlockPos blockposition) { + // CraftBukkit start + return this.startSleepInBed(blockposition, false); + } + -+ public Either startSleepInBed(BlockPosition blockposition, boolean force) { ++ public Either startSleepInBed(BlockPos blockposition, boolean force) { + // CraftBukkit end this.startSleeping(blockposition); this.sleepCounter = 0; diff --git a/nms-patches/net/minecraft/world/entity/projectile/EntityFishingHook.patch b/nms-patches/net/minecraft/world/entity/projectile/EntityFishingHook.patch index 48be1a5e..df5ab8b2 100644 --- a/nms-patches/net/minecraft/world/entity/projectile/EntityFishingHook.patch +++ b/nms-patches/net/minecraft/world/entity/projectile/EntityFishingHook.patch @@ -68,7 +68,7 @@ @Override @@ -300,11 +319,11 @@ int i = 1; - BlockPosition blockposition1 = blockposition.above(); + BlockPos blockposition1 = blockposition.above(); - if (this.random.nextFloat() < 0.25F && this.level().isRainingAt(blockposition1)) { + if (this.rainInfluenced && this.random.nextFloat() < 0.25F && this.level().isRainingAt(blockposition1)) { // CraftBukkit diff --git a/nms-patches/net/minecraft/world/entity/projectile/EntitySmallFireball.patch b/nms-patches/net/minecraft/world/entity/projectile/EntitySmallFireball.patch index a9757221..cbe42387 100644 --- a/nms-patches/net/minecraft/world/entity/projectile/EntitySmallFireball.patch +++ b/nms-patches/net/minecraft/world/entity/projectile/EntitySmallFireball.patch @@ -46,7 +46,7 @@ - if (!(entity instanceof EntityInsentient) || worldserver.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { + if (isIncendiary) { // CraftBukkit - BlockPosition blockposition = movingobjectpositionblock.getBlockPos().relative(movingobjectpositionblock.getDirection()); + BlockPos blockposition = movingobjectpositionblock.getBlockPos().relative(movingobjectpositionblock.getDirection()); - if (this.level().isEmptyBlock(blockposition)) { + if (this.level().isEmptyBlock(blockposition) && !org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(this.level(), blockposition, this).isCancelled()) { // CraftBukkit diff --git a/nms-patches/net/minecraft/world/entity/raid/Raid.patch b/nms-patches/net/minecraft/world/entity/raid/Raid.patch index cff0acd8..0006e541 100644 --- a/nms-patches/net/minecraft/world/entity/raid/Raid.patch +++ b/nms-patches/net/minecraft/world/entity/raid/Raid.patch @@ -113,7 +113,7 @@ + org.bukkit.craftbukkit.event.CraftEventFactory.callRaidSpawnWaveEvent(this, leader, raiders); // CraftBukkit } - public void joinRaid(int i, EntityRaider entityraider, @Nullable BlockPosition blockposition, boolean flag) { + public void joinRaid(int i, EntityRaider entityraider, @Nullable BlockPos blockposition, boolean flag) { @@ -612,7 +635,7 @@ entityraider.finalizeSpawn(this.level, this.level.getCurrentDifficultyAt(blockposition), EntitySpawnReason.EVENT, (GroupDataEntity) null); entityraider.applyRaidBuffs(this.level, i, false); diff --git a/nms-patches/net/minecraft/world/inventory/ContainerAccess.patch b/nms-patches/net/minecraft/world/inventory/ContainerAccess.patch index 72e419a3..393f03e7 100644 --- a/nms-patches/net/minecraft/world/inventory/ContainerAccess.patch +++ b/nms-patches/net/minecraft/world/inventory/ContainerAccess.patch @@ -9,7 +9,7 @@ + throw new UnsupportedOperationException("Not supported yet."); + } + -+ default BlockPosition getPosition() { ++ default BlockPos getPosition() { + throw new UnsupportedOperationException("Not supported yet."); + } + @@ -20,10 +20,10 @@ + ContainerAccess NULL = new ContainerAccess() { @Override - public Optional evaluate(BiFunction bifunction) { + public Optional evaluate(BiFunction bifunction) { @@ -17,6 +31,18 @@ - static ContainerAccess create(final World world, final BlockPosition blockposition) { + static ContainerAccess create(final World world, final BlockPos blockposition) { return new ContainerAccess() { + // CraftBukkit start + @Override @@ -32,11 +32,11 @@ + } + + @Override -+ public BlockPosition getPosition() { ++ public BlockPos getPosition() { + return blockposition; + } + // CraftBukkit end + @Override - public Optional evaluate(BiFunction bifunction) { + public Optional evaluate(BiFunction bifunction) { return Optional.of(bifunction.apply(world, blockposition)); diff --git a/nms-patches/net/minecraft/world/item/ItemBoneMeal.patch b/nms-patches/net/minecraft/world/item/ItemBoneMeal.patch index f658c4a4..342aa398 100644 --- a/nms-patches/net/minecraft/world/item/ItemBoneMeal.patch +++ b/nms-patches/net/minecraft/world/item/ItemBoneMeal.patch @@ -11,8 +11,8 @@ + public static EnumInteractionResult applyBonemeal(ItemActionContext itemactioncontext) { + // CraftBukkit end World world = itemactioncontext.getLevel(); - BlockPosition blockposition = itemactioncontext.getClickedPos(); - BlockPosition blockposition1 = blockposition.relative(itemactioncontext.getClickedFace()); + BlockPos blockposition = itemactioncontext.getClickedPos(); + BlockPos blockposition1 = blockposition.relative(itemactioncontext.getClickedFace()); if (growCrop(itemactioncontext.getItemInHand(), world, blockposition)) { if (!world.isClientSide) { diff --git a/nms-patches/net/minecraft/world/item/ItemBucket.patch b/nms-patches/net/minecraft/world/item/ItemBucket.patch index 63994725..da98669e 100644 --- a/nms-patches/net/minecraft/world/item/ItemBucket.patch +++ b/nms-patches/net/minecraft/world/item/ItemBucket.patch @@ -46,7 +46,7 @@ CriterionTriggers.FILLED_BUCKET.trigger((EntityPlayer) entityhuman, itemstack1); @@ -86,7 +107,7 @@ iblockdata = world.getBlockState(blockposition); - BlockPosition blockposition2 = iblockdata.getBlock() instanceof IFluidContainer && this.content == FluidTypes.WATER ? blockposition : blockposition1; + BlockPos blockposition2 = iblockdata.getBlock() instanceof IFluidContainer && this.content == FluidTypes.WATER ? blockposition : blockposition1; - if (this.emptyContents(entityhuman, world, blockposition2, movingobjectpositionblock)) { + if (this.emptyContents(entityhuman, world, blockposition2, movingobjectpositionblock, movingobjectpositionblock.getDirection(), blockposition, itemstack, enumhand)) { // CraftBukkit @@ -56,12 +56,12 @@ @@ -114,6 +135,12 @@ @Override - public boolean emptyContents(@Nullable EntityHuman entityhuman, World world, BlockPosition blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock) { + public boolean emptyContents(@Nullable EntityHuman entityhuman, World world, BlockPos blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock) { + // CraftBukkit start + return emptyContents(entityhuman, world, blockposition, movingobjectpositionblock, null, null, null, EnumHand.MAIN_HAND); + } + -+ public boolean emptyContents(EntityHuman entityhuman, World world, BlockPosition blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock, EnumDirection enumdirection, BlockPosition clicked, ItemStack itemstack, EnumHand enumhand) { ++ public boolean emptyContents(EntityHuman entityhuman, World world, BlockPos blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock, EnumDirection enumdirection, BlockPos clicked, ItemStack itemstack, EnumHand enumhand) { + // CraftBukkit end FluidType fluidtype = this.content; diff --git a/nms-patches/net/minecraft/world/item/ItemFlintAndSteel.patch b/nms-patches/net/minecraft/world/item/ItemFlintAndSteel.patch index 2c706936..be69f3ba 100644 --- a/nms-patches/net/minecraft/world/item/ItemFlintAndSteel.patch +++ b/nms-patches/net/minecraft/world/item/ItemFlintAndSteel.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/item/ItemFlintAndSteel.java +++ b/net/minecraft/world/item/ItemFlintAndSteel.java @@ -37,6 +37,12 @@ - BlockPosition blockposition1 = blockposition.relative(itemactioncontext.getClickedFace()); + BlockPos blockposition1 = blockposition.relative(itemactioncontext.getClickedFace()); if (BlockFireAbstract.canBePlacedAt(world, blockposition1, itemactioncontext.getHorizontalDirection())) { + // CraftBukkit start - Store the clicked block diff --git a/nms-patches/net/minecraft/world/item/ItemLeash.patch b/nms-patches/net/minecraft/world/item/ItemLeash.patch index 38caf51b..f3ff60e0 100644 --- a/nms-patches/net/minecraft/world/item/ItemLeash.patch +++ b/nms-patches/net/minecraft/world/item/ItemLeash.patch @@ -25,8 +25,8 @@ return EnumInteractionResult.PASS; } -- public static EnumInteractionResult bindPlayerMobs(EntityHuman entityhuman, World world, BlockPosition blockposition) { -+ public static EnumInteractionResult bindPlayerMobs(EntityHuman entityhuman, World world, BlockPosition blockposition, net.minecraft.world.EnumHand enumhand) { // CraftBukkit - Add EnumHand +- public static EnumInteractionResult bindPlayerMobs(EntityHuman entityhuman, World world, BlockPos blockposition) { ++ public static EnumInteractionResult bindPlayerMobs(EntityHuman entityhuman, World world, BlockPos blockposition, net.minecraft.world.EnumHand enumhand) { // CraftBukkit - Add EnumHand EntityLeash entityleash = null; List list = leashableInArea(world, blockposition, (leashable) -> { return leashable.getLeashHolder() == entityhuman; @@ -79,11 +79,11 @@ } + // CraftBukkit start -+ public static EnumInteractionResult bindPlayerMobs(EntityHuman entityhuman, World world, BlockPosition blockposition) { ++ public static EnumInteractionResult bindPlayerMobs(EntityHuman entityhuman, World world, BlockPos blockposition) { + return bindPlayerMobs(entityhuman, world, blockposition, net.minecraft.world.EnumHand.MAIN_HAND); + } + // CraftBukkit end + - public static List leashableInArea(World world, BlockPosition blockposition, Predicate predicate) { + public static List leashableInArea(World world, BlockPos blockposition, Predicate predicate) { double d0 = 7.0D; int i = blockposition.getX(); diff --git a/nms-patches/net/minecraft/world/item/ItemSign.patch b/nms-patches/net/minecraft/world/item/ItemSign.patch index a9723327..ec011265 100644 --- a/nms-patches/net/minecraft/world/item/ItemSign.patch +++ b/nms-patches/net/minecraft/world/item/ItemSign.patch @@ -4,7 +4,7 @@ public class ItemSign extends ItemBlockWallable { -+ public static BlockPosition openSign; // CraftBukkit ++ public static BlockPos openSign; // CraftBukkit + public ItemSign(Block block, Block block1, Item.Info item_info) { super(block, block1, EnumDirection.DOWN, item_info); diff --git a/nms-patches/net/minecraft/world/item/ItemStack.patch b/nms-patches/net/minecraft/world/item/ItemStack.patch index bf9aba51..69ecf6e9 100644 --- a/nms-patches/net/minecraft/world/item/ItemStack.patch +++ b/nms-patches/net/minecraft/world/item/ItemStack.patch @@ -194,7 +194,7 @@ + world.preventPoiUpdated = false; + + // Brute force all possible updates -+ BlockPosition placedPos = ((CraftBlock) placeEvent.getBlock()).getPosition(); ++ BlockPos placedPos = ((CraftBlock) placeEvent.getBlock()).getPosition(); + for (EnumDirection dir : EnumDirection.values()) { + ((EntityPlayer) entityhuman).connection.send(new PacketPlayOutBlockChange(world, placedPos.relative(dir))); + } @@ -206,14 +206,14 @@ + this.setCount(newCount); + } + -+ for (Map.Entry e : world.capturedTileEntities.entrySet()) { ++ for (Map.Entry e : world.capturedTileEntities.entrySet()) { + world.setBlockEntity(e.getValue()); + } + + for (BlockState blockstate : blocks) { + int updateFlag = ((CraftBlockState) blockstate).getFlag(); + IBlockData oldBlock = ((CraftBlockState) blockstate).getHandle(); -+ BlockPosition newblockposition = ((CraftBlockState) blockstate).getPosition(); ++ BlockPos newblockposition = ((CraftBlockState) blockstate).getPosition(); + IBlockData block = world.getBlockState(newblockposition); + + if (!(block.getBlock() instanceof BlockTileEntity)) { // Containers get placed automatically @@ -224,7 +224,7 @@ + } + + if (this.item == Items.WITHER_SKELETON_SKULL) { // Special case skulls to allow wither spawns to be cancelled -+ BlockPosition bp = blockposition; ++ BlockPos bp = blockposition; + if (!world.getBlockState(blockposition).canBeReplaced()) { + if (!world.getBlockState(blockposition).isSolid()) { + bp = null; @@ -255,7 +255,7 @@ + + // SPIGOT-7315: Moved from BlockBed#setPlacedBy + if (placeEvent != null && this.item instanceof ItemBed) { -+ BlockPosition position = ((CraftBlock) placeEvent.getBlock()).getPosition(); ++ BlockPos position = ((CraftBlock) placeEvent.getBlock()).getPosition(); + IBlockData blockData = world.getBlockState(position); + + if (blockData.getBlock() instanceof BlockBed) { diff --git a/nms-patches/net/minecraft/world/level/GeneratorAccess.patch b/nms-patches/net/minecraft/world/level/GeneratorAccess.patch index ff57d08f..2bc6ae45 100644 --- a/nms-patches/net/minecraft/world/level/GeneratorAccess.patch +++ b/nms-patches/net/minecraft/world/level/GeneratorAccess.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/GeneratorAccess.java +++ b/net/minecraft/world/level/GeneratorAccess.java @@ -101,4 +101,6 @@ - default void gameEvent(ResourceKey resourcekey, BlockPosition blockposition, GameEvent.a gameevent_a) { + default void gameEvent(ResourceKey resourcekey, BlockPos blockposition, GameEvent.a gameevent_a) { this.gameEvent((Holder) this.registryAccess().lookupOrThrow(Registries.GAME_EVENT).getOrThrow(resourcekey), blockposition, gameevent_a); } + diff --git a/nms-patches/net/minecraft/world/level/IBlockAccess.patch b/nms-patches/net/minecraft/world/level/IBlockAccess.patch index 0e30f8b4..e40dad56 100644 --- a/nms-patches/net/minecraft/world/level/IBlockAccess.patch +++ b/nms-patches/net/minecraft/world/level/IBlockAccess.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/IBlockAccess.java +++ b/net/minecraft/world/level/IBlockAccess.java @@ -31,7 +31,7 @@ - default Optional getBlockEntity(BlockPosition blockposition, TileEntityTypes tileentitytypes) { + default Optional getBlockEntity(BlockPos blockposition, TileEntityTypes tileentitytypes) { TileEntity tileentity = this.getBlockEntity(blockposition); - return tileentity != null && tileentity.getType() == tileentitytypes ? Optional.of(tileentity) : Optional.empty(); + return tileentity != null && tileentity.getType() == tileentitytypes ? (Optional) Optional.of(tileentity) : Optional.empty(); // CraftBukkit - decompile error } - IBlockData getBlockState(BlockPosition blockposition); + IBlockData getBlockState(BlockPos blockposition); @@ -59,8 +59,8 @@ }); } @@ -16,7 +16,7 @@ - default MovingObjectPositionBlock clip(RayTrace raytrace) { - return (MovingObjectPositionBlock) traverseBlocks(raytrace.getFrom(), raytrace.getTo(), raytrace, (raytrace1, blockposition) -> { + // CraftBukkit start - moved block handling into separate method for use by Block#rayTrace -+ default MovingObjectPositionBlock clip(RayTrace raytrace1, BlockPosition blockposition) { ++ default MovingObjectPositionBlock clip(RayTrace raytrace1, BlockPos blockposition) { IBlockData iblockdata = this.getBlockState(blockposition); Fluid fluid = this.getFluidState(blockposition); Vec3D vec3d = raytrace1.getFrom(); diff --git a/nms-patches/net/minecraft/world/level/MobSpawnerAbstract.patch b/nms-patches/net/minecraft/world/level/MobSpawnerAbstract.patch index 7e6badc7..98d7b4ee 100644 --- a/nms-patches/net/minecraft/world/level/MobSpawnerAbstract.patch +++ b/nms-patches/net/minecraft/world/level/MobSpawnerAbstract.patch @@ -2,12 +2,12 @@ +++ b/net/minecraft/world/level/MobSpawnerAbstract.java @@ -54,6 +54,7 @@ - public void setEntityId(EntityTypes entitytypes, @Nullable World world, RandomSource randomsource, BlockPosition blockposition) { + public void setEntityId(EntityTypes entitytypes, @Nullable World world, RandomSource randomsource, BlockPos blockposition) { this.getOrCreateNextSpawnData(world, randomsource, blockposition).getEntityToSpawn().putString("id", BuiltInRegistries.ENTITY_TYPE.getKey(entitytypes).toString()); + this.spawnPotentials = SimpleWeightedRandomList.empty(); // CraftBukkit - SPIGOT-3496, MC-92282 } - private boolean isNearPlayer(World world, BlockPosition blockposition) { + private boolean isNearPlayer(World world, BlockPos blockposition) { @@ -157,13 +158,18 @@ ((EntityInsentient) entity).finalizeSpawn(worldserver, worldserver.getCurrentDifficultyAt(entity.blockPosition()), EntitySpawnReason.SPAWNER, (GroupDataEntity) null); } diff --git a/nms-patches/net/minecraft/world/level/ServerExplosion.patch b/nms-patches/net/minecraft/world/level/ServerExplosion.patch index e2c17adb..f421a335 100644 --- a/nms-patches/net/minecraft/world/level/ServerExplosion.patch +++ b/nms-patches/net/minecraft/world/level/ServerExplosion.patch @@ -106,7 +106,7 @@ + + List blockList = new ObjectArrayList<>(); + for (int i1 = list.size() - 1; i1 >= 0; i1--) { -+ BlockPosition cpos = list.get(i1); ++ BlockPos cpos = list.get(i1); + org.bukkit.block.Block bblock = bworld.getBlockAt(cpos.getX(), cpos.getY(), cpos.getZ()); + if (!bblock.getType().isAir()) { + blockList.add(bblock); @@ -132,7 +132,7 @@ + list.clear(); + + for (org.bukkit.block.Block bblock : bukkitBlocks) { -+ BlockPosition coords = new BlockPosition(bblock.getX(), bblock.getY(), bblock.getZ()); ++ BlockPos coords = new BlockPos(bblock.getX(), bblock.getY(), bblock.getZ()); + list.add(coords); + } + @@ -143,13 +143,13 @@ Iterator iterator = list.iterator(); while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); + BlockPos blockposition = (BlockPos) iterator.next(); + // CraftBukkit start - TNTPrimeEvent + IBlockData iblockdata = this.level.getBlockState(blockposition); + Block block = iblockdata.getBlock(); + if (block instanceof net.minecraft.world.level.block.BlockTNT) { + Entity sourceEntity = source == null ? null : source; -+ BlockPosition sourceBlock = sourceEntity == null ? BlockPosition.containing(this.center) : null; ++ BlockPos sourceBlock = sourceEntity == null ? BlockPos.containing(this.center) : null; + if (!CraftEventFactory.callTNTPrimeEvent(this.level, blockposition, org.bukkit.event.block.TNTPrimeEvent.PrimeCause.EXPLOSION, sourceEntity, sourceBlock)) { + this.level.sendBlockUpdated(blockposition, Blocks.AIR.defaultBlockState(), iblockdata, 3); // Update the block on the client + continue; @@ -160,7 +160,7 @@ this.level.getBlockState(blockposition).onExplosionHit(this.level, blockposition, this, (itemstack, blockposition1) -> { addOrAppendStack(list1, itemstack, blockposition1); @@ -262,13 +369,22 @@ - BlockPosition blockposition = (BlockPosition) iterator.next(); + BlockPos blockposition = (BlockPos) iterator.next(); if (this.level.random.nextInt(3) == 0 && this.level.getBlockState(blockposition).isAir() && this.level.getBlockState(blockposition.below()).isSolidRender()) { - this.level.setBlockAndUpdate(blockposition, BlockFireAbstract.getState(this.level, blockposition)); @@ -181,12 +181,12 @@ + } + // CraftBukkit end this.level.gameEvent(this.source, (Holder) GameEvent.EXPLODE, this.center); - List list = this.calculateExplodedPositions(); + List list = this.calculateExplodedPositions(); @@ -288,6 +404,7 @@ } - private static void addOrAppendStack(List list, ItemStack itemstack, BlockPosition blockposition) { + private static void addOrAppendStack(List list, ItemStack itemstack, BlockPos blockposition) { + if (itemstack.isEmpty()) return; // CraftBukkit - SPIGOT-5425 Iterator iterator = list.iterator(); diff --git a/nms-patches/net/minecraft/world/level/World.patch b/nms-patches/net/minecraft/world/level/World.patch index 1fdff914..f15987a5 100644 --- a/nms-patches/net/minecraft/world/level/World.patch +++ b/nms-patches/net/minecraft/world/level/World.patch @@ -42,8 +42,8 @@ + public boolean preventPoiUpdated = false; // CraftBukkit - SPIGOT-5710 + public boolean captureBlockStates = false; + public boolean captureTreeGeneration = false; -+ public Map capturedBlockStates = new java.util.LinkedHashMap<>(); -+ public Map capturedTileEntities = new HashMap<>(); ++ public Map capturedBlockStates = new java.util.LinkedHashMap<>(); ++ public Map capturedTileEntities = new HashMap<>(); + public List captureDrops; + public final it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap ticksPerSpawnCategory = new it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap<>(); + public boolean populating; @@ -138,7 +138,7 @@ @@ -206,6 +299,18 @@ @Override - public boolean setBlock(BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + public boolean setBlock(BlockPos blockposition, IBlockData iblockdata, int i, int j) { + // CraftBukkit start - tree generation + if (this.captureTreeGeneration) { + CapturedBlockState blockstate = capturedBlockStates.get(blockposition); @@ -204,7 +204,7 @@ } + // CraftBukkit start - Split off from above in order to directly send client and physic updates -+ public void notifyAndUpdatePhysics(BlockPosition blockposition, Chunk chunk, IBlockData oldBlock, IBlockData newBlock, IBlockData actualBlock, int i, int j) { ++ public void notifyAndUpdatePhysics(BlockPos blockposition, Chunk chunk, IBlockData oldBlock, IBlockData newBlock, IBlockData actualBlock, int i, int j) { + IBlockData iblockdata = newBlock; + IBlockData iblockdata1 = oldBlock; + IBlockData iblockdata2 = actualBlock; @@ -252,13 +252,13 @@ + } + // CraftBukkit end + - public void onBlockStateChange(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) {} + public void onBlockStateChange(BlockPos blockposition, IBlockData iblockdata, IBlockData iblockdata1) {} @Override @@ -339,6 +517,14 @@ @Override - public IBlockData getBlockState(BlockPosition blockposition) { + public IBlockData getBlockState(BlockPos blockposition) { + // CraftBukkit start - tree generation + if (captureTreeGeneration) { + CapturedBlockState previous = capturedBlockStates.get(blockposition); @@ -273,13 +273,13 @@ @@ -509,6 +695,16 @@ @Nullable @Override - public TileEntity getBlockEntity(BlockPosition blockposition) { + public TileEntity getBlockEntity(BlockPos blockposition) { + // CraftBukkit start + return getBlockEntity(blockposition, true); + } + + @Nullable -+ public TileEntity getBlockEntity(BlockPosition blockposition, boolean validate) { ++ public TileEntity getBlockEntity(BlockPos blockposition, boolean validate) { + if (capturedTileEntities.containsKey(blockposition)) { + return capturedTileEntities.get(blockposition); + } @@ -288,7 +288,7 @@ } @@ -516,6 +712,12 @@ - BlockPosition blockposition = tileentity.getBlockPos(); + BlockPos blockposition = tileentity.getBlockPos(); if (!this.isOutsideBuildHeight(blockposition)) { + // CraftBukkit start diff --git a/nms-patches/net/minecraft/world/level/block/BigDripleafBlock.patch b/nms-patches/net/minecraft/world/level/block/BigDripleafBlock.patch index 791bcfe2..9f9187ce 100644 --- a/nms-patches/net/minecraft/world/level/block/BigDripleafBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/BigDripleafBlock.patch @@ -22,7 +22,7 @@ @Override @@ -178,7 +183,20 @@ - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if (!world.isClientSide) { if (iblockdata.getValue(BigDripleafBlock.TILT) == Tilt.NONE && canEntityTilt(blockposition, entity) && !world.hasNeighborSignal(blockposition)) { - this.setTiltAndScheduleTick(iblockdata, world, blockposition, Tilt.UNSTABLE, (SoundEffect) null); @@ -59,10 +59,10 @@ return entity.onGround() && entity.position().y > (double) ((float) blockposition.getY() + 0.6875F); } -- private void setTiltAndScheduleTick(IBlockData iblockdata, World world, BlockPosition blockposition, Tilt tilt, @Nullable SoundEffect soundeffect) { +- private void setTiltAndScheduleTick(IBlockData iblockdata, World world, BlockPos blockposition, Tilt tilt, @Nullable SoundEffect soundeffect) { - setTilt(iblockdata, world, blockposition, tilt); + // CraftBukkit start -+ private void setTiltAndScheduleTick(IBlockData iblockdata, World world, BlockPosition blockposition, Tilt tilt, @Nullable SoundEffect soundeffect, @Nullable Entity entity) { ++ private void setTiltAndScheduleTick(IBlockData iblockdata, World world, BlockPos blockposition, Tilt tilt, @Nullable SoundEffect soundeffect, @Nullable Entity entity) { + if (!setTilt(iblockdata, world, blockposition, tilt, entity)) return; + // CraftBukkit end if (soundeffect != null) { @@ -71,7 +71,7 @@ @@ -235,14 +255,21 @@ } - private static void resetTilt(IBlockData iblockdata, World world, BlockPosition blockposition) { + private static void resetTilt(IBlockData iblockdata, World world, BlockPos blockposition) { - setTilt(iblockdata, world, blockposition, Tilt.NONE); + setTilt(iblockdata, world, blockposition, Tilt.NONE, null); // CraftBukkit if (iblockdata.getValue(BigDripleafBlock.TILT) != Tilt.NONE) { @@ -80,9 +80,9 @@ } -- private static void setTilt(IBlockData iblockdata, World world, BlockPosition blockposition, Tilt tilt) { +- private static void setTilt(IBlockData iblockdata, World world, BlockPos blockposition, Tilt tilt) { + // CraftBukkit start -+ private static boolean setTilt(IBlockData iblockdata, World world, BlockPosition blockposition, Tilt tilt, @Nullable Entity entity) { ++ private static boolean setTilt(IBlockData iblockdata, World world, BlockPos blockposition, Tilt tilt, @Nullable Entity entity) { + if (entity != null) { + if (!CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition, iblockdata.setValue(BigDripleafBlock.TILT, tilt))) { + return false; diff --git a/nms-patches/net/minecraft/world/level/block/Block.patch b/nms-patches/net/minecraft/world/level/block/Block.patch index fe2c7229..80a52170 100644 --- a/nms-patches/net/minecraft/world/level/block/Block.patch +++ b/nms-patches/net/minecraft/world/level/block/Block.patch @@ -17,7 +17,7 @@ } @@ -369,7 +375,7 @@ - public void playerDestroy(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { + public void playerDestroy(World world, EntityHuman entityhuman, BlockPos blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { entityhuman.awardStat(StatisticList.BLOCK_MINED.get(this)); - entityhuman.causeFoodExhaustion(0.005F); + entityhuman.causeFoodExhaustion(0.005F, org.bukkit.event.entity.EntityExhaustionEvent.ExhaustionReason.BLOCK_MINED); // CraftBukkit - EntityExhaustionEvent @@ -28,9 +28,9 @@ return this.builtInRegistryHolder; } -- protected void tryDropExperience(WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, IntProvider intprovider) { +- protected void tryDropExperience(WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, IntProvider intprovider) { + // CraftBukkit start -+ protected int tryDropExperience(WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, IntProvider intprovider) { ++ protected int tryDropExperience(WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, IntProvider intprovider) { int i = EnchantmentManager.processBlockExperience(worldserver, itemstack, intprovider.sample(worldserver.getRandom())); if (i > 0) { @@ -42,7 +42,7 @@ + return 0; } -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { + return 0; + } + // CraftBukkit end diff --git a/nms-patches/net/minecraft/world/level/block/BlockBamboo.patch b/nms-patches/net/minecraft/world/level/block/BlockBamboo.patch index b18e8d37..d272da48 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockBamboo.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockBamboo.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/block/BlockBamboo.java +++ b/net/minecraft/world/level/block/BlockBamboo.java @@ -183,7 +183,7 @@ - BlockPosition blockposition1 = blockposition.above(i); + BlockPos blockposition1 = blockposition.above(i); IBlockData iblockdata1 = worldserver.getBlockState(blockposition1); - if (k >= 16 || (Integer) iblockdata1.getValue(BlockBamboo.STAGE) == 1 || !worldserver.isEmptyBlock(blockposition1.above())) { @@ -10,7 +10,7 @@ } @@ -204,14 +204,18 @@ - BlockPosition blockposition1 = blockposition.below(2); + BlockPos blockposition1 = blockposition.below(2); IBlockData iblockdata2 = world.getBlockState(blockposition1); BlockPropertyBambooSize blockpropertybamboosize = BlockPropertyBambooSize.NONE; + boolean shouldUpdateOthers = false; // CraftBukkit @@ -45,4 +45,4 @@ + // CraftBukkit end } - protected int getHeightAboveUpToMax(IBlockAccess iblockaccess, BlockPosition blockposition) { + protected int getHeightAboveUpToMax(IBlockAccess iblockaccess, BlockPos blockposition) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockBambooSapling.patch b/nms-patches/net/minecraft/world/level/block/BlockBambooSapling.patch index 9bfc7a5c..c93f57db 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockBambooSapling.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockBambooSapling.patch @@ -3,7 +3,7 @@ @@ -87,6 +87,6 @@ } - protected void growBamboo(World world, BlockPosition blockposition) { + protected void growBamboo(World world, BlockPos blockposition) { - world.setBlock(blockposition.above(), (IBlockData) Blocks.BAMBOO.defaultBlockState().setValue(BlockBamboo.LEAVES, BlockPropertyBambooSize.SMALL), 3); + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition.above(), (IBlockData) Blocks.BAMBOO.defaultBlockState().setValue(BlockBamboo.LEAVES, BlockPropertyBambooSize.SMALL), 3); // CraftBukkit - BlockSpreadEvent } diff --git a/nms-patches/net/minecraft/world/level/block/BlockBed.patch b/nms-patches/net/minecraft/world/level/block/BlockBed.patch index 87549359..e37a5e99 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockBed.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockBed.patch @@ -8,7 +8,7 @@ + // CraftBukkit - moved world and biome check into EntityHuman + if (false && !canSetSpawn(world)) { world.removeBlock(blockposition, false); - BlockPosition blockposition1 = blockposition.relative(((EnumDirection) iblockdata.getValue(BlockBed.FACING)).getOpposite()); + BlockPos blockposition1 = blockposition.relative(((EnumDirection) iblockdata.getValue(BlockBed.FACING)).getOpposite()); @@ -114,7 +115,16 @@ @@ -16,7 +16,7 @@ } else { + // CraftBukkit start + IBlockData finaliblockdata = iblockdata; -+ BlockPosition finalblockposition = blockposition; ++ BlockPos finalblockposition = blockposition; + // CraftBukkit end entityhuman.startSleepInBed(blockposition).ifLeft((entityhuman_enumbedresult) -> { + // CraftBukkit start - handling bed explosion from below here @@ -32,12 +32,12 @@ } + // CraftBukkit start -+ private EnumInteractionResult explodeBed(IBlockData iblockdata, World world, BlockPosition blockposition) { ++ private EnumInteractionResult explodeBed(IBlockData iblockdata, World world, BlockPos blockposition) { + { + { + org.bukkit.block.BlockState blockState = org.bukkit.craftbukkit.block.CraftBlock.at(world, blockposition).getState(); // CraftBukkit - capture BlockState before remove block + world.removeBlock(blockposition, false); -+ BlockPosition blockposition1 = blockposition.relative(((EnumDirection) iblockdata.getValue(BlockBed.FACING)).getOpposite()); ++ BlockPos blockposition1 = blockposition.relative(((EnumDirection) iblockdata.getValue(BlockBed.FACING)).getOpposite()); + + if (world.getBlockState(blockposition1).getBlock() == this) { + world.removeBlock(blockposition1, false); @@ -58,9 +58,9 @@ + return true || world.dimensionType().bedWorks(); } - private boolean kickVillagerOutOfBed(World world, BlockPosition blockposition) { + private boolean kickVillagerOutOfBed(World world, BlockPos blockposition) { @@ -325,6 +357,11 @@ - BlockPosition blockposition1 = blockposition.relative((EnumDirection) iblockdata.getValue(BlockBed.FACING)); + BlockPos blockposition1 = blockposition.relative((EnumDirection) iblockdata.getValue(BlockBed.FACING)); world.setBlock(blockposition1, (IBlockData) iblockdata.setValue(BlockBed.PART, BlockPropertyBedPart.HEAD), 3); + // CraftBukkit start - SPIGOT-7315: Don't updated if we capture block states diff --git a/nms-patches/net/minecraft/world/level/block/BlockButtonAbstract.patch b/nms-patches/net/minecraft/world/level/block/BlockButtonAbstract.patch index 5000b862..2186c302 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockButtonAbstract.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockButtonAbstract.patch @@ -35,7 +35,7 @@ @@ -197,11 +215,36 @@ } - protected void checkPressed(IBlockData iblockdata, World world, BlockPosition blockposition) { + protected void checkPressed(IBlockData iblockdata, World world, BlockPos blockposition) { - EntityArrow entityarrow = this.type.canButtonBeActivatedByArrows() ? (EntityArrow) world.getEntitiesOfClass(EntityArrow.class, iblockdata.getShape(world, blockposition).bounds().move(blockposition)).stream().findFirst().orElse((Object) null) : null; + EntityArrow entityarrow = this.type.canButtonBeActivatedByArrows() ? (EntityArrow) world.getEntitiesOfClass(EntityArrow.class, iblockdata.getShape(world, blockposition).bounds().move(blockposition)).stream().findFirst().orElse(null) : null; // CraftBukkit - decompile error boolean flag = entityarrow != null; diff --git a/nms-patches/net/minecraft/world/level/block/BlockCactus.patch b/nms-patches/net/minecraft/world/level/block/BlockCactus.patch index b7357ae0..07cfce57 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCactus.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCactus.patch @@ -21,7 +21,7 @@ @@ -120,7 +122,7 @@ @Override - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { - entity.hurt(world.damageSources().cactus(), 1.0F); + entity.hurt(world.damageSources().cactus().directBlock(world, blockposition), 1.0F); // CraftBukkit } diff --git a/nms-patches/net/minecraft/world/level/block/BlockCampfire.patch b/nms-patches/net/minecraft/world/level/block/BlockCampfire.patch index dcc6445b..47481df9 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCampfire.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCampfire.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockCampfire.java @@ -113,7 +113,7 @@ @Override - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if ((Boolean) iblockdata.getValue(BlockCampfire.LIT) && entity instanceof EntityLiving) { - entity.hurt(world.damageSources().campfire(), (float) this.fireDamage); + entity.hurt(world.damageSources().campfire().directBlock(world, blockposition), (float) this.fireDamage); // CraftBukkit diff --git a/nms-patches/net/minecraft/world/level/block/BlockChest.patch b/nms-patches/net/minecraft/world/level/block/BlockChest.patch index 4f8016bc..70935f61 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockChest.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockChest.patch @@ -68,23 +68,23 @@ @@ -262,7 +277,7 @@ @Override - public DoubleBlockFinder.Result combine(IBlockData iblockdata, World world, BlockPosition blockposition, boolean flag) { + public DoubleBlockFinder.Result combine(IBlockData iblockdata, World world, BlockPos blockposition, boolean flag) { - BiPredicate bipredicate; -+ BiPredicate bipredicate; // CraftBukkit - decompile error ++ BiPredicate bipredicate; // CraftBukkit - decompile error if (flag) { bipredicate = (generatoraccess, blockposition1) -> { @@ -278,7 +293,14 @@ @Nullable @Override - protected ITileInventory getMenuProvider(IBlockData iblockdata, World world, BlockPosition blockposition) { + protected ITileInventory getMenuProvider(IBlockData iblockdata, World world, BlockPos blockposition) { - return (ITileInventory) ((Optional) this.combine(iblockdata, world, blockposition, false).apply(BlockChest.MENU_PROVIDER_COMBINER)).orElse((Object) null); + // CraftBukkit start + return getMenuProvider(iblockdata, world, blockposition, false); + } + + @Nullable -+ public ITileInventory getMenuProvider(IBlockData iblockdata, World world, BlockPosition blockposition, boolean ignoreObstructions) { ++ public ITileInventory getMenuProvider(IBlockData iblockdata, World world, BlockPos blockposition, boolean ignoreObstructions) { + return (ITileInventory) ((Optional) this.combine(iblockdata, world, blockposition, ignoreObstructions).apply(BlockChest.MENU_PROVIDER_COMBINER)).orElse((Object) null); + // CraftBukkit end } diff --git a/nms-patches/net/minecraft/world/level/block/BlockChorusFlower.patch b/nms-patches/net/minecraft/world/level/block/BlockChorusFlower.patch index 04cac1d3..35582157 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockChorusFlower.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockChorusFlower.patch @@ -25,7 +25,7 @@ j = randomsource.nextInt(4); if (flag1) { @@ -118,18 +124,30 @@ - BlockPosition blockposition2 = blockposition.relative(enumdirection); + BlockPos blockposition2 = blockposition.relative(enumdirection); if (worldserver.isEmptyBlock(blockposition2) && worldserver.isEmptyBlock(blockposition2.below()) && allNeighborsEmpty(worldserver, blockposition2, enumdirection.getOpposite())) { - this.placeGrownFlower(worldserver, blockposition2, i + 1); diff --git a/nms-patches/net/minecraft/world/level/block/BlockCocoa.patch b/nms-patches/net/minecraft/world/level/block/BlockCocoa.patch index 3e8d91fa..4aba0117 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCocoa.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCocoa.patch @@ -21,7 +21,7 @@ @@ -131,7 +133,7 @@ @Override - public void performBonemeal(WorldServer worldserver, RandomSource randomsource, BlockPosition blockposition, IBlockData iblockdata) { + public void performBonemeal(WorldServer worldserver, RandomSource randomsource, BlockPos blockposition, IBlockData iblockdata) { - worldserver.setBlock(blockposition, (IBlockData) iblockdata.setValue(BlockCocoa.AGE, (Integer) iblockdata.getValue(BlockCocoa.AGE) + 1), 2); + CraftEventFactory.handleBlockGrowEvent(worldserver, blockposition, (IBlockData) iblockdata.setValue(BlockCocoa.AGE, (Integer) iblockdata.getValue(BlockCocoa.AGE) + 1), 2); // CraftBukkit } diff --git a/nms-patches/net/minecraft/world/level/block/BlockCommand.patch b/nms-patches/net/minecraft/world/level/block/BlockCommand.patch index 3984b69d..24d983d3 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCommand.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCommand.patch @@ -11,7 +11,7 @@ public static final MapCodec CODEC = RecordCodecBuilder.mapCodec((instance) -> { @@ -78,6 +80,15 @@ - private void setPoweredAndUpdate(World world, BlockPosition blockposition, TileEntityCommand tileentitycommand, boolean flag) { + private void setPoweredAndUpdate(World world, BlockPos blockposition, TileEntityCommand tileentitycommand, boolean flag) { boolean flag1 = tileentitycommand.isPowered(); + // CraftBukkit start + org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); diff --git a/nms-patches/net/minecraft/world/level/block/BlockComposter.patch b/nms-patches/net/minecraft/world/level/block/BlockComposter.patch index e858180c..9812fdc1 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockComposter.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockComposter.patch @@ -31,7 +31,7 @@ @@ -277,6 +289,14 @@ } - public static IBlockData extractProduce(Entity entity, IBlockData iblockdata, World world, BlockPosition blockposition) { + public static IBlockData extractProduce(Entity entity, IBlockData iblockdata, World world, BlockPos blockposition) { + // CraftBukkit start + if (entity != null && !(entity instanceof EntityHuman)) { + IBlockData iblockdata1 = empty(entity, iblockdata, DummyGeneratorAccess.INSTANCE, blockposition); @@ -46,12 +46,12 @@ @@ -300,10 +320,16 @@ } - static IBlockData addItem(@Nullable Entity entity, IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, ItemStack itemstack) { + static IBlockData addItem(@Nullable Entity entity, IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPos blockposition, ItemStack itemstack) { + // CraftBukkit start + return addItem(entity, iblockdata, generatoraccess, blockposition, itemstack, generatoraccess.getRandom().nextDouble()); + } + -+ static IBlockData addItem(@Nullable Entity entity, IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, ItemStack itemstack, double rand) { ++ static IBlockData addItem(@Nullable Entity entity, IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPos blockposition, ItemStack itemstack, double rand) { + // CraftBukkit end int i = (Integer) iblockdata.getValue(BlockComposter.LEVEL); float f = BlockComposter.COMPOSTABLES.getFloat(itemstack.getItem()); @@ -62,7 +62,7 @@ } else { int j = i + 1; @@ -352,7 +378,8 @@ - public IWorldInventory getContainer(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { + public IWorldInventory getContainer(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPos blockposition) { int i = (Integer) iblockdata.getValue(BlockComposter.LEVEL); - return (IWorldInventory) (i == 8 ? new BlockComposter.ContainerOutput(iblockdata, generatoraccess, blockposition, new ItemStack(Items.BONE_MEAL)) : (i < 7 ? new BlockComposter.ContainerInput(iblockdata, generatoraccess, blockposition) : new BlockComposter.ContainerEmpty())); @@ -97,7 +97,7 @@ @@ -405,6 +440,7 @@ - public ContainerInput(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { + public ContainerInput(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPos blockposition) { super(1); + this.bukkitOwner = new CraftBlockInventoryHolder(generatoraccess, blockposition, this); // CraftBukkit this.state = iblockdata; @@ -108,7 +108,7 @@ public static class ContainerEmpty extends InventorySubcontainer implements IWorldInventory { - public ContainerEmpty() { -+ public ContainerEmpty(GeneratorAccess generatoraccess, BlockPosition blockposition) { // CraftBukkit ++ public ContainerEmpty(GeneratorAccess generatoraccess, BlockPos blockposition) { // CraftBukkit super(0); + this.bukkitOwner = new CraftBlockInventoryHolder(generatoraccess, blockposition, this); // CraftBukkit } diff --git a/nms-patches/net/minecraft/world/level/block/BlockConcretePowder.patch b/nms-patches/net/minecraft/world/level/block/BlockConcretePowder.patch index f828b830..5b5a90cc 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockConcretePowder.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockConcretePowder.patch @@ -15,7 +15,7 @@ public static final MapCodec CODEC = RecordCodecBuilder.mapCodec((instance) -> { @@ -38,7 +44,7 @@ @Override - public void onLand(World world, BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1, EntityFallingBlock entityfallingblock) { + public void onLand(World world, BlockPos blockposition, IBlockData iblockdata, IBlockData iblockdata1, EntityFallingBlock entityfallingblock) { if (shouldSolidify(world, blockposition, iblockdata1)) { - world.setBlock(blockposition, this.concrete.defaultBlockState(), 3); + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(world, blockposition, this.concrete.defaultBlockState(), 3); // CraftBukkit @@ -23,7 +23,7 @@ } @@ -49,7 +55,24 @@ - BlockPosition blockposition = blockactioncontext.getClickedPos(); + BlockPos blockposition = blockactioncontext.getClickedPos(); IBlockData iblockdata = world.getBlockState(blockposition); - return shouldSolidify(world, blockposition, iblockdata) ? this.concrete.defaultBlockState() : super.getStateForPlacement(blockactioncontext); @@ -47,11 +47,11 @@ + // CraftBukkit end } - private static boolean shouldSolidify(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { + private static boolean shouldSolidify(IBlockAccess iblockaccess, BlockPos blockposition, IBlockData iblockdata) { @@ -85,7 +108,25 @@ @Override - protected IBlockData updateShape(IBlockData iblockdata, IWorldReader iworldreader, ScheduledTickAccess scheduledtickaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition blockposition1, IBlockData iblockdata1, RandomSource randomsource) { + protected IBlockData updateShape(IBlockData iblockdata, IWorldReader iworldreader, ScheduledTickAccess scheduledtickaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos blockposition1, IBlockData iblockdata1, RandomSource randomsource) { - return touchesLiquid(iworldreader, blockposition) ? this.concrete.defaultBlockState() : super.updateShape(iblockdata, iworldreader, scheduledtickaccess, blockposition, enumdirection, blockposition1, iblockdata1, randomsource); + // CraftBukkit start + if (touchesLiquid(iworldreader, blockposition)) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockCoral.patch b/nms-patches/net/minecraft/world/level/block/BlockCoral.patch index 17128dac..df9f2ecb 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCoral.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCoral.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockCoral.java @@ -40,6 +40,11 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (!this.scanForWater(worldserver, blockposition)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, this.deadBlock.defaultBlockState()).isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockCoralFan.patch b/nms-patches/net/minecraft/world/level/block/BlockCoralFan.patch index d885679e..ad8d1f78 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCoralFan.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCoralFan.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockCoralFan.java @@ -41,6 +41,11 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (!scanForWater(iblockdata, worldserver, blockposition)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, this.deadBlock.defaultBlockState().setValue(BlockCoralFan.WATERLOGGED, false)).isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockCoralFanWall.patch b/nms-patches/net/minecraft/world/level/block/BlockCoralFanWall.patch index 304e1b53..45e5ab54 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCoralFanWall.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCoralFanWall.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockCoralFanWall.java @@ -41,6 +41,11 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (!scanForWater(iblockdata, worldserver, blockposition)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, this.deadBlock.defaultBlockState().setValue(BlockCoralFanWall.WATERLOGGED, false).setValue(BlockCoralFanWall.FACING, iblockdata.getValue(BlockCoralFanWall.FACING))).isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockCoralPlant.patch b/nms-patches/net/minecraft/world/level/block/BlockCoralPlant.patch index 44e06a24..d6292ad7 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCoralPlant.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCoralPlant.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockCoralPlant.java @@ -46,6 +46,11 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (!scanForWater(iblockdata, worldserver, blockposition)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, this.deadBlock.defaultBlockState().setValue(BlockCoralPlant.WATERLOGGED, false)).isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockCrops.patch b/nms-patches/net/minecraft/world/level/block/BlockCrops.patch index bf16556b..5d270deb 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockCrops.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockCrops.patch @@ -29,7 +29,7 @@ protected int getBonemealAgeIncrease(World world) { @@ -161,7 +163,7 @@ @Override - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if (world instanceof WorldServer worldserver) { - if (entity instanceof EntityRavager && worldserver.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) { + if (entity instanceof EntityRavager && CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition, Blocks.AIR.defaultBlockState(), !worldserver.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING))) { // CraftBukkit diff --git a/nms-patches/net/minecraft/world/level/block/BlockDirtSnowSpreadable.patch b/nms-patches/net/minecraft/world/level/block/BlockDirtSnowSpreadable.patch index 187fabc5..7b749fb4 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockDirtSnowSpreadable.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockDirtSnowSpreadable.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockDirtSnowSpreadable.java @@ -44,6 +44,11 @@ @Override - protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (!canBeGrass(iblockdata, worldserver, blockposition)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, Blocks.DIRT.defaultBlockState()).isCancelled()) { @@ -13,7 +13,7 @@ } else { if (worldserver.getMaxLocalRawBrightness(blockposition.above()) >= 9) { @@ -53,7 +58,7 @@ - BlockPosition blockposition1 = blockposition.offset(randomsource.nextInt(3) - 1, randomsource.nextInt(5) - 3, randomsource.nextInt(3) - 1); + BlockPos blockposition1 = blockposition.offset(randomsource.nextInt(3) - 1, randomsource.nextInt(5) - 3, randomsource.nextInt(3) - 1); if (worldserver.getBlockState(blockposition1).is(Blocks.DIRT) && canPropagate(iblockdata1, worldserver, blockposition1)) { - worldserver.setBlockAndUpdate(blockposition1, (IBlockData) iblockdata1.setValue(BlockDirtSnowSpreadable.SNOWY, worldserver.getBlockState(blockposition1.above()).is(Blocks.SNOW))); diff --git a/nms-patches/net/minecraft/world/level/block/BlockDispenser.patch b/nms-patches/net/minecraft/world/level/block/BlockDispenser.patch index 8b0139e0..c967ecf7 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockDispenser.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockDispenser.patch @@ -11,7 +11,7 @@ @@ -88,7 +89,7 @@ } - public void dispenseFrom(WorldServer worldserver, IBlockData iblockdata, BlockPosition blockposition) { + public void dispenseFrom(WorldServer worldserver, IBlockData iblockdata, BlockPos blockposition) { - TileEntityDispenser tileentitydispenser = (TileEntityDispenser) worldserver.getBlockEntity(blockposition, TileEntityTypes.DISPENSER).orElse((Object) null); + TileEntityDispenser tileentitydispenser = (TileEntityDispenser) worldserver.getBlockEntity(blockposition, TileEntityTypes.DISPENSER).orElse(null); // CraftBukkit - decompile error diff --git a/nms-patches/net/minecraft/world/level/block/BlockDoor.patch b/nms-patches/net/minecraft/world/level/block/BlockDoor.patch index d62163d0..05158835 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockDoor.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockDoor.patch @@ -12,10 +12,10 @@ @@ -222,9 +224,24 @@ @Override - protected void neighborChanged(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, @Nullable Orientation orientation, boolean flag) { + protected void neighborChanged(IBlockData iblockdata, World world, BlockPos blockposition, Block block, @Nullable Orientation orientation, boolean flag) { - boolean flag1 = world.hasNeighborSignal(blockposition) || world.hasNeighborSignal(blockposition.relative(iblockdata.getValue(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER ? EnumDirection.UP : EnumDirection.DOWN)); + // CraftBukkit start -+ BlockPosition otherHalf = blockposition.relative(iblockdata.getValue(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER ? EnumDirection.UP : EnumDirection.DOWN); ++ BlockPos otherHalf = blockposition.relative(iblockdata.getValue(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER ? EnumDirection.UP : EnumDirection.DOWN); - if (!this.defaultBlockState().is(block) && flag1 != (Boolean) iblockdata.getValue(BlockDoor.POWERED)) { + org.bukkit.World bworld = world.getWorld(); diff --git a/nms-patches/net/minecraft/world/level/block/BlockDragonEgg.patch b/nms-patches/net/minecraft/world/level/block/BlockDragonEgg.patch index c7129ecf..1729d2f7 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockDragonEgg.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockDragonEgg.patch @@ -10,7 +10,7 @@ public static final MapCodec CODEC = simpleCodec(BlockDragonEgg::new); @@ -53,6 +55,18 @@ - BlockPosition blockposition1 = blockposition.offset(world.random.nextInt(16) - world.random.nextInt(16), world.random.nextInt(8) - world.random.nextInt(8), world.random.nextInt(16) - world.random.nextInt(16)); + BlockPos blockposition1 = blockposition.offset(world.random.nextInt(16) - world.random.nextInt(16), world.random.nextInt(8) - world.random.nextInt(8), world.random.nextInt(16) - world.random.nextInt(16)); if (world.getBlockState(blockposition1).isAir() && worldborder.isWithinBounds(blockposition1)) { + // CraftBukkit start @@ -23,7 +23,7 @@ + return; + } + -+ blockposition1 = new BlockPosition(event.getToBlock().getX(), event.getToBlock().getY(), event.getToBlock().getZ()); ++ blockposition1 = new BlockPos(event.getToBlock().getX(), event.getToBlock().getY(), event.getToBlock().getZ()); + // CraftBukkit end if (world.isClientSide) { for (int j = 0; j < 128; ++j) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockDropper.patch b/nms-patches/net/minecraft/world/level/block/BlockDropper.patch index 79049d7f..94fecd0f 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockDropper.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockDropper.patch @@ -22,7 +22,7 @@ @@ -47,7 +53,7 @@ @Override - public void dispenseFrom(WorldServer worldserver, IBlockData iblockdata, BlockPosition blockposition) { + public void dispenseFrom(WorldServer worldserver, IBlockData iblockdata, BlockPos blockposition) { - TileEntityDispenser tileentitydispenser = (TileEntityDispenser) worldserver.getBlockEntity(blockposition, TileEntityTypes.DROPPER).orElse((Object) null); + TileEntityDispenser tileentitydispenser = (TileEntityDispenser) worldserver.getBlockEntity(blockposition, TileEntityTypes.DROPPER).orElse(null); // CraftBukkit - decompile error diff --git a/nms-patches/net/minecraft/world/level/block/BlockEnderPortal.patch b/nms-patches/net/minecraft/world/level/block/BlockEnderPortal.patch index 85f651ff..10853c0d 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockEnderPortal.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockEnderPortal.patch @@ -22,7 +22,7 @@ public static final MapCodec CODEC = simpleCodec(BlockEnderPortal::new); @@ -58,6 +71,10 @@ @Override - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if (entity.canUsePortal(false)) { + // CraftBukkit start - Entity in portal + EntityPortalEnterEvent event = new EntityPortalEnterEvent(entity.getBukkitEntity(), new org.bukkit.Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ())); @@ -34,7 +34,7 @@ @@ -74,11 +91,11 @@ @Override - public TeleportTransition getPortalDestination(WorldServer worldserver, Entity entity, BlockPosition blockposition) { + public TeleportTransition getPortalDestination(WorldServer worldserver, Entity entity, BlockPos blockposition) { - ResourceKey resourcekey = worldserver.dimension() == World.END ? World.OVERWORLD : World.END; + ResourceKey resourcekey = worldserver.getTypeKey() == WorldDimension.END ? World.OVERWORLD : World.END; // CraftBukkit - SPIGOT-6152: send back to main overworld in custom ends WorldServer worldserver1 = worldserver.getServer().getLevel(resourcekey); @@ -44,13 +44,13 @@ + return new TeleportTransition(PlayerTeleportEvent.TeleportCause.END_PORTAL); // CraftBukkit- always fire event in case plugins wish to change it } else { boolean flag = resourcekey == World.END; - BlockPosition blockposition1 = flag ? WorldServer.END_SPAWN_POINT : worldserver1.getSharedSpawnPos(); + BlockPos blockposition1 = flag ? WorldServer.END_SPAWN_POINT : worldserver1.getSharedSpawnPos(); @@ -87,7 +104,7 @@ Set set; if (flag) { -- EndPlatformFeature.createEndPlatform(worldserver1, BlockPosition.containing(vec3d).below(), true); -+ EndPlatformFeature.createEndPlatform(worldserver1, BlockPosition.containing(vec3d).below(), true, entity); // CraftBukkit +- EndPlatformFeature.createEndPlatform(worldserver1, BlockPos.containing(vec3d).below(), true); ++ EndPlatformFeature.createEndPlatform(worldserver1, BlockPos.containing(vec3d).below(), true, entity); // CraftBukkit f = EnumDirection.WEST.toYRot(); set = Relative.union(Relative.DELTA, Set.of(Relative.X_ROT)); if (entity instanceof EntityPlayer) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockFenceGate.patch b/nms-patches/net/minecraft/world/level/block/BlockFenceGate.patch index 9665e2b1..68c15bfc 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockFenceGate.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockFenceGate.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/block/BlockFenceGate.java +++ b/net/minecraft/world/level/block/BlockFenceGate.java @@ -173,6 +173,17 @@ - protected void neighborChanged(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, @Nullable Orientation orientation, boolean flag) { + protected void neighborChanged(IBlockData iblockdata, World world, BlockPos blockposition, Block block, @Nullable Orientation orientation, boolean flag) { if (!world.isClientSide) { boolean flag1 = world.hasNeighborSignal(blockposition); + // CraftBukkit start diff --git a/nms-patches/net/minecraft/world/level/block/BlockFire.patch b/nms-patches/net/minecraft/world/level/block/BlockFire.patch index beab20b9..63275de5 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockFire.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockFire.patch @@ -19,7 +19,7 @@ @@ -100,7 +109,24 @@ @Override - protected IBlockData updateShape(IBlockData iblockdata, IWorldReader iworldreader, ScheduledTickAccess scheduledtickaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition blockposition1, IBlockData iblockdata1, RandomSource randomsource) { + protected IBlockData updateShape(IBlockData iblockdata, IWorldReader iworldreader, ScheduledTickAccess scheduledtickaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos blockposition1, IBlockData iblockdata1, RandomSource randomsource) { - return this.canSurvive(iblockdata, iworldreader, blockposition) ? this.getStateWithAge(iworldreader, blockposition, (Integer) iblockdata.getValue(BlockFire.AGE)) : Blocks.AIR.defaultBlockState(); + // CraftBukkit start + if (!this.canSurvive(iblockdata, iworldreader, blockposition)) { @@ -61,7 +61,7 @@ int j = Math.min(15, i + randomsource.nextInt(3) / 2); @@ -171,14 +197,14 @@ - BlockPosition blockposition1 = blockposition.below(); + BlockPos blockposition1 = blockposition.below(); if (!worldserver.getBlockState(blockposition1).isFaceSturdy(worldserver, blockposition1, EnumDirection.UP) || i > 3) { - worldserver.removeBlock(blockposition, false); @@ -95,7 +95,7 @@ + this.trySpread(worldserver, blockposition.north(), 300 + k, randomsource, i, blockposition); + this.trySpread(worldserver, blockposition.south(), 300 + k, randomsource, i, blockposition); + // CraftBukkit end - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + BlockPos.MutableBlockPos blockposition_mutableblockposition = new BlockPos.MutableBlockPos(); for (int l = -1; l <= 1; ++l) { @@ -217,7 +245,15 @@ @@ -119,8 +119,8 @@ return iblockdata.hasProperty(BlockProperties.WATERLOGGED) && (Boolean) iblockdata.getValue(BlockProperties.WATERLOGGED) ? 0 : this.igniteOdds.getInt(iblockdata.getBlock()); } -- private void checkBurnOut(World world, BlockPosition blockposition, int i, RandomSource randomsource, int j) { -+ private void trySpread(World world, BlockPosition blockposition, int i, RandomSource randomsource, int j, BlockPosition sourceposition) { // CraftBukkit add sourceposition +- private void checkBurnOut(World world, BlockPos blockposition, int i, RandomSource randomsource, int j) { ++ private void trySpread(World world, BlockPos blockposition, int i, RandomSource randomsource, int j, BlockPos sourceposition) { // CraftBukkit add sourceposition int k = this.getBurnOdds(world.getBlockState(blockposition)); if (randomsource.nextInt(i) < k) { @@ -149,10 +149,10 @@ } @Override -- protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { +- protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag) { - super.onPlace(iblockdata, world, blockposition, iblockdata1, flag); + // CraftBukkit start - context -+ protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag, ItemActionContext context) { ++ protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag, ItemActionContext context) { + super.onPlace(iblockdata, world, blockposition, iblockdata1, flag, context); + // CraftBukkit end world.scheduleTick(blockposition, (Block) this, getFireTickDelay(world.random)); diff --git a/nms-patches/net/minecraft/world/level/block/BlockFireAbstract.patch b/nms-patches/net/minecraft/world/level/block/BlockFireAbstract.patch index 639176c4..fe2baf03 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockFireAbstract.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockFireAbstract.patch @@ -31,8 +31,8 @@ } @Override -- protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { -+ protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag, ItemActionContext context) { // CraftBukkit - context +- protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag) { ++ protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag, ItemActionContext context) { // CraftBukkit - context if (!iblockdata1.is(iblockdata.getBlock())) { if (inPortalDimension(world)) { Optional optional = BlockPortalShape.findEmptyPortalShape(world, blockposition, EnumDirection.EnumAxis.X); @@ -64,7 +64,7 @@ } + + // CraftBukkit start -+ protected void fireExtinguished(net.minecraft.world.level.GeneratorAccess world, BlockPosition position) { ++ protected void fireExtinguished(net.minecraft.world.level.GeneratorAccess world, BlockPos position) { + if (!org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, position, Blocks.AIR.defaultBlockState()).isCancelled()) { + world.removeBlock(position, false); + } diff --git a/nms-patches/net/minecraft/world/level/block/BlockFungi.patch b/nms-patches/net/minecraft/world/level/block/BlockFungi.patch index 3f128a97..0f3e50c0 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockFungi.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockFungi.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockFungi.java @@ -74,6 +74,13 @@ @Override - public void performBonemeal(WorldServer worldserver, RandomSource randomsource, BlockPosition blockposition, IBlockData iblockdata) { + public void performBonemeal(WorldServer worldserver, RandomSource randomsource, BlockPos blockposition, IBlockData iblockdata) { this.getFeature(worldserver).ifPresent((holder) -> { + // CraftBukkit start + if (this == Blocks.WARPED_FUNGUS) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockGrassPath.patch b/nms-patches/net/minecraft/world/level/block/BlockGrassPath.patch index b6d410b9..2c735f5a 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockGrassPath.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockGrassPath.patch @@ -3,7 +3,7 @@ @@ -51,6 +51,11 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { + // CraftBukkit start - do not fade if the block is valid here + if (iblockdata.canSurvive(worldserver, blockposition)) { + return; diff --git a/nms-patches/net/minecraft/world/level/block/BlockGrowingTop.patch b/nms-patches/net/minecraft/world/level/block/BlockGrowingTop.patch index 6421b072..7817be43 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockGrowingTop.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockGrowingTop.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/block/BlockGrowingTop.java +++ b/net/minecraft/world/level/block/BlockGrowingTop.java @@ -48,7 +48,7 @@ - BlockPosition blockposition1 = blockposition.relative(this.growthDirection); + BlockPos blockposition1 = blockposition.relative(this.growthDirection); if (this.canGrowInto(worldserver.getBlockState(blockposition1))) { - worldserver.setBlockAndUpdate(blockposition1, this.getGrowIntoState(iblockdata, worldserver.random)); diff --git a/nms-patches/net/minecraft/world/level/block/BlockIce.patch b/nms-patches/net/minecraft/world/level/block/BlockIce.patch index 4c22d943..040b9108 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockIce.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockIce.patch @@ -3,7 +3,7 @@ @@ -60,6 +60,11 @@ } - protected void melt(IBlockData iblockdata, World world, BlockPosition blockposition) { + protected void melt(IBlockData iblockdata, World world, BlockPos blockposition) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, world.dimensionType().ultraWarm() ? Blocks.AIR.defaultBlockState() : Blocks.WATER.defaultBlockState()).isCancelled()) { + return; diff --git a/nms-patches/net/minecraft/world/level/block/BlockLeaves.patch b/nms-patches/net/minecraft/world/level/block/BlockLeaves.patch index 31ae1d48..29af0fcc 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockLeaves.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockLeaves.patch @@ -11,7 +11,7 @@ public static final MapCodec CODEC = simpleCodec(BlockLeaves::new); @@ -59,6 +61,14 @@ @Override - protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (this.decaying(iblockdata)) { + // CraftBukkit start + LeavesDecayEvent event = new LeavesDecayEvent(worldserver.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ())); diff --git a/nms-patches/net/minecraft/world/level/block/BlockLectern.patch b/nms-patches/net/minecraft/world/level/block/BlockLectern.patch index 2e2f29d8..22aa2711 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockLectern.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockLectern.patch @@ -3,7 +3,7 @@ @@ -211,11 +211,12 @@ } - private void popBook(IBlockData iblockdata, World world, BlockPosition blockposition) { + private void popBook(IBlockData iblockdata, World world, BlockPos blockposition) { - TileEntity tileentity = world.getBlockEntity(blockposition); + TileEntity tileentity = world.getBlockEntity(blockposition, false); // CraftBukkit - don't validate, type may be changed already diff --git a/nms-patches/net/minecraft/world/level/block/BlockMagma.patch b/nms-patches/net/minecraft/world/level/block/BlockMagma.patch index 8c863e49..44d9afe5 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockMagma.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockMagma.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockMagma.java @@ -30,7 +30,7 @@ @Override - public void stepOn(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + public void stepOn(World world, BlockPos blockposition, IBlockData iblockdata, Entity entity) { if (!entity.isSteppingCarefully() && entity instanceof EntityLiving) { - entity.hurt(world.damageSources().hotFloor(), 1.0F); + entity.hurt(world.damageSources().hotFloor().directBlock(world, blockposition), 1.0F); // CraftBukkit diff --git a/nms-patches/net/minecraft/world/level/block/BlockMobSpawner.patch b/nms-patches/net/minecraft/world/level/block/BlockMobSpawner.patch index 99b013b0..4b4c915c 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockMobSpawner.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockMobSpawner.patch @@ -2,13 +2,13 @@ +++ b/net/minecraft/world/level/block/BlockMobSpawner.java @@ -45,12 +45,20 @@ @Override - protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { + protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack, flag); + // CraftBukkit start - Delegate to getExpDrop + } + + @Override -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { if (flag) { int i = 15 + worldserver.random.nextInt(15) + worldserver.random.nextInt(15); diff --git a/nms-patches/net/minecraft/world/level/block/BlockNote.patch b/nms-patches/net/minecraft/world/level/block/BlockNote.patch index 74c8339f..9746d2c8 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockNote.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockNote.patch @@ -10,7 +10,7 @@ world.setBlock(blockposition, (IBlockData) iblockdata.setValue(BlockNote.POWERED, flag1), 3); @@ -94,6 +95,12 @@ - private void playNote(@Nullable Entity entity, IBlockData iblockdata, World world, BlockPosition blockposition) { + private void playNote(@Nullable Entity entity, IBlockData iblockdata, World world, BlockPos blockposition) { if (((BlockPropertyInstrument) iblockdata.getValue(BlockNote.INSTRUMENT)).worksAboveNoteBlock() || world.getBlockState(blockposition.above()).isAir()) { + // CraftBukkit start + org.bukkit.event.block.NotePlayEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callNotePlayEvent(world, blockposition, iblockdata.getValue(BlockNote.INSTRUMENT), iblockdata.getValue(BlockNote.NOTE)); diff --git a/nms-patches/net/minecraft/world/level/block/BlockNylium.patch b/nms-patches/net/minecraft/world/level/block/BlockNylium.patch index 244c15ed..e7ac3d96 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockNylium.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockNylium.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockNylium.java @@ -41,6 +41,11 @@ @Override - protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (!canBeNylium(iblockdata, worldserver, blockposition)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, Blocks.NETHERRACK.defaultBlockState()).isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockObserver.patch b/nms-patches/net/minecraft/world/level/block/BlockObserver.patch index b76c2f04..b9f861f5 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockObserver.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockObserver.patch @@ -11,7 +11,7 @@ public static final MapCodec CODEC = simpleCodec(BlockObserver::new); @@ -51,8 +53,18 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if ((Boolean) iblockdata.getValue(BlockObserver.POWERED)) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(worldserver, blockposition, 15, 0).getNewCurrent() != 0) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockPlant.patch b/nms-patches/net/minecraft/world/level/block/BlockPlant.patch index 274403a3..1c12696c 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockPlant.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockPlant.patch @@ -14,7 +14,7 @@ @@ -27,7 +31,15 @@ @Override - protected IBlockData updateShape(IBlockData iblockdata, IWorldReader iworldreader, ScheduledTickAccess scheduledtickaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition blockposition1, IBlockData iblockdata1, RandomSource randomsource) { + protected IBlockData updateShape(IBlockData iblockdata, IWorldReader iworldreader, ScheduledTickAccess scheduledtickaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos blockposition1, IBlockData iblockdata1, RandomSource randomsource) { - return !iblockdata.canSurvive(iworldreader, blockposition) ? Blocks.AIR.defaultBlockState() : super.updateShape(iblockdata, iworldreader, scheduledtickaccess, blockposition, enumdirection, blockposition1, iblockdata1, randomsource); + // CraftBukkit start + if (!iblockdata.canSurvive(iworldreader, blockposition)) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockPortal.patch b/nms-patches/net/minecraft/world/level/block/BlockPortal.patch index 70f5f61d..04791bb3 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockPortal.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockPortal.patch @@ -28,7 +28,7 @@ entity.setPortalCooldown(); @@ -104,6 +114,10 @@ @Override - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if (entity.canUsePortal(false)) { + // CraftBukkit start - Entity in portal + EntityPortalEnterEvent event = new EntityPortalEnterEvent(entity.getBukkitEntity(), new org.bukkit.Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ())); @@ -40,7 +40,7 @@ @@ -121,24 +135,34 @@ @Nullable @Override - public TeleportTransition getPortalDestination(WorldServer worldserver, Entity entity, BlockPosition blockposition) { + public TeleportTransition getPortalDestination(WorldServer worldserver, Entity entity, BlockPos blockposition) { - ResourceKey resourcekey = worldserver.dimension() == World.NETHER ? World.OVERWORLD : World.NETHER; + // CraftBukkit start + ResourceKey resourcekey = worldserver.getTypeKey() == WorldDimension.NETHER ? World.OVERWORLD : World.NETHER; @@ -55,7 +55,7 @@ + // CraftBukkit end WorldBorder worldborder = worldserver1.getWorldBorder(); double d0 = DimensionManager.getTeleportationScale(worldserver.dimensionType(), worldserver1.dimensionType()); - BlockPosition blockposition1 = worldborder.clampToBounds(entity.getX() * d0, entity.getY(), entity.getZ() * d0); + BlockPos blockposition1 = worldborder.clampToBounds(entity.getX() * d0, entity.getY(), entity.getZ() * d0); + // CraftBukkit start + CraftPortalEvent event = entity.callPortalEvent(entity, CraftLocation.toBukkit(blockposition1, worldserver1.getWorld()), PlayerTeleportEvent.TeleportCause.NETHER_PORTAL, flag ? 16 : 128, 16); + if (event == null) { @@ -71,10 +71,10 @@ } @Nullable -- private TeleportTransition getExitPortal(WorldServer worldserver, Entity entity, BlockPosition blockposition, BlockPosition blockposition1, boolean flag, WorldBorder worldborder) { -- Optional optional = worldserver.getPortalForcer().findClosestPortalPosition(blockposition1, flag, worldborder); -+ private TeleportTransition getExitPortal(WorldServer worldserver, Entity entity, BlockPosition blockposition, BlockPosition blockposition1, boolean flag, WorldBorder worldborder, int searchRadius, boolean canCreatePortal, int createRadius) { -+ Optional optional = worldserver.getPortalForcer().findClosestPortalPosition(blockposition1, worldborder, searchRadius); +- private TeleportTransition getExitPortal(WorldServer worldserver, Entity entity, BlockPos blockposition, BlockPos blockposition1, boolean flag, WorldBorder worldborder) { +- Optional optional = worldserver.getPortalForcer().findClosestPortalPosition(blockposition1, flag, worldborder); ++ private TeleportTransition getExitPortal(WorldServer worldserver, Entity entity, BlockPos blockposition, BlockPos blockposition1, boolean flag, WorldBorder worldborder, int searchRadius, boolean canCreatePortal, int createRadius) { ++ Optional optional = worldserver.getPortalForcer().findClosestPortalPosition(blockposition1, worldborder, searchRadius); BlockUtil.Rectangle blockutil_rectangle; TeleportTransition.a teleporttransition_a; diff --git a/nms-patches/net/minecraft/world/level/block/BlockPressurePlateAbstract.patch b/nms-patches/net/minecraft/world/level/block/BlockPressurePlateAbstract.patch index e429e95a..dd5edcbb 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockPressurePlateAbstract.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockPressurePlateAbstract.patch @@ -45,4 +45,4 @@ + })); // CraftBukkit } - protected abstract int getSignalStrength(World world, BlockPosition blockposition); + protected abstract int getSignalStrength(World world, BlockPos blockposition); diff --git a/nms-patches/net/minecraft/world/level/block/BlockPressurePlateBinary.patch b/nms-patches/net/minecraft/world/level/block/BlockPressurePlateBinary.patch index 43f9df9d..41985e33 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockPressurePlateBinary.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockPressurePlateBinary.patch @@ -15,7 +15,7 @@ @@ -44,7 +49,7 @@ @Override - protected int getSignalStrength(World world, BlockPosition blockposition) { + protected int getSignalStrength(World world, BlockPos blockposition) { - Class oclass; + Class oclass; // CraftBukkit diff --git a/nms-patches/net/minecraft/world/level/block/BlockPressurePlateWeighted.patch b/nms-patches/net/minecraft/world/level/block/BlockPressurePlateWeighted.patch index 39a40e09..d6819bce 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockPressurePlateWeighted.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockPressurePlateWeighted.patch @@ -15,7 +15,7 @@ @@ -39,7 +44,27 @@ @Override - protected int getSignalStrength(World world, BlockPosition blockposition) { + protected int getSignalStrength(World world, BlockPos blockposition) { - int i = Math.min(getEntityCount(world, BlockPressurePlateWeighted.TOUCH_AABB.move(blockposition), Entity.class), this.maxWeight); + // CraftBukkit start + // int i = Math.min(getEntityCount(world, BlockPressurePlateWeighted.TOUCH_AABB.move(blockposition), Entity.class), this.maxWeight); diff --git a/nms-patches/net/minecraft/world/level/block/BlockPumpkinCarved.patch b/nms-patches/net/minecraft/world/level/block/BlockPumpkinCarved.patch index c7033e7a..927787b7 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockPumpkinCarved.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockPumpkinCarved.patch @@ -14,7 +14,7 @@ @@ -87,9 +91,14 @@ } - private static void spawnGolemInWorld(World world, ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection, Entity entity, BlockPosition blockposition) { + private static void spawnGolemInWorld(World world, ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection, Entity entity, BlockPos blockposition) { - clearPatternBlocks(world, shapedetector_shapedetectorcollection); + // clearPatternBlocks(world, shapedetector_shapedetectorcollection); // CraftBukkit - moved down entity.moveTo((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.05D, (double) blockposition.getZ() + 0.5D, 0.0F, 0.0F); diff --git a/nms-patches/net/minecraft/world/level/block/BlockRedstoneComparator.patch b/nms-patches/net/minecraft/world/level/block/BlockRedstoneComparator.patch index dc9826b6..064cfac5 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockRedstoneComparator.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockRedstoneComparator.patch @@ -12,7 +12,7 @@ @@ -110,7 +112,8 @@ @Nullable - private EntityItemFrame getItemFrame(World world, EnumDirection enumdirection, BlockPosition blockposition) { + private EntityItemFrame getItemFrame(World world, EnumDirection enumdirection, BlockPos blockposition) { - List list = world.getEntitiesOfClass(EntityItemFrame.class, new AxisAlignedBB((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), (double) (blockposition.getX() + 1), (double) (blockposition.getY() + 1), (double) (blockposition.getZ() + 1)), (entityitemframe) -> { + // CraftBukkit - decompile error + List list = world.getEntitiesOfClass(EntityItemFrame.class, new AxisAlignedBB((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), (double) (blockposition.getX() + 1), (double) (blockposition.getY() + 1), (double) (blockposition.getZ() + 1)), (java.util.function.Predicate) (entityitemframe) -> { diff --git a/nms-patches/net/minecraft/world/level/block/BlockRedstoneLamp.patch b/nms-patches/net/minecraft/world/level/block/BlockRedstoneLamp.patch index c90e0052..188dda63 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockRedstoneLamp.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockRedstoneLamp.patch @@ -23,7 +23,7 @@ } @@ -53,6 +60,11 @@ @Override - protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void tick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if ((Boolean) iblockdata.getValue(BlockRedstoneLamp.LIT) && !worldserver.hasNeighborSignal(blockposition)) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(worldserver, blockposition, 15, 0).getNewCurrent() != 0) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockRedstoneOre.patch b/nms-patches/net/minecraft/world/level/block/BlockRedstoneOre.patch index 1bd1a91b..66c9775d 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockRedstoneOre.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockRedstoneOre.patch @@ -15,14 +15,14 @@ @@ -38,14 +43,27 @@ @Override - protected void attack(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) { + protected void attack(IBlockData iblockdata, World world, BlockPos blockposition, EntityHuman entityhuman) { - interact(iblockdata, world, blockposition); + interact(iblockdata, world, blockposition, entityhuman); // CraftBukkit - add entityhuman super.attack(iblockdata, world, blockposition, entityhuman); } @Override - public void stepOn(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + public void stepOn(World world, BlockPos blockposition, IBlockData iblockdata, Entity entity) { if (!entity.isSteppingCarefully()) { - interact(iblockdata, world, blockposition); + // CraftBukkit start @@ -53,8 +53,8 @@ return (EnumInteractionResult) (itemstack.getItem() instanceof ItemBlock && (new BlockActionContext(entityhuman, enumhand, itemstack, movingobjectpositionblock)).canPlace() ? EnumInteractionResult.PASS : EnumInteractionResult.SUCCESS); } -- private static void interact(IBlockData iblockdata, World world, BlockPosition blockposition) { -+ private static void interact(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { // CraftBukkit - add Entity +- private static void interact(IBlockData iblockdata, World world, BlockPos blockposition) { ++ private static void interact(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { // CraftBukkit - add Entity spawnParticles(world, blockposition); if (!(Boolean) iblockdata.getValue(BlockRedstoneOre.LIT)) { + // CraftBukkit start @@ -67,7 +67,7 @@ @@ -78,6 +101,11 @@ @Override - protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if ((Boolean) iblockdata.getValue(BlockRedstoneOre.LIT)) { + // CraftBukkit start + if (CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, iblockdata.setValue(BlockRedstoneOre.LIT, false)).isCancelled()) { @@ -79,13 +79,13 @@ @@ -86,10 +114,17 @@ @Override - protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { + protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack, flag); + // CraftBukkit start - Delegated to getExpDrop + } + + @Override -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { if (flag) { - this.tryDropExperience(worldserver, blockposition, itemstack, UniformInt.of(1, 5)); + return this.tryDropExperience(worldserver, blockposition, itemstack, UniformInt.of(1, 5)); diff --git a/nms-patches/net/minecraft/world/level/block/BlockRespawnAnchor.patch b/nms-patches/net/minecraft/world/level/block/BlockRespawnAnchor.patch index 3dc1bbb4..df981b17 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockRespawnAnchor.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockRespawnAnchor.patch @@ -12,7 +12,7 @@ @@ -127,15 +127,16 @@ } - private void explode(IBlockData iblockdata, World world, final BlockPosition blockposition) { + private void explode(IBlockData iblockdata, World world, final BlockPos blockposition) { + org.bukkit.block.BlockState blockState = org.bukkit.craftbukkit.block.CraftBlock.at(world, blockposition).getState(); // CraftBukkit - capture BlockState before remove block world.removeBlock(blockposition, false); - Stream stream = EnumDirection.EnumDirectionLimit.HORIZONTAL.stream(); @@ -26,7 +26,7 @@ - ExplosionDamageCalculator explosiondamagecalculator = new ExplosionDamageCalculator(this) { + ExplosionDamageCalculator explosiondamagecalculator = new ExplosionDamageCalculator() { // CraftBukkit - decompile error @Override - public Optional getBlockExplosionResistance(Explosion explosion, IBlockAccess iblockaccess, BlockPosition blockposition1, IBlockData iblockdata1, Fluid fluid) { + public Optional getBlockExplosionResistance(Explosion explosion, IBlockAccess iblockaccess, BlockPos blockposition1, IBlockData iblockdata1, Fluid fluid) { return blockposition1.equals(blockposition) && flag1 ? Optional.of(Blocks.WATER.getExplosionResistance()) : super.getBlockExplosionResistance(explosion, iblockaccess, blockposition1, iblockdata1, fluid); @@ -143,7 +144,7 @@ }; diff --git a/nms-patches/net/minecraft/world/level/block/BlockSnow.patch b/nms-patches/net/minecraft/world/level/block/BlockSnow.patch index 17758fcc..343fa058 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockSnow.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockSnow.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/block/BlockSnow.java @@ -99,6 +99,11 @@ @Override - protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, RandomSource randomsource) { + protected void randomTick(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, RandomSource randomsource) { if (worldserver.getBrightness(EnumSkyBlock.BLOCK, blockposition) > 11) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(worldserver, blockposition, Blocks.AIR.defaultBlockState()).isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/block/BlockSoil.patch b/nms-patches/net/minecraft/world/level/block/BlockSoil.patch index 4f6c91e2..22939537 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockSoil.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockSoil.patch @@ -29,7 +29,7 @@ } @Override - public void fallOn(World world, IBlockData iblockdata, BlockPosition blockposition, Entity entity, float f) { + public void fallOn(World world, IBlockData iblockdata, BlockPos blockposition, Entity entity, float f) { + super.fallOn(world, iblockdata, blockposition, entity, f); // CraftBukkit - moved here as game rules / events shouldn't affect fall damage. if (world instanceof WorldServer worldserver) { if (world.random.nextFloat() < f - 0.5F && entity instanceof EntityLiving && (entity instanceof EntityHuman || worldserver.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING)) && entity.getBbWidth() * entity.getBbWidth() * entity.getBbHeight() > 0.512F) { @@ -58,7 +58,7 @@ + // super.fallOn(world, iblockdata, blockposition, entity, f); // CraftBukkit - moved up } - public static void turnToDirt(@Nullable Entity entity, IBlockData iblockdata, World world, BlockPosition blockposition) { + public static void turnToDirt(@Nullable Entity entity, IBlockData iblockdata, World world, BlockPos blockposition) { + // CraftBukkit start + if (CraftEventFactory.callBlockFadeEvent(world, blockposition, Blocks.DIRT.defaultBlockState()).isCancelled()) { + return; diff --git a/nms-patches/net/minecraft/world/level/block/BlockSponge.patch b/nms-patches/net/minecraft/world/level/block/BlockSponge.patch index cb7d20fd..7823ce59 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockSponge.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockSponge.patch @@ -17,10 +17,10 @@ @@ -53,7 +60,8 @@ } - private boolean removeWaterBreadthFirstSearch(World world, BlockPosition blockposition) { -- return BlockPosition.breadthFirstTraversal(blockposition, 6, 65, (blockposition1, consumer) -> { + private boolean removeWaterBreadthFirstSearch(World world, BlockPos blockposition) { +- return BlockPos.breadthFirstTraversal(blockposition, 6, 65, (blockposition1, consumer) -> { + BlockStateListPopulator blockList = new BlockStateListPopulator(world); // CraftBukkit - Use BlockStateListPopulator -+ BlockPosition.breadthFirstTraversal(blockposition, 6, 65, (blockposition1, consumer) -> { ++ BlockPos.breadthFirstTraversal(blockposition, 6, 65, (blockposition1, consumer) -> { EnumDirection[] aenumdirection = BlockSponge.ALL_DIRECTIONS; int i = aenumdirection.length; @@ -84,7 +84,7 @@ + } + + for (CraftBlockState block : blocks) { -+ BlockPosition blockposition1 = block.getPosition(); ++ BlockPos blockposition1 = block.getPosition(); + IBlockData iblockdata = world.getBlockState(blockposition1); + Fluid fluid = world.getFluidState(blockposition1); + diff --git a/nms-patches/net/minecraft/world/level/block/BlockStem.patch b/nms-patches/net/minecraft/world/level/block/BlockStem.patch index d1f2af04..3efd62dd 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockStem.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockStem.patch @@ -17,7 +17,7 @@ + CraftEventFactory.handleBlockGrowEvent(worldserver, blockposition, iblockdata, 2); // CraftBukkit } else { EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.getRandomDirection(randomsource); - BlockPosition blockposition1 = blockposition.relative(enumdirection); + BlockPos blockposition1 = blockposition.relative(enumdirection); @@ -91,7 +93,11 @@ Optional optional1 = iregistry.getOptional(this.attachedStem); diff --git a/nms-patches/net/minecraft/world/level/block/BlockTNT.patch b/nms-patches/net/minecraft/world/level/block/BlockTNT.patch index 9c744572..e6bc2b2f 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockTNT.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockTNT.patch @@ -14,7 +14,7 @@ public static final MapCodec CODEC = simpleCodec(BlockTNT::new); @@ -47,7 +52,7 @@ @Override - protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { + protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag) { if (!iblockdata1.is(iblockdata.getBlock())) { - if (world.hasNeighborSignal(blockposition)) { + if (world.hasNeighborSignal(blockposition) && CraftEventFactory.callTNTPrimeEvent(world, blockposition, PrimeCause.REDSTONE, null, null)) { // CraftBukkit - TNTPrimeEvent @@ -24,7 +24,7 @@ @@ -57,7 +62,7 @@ @Override - protected void neighborChanged(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, @Nullable Orientation orientation, boolean flag) { + protected void neighborChanged(IBlockData iblockdata, World world, BlockPos blockposition, Block block, @Nullable Orientation orientation, boolean flag) { - if (world.hasNeighborSignal(blockposition)) { + if (world.hasNeighborSignal(blockposition) && CraftEventFactory.callTNTPrimeEvent(world, blockposition, PrimeCause.REDSTONE, null, null)) { // CraftBukkit - TNTPrimeEvent explode(world, blockposition); @@ -33,7 +33,7 @@ @@ -66,7 +71,7 @@ @Override - public IBlockData playerWillDestroy(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + public IBlockData playerWillDestroy(World world, BlockPos blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - if (!world.isClientSide() && !entityhuman.isCreative() && (Boolean) iblockdata.getValue(BlockTNT.UNSTABLE)) { + if (!world.isClientSide() && !entityhuman.isCreative() && (Boolean) iblockdata.getValue(BlockTNT.UNSTABLE) && CraftEventFactory.callTNTPrimeEvent(world, blockposition, PrimeCause.BLOCK_BREAK, entityhuman, null)) { // CraftBukkit - TNTPrimeEvent explode(world, blockposition); diff --git a/nms-patches/net/minecraft/world/level/block/BlockTallPlant.patch b/nms-patches/net/minecraft/world/level/block/BlockTallPlant.patch index af55991d..c6be3840 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockTallPlant.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockTallPlant.patch @@ -3,7 +3,7 @@ @@ -103,6 +103,11 @@ } - protected static void preventDropFromBottomPart(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + protected static void preventDropFromBottomPart(World world, BlockPos blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPhysicsEvent(world, blockposition).isCancelled()) { + return; diff --git a/nms-patches/net/minecraft/world/level/block/BlockTurtleEgg.patch b/nms-patches/net/minecraft/world/level/block/BlockTurtleEgg.patch index f9aedfa8..ac9eb96d 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockTurtleEgg.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockTurtleEgg.patch @@ -14,7 +14,7 @@ public static final MapCodec CODEC = simpleCodec(BlockTurtleEgg::new); @@ -74,6 +80,19 @@ - private void destroyEgg(World world, IBlockData iblockdata, BlockPosition blockposition, Entity entity, int i) { + private void destroyEgg(World world, IBlockData iblockdata, BlockPos blockposition, Entity entity, int i) { if (iblockdata.is(Blocks.TURTLE_EGG) && world instanceof WorldServer worldserver) { if (this.canDestroyEgg(worldserver, entity) && world.random.nextInt(i) == 0) { + // CraftBukkit start - Step on eggs diff --git a/nms-patches/net/minecraft/world/level/block/BlockVine.patch b/nms-patches/net/minecraft/world/level/block/BlockVine.patch index 7ebaef3b..44b21f07 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockVine.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockVine.patch @@ -10,11 +10,11 @@ public static final MapCodec CODEC = simpleCodec(BlockVine::new); @@ -203,30 +205,34 @@ - BlockPosition blockposition3 = blockposition2.relative(enumdirection1); - BlockPosition blockposition4 = blockposition2.relative(enumdirection2); + BlockPos blockposition3 = blockposition2.relative(enumdirection1); + BlockPos blockposition4 = blockposition2.relative(enumdirection2); + // CraftBukkit start - Call BlockSpreadEvent -+ BlockPosition source = blockposition; ++ BlockPos source = blockposition; + if (flag && isAcceptableNeighbour(worldserver, blockposition3, enumdirection1)) { - worldserver.setBlock(blockposition2, (IBlockData) this.defaultBlockState().setValue(getPropertyForFace(enumdirection1), true), 2); diff --git a/nms-patches/net/minecraft/world/level/block/BlockWaterLily.patch b/nms-patches/net/minecraft/world/level/block/BlockWaterLily.patch index 6423b8bb..3f686589 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockWaterLily.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockWaterLily.patch @@ -12,7 +12,7 @@ public static final MapCodec CODEC = simpleCodec(BlockWaterLily::new); @@ -32,6 +36,11 @@ - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { super.entityInside(iblockdata, world, blockposition, entity); if (world instanceof WorldServer && entity instanceof AbstractBoat) { + // CraftBukkit start @@ -20,6 +20,6 @@ + return; + } + // CraftBukkit end - world.destroyBlock(new BlockPosition(blockposition), true, entity); + world.destroyBlock(new BlockPos(blockposition), true, entity); } diff --git a/nms-patches/net/minecraft/world/level/block/BlockWitherSkull.patch b/nms-patches/net/minecraft/world/level/block/BlockWitherSkull.patch index 099a259f..208a4362 100644 --- a/nms-patches/net/minecraft/world/level/block/BlockWitherSkull.patch +++ b/nms-patches/net/minecraft/world/level/block/BlockWitherSkull.patch @@ -14,7 +14,7 @@ @@ -58,6 +62,7 @@ } - public static void checkSpawn(World world, BlockPosition blockposition, TileEntitySkull tileentityskull) { + public static void checkSpawn(World world, BlockPos blockposition, TileEntitySkull tileentityskull) { + if (world.captureBlockStates) return; // CraftBukkit if (!world.isClientSide) { IBlockData iblockdata = tileentityskull.getBlockState(); @@ -25,7 +25,7 @@ if (entitywither != null) { - BlockPumpkinCarved.clearPatternBlocks(world, shapedetector_shapedetectorcollection); + // BlockPumpkinCarved.clearPatternBlocks(world, shapedetector_shapedetectorcollection); // CraftBukkit - move down - BlockPosition blockposition1 = shapedetector_shapedetectorcollection.getBlock(1, 2, 0).getPos(); + BlockPos blockposition1 = shapedetector_shapedetectorcollection.getBlock(1, 2, 0).getPos(); entitywither.moveTo((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.55D, (double) blockposition1.getZ() + 0.5D, shapedetector_shapedetectorcollection.getForwards().getAxis() == EnumDirection.EnumAxis.X ? 0.0F : 90.0F, 0.0F); entitywither.yBodyRot = shapedetector_shapedetectorcollection.getForwards().getAxis() == EnumDirection.EnumAxis.X ? 0.0F : 90.0F; diff --git a/nms-patches/net/minecraft/world/level/block/CaveVines.patch b/nms-patches/net/minecraft/world/level/block/CaveVines.patch index 1184f18f..07a04bc1 100644 --- a/nms-patches/net/minecraft/world/level/block/CaveVines.patch +++ b/nms-patches/net/minecraft/world/level/block/CaveVines.patch @@ -16,7 +16,7 @@ VoxelShape SHAPE = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 16.0D, 15.0D); @@ -26,7 +33,24 @@ - static EnumInteractionResult use(@Nullable Entity entity, IBlockData iblockdata, World world, BlockPosition blockposition) { + static EnumInteractionResult use(@Nullable Entity entity, IBlockData iblockdata, World world, BlockPos blockposition) { if ((Boolean) iblockdata.getValue(CaveVines.BERRIES)) { - Block.popResource(world, blockposition, new ItemStack(Items.GLOW_BERRIES, 1)); + // CraftBukkit start diff --git a/nms-patches/net/minecraft/world/level/block/DropExperienceBlock.patch b/nms-patches/net/minecraft/world/level/block/DropExperienceBlock.patch index 6695cab7..b8d5cfc6 100644 --- a/nms-patches/net/minecraft/world/level/block/DropExperienceBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/DropExperienceBlock.patch @@ -2,13 +2,13 @@ +++ b/net/minecraft/world/level/block/DropExperienceBlock.java @@ -31,9 +31,16 @@ @Override - protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { + protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack, flag); + // CraftBukkit start - Delegate to getExpDrop + } + + @Override -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { if (flag) { - this.tryDropExperience(worldserver, blockposition, itemstack, this.xpRange); + return this.tryDropExperience(worldserver, blockposition, itemstack, this.xpRange); diff --git a/nms-patches/net/minecraft/world/level/block/LayeredCauldronBlock.patch b/nms-patches/net/minecraft/world/level/block/LayeredCauldronBlock.patch index f2eebd06..a6114058 100644 --- a/nms-patches/net/minecraft/world/level/block/LayeredCauldronBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/LayeredCauldronBlock.patch @@ -14,7 +14,7 @@ public static final MapCodec CODEC = RecordCodecBuilder.mapCodec((instance) -> { @@ -64,39 +70,67 @@ - protected void entityInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { + protected void entityInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if (world instanceof WorldServer worldserver) { if (entity.isOnFire() && this.isEntityInsideContent(iblockdata, blockposition, entity)) { - entity.clearFire(); @@ -32,9 +32,9 @@ } -- private void handleEntityOnFireInside(IBlockData iblockdata, World world, BlockPosition blockposition) { +- private void handleEntityOnFireInside(IBlockData iblockdata, World world, BlockPos blockposition) { + // CraftBukkit start -+ private boolean handleEntityOnFireInside(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { ++ private boolean handleEntityOnFireInside(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity) { if (this.precipitationType == BiomeBase.Precipitation.SNOW) { - lowerFillLevel((IBlockData) Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL, (Integer) iblockdata.getValue(LayeredCauldronBlock.LEVEL)), world, blockposition); + return lowerFillLevel((IBlockData) Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL, (Integer) iblockdata.getValue(LayeredCauldronBlock.LEVEL)), world, blockposition, entity, CauldronLevelChangeEvent.ChangeReason.EXTINGUISH); @@ -46,12 +46,12 @@ } - public static void lowerFillLevel(IBlockData iblockdata, World world, BlockPosition blockposition) { + public static void lowerFillLevel(IBlockData iblockdata, World world, BlockPos blockposition) { + // CraftBukkit start + lowerFillLevel(iblockdata, world, blockposition, null, CauldronLevelChangeEvent.ChangeReason.UNKNOWN); + } + -+ public static boolean lowerFillLevel(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity, CauldronLevelChangeEvent.ChangeReason reason) { ++ public static boolean lowerFillLevel(IBlockData iblockdata, World world, BlockPos blockposition, Entity entity, CauldronLevelChangeEvent.ChangeReason reason) { int i = (Integer) iblockdata.getValue(LayeredCauldronBlock.LEVEL) - 1; IBlockData iblockdata1 = i == 0 ? Blocks.CAULDRON.defaultBlockState() : (IBlockData) iblockdata.setValue(LayeredCauldronBlock.LEVEL, i); @@ -61,7 +61,7 @@ } + // CraftBukkit start -+ public static boolean changeLevel(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData newBlock, Entity entity, CauldronLevelChangeEvent.ChangeReason reason) { ++ public static boolean changeLevel(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData newBlock, Entity entity, CauldronLevelChangeEvent.ChangeReason reason) { + CraftBlockState newState = CraftBlockStates.getBlockState(world, blockposition); + newState.setData(newBlock); + @@ -80,7 +80,7 @@ + // CraftBukkit end + @Override - public void handlePrecipitation(IBlockData iblockdata, World world, BlockPosition blockposition, BiomeBase.Precipitation biomebase_precipitation) { + public void handlePrecipitation(IBlockData iblockdata, World world, BlockPos blockposition, BiomeBase.Precipitation biomebase_precipitation) { if (BlockCauldron.shouldHandlePrecipitation(world, biomebase_precipitation) && (Integer) iblockdata.getValue(LayeredCauldronBlock.LEVEL) != 3 && biomebase_precipitation == this.precipitationType) { IBlockData iblockdata1 = (IBlockData) iblockdata.cycle(LayeredCauldronBlock.LEVEL); diff --git a/nms-patches/net/minecraft/world/level/block/LightningRodBlock.patch b/nms-patches/net/minecraft/world/level/block/LightningRodBlock.patch index 8a36902c..b6991bbc 100644 --- a/nms-patches/net/minecraft/world/level/block/LightningRodBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/LightningRodBlock.patch @@ -15,7 +15,7 @@ @@ -76,6 +81,18 @@ } - public void onLightningStrike(IBlockData iblockdata, World world, BlockPosition blockposition) { + public void onLightningStrike(IBlockData iblockdata, World world, BlockPos blockposition) { + // CraftBukkit start + boolean powered = iblockdata.getValue(LightningRodBlock.POWERED); + int old = (powered) ? 15 : 0; diff --git a/nms-patches/net/minecraft/world/level/block/MultifaceSpreader.patch b/nms-patches/net/minecraft/world/level/block/MultifaceSpreader.patch index 216e14a2..d20ed01d 100644 --- a/nms-patches/net/minecraft/world/level/block/MultifaceSpreader.patch +++ b/nms-patches/net/minecraft/world/level/block/MultifaceSpreader.patch @@ -12,32 +12,32 @@ @@ -174,19 +174,19 @@ SAME_POSITION { @Override - public MultifaceSpreader.c getSpreadPos(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1) { + public MultifaceSpreader.c getSpreadPos(BlockPos blockposition, EnumDirection enumdirection, EnumDirection enumdirection1) { - return new MultifaceSpreader.c(blockposition, enumdirection); + return new MultifaceSpreader.c(blockposition, enumdirection, blockposition); // CraftBukkit } }, SAME_PLANE { @Override - public MultifaceSpreader.c getSpreadPos(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1) { + public MultifaceSpreader.c getSpreadPos(BlockPos blockposition, EnumDirection enumdirection, EnumDirection enumdirection1) { - return new MultifaceSpreader.c(blockposition.relative(enumdirection), enumdirection1); + return new MultifaceSpreader.c(blockposition.relative(enumdirection), enumdirection1, blockposition); // CraftBukkit } }, WRAP_AROUND { @Override - public MultifaceSpreader.c getSpreadPos(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1) { + public MultifaceSpreader.c getSpreadPos(BlockPos blockposition, EnumDirection enumdirection, EnumDirection enumdirection1) { - return new MultifaceSpreader.c(blockposition.relative(enumdirection).relative(enumdirection1), enumdirection.getOpposite()); + return new MultifaceSpreader.c(blockposition.relative(enumdirection).relative(enumdirection1), enumdirection.getOpposite(), blockposition); // CraftBukkit } }; @@ -195,7 +195,7 @@ - public abstract MultifaceSpreader.c getSpreadPos(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1); + public abstract MultifaceSpreader.c getSpreadPos(BlockPos blockposition, EnumDirection enumdirection, EnumDirection enumdirection1); } -- public static record c(BlockPosition pos, EnumDirection face) { -+ public static record c(BlockPosition pos, EnumDirection face, BlockPosition source) { // CraftBukkit +- public static record c(BlockPos pos, EnumDirection face) { ++ public static record c(BlockPos pos, EnumDirection face, BlockPos source) { // CraftBukkit } } diff --git a/nms-patches/net/minecraft/world/level/block/PointedDripstoneBlock.patch b/nms-patches/net/minecraft/world/level/block/PointedDripstoneBlock.patch index 0ce0a173..f2b69bb7 100644 --- a/nms-patches/net/minecraft/world/level/block/PointedDripstoneBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/PointedDripstoneBlock.patch @@ -14,7 +14,7 @@ } @@ -146,7 +151,7 @@ @Override - public void fallOn(World world, IBlockData iblockdata, BlockPosition blockposition, Entity entity, float f) { + public void fallOn(World world, IBlockData iblockdata, BlockPos blockposition, Entity entity, float f) { if (iblockdata.getValue(PointedDripstoneBlock.TIP_DIRECTION) == EnumDirection.UP && iblockdata.getValue(PointedDripstoneBlock.THICKNESS) == DripstoneThickness.TIP) { - entity.causeFallDamage(f + 2.0F, 2.0F, world.damageSources().stalagmite()); + entity.causeFallDamage(f + 2.0F, 2.0F, world.damageSources().stalagmite().directBlock(world, blockposition)); // CraftBukkit @@ -31,15 +31,15 @@ } -- private static void createDripstone(GeneratorAccess generatoraccess, BlockPosition blockposition, EnumDirection enumdirection, DripstoneThickness dripstonethickness) { -+ private static void createDripstone(GeneratorAccess generatoraccess, BlockPosition blockposition, EnumDirection enumdirection, DripstoneThickness dripstonethickness, BlockPosition source) { // CraftBukkit +- private static void createDripstone(GeneratorAccess generatoraccess, BlockPos blockposition, EnumDirection enumdirection, DripstoneThickness dripstonethickness) { ++ private static void createDripstone(GeneratorAccess generatoraccess, BlockPos blockposition, EnumDirection enumdirection, DripstoneThickness dripstonethickness, BlockPos source) { // CraftBukkit IBlockData iblockdata = (IBlockData) ((IBlockData) ((IBlockData) Blocks.POINTED_DRIPSTONE.defaultBlockState().setValue(PointedDripstoneBlock.TIP_DIRECTION, enumdirection)).setValue(PointedDripstoneBlock.THICKNESS, dripstonethickness)).setValue(PointedDripstoneBlock.WATERLOGGED, generatoraccess.getFluidState(blockposition).getType() == FluidTypes.WATER); - generatoraccess.setBlock(blockposition, iblockdata, 3); + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(generatoraccess, source, blockposition, iblockdata, 3); // CraftBukkit } - private static void createMergedTips(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { + private static void createMergedTips(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPos blockposition) { @@ -414,8 +419,8 @@ blockposition1 = blockposition.below(); } @@ -50,10 +50,10 @@ + createDripstone(generatoraccess, blockposition1, EnumDirection.UP, DripstoneThickness.TIP_MERGE, blockposition); // CraftBukkit } - public static void spawnDripParticle(World world, BlockPosition blockposition, IBlockData iblockdata) { + public static void spawnDripParticle(World world, BlockPos blockposition, IBlockData iblockdata) { @@ -448,7 +453,7 @@ - return (BlockPosition) findBlockVertical(generatoraccess, blockposition, enumdirection.getAxisDirection(), bipredicate, (iblockdata1) -> { + return (BlockPos) findBlockVertical(generatoraccess, blockposition, enumdirection.getAxisDirection(), bipredicate, (iblockdata1) -> { return isTip(iblockdata1, flag); - }, i).orElse((Object) null); + }, i).orElse(null); // CraftBukkit - decompile error @@ -64,8 +64,8 @@ return canDripThrough(world, blockposition1, iblockdata); }; -- return (BlockPosition) findBlockVertical(world, blockposition, EnumDirection.DOWN.getAxisDirection(), bipredicate, predicate, 11).orElse((Object) null); -+ return (BlockPosition) findBlockVertical(world, blockposition, EnumDirection.DOWN.getAxisDirection(), bipredicate, predicate, 11).orElse(null); // CraftBukkit - decompile error +- return (BlockPos) findBlockVertical(world, blockposition, EnumDirection.DOWN.getAxisDirection(), bipredicate, predicate, 11).orElse((Object) null); ++ return (BlockPos) findBlockVertical(world, blockposition, EnumDirection.DOWN.getAxisDirection(), bipredicate, predicate, 11).orElse(null); // CraftBukkit - decompile error } @Nullable @@ -73,8 +73,8 @@ return canDripThrough(world, blockposition1, iblockdata); }; -- return (BlockPosition) findBlockVertical(world, blockposition, EnumDirection.UP.getAxisDirection(), bipredicate, PointedDripstoneBlock::canDrip, 11).orElse((Object) null); -+ return (BlockPosition) findBlockVertical(world, blockposition, EnumDirection.UP.getAxisDirection(), bipredicate, PointedDripstoneBlock::canDrip, 11).orElse(null); // CraftBukkit - decompile error +- return (BlockPos) findBlockVertical(world, blockposition, EnumDirection.UP.getAxisDirection(), bipredicate, PointedDripstoneBlock::canDrip, 11).orElse((Object) null); ++ return (BlockPos) findBlockVertical(world, blockposition, EnumDirection.UP.getAxisDirection(), bipredicate, PointedDripstoneBlock::canDrip, 11).orElse(null); // CraftBukkit - decompile error } - public static FluidType getCauldronFillFluidType(WorldServer worldserver, BlockPosition blockposition) { + public static FluidType getCauldronFillFluidType(WorldServer worldserver, BlockPos blockposition) { diff --git a/nms-patches/net/minecraft/world/level/block/RootedDirtBlock.patch b/nms-patches/net/minecraft/world/level/block/RootedDirtBlock.patch index bd12ce85..1ea79c6c 100644 --- a/nms-patches/net/minecraft/world/level/block/RootedDirtBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/RootedDirtBlock.patch @@ -3,7 +3,7 @@ @@ -34,7 +34,7 @@ @Override - public void performBonemeal(WorldServer worldserver, RandomSource randomsource, BlockPosition blockposition, IBlockData iblockdata) { + public void performBonemeal(WorldServer worldserver, RandomSource randomsource, BlockPos blockposition, IBlockData iblockdata) { - worldserver.setBlockAndUpdate(blockposition.below(), Blocks.HANGING_ROOTS.defaultBlockState()); + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(worldserver, blockposition, blockposition.below(), Blocks.HANGING_ROOTS.defaultBlockState()); // CraftBukkit } diff --git a/nms-patches/net/minecraft/world/level/block/SculkBlock.patch b/nms-patches/net/minecraft/world/level/block/SculkBlock.patch index e6fd17ee..7b58023f 100644 --- a/nms-patches/net/minecraft/world/level/block/SculkBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/SculkBlock.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/block/SculkBlock.java +++ b/net/minecraft/world/level/block/SculkBlock.java @@ -43,8 +43,11 @@ - BlockPosition blockposition2 = blockposition1.above(); + BlockPos blockposition2 = blockposition1.above(); IBlockData iblockdata = this.getRandomGrowthState(generatoraccess, blockposition2, randomsource, sculkspreader.isWorldGeneration()); - generatoraccess.setBlock(blockposition2, iblockdata, 3); diff --git a/nms-patches/net/minecraft/world/level/block/SculkCatalystBlock.patch b/nms-patches/net/minecraft/world/level/block/SculkCatalystBlock.patch index adff3a8d..624c1be6 100644 --- a/nms-patches/net/minecraft/world/level/block/SculkCatalystBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/SculkCatalystBlock.patch @@ -2,13 +2,13 @@ +++ b/net/minecraft/world/level/block/SculkCatalystBlock.java @@ -68,9 +68,16 @@ @Override - protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { + protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack, flag); + // CraftBukkit start - Delegate to getExpDrop + } + + @Override -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { if (flag) { - this.tryDropExperience(worldserver, blockposition, itemstack, this.xpRange); + return this.tryDropExperience(worldserver, blockposition, itemstack, this.xpRange); diff --git a/nms-patches/net/minecraft/world/level/block/SculkSensorBlock.patch b/nms-patches/net/minecraft/world/level/block/SculkSensorBlock.patch index d66c4e3e..9d667b43 100644 --- a/nms-patches/net/minecraft/world/level/block/SculkSensorBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/SculkSensorBlock.patch @@ -14,7 +14,7 @@ public static final MapCodec CODEC = simpleCodec(SculkSensorBlock::new); @@ -104,6 +109,18 @@ @Override - public void stepOn(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + public void stepOn(World world, BlockPos blockposition, IBlockData iblockdata, Entity entity) { if (!world.isClientSide() && canActivate(iblockdata) && entity.getType() != EntityTypes.WARDEN) { + // CraftBukkit start + org.bukkit.event.Cancellable cancellable; @@ -34,7 +34,7 @@ @@ -207,6 +224,15 @@ } - public static void deactivate(World world, BlockPosition blockposition, IBlockData iblockdata) { + public static void deactivate(World world, BlockPos blockposition, IBlockData iblockdata) { + // CraftBukkit start + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(CraftBlock.at(world, blockposition), iblockdata.getValue(SculkSensorBlock.POWER), 0); + world.getCraftServer().getPluginManager().callEvent(eventRedstone); @@ -50,7 +50,7 @@ @@ -218,6 +244,15 @@ } - public void activate(@Nullable Entity entity, World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + public void activate(@Nullable Entity entity, World world, BlockPos blockposition, IBlockData iblockdata, int i, int j) { + // CraftBukkit start + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(CraftBlock.at(world, blockposition), iblockdata.getValue(SculkSensorBlock.POWER), i); + world.getCraftServer().getPluginManager().callEvent(eventRedstone); @@ -65,13 +65,13 @@ updateNeighbours(world, blockposition, iblockdata); @@ -298,9 +333,16 @@ @Override - protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { + protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack, flag); + // CraftBukkit start - Delegate to getExpDrop + } + + @Override -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { if (flag) { - this.tryDropExperience(worldserver, blockposition, itemstack, ConstantInt.of(5)); + return this.tryDropExperience(worldserver, blockposition, itemstack, ConstantInt.of(5)); diff --git a/nms-patches/net/minecraft/world/level/block/SculkShriekerBlock.patch b/nms-patches/net/minecraft/world/level/block/SculkShriekerBlock.patch index 41ec5aee..2cb5d903 100644 --- a/nms-patches/net/minecraft/world/level/block/SculkShriekerBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/SculkShriekerBlock.patch @@ -10,13 +10,13 @@ }); @@ -145,10 +146,17 @@ @Override - protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { + protected void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack, flag); + // CraftBukkit start - Delegate to getExpDrop + } + + @Override -+ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack, boolean flag) { ++ public int getExpDrop(IBlockData iblockdata, WorldServer worldserver, BlockPos blockposition, ItemStack itemstack, boolean flag) { if (flag) { - this.tryDropExperience(worldserver, blockposition, itemstack, ConstantInt.of(5)); + return this.tryDropExperience(worldserver, blockposition, itemstack, ConstantInt.of(5)); diff --git a/nms-patches/net/minecraft/world/level/block/SculkSpreader.patch b/nms-patches/net/minecraft/world/level/block/SculkSpreader.patch index 0a02154d..55b8f99e 100644 --- a/nms-patches/net/minecraft/world/level/block/SculkSpreader.patch +++ b/nms-patches/net/minecraft/world/level/block/SculkSpreader.patch @@ -69,4 +69,4 @@ + this.facings = (Set) optional.orElse(null); // CraftBukkit - decompile error } - public a(BlockPosition blockposition, int i) { + public a(BlockPos blockposition, int i) { diff --git a/nms-patches/net/minecraft/world/level/block/SculkVeinBlock.patch b/nms-patches/net/minecraft/world/level/block/SculkVeinBlock.patch index f9aa1f54..ad31ba08 100644 --- a/nms-patches/net/minecraft/world/level/block/SculkVeinBlock.patch +++ b/nms-patches/net/minecraft/world/level/block/SculkVeinBlock.patch @@ -3,14 +3,14 @@ @@ -110,10 +110,11 @@ @Override - public int attemptUseCharge(SculkSpreader.a sculkspreader_a, GeneratorAccess generatoraccess, BlockPosition blockposition, RandomSource randomsource, SculkSpreader sculkspreader, boolean flag) { + public int attemptUseCharge(SculkSpreader.a sculkspreader_a, GeneratorAccess generatoraccess, BlockPos blockposition, RandomSource randomsource, SculkSpreader sculkspreader, boolean flag) { - return flag && this.attemptPlaceSculk(sculkspreader, generatoraccess, sculkspreader_a.getPos(), randomsource) ? sculkspreader_a.getCharge() - 1 : (randomsource.nextInt(sculkspreader.chargeDecayRate()) == 0 ? MathHelper.floor((float) sculkspreader_a.getCharge() * 0.5F) : sculkspreader_a.getCharge()); + // CraftBukkit - add source block + return flag && this.attemptPlaceSculk(sculkspreader, generatoraccess, sculkspreader_a.getPos(), randomsource, blockposition) ? sculkspreader_a.getCharge() - 1 : (randomsource.nextInt(sculkspreader.chargeDecayRate()) == 0 ? MathHelper.floor((float) sculkspreader_a.getCharge() * 0.5F) : sculkspreader_a.getCharge()); } -- private boolean attemptPlaceSculk(SculkSpreader sculkspreader, GeneratorAccess generatoraccess, BlockPosition blockposition, RandomSource randomsource) { -+ private boolean attemptPlaceSculk(SculkSpreader sculkspreader, GeneratorAccess generatoraccess, BlockPosition blockposition, RandomSource randomsource, BlockPosition sourceBlock) { // CraftBukkit +- private boolean attemptPlaceSculk(SculkSpreader sculkspreader, GeneratorAccess generatoraccess, BlockPos blockposition, RandomSource randomsource) { ++ private boolean attemptPlaceSculk(SculkSpreader sculkspreader, GeneratorAccess generatoraccess, BlockPos blockposition, RandomSource randomsource, BlockPos sourceBlock) { // CraftBukkit IBlockData iblockdata = generatoraccess.getBlockState(blockposition); TagKey tagkey = sculkspreader.replaceableBlocks(); Iterator iterator = EnumDirection.allShuffled(randomsource).iterator(); diff --git a/nms-patches/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.patch b/nms-patches/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.patch index 449bad12..ad3cfb3f 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/ChiseledBookShelfBlockEntity.patch @@ -53,7 +53,7 @@ + } + // CraftBukkit end - public ChiseledBookShelfBlockEntity(BlockPosition blockposition, IBlockData iblockdata) { + public ChiseledBookShelfBlockEntity(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.CHISELED_BOOKSHELF, blockposition, iblockdata); @@ -100,7 +142,7 @@ diff --git a/nms-patches/net/minecraft/world/level/block/entity/ContainerOpenersCounter.patch b/nms-patches/net/minecraft/world/level/block/entity/ContainerOpenersCounter.patch index 87d8f1a7..6b2890b2 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/ContainerOpenersCounter.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/ContainerOpenersCounter.patch @@ -10,25 +10,25 @@ @@ -26,11 +27,36 @@ - protected abstract void openerCountChanged(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j); + protected abstract void openerCountChanged(World world, BlockPos blockposition, IBlockData iblockdata, int i, int j); + // CraftBukkit start -+ public void onAPIOpen(World world, BlockPosition blockposition, IBlockData iblockdata) { ++ public void onAPIOpen(World world, BlockPos blockposition, IBlockData iblockdata) { + onOpen(world, blockposition, iblockdata); + } + -+ public void onAPIClose(World world, BlockPosition blockposition, IBlockData iblockdata) { ++ public void onAPIClose(World world, BlockPos blockposition, IBlockData iblockdata) { + onClose(world, blockposition, iblockdata); + } + -+ public void openerAPICountChanged(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { ++ public void openerAPICountChanged(World world, BlockPos blockposition, IBlockData iblockdata, int i, int j) { + openerCountChanged(world, blockposition, iblockdata, i, j); + } + // CraftBukkit end + protected abstract boolean isOwnContainer(EntityHuman entityhuman); - public void incrementOpeners(EntityHuman entityhuman, World world, BlockPosition blockposition, IBlockData iblockdata) { + public void incrementOpeners(EntityHuman entityhuman, World world, BlockPos blockposition, IBlockData iblockdata) { + int oldPower = Math.max(0, Math.min(15, this.openCount)); // CraftBukkit - Get power before new viewer is added int i = this.openCount++; @@ -48,7 +48,7 @@ @@ -42,8 +68,19 @@ } - public void decrementOpeners(EntityHuman entityhuman, World world, BlockPosition blockposition, IBlockData iblockdata) { + public void decrementOpeners(EntityHuman entityhuman, World world, BlockPos blockposition, IBlockData iblockdata) { + int oldPower = Math.max(0, Math.min(15, this.openCount)); // CraftBukkit - Get power before new viewer is added int i = this.openCount--; diff --git a/nms-patches/net/minecraft/world/level/block/entity/CrafterBlockEntity.patch b/nms-patches/net/minecraft/world/level/block/entity/CrafterBlockEntity.patch index 90eb9c7d..31187f4c 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/CrafterBlockEntity.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/CrafterBlockEntity.patch @@ -58,7 +58,7 @@ + } + // CraftBukkit end - public CrafterBlockEntity(BlockPosition blockposition, IBlockData iblockdata) { + public CrafterBlockEntity(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.CRAFTER, blockposition, iblockdata); this.items = NonNullList.withSize(9, ItemStack.EMPTY); this.craftingTicksRemaining = 0; diff --git a/nms-patches/net/minecraft/world/level/block/entity/SculkCatalystBlockEntity.patch b/nms-patches/net/minecraft/world/level/block/entity/SculkCatalystBlockEntity.patch index 5186a7c5..304a1f69 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/SculkCatalystBlockEntity.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/SculkCatalystBlockEntity.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/block/entity/SculkCatalystBlockEntity.java +++ b/net/minecraft/world/level/block/entity/SculkCatalystBlockEntity.java @@ -35,10 +35,13 @@ - public SculkCatalystBlockEntity(BlockPosition blockposition, IBlockData iblockdata) { + public SculkCatalystBlockEntity(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.SCULK_CATALYST, blockposition, iblockdata); - this.catalystListener = new SculkCatalystBlockEntity.CatalystListener(iblockdata, new BlockPositionSource(blockposition)); + this.catalystListener = new SculkCatalystBlockEntity.CatalystListener(iblockdata, new BlockPosSource(blockposition)); + catalystListener.level = level; // CraftBukkit } - public static void serverTick(World world, BlockPosition blockposition, IBlockData iblockdata, SculkCatalystBlockEntity sculkcatalystblockentity) { -+ org.bukkit.craftbukkit.event.CraftEventFactory.sourceBlockOverride = sculkcatalystblockentity.getBlockPos(); // CraftBukkit - SPIGOT-7068: Add source block override, not the most elegant way but better than passing down a BlockPosition up to five methods deep. + public static void serverTick(World world, BlockPos blockposition, IBlockData iblockdata, SculkCatalystBlockEntity sculkcatalystblockentity) { ++ org.bukkit.craftbukkit.event.CraftEventFactory.sourceBlockOverride = sculkcatalystblockentity.getBlockPos(); // CraftBukkit - SPIGOT-7068: Add source block override, not the most elegant way but better than passing down a BlockPos up to five methods deep. sculkcatalystblockentity.catalystListener.getSculkSpreader().updateCursors(world, blockposition, world.getRandom(), true); + org.bukkit.craftbukkit.event.CraftEventFactory.sourceBlockOverride = null; // CraftBukkit } diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeacon.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeacon.patch index fa7669c3..8e8d02f9 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeacon.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeacon.patch @@ -32,7 +32,7 @@ super.setRemoved(); } -- private static void applyEffects(World world, BlockPosition blockposition, int i, @Nullable Holder holder, @Nullable Holder holder1) { +- private static void applyEffects(World world, BlockPos blockposition, int i, @Nullable Holder holder, @Nullable Holder holder1) { - if (!world.isClientSide && holder != null) { - double d0 = (double) (i * 10 + 10); + // CraftBukkit start - split into components @@ -55,7 +55,7 @@ + } + } + -+ public static List getHumansInRange(World world, BlockPosition blockposition, int i) { ++ public static List getHumansInRange(World world, BlockPos blockposition, int i) { + { + double d0 = (double) (i * 10 + 10); + @@ -96,7 +96,7 @@ + } + } + -+ private static void applyEffects(World world, BlockPosition blockposition, int i, @Nullable Holder holder, @Nullable Holder holder1) { ++ private static void applyEffects(World world, BlockPos blockposition, int i, @Nullable Holder holder, @Nullable Holder holder1) { + if (!world.isClientSide && holder != null) { + double d0 = (double) (i * 10 + 10); + byte b0 = getAmplification(i, holder, holder1); @@ -114,7 +114,7 @@ } + // CraftBukkit end - public static void playSound(World world, BlockPosition blockposition, SoundEffect soundeffect) { + public static void playSound(World world, BlockPos blockposition, SoundEffect soundeffect) { world.playSound((EntityHuman) null, blockposition, soundeffect, SoundCategory.BLOCKS, 1.0F, 1.0F); @@ -316,7 +369,7 @@ if (nbttagcompound.contains(s, 8)) { diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeehive.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeehive.patch index 8874e644..09b110ef 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeehive.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBeehive.patch @@ -14,10 +14,10 @@ @@ -56,6 +60,7 @@ private List stored = Lists.newArrayList(); @Nullable - public BlockPosition savedFlowerPos; + public BlockPos savedFlowerPos; + public int maxBees = 3; // CraftBukkit - allow setting max amount of bees a hive can hold - public TileEntityBeehive(BlockPosition blockposition, IBlockData iblockdata) { + public TileEntityBeehive(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.BEEHIVE, blockposition, iblockdata); @@ -95,7 +100,7 @@ } @@ -88,13 +88,13 @@ @@ -180,7 +203,13 @@ } - private static boolean releaseOccupant(World world, BlockPosition blockposition, IBlockData iblockdata, TileEntityBeehive.c tileentitybeehive_c, @Nullable List list, TileEntityBeehive.ReleaseStatus tileentitybeehive_releasestatus, @Nullable BlockPosition blockposition1) { + private static boolean releaseOccupant(World world, BlockPos blockposition, IBlockData iblockdata, TileEntityBeehive.c tileentitybeehive_c, @Nullable List list, TileEntityBeehive.ReleaseStatus tileentitybeehive_releasestatus, @Nullable BlockPos blockposition1) { - if (EntityBee.isNightOrRaining(world) && tileentitybeehive_releasestatus != TileEntityBeehive.ReleaseStatus.EMERGENCY) { + // CraftBukkit start - This allows us to bypass the night/rain/emergency check + return releaseOccupant(world, blockposition, iblockdata, tileentitybeehive_c, list, tileentitybeehive_releasestatus, blockposition1, false); + } + -+ private static boolean releaseOccupant(World world, BlockPosition blockposition, IBlockData iblockdata, TileEntityBeehive.c tileentitybeehive_c, @Nullable List list, TileEntityBeehive.ReleaseStatus tileentitybeehive_releasestatus, @Nullable BlockPosition blockposition1, boolean force) { ++ private static boolean releaseOccupant(World world, BlockPos blockposition, IBlockData iblockdata, TileEntityBeehive.c tileentitybeehive_c, @Nullable List list, TileEntityBeehive.ReleaseStatus tileentitybeehive_releasestatus, @Nullable BlockPos blockposition1, boolean force) { + if (!force && EntityBee.isNightOrRaining(world) && tileentitybeehive_releasestatus != TileEntityBeehive.ReleaseStatus.EMERGENCY) { + // CraftBukkit end return false; @@ -165,8 +165,8 @@ }); } -- this.savedFlowerPos = (BlockPosition) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse((Object) null); -+ this.savedFlowerPos = (BlockPosition) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse(null); // CraftBukkit - decompile error +- this.savedFlowerPos = (BlockPos) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse((Object) null); ++ this.savedFlowerPos = (BlockPos) GameProfileSerializer.readBlockPos(nbttagcompound, "flower_pos").orElse(null); // CraftBukkit - decompile error + // CraftBukkit start + if (nbttagcompound.contains("Bukkit.MaxEntities")) { + this.maxBees = nbttagcompound.getInt("Bukkit.MaxEntities"); @@ -202,7 +202,7 @@ list.forEach(nbttagcompound::remove); @@ -370,7 +423,7 @@ @Nullable - public Entity createEntity(World world, BlockPosition blockposition) { + public Entity createEntity(World world, BlockPos blockposition) { NBTTagCompound nbttagcompound = this.entityData.copyTag(); - List list = TileEntityBeehive.IGNORED_BEE_TAGS; + List list = TileEntityBeehive.IGNORED_BEE_TAGS; // CraftBukkit - decompile error diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBell.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBell.patch index c54d843b..731f1f45 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBell.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBell.patch @@ -12,7 +12,7 @@ @@ -144,9 +144,13 @@ } - private static void makeRaidersGlow(World world, BlockPosition blockposition, List list) { + private static void makeRaidersGlow(World world, BlockPos blockposition, List list) { + List entities = // CraftBukkit list.stream().filter((entityliving) -> { return isRaiderWithinRange(blockposition, entityliving); @@ -23,4 +23,4 @@ + // CraftBukkit end } - private static void showBellParticles(World world, BlockPosition blockposition, List list) { + private static void showBellParticles(World world, BlockPos blockposition, List list) { diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBrewingStand.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBrewingStand.patch index 002abf34..4a8f0d70 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityBrewingStand.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityBrewingStand.patch @@ -56,7 +56,7 @@ + } + // CraftBukkit end - public TileEntityBrewingStand(BlockPosition blockposition, IBlockData iblockdata) { + public TileEntityBrewingStand(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.BREWING_STAND, blockposition, iblockdata); @@ -107,8 +151,19 @@ ItemStack itemstack = (ItemStack) tileentitybrewingstand.items.get(4); @@ -118,8 +118,8 @@ } } -- private static void doBrew(World world, BlockPosition blockposition, NonNullList nonnulllist) { -+ private static void doBrew(World world, BlockPosition blockposition, NonNullList nonnulllist, TileEntityBrewingStand tileentitybrewingstand) { // CraftBukkit +- private static void doBrew(World world, BlockPos blockposition, NonNullList nonnulllist) { ++ private static void doBrew(World world, BlockPos blockposition, NonNullList nonnulllist, TileEntityBrewingStand tileentitybrewingstand) { // CraftBukkit ItemStack itemstack = (ItemStack) nonnulllist.get(3); PotionBrewer potionbrewer = world.potionBrewing(); diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityChest.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityChest.patch index 328ceec0..8a7ca313 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityChest.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityChest.patch @@ -47,7 +47,7 @@ + } + // CraftBukkit end + - protected TileEntityChest(TileEntityTypes tileentitytypes, BlockPosition blockposition, IBlockData iblockdata) { + protected TileEntityChest(TileEntityTypes tileentitytypes, BlockPos blockposition, IBlockData iblockdata) { super(tileentitytypes, blockposition, iblockdata); this.items = NonNullList.withSize(27, ItemStack.EMPTY); @@ -199,4 +235,11 @@ diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityConduit.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityConduit.patch index 033b3ba2..2264fd95 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityConduit.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityConduit.patch @@ -14,12 +14,12 @@ @@ -187,8 +191,20 @@ } - private static void applyEffects(World world, BlockPosition blockposition, List list) { + private static void applyEffects(World world, BlockPos blockposition, List list) { + // CraftBukkit start + applyEffects(world, blockposition, getRange(list)); + } + -+ public static int getRange(List list) { ++ public static int getRange(List list) { + // CraftBukkit end int i = list.size(); int j = i / 7 * 16; @@ -27,7 +27,7 @@ + return j; + } + -+ private static void applyEffects(World world, BlockPosition blockposition, int j) { // j = effect range in blocks ++ private static void applyEffects(World world, BlockPos blockposition, int j) { // j = effect range in blocks + // CraftBukkit end int k = blockposition.getX(); int l = blockposition.getY(); @@ -44,12 +44,12 @@ @@ -210,6 +226,12 @@ } - private static void updateDestroyTarget(World world, BlockPosition blockposition, IBlockData iblockdata, List list, TileEntityConduit tileentityconduit) { + private static void updateDestroyTarget(World world, BlockPos blockposition, IBlockData iblockdata, List list, TileEntityConduit tileentityconduit) { + // CraftBukkit start - add "damageTarget" boolean + updateDestroyTarget(world, blockposition, iblockdata, list, tileentityconduit, true); + } + -+ public static void updateDestroyTarget(World world, BlockPosition blockposition, IBlockData iblockdata, List list, TileEntityConduit tileentityconduit, boolean damageTarget) { ++ public static void updateDestroyTarget(World world, BlockPos blockposition, IBlockData iblockdata, List list, TileEntityConduit tileentityconduit, boolean damageTarget) { + // CraftBukkit end EntityLiving entityliving = tileentityconduit.destroyTarget; int i = list.size(); diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityDispenser.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityDispenser.patch index 1fae288d..d652004d 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityDispenser.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityDispenser.patch @@ -45,6 +45,6 @@ + } + // CraftBukkit end + - protected TileEntityDispenser(TileEntityTypes tileentitytypes, BlockPosition blockposition, IBlockData iblockdata) { + protected TileEntityDispenser(TileEntityTypes tileentitytypes, BlockPos blockposition, IBlockData iblockdata) { super(tileentitytypes, blockposition, iblockdata); this.items = NonNullList.withSize(9, ItemStack.EMPTY); diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityEndGateway.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityEndGateway.patch index e6456e8f..30ef04a9 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityEndGateway.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityEndGateway.patch @@ -12,8 +12,8 @@ private static final Logger LOGGER = LogUtils.getLogger(); @@ -143,7 +147,7 @@ - public Vec3D getPortalPosition(WorldServer worldserver, BlockPosition blockposition) { - BlockPosition blockposition1; + public Vec3D getPortalPosition(WorldServer worldserver, BlockPos blockposition) { + BlockPos blockposition1; - if (this.exitPortal == null && worldserver.dimension() == World.END) { + if (this.exitPortal == null && worldserver.getTypeKey() == WorldDimension.END) { // CraftBukkit - work in alternate worlds diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityFurnace.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityFurnace.patch index be3111dc..493807db 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityFurnace.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityFurnace.patch @@ -125,7 +125,7 @@ } - private static boolean burn(IRegistryCustom iregistrycustom, @Nullable RecipeHolder recipeholder, SingleRecipeInput singlerecipeinput, NonNullList nonnulllist, int i) { -+ private static boolean burn(World world, BlockPosition blockposition, IRegistryCustom iregistrycustom, @Nullable RecipeHolder recipeholder, SingleRecipeInput singlerecipeinput, NonNullList nonnulllist, int i) { // CraftBukkit ++ private static boolean burn(World world, BlockPos blockposition, IRegistryCustom iregistrycustom, @Nullable RecipeHolder recipeholder, SingleRecipeInput singlerecipeinput, NonNullList nonnulllist, int i) { // CraftBukkit if (recipeholder != null && canBurn(iregistrycustom, recipeholder, singlerecipeinput, nonnulllist, i)) { ItemStack itemstack = (ItemStack) nonnulllist.get(0); ItemStack itemstack1 = ((RecipeCooking) recipeholder.value()).assemble(singlerecipeinput, iregistrycustom); @@ -193,7 +193,7 @@ + return this.getRecipesToAwardAndPopExperience(worldserver, vec3d, this.worldPosition, null, null, 0); + } + -+ public List> getRecipesToAwardAndPopExperience(WorldServer worldserver, Vec3D vec3d, BlockPosition blockposition, EntityPlayer entityplayer, ItemStack itemstack, int amount) { ++ public List> getRecipesToAwardAndPopExperience(WorldServer worldserver, Vec3D vec3d, BlockPos blockposition, EntityPlayer entityplayer, ItemStack itemstack, int amount) { + // CraftBukkit end List> list = Lists.newArrayList(); ObjectIterator objectiterator = this.recipesUsed.reference2IntEntrySet().iterator(); @@ -213,7 +213,7 @@ } - private static void createExperience(WorldServer worldserver, Vec3D vec3d, int i, float f) { -+ private static void createExperience(WorldServer worldserver, Vec3D vec3d, int i, float f, BlockPosition blockposition, EntityHuman entityhuman, ItemStack itemstack, int amount) { // CraftBukkit ++ private static void createExperience(WorldServer worldserver, Vec3D vec3d, int i, float f, BlockPos blockposition, EntityHuman entityhuman, ItemStack itemstack, int amount) { // CraftBukkit int j = MathHelper.floor((float) i * f); float f1 = MathHelper.frac((float) i * f); diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityHopper.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityHopper.patch index c54c3dbe..acdeea90 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityHopper.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityHopper.patch @@ -57,7 +57,7 @@ + } + // CraftBukkit end + - public TileEntityHopper(BlockPosition blockposition, IBlockData iblockdata) { + public TileEntityHopper(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.HOPPER, blockposition, iblockdata); this.items = NonNullList.withSize(5, ItemStack.EMPTY); @@ -167,7 +213,29 @@ @@ -164,10 +164,10 @@ + // CraftBukkit end + @Nullable - private static IInventory getAttachedContainer(World world, BlockPosition blockposition, TileEntityHopper tileentityhopper) { + private static IInventory getAttachedContainer(World world, BlockPos blockposition, TileEntityHopper tileentityhopper) { - return getContainerAt(world, blockposition.relative(tileentityhopper.facing)); + // CraftBukkit start -+ BlockPosition searchPosition = blockposition.relative(tileentityhopper.facing); ++ BlockPos searchPosition = blockposition.relative(tileentityhopper.facing); + IInventory inventory = getContainerAt(world, searchPosition); + + CraftBlock hopper = CraftBlock.at(world, blockposition); @@ -177,12 +177,12 @@ } @Nullable - private static IInventory getSourceContainer(World world, IHopper ihopper, BlockPosition blockposition, IBlockData iblockdata) { + private static IInventory getSourceContainer(World world, IHopper ihopper, BlockPos blockposition, IBlockData iblockdata) { - return getContainerAt(world, blockposition, iblockdata, ihopper.getLevelX(), ihopper.getLevelY() + 1.0D, ihopper.getLevelZ()); + // CraftBukkit start + IInventory inventory = getContainerAt(world, blockposition, iblockdata, ihopper.getLevelX(), ihopper.getLevelY() + 1.0D, ihopper.getLevelZ()); + -+ BlockPosition blockPosition = BlockPosition.containing(ihopper.getLevelX(), ihopper.getLevelY(), ihopper.getLevelZ()); ++ BlockPos blockPosition = BlockPos.containing(ihopper.getLevelX(), ihopper.getLevelY(), ihopper.getLevelZ()); + CraftBlock hopper = CraftBlock.at(world, blockPosition); + CraftBlock container = CraftBlock.at(world, blockPosition.above()); + return runHopperInventorySearchEvent(inventory, hopper, container, HopperInventorySearchEvent.ContainerType.SOURCE); diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityJukeBox.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityJukeBox.patch index cd407858..973a63af 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityJukeBox.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityJukeBox.patch @@ -55,7 +55,7 @@ + } + // CraftBukkit end - public TileEntityJukeBox(BlockPosition blockposition, IBlockData iblockdata) { + public TileEntityJukeBox(BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.JUKEBOX, blockposition, iblockdata); @@ -133,7 +177,7 @@ diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntityShulkerBox.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntityShulkerBox.patch index 971f7399..c31ecebe 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntityShulkerBox.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntityShulkerBox.patch @@ -47,7 +47,7 @@ + } + // CraftBukkit end + - public TileEntityShulkerBox(@Nullable EnumColor enumcolor, BlockPosition blockposition, IBlockData iblockdata) { + public TileEntityShulkerBox(@Nullable EnumColor enumcolor, BlockPos blockposition, IBlockData iblockdata) { super(TileEntityTypes.SHULKER_BOX, blockposition, iblockdata); this.itemStacks = NonNullList.withSize(27, ItemStack.EMPTY); @@ -173,6 +209,7 @@ diff --git a/nms-patches/net/minecraft/world/level/block/entity/TileEntitySign.patch b/nms-patches/net/minecraft/world/level/block/entity/TileEntitySign.patch index 4c2e6b73..3fab9b26 100644 --- a/nms-patches/net/minecraft/world/level/block/entity/TileEntitySign.patch +++ b/nms-patches/net/minecraft/world/level/block/entity/TileEntitySign.patch @@ -94,7 +94,7 @@ return flag1; } -- private static CommandListenerWrapper createCommandSourceStack(@Nullable EntityHuman entityhuman, World world, BlockPosition blockposition) { +- private static CommandListenerWrapper createCommandSourceStack(@Nullable EntityHuman entityhuman, World world, BlockPos blockposition) { + // CraftBukkit start + private final ICommandListener commandSource = new ICommandListener() { + @@ -122,7 +122,7 @@ + } + }; + -+ private CommandListenerWrapper createCommandSourceStack(@Nullable EntityHuman entityhuman, World world, BlockPosition blockposition) { ++ private CommandListenerWrapper createCommandSourceStack(@Nullable EntityHuman entityhuman, World world, BlockPos blockposition) { + // CraftBukkit end String s = entityhuman == null ? "Sign" : entityhuman.getName().getString(); Object object = entityhuman == null ? IChatBaseComponent.literal("Sign") : entityhuman.getDisplayName(); diff --git a/nms-patches/net/minecraft/world/level/block/grower/WorldGenTreeProvider.patch b/nms-patches/net/minecraft/world/level/block/grower/WorldGenTreeProvider.patch index 0a014858..be731d49 100644 --- a/nms-patches/net/minecraft/world/level/block/grower/WorldGenTreeProvider.patch +++ b/nms-patches/net/minecraft/world/level/block/grower/WorldGenTreeProvider.patch @@ -27,7 +27,7 @@ + return this.secondaryMegaTree.isPresent() && randomsource.nextFloat() < this.secondaryChance ? (ResourceKey) this.secondaryMegaTree.get() : (ResourceKey) this.megaTree.orElse(null); // CraftBukkit - decompile error } - public boolean growTree(WorldServer worldserver, ChunkGenerator chunkgenerator, BlockPosition blockposition, IBlockData iblockdata, RandomSource randomsource) { + public boolean growTree(WorldServer worldserver, ChunkGenerator chunkgenerator, BlockPos blockposition, IBlockData iblockdata, RandomSource randomsource) { ResourceKey> resourcekey = this.getConfiguredMegaFeature(randomsource); if (resourcekey != null) { diff --git a/nms-patches/net/minecraft/world/level/block/piston/BlockPiston.patch b/nms-patches/net/minecraft/world/level/block/piston/BlockPiston.patch index 7b2160e5..2d48348a 100644 --- a/nms-patches/net/minecraft/world/level/block/piston/BlockPiston.patch +++ b/nms-patches/net/minecraft/world/level/block/piston/BlockPiston.patch @@ -41,8 +41,8 @@ + // CraftBukkit start + final org.bukkit.block.Block bblock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + -+ final List moved = pistonextendschecker.getToPush(); -+ final List broken = pistonextendschecker.getToDestroy(); ++ final List moved = pistonextendschecker.getToPush(); ++ final List broken = pistonextendschecker.getToDestroy(); + + List blocks = new AbstractList() { + @@ -56,7 +56,7 @@ + if (index >= size() || index < 0) { + throw new ArrayIndexOutOfBoundsException(index); + } -+ BlockPosition pos = (BlockPosition) (index < moved.size() ? moved.get(index) : broken.get(index - moved.size())); ++ BlockPos pos = (BlockPos) (index < moved.size() ? moved.get(index) : broken.get(index - moved.size())); + return bblock.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); + } + }; @@ -69,10 +69,10 @@ + world.getCraftServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { -+ for (BlockPosition b : broken) { ++ for (BlockPos b : broken) { + world.sendBlockUpdated(b, Blocks.AIR.defaultBlockState(), world.getBlockState(b), 3); + } -+ for (BlockPosition b : moved) { ++ for (BlockPos b : moved) { + world.sendBlockUpdated(b, Blocks.AIR.defaultBlockState(), world.getBlockState(b), 3); + b = b.relative(enumdirection1); + world.sendBlockUpdated(b, Blocks.AIR.defaultBlockState(), world.getBlockState(b), 3); @@ -81,5 +81,5 @@ + } + // CraftBukkit end - BlockPosition blockposition3; + BlockPos blockposition3; int j; diff --git a/nms-patches/net/minecraft/world/level/block/state/BlockBase.patch b/nms-patches/net/minecraft/world/level/block/state/BlockBase.patch index bc6135f2..5eac132f 100644 --- a/nms-patches/net/minecraft/world/level/block/state/BlockBase.patch +++ b/nms-patches/net/minecraft/world/level/block/state/BlockBase.patch @@ -14,15 +14,15 @@ protected static final EnumDirection[] UPDATE_SHAPE_ORDER = new EnumDirection[]{EnumDirection.WEST, EnumDirection.EAST, EnumDirection.NORTH, EnumDirection.SOUTH, EnumDirection.DOWN, EnumDirection.UP}; @@ -158,6 +163,12 @@ - protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) {} + protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag) {} + // CraftBukkit start -+ protected void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag, @Nullable ItemActionContext context) { ++ protected void onPlace(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag, @Nullable ItemActionContext context) { + this.onPlace(iblockdata, world, blockposition, iblockdata1, flag); + } + // CraftBukkit end + - protected void onRemove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { + protected void onRemove(IBlockData iblockdata, World world, BlockPos blockposition, IBlockData iblockdata1, boolean flag) { if (iblockdata.hasBlockEntity() && !iblockdata.is(iblockdata1.getBlock())) { world.removeBlockEntity(blockposition); @@ -174,8 +185,10 @@ @@ -41,15 +41,15 @@ @@ -1121,7 +1134,13 @@ } - public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + public void onPlace(World world, BlockPos blockposition, IBlockData iblockdata, boolean flag) { - this.getBlock().onPlace(this.asState(), world, blockposition, iblockdata, flag); + // CraftBukkit start + this.onPlace(world, blockposition, iblockdata, flag, null); + } + -+ public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag, @Nullable ItemActionContext context) { ++ public void onPlace(World world, BlockPos blockposition, IBlockData iblockdata, boolean flag, @Nullable ItemActionContext context) { + this.getBlock().onPlace(this.asState(), world, blockposition, iblockdata, flag, context); + // CraftBukkit end } - public void onRemove(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + public void onRemove(World world, BlockPos blockposition, IBlockData iblockdata, boolean flag) { diff --git a/nms-patches/net/minecraft/world/level/chunk/Chunk.patch b/nms-patches/net/minecraft/world/level/chunk/Chunk.patch index 245064ce..4b41510a 100644 --- a/nms-patches/net/minecraft/world/level/chunk/Chunk.patch +++ b/nms-patches/net/minecraft/world/level/chunk/Chunk.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/chunk/Chunk.java @@ -78,7 +78,7 @@ }; - private final Map tickersInLevel; + private final Map tickersInLevel; public boolean loaded; - public final World level; + public final WorldServer level; // CraftBukkit - type @@ -48,12 +48,12 @@ + // CraftBukkit start @Nullable @Override - public IBlockData setBlockState(BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + public IBlockData setBlockState(BlockPos blockposition, IBlockData iblockdata, boolean flag) { + return this.setBlockState(blockposition, iblockdata, flag, true); + } + + @Nullable -+ public IBlockData setBlockState(BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean doPlace) { ++ public IBlockData setBlockState(BlockPos blockposition, IBlockData iblockdata, boolean flag, boolean doPlace) { + // CraftBukkit end int i = blockposition.getY(); ChunkSection chunksection = this.getSection(this.getSectionIndex(i)); @@ -71,7 +71,7 @@ @@ -370,7 +387,12 @@ @Nullable - public TileEntity getBlockEntity(BlockPosition blockposition, Chunk.EnumTileEntityState chunk_enumtileentitystate) { + public TileEntity getBlockEntity(BlockPos blockposition, Chunk.EnumTileEntityState chunk_enumtileentitystate) { - TileEntity tileentity = (TileEntity) this.blockEntities.get(blockposition); + // CraftBukkit start + TileEntity tileentity = level.capturedTileEntities.get(blockposition); diff --git a/nms-patches/net/minecraft/world/level/dimension/end/EnderDragonBattle.patch b/nms-patches/net/minecraft/world/level/dimension/end/EnderDragonBattle.patch index ad62a4bf..451da1cc 100644 --- a/nms-patches/net/minecraft/world/level/dimension/end/EnderDragonBattle.patch +++ b/nms-patches/net/minecraft/world/level/dimension/end/EnderDragonBattle.patch @@ -12,8 +12,8 @@ this.respawnStage = EnumDragonRespawn.START; } -- this.portalLocation = (BlockPosition) enderdragonbattle_a.exitPortalLocation.orElse((Object) null); -+ this.portalLocation = (BlockPosition) enderdragonbattle_a.exitPortalLocation.orElse(null); // CraftBukkit - decompile error +- this.portalLocation = (BlockPos) enderdragonbattle_a.exitPortalLocation.orElse((Object) null); ++ this.portalLocation = (BlockPos) enderdragonbattle_a.exitPortalLocation.orElse(null); // CraftBukkit - decompile error this.gateways.addAll((Collection) enderdragonbattle_a.gateways.orElseGet(() -> { ObjectArrayList objectarraylist = new ObjectArrayList(ContiguousSet.create(Range.closedOpen(0, 20), DiscreteDomain.integers())); @@ -33,7 +33,7 @@ - public void tryRespawn() { + public boolean tryRespawn() { // CraftBukkit - return boolean if (this.dragonKilled && this.respawnStage == null) { - BlockPosition blockposition = this.portalLocation; + BlockPos blockposition = this.portalLocation; @@ -540,19 +540,19 @@ List list1 = this.level.getEntitiesOfClass(EntityEnderCrystal.class, new AxisAlignedBB(blockposition1.relative(enumdirection, 2))); diff --git a/nms-patches/net/minecraft/world/level/dimension/end/EnumDragonRespawn.patch b/nms-patches/net/minecraft/world/level/dimension/end/EnumDragonRespawn.patch index 7ffc939c..f4c5235d 100644 --- a/nms-patches/net/minecraft/world/level/dimension/end/EnumDragonRespawn.patch +++ b/nms-patches/net/minecraft/world/level/dimension/end/EnumDragonRespawn.patch @@ -21,7 +21,7 @@ }, PREPARING_TO_SUMMON_PILLARS { @@ -38,7 +42,7 @@ - worldserver.levelEvent(3001, new BlockPosition(0, 128, 0), 0); + worldserver.levelEvent(3001, new BlockPos(0, 128, 0), 0); } } else { - enderdragonbattle.setRespawnStage(null.SUMMONING_PILLARS); @@ -30,7 +30,7 @@ } @@ -81,7 +85,7 @@ - WorldGenerator.END_SPIKE.place(worldgenfeatureendspikeconfiguration, worldserver, worldserver.getChunkSource().getGenerator(), RandomSource.create(), new BlockPosition(worldgenender_spike.getCenterX(), 45, worldgenender_spike.getCenterZ())); + WorldGenerator.END_SPIKE.place(worldgenfeatureendspikeconfiguration, worldserver, worldserver.getChunkSource().getGenerator(), RandomSource.create(), new BlockPos(worldgenender_spike.getCenterX(), 45, worldgenender_spike.getCenterZ())); } } else if (flag1) { - enderdragonbattle.setRespawnStage(null.SUMMONING_DRAGON); @@ -49,10 +49,10 @@ @@ -102,7 +106,7 @@ entityendercrystal = (EntityEnderCrystal) iterator.next(); - entityendercrystal.setBeamTarget((BlockPosition) null); + entityendercrystal.setBeamTarget((BlockPos) null); worldserver.explode(entityendercrystal, entityendercrystal.getX(), entityendercrystal.getY(), entityendercrystal.getZ(), 6.0F, World.a.NONE); - entityendercrystal.discard(); + entityendercrystal.discard(EntityRemoveEvent.Cause.EXPLODE); // CraftBukkit - add Bukkit remove cause } } else if (i >= 80) { - worldserver.levelEvent(3001, new BlockPosition(0, 128, 0), 0); + worldserver.levelEvent(3001, new BlockPos(0, 128, 0), 0); diff --git a/nms-patches/net/minecraft/world/level/gameevent/GameEventDispatcher.patch b/nms-patches/net/minecraft/world/level/gameevent/GameEventDispatcher.patch index d3e07b31..14a4594b 100644 --- a/nms-patches/net/minecraft/world/level/gameevent/GameEventDispatcher.patch +++ b/nms-patches/net/minecraft/world/level/gameevent/GameEventDispatcher.patch @@ -17,7 +17,7 @@ @@ -23,6 +30,14 @@ public void post(Holder holder, Vec3D vec3d, GameEvent.a gameevent_a) { int i = ((GameEvent) holder.value()).notificationRadius(); - BlockPosition blockposition = BlockPosition.containing(vec3d); + BlockPos blockposition = BlockPos.containing(vec3d); + // CraftBukkit start + GenericGameEvent event = new GenericGameEvent(CraftGameEvent.minecraftToBukkit(holder.value()), CraftLocation.toBukkit(blockposition, level.getWorld()), (gameevent_a.sourceEntity() == null) ? null : gameevent_a.sourceEntity().getBukkitEntity(), i, !Bukkit.isPrimaryThread()); + level.getCraftServer().getPluginManager().callEvent(event); diff --git a/nms-patches/net/minecraft/world/level/gameevent/vibrations/VibrationSystem.patch b/nms-patches/net/minecraft/world/level/gameevent/vibrations/VibrationSystem.patch index 0b7640d2..71f6e119 100644 --- a/nms-patches/net/minecraft/world/level/gameevent/vibrations/VibrationSystem.patch +++ b/nms-patches/net/minecraft/world/level/gameevent/vibrations/VibrationSystem.patch @@ -28,11 +28,11 @@ } else { Vec3D vec3d1 = (Vec3D) optional.get(); - -- if (!vibrationsystem_d.canReceiveVibration(worldserver, BlockPosition.containing(vec3d), holder, gameevent_a)) { +- if (!vibrationsystem_d.canReceiveVibration(worldserver, BlockPos.containing(vec3d), holder, gameevent_a)) { + // CraftBukkit start -+ boolean defaultCancel = !vibrationsystem_d.canReceiveVibration(worldserver, BlockPosition.containing(vec3d), holder, gameevent_a); ++ boolean defaultCancel = !vibrationsystem_d.canReceiveVibration(worldserver, BlockPos.containing(vec3d), holder, gameevent_a); + Entity entity = gameevent_a.sourceEntity(); -+ BlockReceiveGameEvent event = new BlockReceiveGameEvent(CraftGameEvent.minecraftToBukkit(holder.value()), CraftBlock.at(worldserver, BlockPosition.containing(vec3d1)), (entity == null) ? null : entity.getBukkitEntity()); ++ BlockReceiveGameEvent event = new BlockReceiveGameEvent(CraftGameEvent.minecraftToBukkit(holder.value()), CraftBlock.at(worldserver, BlockPos.containing(vec3d1)), (entity == null) ? null : entity.getBukkitEntity()); + event.setCancelled(defaultCancel); + worldserver.getCraftServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { diff --git a/nms-patches/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.patch b/nms-patches/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.patch index f8a04e34..27b8a13c 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/feature/EndPlatformFeature.patch @@ -16,19 +16,19 @@ @@ -21,6 +27,13 @@ } - public static void createEndPlatform(WorldAccess worldaccess, BlockPosition blockposition, boolean flag) { + public static void createEndPlatform(WorldAccess worldaccess, BlockPos blockposition, boolean flag) { + createEndPlatform(worldaccess, blockposition, flag, null); + // CraftBukkit start + } + -+ public static void createEndPlatform(WorldAccess worldaccess, BlockPosition blockposition, boolean flag, Entity entity) { ++ public static void createEndPlatform(WorldAccess worldaccess, BlockPos blockposition, boolean flag, Entity entity) { + org.bukkit.craftbukkit.util.BlockStateListPopulator blockList = new org.bukkit.craftbukkit.util.BlockStateListPopulator(worldaccess); + // CraftBukkit end - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = blockposition.mutable(); + BlockPos.MutableBlockPos blockposition_mutableblockposition = blockposition.mutable(); for (int i = -2; i <= 2; ++i) { @@ -29,16 +42,36 @@ - BlockPosition.MutableBlockPosition blockposition_mutableblockposition1 = blockposition_mutableblockposition.set(blockposition).move(j, k, i); + BlockPos.MutableBlockPos blockposition_mutableblockposition1 = blockposition_mutableblockposition.set(blockposition).move(j, k, i); Block block = k == -1 ? Blocks.OBSIDIAN : Blocks.AIR; - if (!worldaccess.getBlockState(blockposition_mutableblockposition1).is(block)) { diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/StructurePiece.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/StructurePiece.patch index e9a12400..46dcfb7a 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/StructurePiece.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/StructurePiece.patch @@ -44,7 +44,7 @@ } + // CraftBukkit start -+ protected boolean placeCraftBlockEntity(WorldAccess worldAccess, BlockPosition position, org.bukkit.craftbukkit.block.CraftBlockEntityState craftBlockEntityState, int i) { ++ protected boolean placeCraftBlockEntity(WorldAccess worldAccess, BlockPos position, org.bukkit.craftbukkit.block.CraftBlockEntityState craftBlockEntityState, int i) { + if (worldAccess instanceof org.bukkit.craftbukkit.util.TransformerGeneratorAccess transformerAccess) { + return transformerAccess.setCraftBlock(position, craftBlockEntityState, i); + } @@ -56,14 +56,14 @@ + return result; + } + -+ protected void placeCraftSpawner(WorldAccess worldAccess, BlockPosition position, org.bukkit.entity.EntityType entityType, int i) { ++ protected void placeCraftSpawner(WorldAccess worldAccess, BlockPos position, org.bukkit.entity.EntityType entityType, int i) { + // This method is used in structures that are generated by code and place spawners as they set the entity after the block was placed making it impossible for plugins to access that information + org.bukkit.craftbukkit.block.CraftCreatureSpawner spawner = (org.bukkit.craftbukkit.block.CraftCreatureSpawner) org.bukkit.craftbukkit.block.CraftBlockStates.getBlockState(worldAccess, position, Blocks.SPAWNER.defaultBlockState(), null); + spawner.setSpawnedType(entityType); + placeCraftBlockEntity(worldAccess, position, spawner, i); + } + -+ protected void setCraftLootTable(WorldAccess worldAccess, BlockPosition position, RandomSource randomSource, ResourceKey loottableKey) { ++ protected void setCraftLootTable(WorldAccess worldAccess, BlockPos position, RandomSource randomSource, ResourceKey loottableKey) { + // This method is used in structures that use data markers to a loot table to loot containers as otherwise plugins won't have access to that information. + net.minecraft.world.level.block.entity.TileEntity tileEntity = worldAccess.getBlockEntity(position); + if (tileEntity instanceof net.minecraft.world.level.block.entity.TileEntityLootable tileEntityLootable) { @@ -100,7 +100,7 @@ return true; } else { @@ -410,12 +453,31 @@ - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = this.getWorldPos(i, j, k); + BlockPos.MutableBlockPos blockposition_mutableblockposition = this.getWorldPos(i, j, k); if (structureboundingbox.isInside(blockposition_mutableblockposition) && !generatoraccessseed.getBlockState(blockposition_mutableblockposition).is(Blocks.DISPENSER)) { + // CraftBukkit start diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/StructureStart.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/StructureStart.patch index cf6f6199..087e4ac9 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/StructureStart.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/StructureStart.patch @@ -15,8 +15,8 @@ this.chunkPos = chunkcoordintpair; @@ -91,6 +97,8 @@ StructureBoundingBox structureboundingbox1 = ((StructurePiece) list.get(0)).boundingBox; - BlockPosition blockposition = structureboundingbox1.getCenter(); - BlockPosition blockposition1 = new BlockPosition(blockposition.getX(), structureboundingbox1.minY(), blockposition.getZ()); + BlockPos blockposition = structureboundingbox1.getCenter(); + BlockPos blockposition1 = new BlockPos(blockposition.getX(), structureboundingbox1.minY(), blockposition.getZ()); + // CraftBukkit start + /* Iterator iterator = list.iterator(); diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/DesertPyramidStructure.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/DesertPyramidStructure.patch index 8da3c907..cf5028e2 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/DesertPyramidStructure.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/DesertPyramidStructure.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/levelgen/structure/structures/DesertPyramidStructure.java @@ -68,6 +68,15 @@ - private static void placeSuspiciousSand(StructureBoundingBox structureboundingbox, GeneratorAccessSeed generatoraccessseed, BlockPosition blockposition) { + private static void placeSuspiciousSand(StructureBoundingBox structureboundingbox, GeneratorAccessSeed generatoraccessseed, BlockPos blockposition) { if (structureboundingbox.isInside(blockposition)) { + // CraftBukkit start + if (generatoraccessseed instanceof org.bukkit.craftbukkit.util.TransformerGeneratorAccess transformerAccess) { diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/EndCityPieces.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/EndCityPieces.patch index 9aea5241..a618ad1f 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/EndCityPieces.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/EndCityPieces.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/levelgen/structure/structures/EndCityPieces.java +++ b/net/minecraft/world/level/levelgen/structure/structures/EndCityPieces.java @@ -285,7 +285,12 @@ - BlockPosition blockposition1 = blockposition.below(); + BlockPos blockposition1 = blockposition.below(); if (structureboundingbox.isInside(blockposition1)) { + // CraftBukkit start - ensure block transformation diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/IglooPieces.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/IglooPieces.patch index 85ee41d1..9766045d 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/IglooPieces.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/IglooPieces.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/levelgen/structure/structures/IglooPieces.java +++ b/net/minecraft/world/level/levelgen/structure/structures/IglooPieces.java @@ -86,11 +86,16 @@ - protected void handleDataMarker(String s, BlockPosition blockposition, WorldAccess worldaccess, RandomSource randomsource, StructureBoundingBox structureboundingbox) { + protected void handleDataMarker(String s, BlockPos blockposition, WorldAccess worldaccess, RandomSource randomsource, StructureBoundingBox structureboundingbox) { if ("chest".equals(s)) { worldaccess.setBlock(blockposition, Blocks.AIR.defaultBlockState(), 3); + // CraftBukkit start - ensure block transformation diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/OceanRuinPieces.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/OceanRuinPieces.patch index bfb61781..63c10a77 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/structures/OceanRuinPieces.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/structures/OceanRuinPieces.patch @@ -2,7 +2,7 @@ +++ b/net/minecraft/world/level/levelgen/structure/structures/OceanRuinPieces.java @@ -200,12 +200,20 @@ @Override - protected void handleDataMarker(String s, BlockPosition blockposition, WorldAccess worldaccess, RandomSource randomsource, StructureBoundingBox structureboundingbox) { + protected void handleDataMarker(String s, BlockPos blockposition, WorldAccess worldaccess, RandomSource randomsource, StructureBoundingBox structureboundingbox) { if ("chest".equals(s)) { + // CraftBukkit start - transform block to ensure loot table is accessible + /* diff --git a/nms-patches/net/minecraft/world/level/levelgen/structure/templatesystem/DefinedStructure.patch b/nms-patches/net/minecraft/world/level/levelgen/structure/templatesystem/DefinedStructure.patch index f8027cf9..df0a03c0 100644 --- a/nms-patches/net/minecraft/world/level/levelgen/structure/templatesystem/DefinedStructure.patch +++ b/nms-patches/net/minecraft/world/level/levelgen/structure/templatesystem/DefinedStructure.patch @@ -14,7 +14,7 @@ public static final String PALETTE_TAG = "palette"; @@ -74,6 +80,11 @@ - private BaseBlockPosition size; + private BaseBlockPos size; private String author; + // CraftBukkit start - data containers @@ -23,7 +23,7 @@ + // CraftBukkit end + public DefinedStructure() { - this.size = BaseBlockPosition.ZERO; + this.size = BaseBlockPos.ZERO; this.author = "?"; @@ -147,7 +158,7 @@ } @@ -110,7 +110,7 @@ + // CraftBukkit end } - public BaseBlockPosition getSize(EnumBlockRotation enumblockrotation) { + public BaseBlockPos getSize(EnumBlockRotation enumblockrotation) { @@ -721,6 +761,11 @@ nbttagcompound.put("entities", nbttaglist3); diff --git a/nms-patches/net/minecraft/world/level/material/FluidTypeFlowing.patch b/nms-patches/net/minecraft/world/level/material/FluidTypeFlowing.patch index 0cff368d..9582351d 100644 --- a/nms-patches/net/minecraft/world/level/material/FluidTypeFlowing.patch +++ b/nms-patches/net/minecraft/world/level/material/FluidTypeFlowing.patch @@ -34,7 +34,7 @@ this.spreadToSides(worldserver, blockposition, fluid, iblockdata); @@ -168,6 +186,15 @@ Fluid fluid1 = (Fluid) entry.getValue(); - BlockPosition blockposition1 = blockposition.relative(enumdirection); + BlockPos blockposition1 = blockposition.relative(enumdirection); + // CraftBukkit start + org.bukkit.block.Block source = CraftBlock.at(worldserver, blockposition); diff --git a/nms-patches/net/minecraft/world/level/material/FluidTypeLava.patch b/nms-patches/net/minecraft/world/level/material/FluidTypeLava.patch index b77cab1d..df878c94 100644 --- a/nms-patches/net/minecraft/world/level/material/FluidTypeLava.patch +++ b/nms-patches/net/minecraft/world/level/material/FluidTypeLava.patch @@ -19,7 +19,7 @@ if (worldserver.isEmptyBlock(blockposition2.above()) && this.isFlammable(worldserver, blockposition2)) { + // CraftBukkit start - Prevent lava putting something on fire -+ BlockPosition up = blockposition2.above(); ++ BlockPos up = blockposition2.above(); + if (worldserver.getBlockState(up).getBlock() != Blocks.FIRE) { + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(worldserver, up, blockposition).isCancelled()) { + continue; diff --git a/nms-patches/net/minecraft/world/level/portal/BlockPortalShape.patch b/nms-patches/net/minecraft/world/level/portal/BlockPortalShape.patch index 903517a8..f951860f 100644 --- a/nms-patches/net/minecraft/world/level/portal/BlockPortalShape.patch +++ b/nms-patches/net/minecraft/world/level/portal/BlockPortalShape.patch @@ -13,14 +13,14 @@ private static final int MIN_WIDTH = 2; @@ -40,8 +45,12 @@ - private final BlockPosition bottomLeft; + private final BlockPos bottomLeft; private final int height; private final int width; + // CraftBukkit start - add field + private final BlockStateListPopulator blocks; -- private BlockPortalShape(EnumDirection.EnumAxis enumdirection_enumaxis, int i, EnumDirection enumdirection, BlockPosition blockposition, int j, int k) { -+ private BlockPortalShape(EnumDirection.EnumAxis enumdirection_enumaxis, int i, EnumDirection enumdirection, BlockPosition blockposition, int j, int k, BlockStateListPopulator blocks) { +- private BlockPortalShape(EnumDirection.EnumAxis enumdirection_enumaxis, int i, EnumDirection enumdirection, BlockPos blockposition, int j, int k) { ++ private BlockPortalShape(EnumDirection.EnumAxis enumdirection_enumaxis, int i, EnumDirection enumdirection, BlockPos blockposition, int j, int k, BlockStateListPopulator blocks) { + this.blocks = blocks; + // CraftBukkit end this.axis = enumdirection_enumaxis; @@ -29,11 +29,11 @@ @@ -69,44 +78,45 @@ } - public static BlockPortalShape findAnyShape(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection.EnumAxis enumdirection_enumaxis) { + public static BlockPortalShape findAnyShape(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection.EnumAxis enumdirection_enumaxis) { + BlockStateListPopulator blocks = new BlockStateListPopulator(((GeneratorAccess) iblockaccess).getMinecraftWorld()); // CraftBukkit EnumDirection enumdirection = enumdirection_enumaxis == EnumDirection.EnumAxis.X ? EnumDirection.WEST : EnumDirection.SOUTH; -- BlockPosition blockposition1 = calculateBottomLeft(iblockaccess, enumdirection, blockposition); -+ BlockPosition blockposition1 = calculateBottomLeft(iblockaccess, enumdirection, blockposition, blocks); // CraftBukkit +- BlockPos blockposition1 = calculateBottomLeft(iblockaccess, enumdirection, blockposition); ++ BlockPos blockposition1 = calculateBottomLeft(iblockaccess, enumdirection, blockposition, blocks); // CraftBukkit if (blockposition1 == null) { - return new BlockPortalShape(enumdirection_enumaxis, 0, enumdirection, blockposition, 0, 0); @@ -57,8 +57,8 @@ } @Nullable -- private static BlockPosition calculateBottomLeft(IBlockAccess iblockaccess, EnumDirection enumdirection, BlockPosition blockposition) { -+ private static BlockPosition calculateBottomLeft(IBlockAccess iblockaccess, EnumDirection enumdirection, BlockPosition blockposition, BlockStateListPopulator blocks) { // CraftBukkit +- private static BlockPos calculateBottomLeft(IBlockAccess iblockaccess, EnumDirection enumdirection, BlockPos blockposition) { ++ private static BlockPos calculateBottomLeft(IBlockAccess iblockaccess, EnumDirection enumdirection, BlockPos blockposition, BlockStateListPopulator blocks) { // CraftBukkit for (int i = Math.max(iblockaccess.getMinY(), blockposition.getY() - 21); blockposition.getY() > i && isEmpty(iblockaccess.getBlockState(blockposition.below())); blockposition = blockposition.below()) { ; } @@ -70,17 +70,17 @@ return j < 0 ? null : blockposition.relative(enumdirection1, j); } -- private static int calculateWidth(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { +- private static int calculateWidth(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection) { - int i = getDistanceUntilEdgeAboveFrame(iblockaccess, blockposition, enumdirection); -+ private static int calculateWidth(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockStateListPopulator blocks) { // CraftBukkit ++ private static int calculateWidth(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, BlockStateListPopulator blocks) { // CraftBukkit + int i = getDistanceUntilEdgeAboveFrame(iblockaccess, blockposition, enumdirection, blocks); // CraftBukkit return i >= 2 && i <= 21 ? i : 0; } -- private static int getDistanceUntilEdgeAboveFrame(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { -+ private static int getDistanceUntilEdgeAboveFrame(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockStateListPopulator blocks) { // CraftBukkit - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); +- private static int getDistanceUntilEdgeAboveFrame(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection) { ++ private static int getDistanceUntilEdgeAboveFrame(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, BlockStateListPopulator blocks) { // CraftBukkit + BlockPos.MutableBlockPos blockposition_mutableblockposition = new BlockPos.MutableBlockPos(); for (int i = 0; i <= 21; ++i) { @@ -115,6 +125,7 @@ @@ -101,9 +101,9 @@ return 0; } -- private static int calculateHeight(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, int i, MutableInt mutableint) { -+ private static int calculateHeight(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, int i, MutableInt mutableint, BlockStateListPopulator blocks) { // CraftBukkit - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); +- private static int calculateHeight(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, int i, MutableInt mutableint) { ++ private static int calculateHeight(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, int i, MutableInt mutableint, BlockStateListPopulator blocks) { // CraftBukkit + BlockPos.MutableBlockPos blockposition_mutableblockposition = new BlockPos.MutableBlockPos(); - int j = getDistanceUntilTop(iblockaccess, blockposition, enumdirection, blockposition_mutableblockposition, i, mutableint); + int j = getDistanceUntilTop(iblockaccess, blockposition, enumdirection, blockposition_mutableblockposition, i, mutableint, blocks); // CraftBukkit @@ -111,10 +111,10 @@ + return j >= 3 && j <= 21 && hasTopFrame(iblockaccess, blockposition, enumdirection, blockposition_mutableblockposition, i, j, blocks) ? j : 0; // CraftBukkit } -- private static boolean hasTopFrame(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition.MutableBlockPosition blockposition_mutableblockposition, int i, int j) { -+ private static boolean hasTopFrame(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition.MutableBlockPosition blockposition_mutableblockposition, int i, int j, BlockStateListPopulator blocks) { // CraftBukkit +- private static boolean hasTopFrame(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos.MutableBlockPos blockposition_mutableblockposition, int i, int j) { ++ private static boolean hasTopFrame(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos.MutableBlockPos blockposition_mutableblockposition, int i, int j, BlockStateListPopulator blocks) { // CraftBukkit for (int k = 0; k < i; ++k) { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition1 = blockposition_mutableblockposition.set(blockposition).move(EnumDirection.UP, j).move(enumdirection, k); + BlockPos.MutableBlockPos blockposition_mutableblockposition1 = blockposition_mutableblockposition.set(blockposition).move(EnumDirection.UP, j).move(enumdirection, k); if (!BlockPortalShape.FRAME.test(iblockaccess.getBlockState(blockposition_mutableblockposition1), iblockaccess, blockposition_mutableblockposition1)) { return false; @@ -125,8 +125,8 @@ return true; } -- private static int getDistanceUntilTop(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition.MutableBlockPosition blockposition_mutableblockposition, int i, MutableInt mutableint) { -+ private static int getDistanceUntilTop(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection, BlockPosition.MutableBlockPosition blockposition_mutableblockposition, int i, MutableInt mutableint, BlockStateListPopulator blocks) { // CraftBukkit +- private static int getDistanceUntilTop(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos.MutableBlockPos blockposition_mutableblockposition, int i, MutableInt mutableint) { ++ private static int getDistanceUntilTop(IBlockAccess iblockaccess, BlockPos blockposition, EnumDirection enumdirection, BlockPos.MutableBlockPos blockposition_mutableblockposition, int i, MutableInt mutableint, BlockStateListPopulator blocks) { // CraftBukkit for (int j = 0; j < 21; ++j) { blockposition_mutableblockposition.set(blockposition).move(EnumDirection.UP, j).move(enumdirection, -1); if (!BlockPortalShape.FRAME.test(iblockaccess.getBlockState(blockposition_mutableblockposition), iblockaccess, blockposition_mutableblockposition)) { @@ -153,7 +153,7 @@ + // Copy below for loop IBlockData iblockdata = (IBlockData) Blocks.NETHER_PORTAL.defaultBlockState().setValue(BlockPortal.AXIS, this.axis); - BlockPosition.betweenClosed(this.bottomLeft, this.bottomLeft.relative(EnumDirection.UP, this.height - 1).relative(this.rightDir, this.width - 1)).forEach((blockposition) -> { + BlockPos.betweenClosed(this.bottomLeft, this.bottomLeft.relative(EnumDirection.UP, this.height - 1).relative(this.rightDir, this.width - 1)).forEach((blockposition) -> { + blocks.setBlock(blockposition, iblockdata, 18); + }); + @@ -164,7 +164,7 @@ + return false; + } + // CraftBukkit end -+ BlockPosition.betweenClosed(this.bottomLeft, this.bottomLeft.relative(EnumDirection.UP, this.height - 1).relative(this.rightDir, this.width - 1)).forEach((blockposition) -> { ++ BlockPos.betweenClosed(this.bottomLeft, this.bottomLeft.relative(EnumDirection.UP, this.height - 1).relative(this.rightDir, this.width - 1)).forEach((blockposition) -> { generatoraccess.setBlock(blockposition, iblockdata, 18); }); + return true; // CraftBukkit diff --git a/nms-patches/net/minecraft/world/level/portal/PortalTravelAgent.patch b/nms-patches/net/minecraft/world/level/portal/PortalTravelAgent.patch index 0f5b050a..c52c052d 100644 --- a/nms-patches/net/minecraft/world/level/portal/PortalTravelAgent.patch +++ b/nms-patches/net/minecraft/world/level/portal/PortalTravelAgent.patch @@ -3,12 +3,12 @@ @@ -43,23 +43,35 @@ } - public Optional findClosestPortalPosition(BlockPosition blockposition, boolean flag, WorldBorder worldborder) { + public Optional findClosestPortalPosition(BlockPos blockposition, boolean flag, WorldBorder worldborder) { + // CraftBukkit start + return findClosestPortalPosition(blockposition, worldborder, flag ? 16 : 128); // Search Radius + } + -+ public Optional findClosestPortalPosition(BlockPosition blockposition, WorldBorder worldborder, int i) { ++ public Optional findClosestPortalPosition(BlockPos blockposition, WorldBorder worldborder, int i) { VillagePlace villageplace = this.level.getPoiManager(); - int i = flag ? 16 : 128; + // int i = flag ? 16 : 128; @@ -16,7 +16,7 @@ villageplace.ensureLoadedAndValid(this.level, blockposition, i); - Stream stream = villageplace.getInSquare((holder) -> { -+ Stream stream = villageplace.getInSquare((holder) -> { // CraftBukkit - decompile error ++ Stream stream = villageplace.getInSquare((holder) -> { // CraftBukkit - decompile error return holder.is(PoiTypes.NETHER_PORTAL); }, blockposition, i, VillagePlace.Occupancy.ANY).map(VillagePlaceRecord::getPos); @@ -24,27 +24,27 @@ return stream.filter(worldborder::isWithinBounds).filter((blockposition1) -> { return this.level.getBlockState(blockposition1).hasProperty(BlockProperties.HORIZONTAL_AXIS); - }).min(Comparator.comparingDouble((blockposition1) -> { -+ }).min(Comparator.comparingDouble((BlockPosition blockposition1) -> { // CraftBukkit - decompile error ++ }).min(Comparator.comparingDouble((BlockPos blockposition1) -> { // CraftBukkit - decompile error return blockposition1.distSqr(blockposition); - }).thenComparingInt(BaseBlockPosition::getY)); + }).thenComparingInt(BaseBlockPos::getY)); } - public Optional createPortal(BlockPosition blockposition, EnumDirection.EnumAxis enumdirection_enumaxis) { + public Optional createPortal(BlockPos blockposition, EnumDirection.EnumAxis enumdirection_enumaxis) { + // CraftBukkit start + return this.createPortal(blockposition, enumdirection_enumaxis, null, 16); + } + -+ public Optional createPortal(BlockPosition blockposition, EnumDirection.EnumAxis enumdirection_enumaxis, net.minecraft.world.entity.Entity entity, int createRadius) { ++ public Optional createPortal(BlockPos blockposition, EnumDirection.EnumAxis enumdirection_enumaxis, net.minecraft.world.entity.Entity entity, int createRadius) { + // CraftBukkit end EnumDirection enumdirection = EnumDirection.get(EnumDirection.EnumAxisDirection.POSITIVE, enumdirection_enumaxis); double d0 = -1.0D; - BlockPosition blockposition1 = null; + BlockPos blockposition1 = null; @@ -69,7 +81,7 @@ int i = Math.min(this.level.getMaxY(), this.level.getMinY() + this.level.getLogicalHeight() - 1); boolean flag = true; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = blockposition.mutable(); -- Iterator iterator = BlockPosition.spiralAround(blockposition, 16, EnumDirection.EAST, EnumDirection.SOUTH).iterator(); -+ Iterator iterator = BlockPosition.spiralAround(blockposition, createRadius, EnumDirection.EAST, EnumDirection.SOUTH).iterator(); // CraftBukkit + BlockPos.MutableBlockPos blockposition_mutableblockposition = blockposition.mutable(); +- Iterator iterator = BlockPos.spiralAround(blockposition, 16, EnumDirection.EAST, EnumDirection.SOUTH).iterator(); ++ Iterator iterator = BlockPos.spiralAround(blockposition, createRadius, EnumDirection.EAST, EnumDirection.SOUTH).iterator(); // CraftBukkit int j; int k; diff --git a/nms-patches/net/minecraft/world/level/redstone/DefaultRedstoneWireEvaluator.patch b/nms-patches/net/minecraft/world/level/redstone/DefaultRedstoneWireEvaluator.patch index c98450b0..50aaa8bd 100644 --- a/nms-patches/net/minecraft/world/level/redstone/DefaultRedstoneWireEvaluator.patch +++ b/nms-patches/net/minecraft/world/level/redstone/DefaultRedstoneWireEvaluator.patch @@ -13,7 +13,7 @@ public DefaultRedstoneWireEvaluator(BlockRedstoneWire blockredstonewire) { @@ -20,7 +25,16 @@ - public void updatePowerStrength(World world, BlockPosition blockposition, IBlockData iblockdata, @Nullable Orientation orientation, boolean flag) { + public void updatePowerStrength(World world, BlockPos blockposition, IBlockData iblockdata, @Nullable Orientation orientation, boolean flag) { int i = this.calculateTargetStrength(world, blockposition); - if ((Integer) iblockdata.getValue(BlockRedstoneWire.POWER) != i) { diff --git a/nms-patches/net/minecraft/world/level/redstone/ExperimentalRedstoneWireEvaluator.patch b/nms-patches/net/minecraft/world/level/redstone/ExperimentalRedstoneWireEvaluator.patch index 16399707..0323d4cf 100644 --- a/nms-patches/net/minecraft/world/level/redstone/ExperimentalRedstoneWireEvaluator.patch +++ b/nms-patches/net/minecraft/world/level/redstone/ExperimentalRedstoneWireEvaluator.patch @@ -11,7 +11,7 @@ + public class ExperimentalRedstoneWireEvaluator extends RedstoneWireEvaluator { - private final Deque wiresToTurnOff = new ArrayDeque(); + private final Deque wiresToTurnOff = new ArrayDeque(); @@ -41,7 +46,16 @@ int j = unpackPower(i); IBlockData iblockdata1 = world.getBlockState(blockposition1); diff --git a/nms-patches/net/minecraft/world/level/redstone/NeighborUpdater.patch b/nms-patches/net/minecraft/world/level/redstone/NeighborUpdater.patch index 3d8cac6f..e5760942 100644 --- a/nms-patches/net/minecraft/world/level/redstone/NeighborUpdater.patch +++ b/nms-patches/net/minecraft/world/level/redstone/NeighborUpdater.patch @@ -16,7 +16,7 @@ @@ -50,6 +57,17 @@ - static void executeUpdate(World world, IBlockData iblockdata, BlockPosition blockposition, Block block, @Nullable Orientation orientation, boolean flag) { + static void executeUpdate(World world, IBlockData iblockdata, BlockPos blockposition, Block block, @Nullable Orientation orientation, boolean flag) { try { + // CraftBukkit start + CraftWorld cworld = ((WorldServer) world).getWorld(); diff --git a/nms-patches/net/minecraft/world/level/storage/WorldDataServer.patch b/nms-patches/net/minecraft/world/level/storage/WorldDataServer.patch index cf2dffac..7db54e49 100644 --- a/nms-patches/net/minecraft/world/level/storage/WorldDataServer.patch +++ b/nms-patches/net/minecraft/world/level/storage/WorldDataServer.patch @@ -39,7 +39,7 @@ + } + // CraftBukkit end - private WorldDataServer(@Nullable NBTTagCompound nbttagcompound, boolean flag, BlockPosition blockposition, float f, long i, long j, int k, int l, int i1, boolean flag1, int j1, boolean flag2, boolean flag3, boolean flag4, WorldBorder.c worldborder_c, int k1, int l1, @Nullable UUID uuid, Set set, Set set1, CustomFunctionCallbackTimerQueue customfunctioncallbacktimerqueue, @Nullable NBTTagCompound nbttagcompound1, EnderDragonBattle.a enderdragonbattle_a, WorldSettings worldsettings, WorldOptions worldoptions, WorldDataServer.a worlddataserver_a, Lifecycle lifecycle) { + private WorldDataServer(@Nullable NBTTagCompound nbttagcompound, boolean flag, BlockPos blockposition, float f, long i, long j, int k, int l, int i1, boolean flag1, int j1, boolean flag2, boolean flag3, boolean flag4, WorldBorder.c worldborder_c, int k1, int l1, @Nullable UUID uuid, Set set, Set set1, CustomFunctionCallbackTimerQueue customfunctioncallbacktimerqueue, @Nullable NBTTagCompound nbttagcompound1, EnderDragonBattle.a enderdragonbattle_a, WorldSettings worldsettings, WorldOptions worldoptions, WorldDataServer.a worlddataserver_a, Lifecycle lifecycle) { this.wasModded = flag; @@ -116,7 +143,7 @@ diff --git a/src/main/java/com/mojang/brigadier/CommandDispatcher.java b/src/main/java/com/mojang/brigadier/CommandDispatcher.java new file mode 100644 index 00000000..b851f9a4 --- /dev/null +++ b/src/main/java/com/mojang/brigadier/CommandDispatcher.java @@ -0,0 +1,651 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +package com.mojang.brigadier; + +// CHECKSTYLE:OFF +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.context.CommandContextBuilder; +import com.mojang.brigadier.context.ContextChain; +import com.mojang.brigadier.context.SuggestionContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import com.mojang.brigadier.tree.CommandNode; +import com.mojang.brigadier.tree.LiteralCommandNode; +import com.mojang.brigadier.tree.RootCommandNode; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.Predicate; +import java.util.stream.Collectors; + + +/** + * The core command dispatcher, for registering, parsing, and executing commands. + * + * @param a custom "source" type, such as a user or originator of a command + */ +public class CommandDispatcher { + /** + * The string required to separate individual arguments in an input string + * + * @see #ARGUMENT_SEPARATOR_CHAR + */ + public static final String ARGUMENT_SEPARATOR = " "; + + /** + * The char required to separate individual arguments in an input string + * + * @see #ARGUMENT_SEPARATOR + */ + public static final char ARGUMENT_SEPARATOR_CHAR = ' '; + + private static final String USAGE_OPTIONAL_OPEN = "["; + private static final String USAGE_OPTIONAL_CLOSE = "]"; + private static final String USAGE_REQUIRED_OPEN = "("; + private static final String USAGE_REQUIRED_CLOSE = ")"; + private static final String USAGE_OR = "|"; + + private final RootCommandNode root; + + private final Predicate> hasCommand = new Predicate>() { + @Override + public boolean test(final CommandNode input) { + return input != null && (input.getCommand() != null || input.getChildren().stream().anyMatch(hasCommand)); + } + }; + private ResultConsumer consumer = (c, s, r) -> { + }; + + /** + * Create a new {@link CommandDispatcher} with the specified root node. + * + *

This is often useful to copy existing or pre-defined command trees.

+ * + * @param root the existing {@link RootCommandNode} to use as the basis for this tree + */ + public CommandDispatcher(final RootCommandNode root) { + this.root = root; + } + + /** + * Creates a new {@link CommandDispatcher} with an empty command tree. + */ + public CommandDispatcher() { + this(new RootCommandNode<>()); + } + + /** + * Utility method for registering new commands. + * + *

This is a shortcut for calling {@link RootCommandNode#addChild(CommandNode)} after building the provided {@code command}.

+ * + *

As {@link RootCommandNode} can only hold literals, this method will only allow literal arguments.

+ * + * @param command a literal argument builder to add to this command tree + * @return the node added to this tree + */ + public LiteralCommandNode register(final LiteralArgumentBuilder command) { + final LiteralCommandNode build = command.build(); + root.addChild(build); + return build; + } + + /** + * Sets a callback to be informed of the result of every command. + * + * @param consumer the new result consumer to be called + */ + public void setConsumer(final ResultConsumer consumer) { + this.consumer = consumer; + } + + /** + * Parses and executes a given command. + * + *

This is a shortcut to first {@link #parse(StringReader, Object)} and then {@link #execute(ParseResults)}.

+ * + *

It is recommended to parse and execute as separate steps, as parsing is often the most expensive step, and easiest to cache.

+ * + *

If this command returns a value, then it successfully executed something. If it could not parse the command, or the execution was a failure, + * then an exception will be thrown. Most exceptions will be of type {@link CommandSyntaxException}, but it is possible that a {@link RuntimeException} + * may bubble up from the result of a command. The meaning behind the returned result is arbitrary, and will depend + * entirely on what command was performed.

+ * + *

If the command passes through a node that is {@link CommandNode#isFork()} then it will be 'forked'. + * A forked command will not bubble up any {@link CommandSyntaxException}s, and the 'result' returned will turn into + * 'amount of successful commands executes'.

+ * + *

After each and any command is ran, a registered callback given to {@link #setConsumer(ResultConsumer)} + * will be notified of the result and success of the command. You can use that method to gather more meaningful + * results than this method will return, especially when a command forks.

+ * + * @param input a command string to parse & execute + * @param source a custom "source" object, usually representing the originator of this command + * @return a numeric result from a "command" that was performed + * @throws CommandSyntaxException if the command failed to parse or execute + * @throws RuntimeException if the command failed to execute and was not handled gracefully + * @see #parse(String, Object) + * @see #parse(StringReader, Object) + * @see #execute(ParseResults) + * @see #execute(StringReader, Object) + */ + public int execute(final String input, final S source) throws CommandSyntaxException { + return execute(new StringReader(input), source); + } + + /** + * Parses and executes a given command. + * + *

This is a shortcut to first {@link #parse(StringReader, Object)} and then {@link #execute(ParseResults)}.

+ * + *

It is recommended to parse and execute as separate steps, as parsing is often the most expensive step, and easiest to cache.

+ * + *

If this command returns a value, then it successfully executed something. If it could not parse the command, or the execution was a failure, + * then an exception will be thrown. Most exceptions will be of type {@link CommandSyntaxException}, but it is possible that a {@link RuntimeException} + * may bubble up from the result of a command. The meaning behind the returned result is arbitrary, and will depend + * entirely on what command was performed.

+ * + *

If the command passes through a node that is {@link CommandNode#isFork()} then it will be 'forked'. + * A forked command will not bubble up any {@link CommandSyntaxException}s, and the 'result' returned will turn into + * 'amount of successful commands executes'.

+ * + *

After each and any command is ran, a registered callback given to {@link #setConsumer(ResultConsumer)} + * will be notified of the result and success of the command. You can use that method to gather more meaningful + * results than this method will return, especially when a command forks.

+ * + * @param input a command string to parse & execute + * @param source a custom "source" object, usually representing the originator of this command + * @return a numeric result from a "command" that was performed + * @throws CommandSyntaxException if the command failed to parse or execute + * @throws RuntimeException if the command failed to execute and was not handled gracefully + * @see #parse(String, Object) + * @see #parse(StringReader, Object) + * @see #execute(ParseResults) + * @see #execute(String, Object) + */ + public int execute(final StringReader input, final S source) throws CommandSyntaxException { + final ParseResults parse = parse(input, source); + return execute(parse); + } + + /** + * Executes a given pre-parsed command. + * + *

If this command returns a value, then it successfully executed something. If the execution was a failure, + * then an exception will be thrown. + * Most exceptions will be of type {@link CommandSyntaxException}, but it is possible that a {@link RuntimeException} + * may bubble up from the result of a command. The meaning behind the returned result is arbitrary, and will depend + * entirely on what command was performed.

+ * + *

If the command passes through a node that is {@link CommandNode#isFork()} then it will be 'forked'. + * A forked command will not bubble up any {@link CommandSyntaxException}s, and the 'result' returned will turn into + * 'amount of successful commands executes'.

+ * + *

After each and any command is ran, a registered callback given to {@link #setConsumer(ResultConsumer)} + * will be notified of the result and success of the command. You can use that method to gather more meaningful + * results than this method will return, especially when a command forks.

+ * + * @param parse the result of a successful {@link #parse(StringReader, Object)} + * @return a numeric result from a "command" that was performed. + * @throws CommandSyntaxException if the command failed to parse or execute + * @throws RuntimeException if the command failed to execute and was not handled gracefully + * @see #parse(String, Object) + * @see #parse(StringReader, Object) + * @see #execute(String, Object) + * @see #execute(StringReader, Object) + */ + public int execute(final ParseResults parse) throws CommandSyntaxException { + if (parse.getReader().canRead()) { + if (parse.getExceptions().size() == 1) { + throw parse.getExceptions().values().iterator().next(); + } else if (parse.getContext().getRange().isEmpty()) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parse.getReader()); + } else { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(parse.getReader()); + } + } + + final String command = parse.getReader().getString(); + final CommandContext original = parse.getContext().build(command); + + final Optional> flatContext = ContextChain.tryFlatten(original); + if (!flatContext.isPresent()) { + consumer.onCommandComplete(original, false, 0); + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parse.getReader()); + } + + return flatContext.get().executeAll(original.getSource(), consumer); + } + + /** + * Parses a given command. + * + *

The result of this method can be cached, and it is advised to do so where appropriate. Parsing is often the + * most expensive step, and this allows you to essentially "precompile" a command if it will be ran often.

+ * + *

If the command passes through a node that is {@link CommandNode#isFork()} then the resulting context will be marked as 'forked'. + * Forked contexts may contain child contexts, which may be modified by the {@link RedirectModifier} attached to the fork.

+ * + *

Parsing a command can never fail, you will always be provided with a new {@link ParseResults}. + * However, that does not mean that it will always parse into a valid command. You should inspect the returned results + * to check for validity. If its {@link ParseResults#getReader()} {@link StringReader#canRead()} then it did not finish + * parsing successfully. You can use that position as an indicator to the user where the command stopped being valid. + * You may inspect {@link ParseResults#getExceptions()} if you know the parse failed, as it will explain why it could + * not find any valid commands. It may contain multiple exceptions, one for each "potential node" that it could have visited, + * explaining why it did not go down that node.

+ * + *

When you eventually call {@link #execute(ParseResults)} with the result of this method, the above error checking + * will occur. You only need to inspect it yourself if you wish to handle that yourself.

+ * + * @param command a command string to parse + * @param source a custom "source" object, usually representing the originator of this command + * @return the result of parsing this command + * @see #parse(StringReader, Object) + * @see #execute(ParseResults) + * @see #execute(String, Object) + */ + public ParseResults parse(final String command, final S source) { + return parse(new StringReader(command), source); + } + + /** + * Parses a given command. + * + *

The result of this method can be cached, and it is advised to do so where appropriate. Parsing is often the + * most expensive step, and this allows you to essentially "precompile" a command if it will be ran often.

+ * + *

If the command passes through a node that is {@link CommandNode#isFork()} then the resulting context will be marked as 'forked'. + * Forked contexts may contain child contexts, which may be modified by the {@link RedirectModifier} attached to the fork.

+ * + *

Parsing a command can never fail, you will always be provided with a new {@link ParseResults}. + * However, that does not mean that it will always parse into a valid command. You should inspect the returned results + * to check for validity. If its {@link ParseResults#getReader()} {@link StringReader#canRead()} then it did not finish + * parsing successfully. You can use that position as an indicator to the user where the command stopped being valid. + * You may inspect {@link ParseResults#getExceptions()} if you know the parse failed, as it will explain why it could + * not find any valid commands. It may contain multiple exceptions, one for each "potential node" that it could have visited, + * explaining why it did not go down that node.

+ * + *

When you eventually call {@link #execute(ParseResults)} with the result of this method, the above error checking + * will occur. You only need to inspect it yourself if you wish to handle that yourself.

+ * + * @param command a command string to parse + * @param source a custom "source" object, usually representing the originator of this command + * @return the result of parsing this command + * @see #parse(String, Object) + * @see #execute(ParseResults) + * @see #execute(String, Object) + */ + public ParseResults parse(final StringReader command, final S source) { + final CommandContextBuilder context = new CommandContextBuilder<>(this, source, root, command.getCursor()); + return parseNodes(root, command, context); + } + + private ParseResults parseNodes(final CommandNode node, final StringReader originalReader, final CommandContextBuilder contextSoFar) { + final S source = contextSoFar.getSource(); + Map, CommandSyntaxException> errors = null; + List> potentials = null; + final int cursor = originalReader.getCursor(); + + for (final CommandNode child : node.getRelevantNodes(originalReader)) { + if (!child.canUse(source)) { + continue; + } + final CommandContextBuilder context = contextSoFar.copy(); + final StringReader reader = new StringReader(originalReader); + try { + try { + child.parse(reader, context); + } catch (final RuntimeException ex) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherParseException().createWithContext(reader, ex.getMessage()); + } + if (reader.canRead()) { + if (reader.peek() != ARGUMENT_SEPARATOR_CHAR) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherExpectedArgumentSeparator().createWithContext(reader); + } + } + } catch (final CommandSyntaxException ex) { + if (errors == null) { + errors = new LinkedHashMap<>(); + } + errors.put(child, ex); + reader.setCursor(cursor); + continue; + } + + context.withCommand(child.getCommand()); + if (reader.canRead(child.getRedirect() == null ? 2 : 1)) { + reader.skip(); + if (child.getRedirect() != null) { + final CommandContextBuilder childContext = new CommandContextBuilder<>(this, source, child.getRedirect(), reader.getCursor()); + final ParseResults parse = parseNodes(child.getRedirect(), reader, childContext); + context.withChild(parse.getContext()); + return new ParseResults<>(context, parse.getReader(), parse.getExceptions()); + } else { + final ParseResults parse = parseNodes(child, reader, context); + if (potentials == null) { + potentials = new ArrayList<>(1); + } + potentials.add(parse); + } + } else { + if (potentials == null) { + potentials = new ArrayList<>(1); + } + potentials.add(new ParseResults<>(context, reader, Collections.emptyMap())); + } + } + + if (potentials != null) { + if (potentials.size() > 1) { + potentials.sort((a, b) -> { + if (!a.getReader().canRead() && b.getReader().canRead()) { + return -1; + } + if (a.getReader().canRead() && !b.getReader().canRead()) { + return 1; + } + if (a.getExceptions().isEmpty() && !b.getExceptions().isEmpty()) { + return -1; + } + if (!a.getExceptions().isEmpty() && b.getExceptions().isEmpty()) { + return 1; + } + return 0; + }); + } + return potentials.get(0); + } + + return new ParseResults<>(contextSoFar, originalReader, errors == null ? Collections.emptyMap() : errors); + } + + /** + * Gets all possible executable commands following the given node. + * + *

You may use {@link #getRoot()} as a target to get all usage data for the entire command tree.

+ * + *

The returned syntax will be in "simple" form: {@code } and {@code literal}. "Optional" nodes will be + * listed as multiple entries: the parent node, and the child nodes. + * For example, a required literal "foo" followed by an optional param "int" will be two nodes:

+ *
    + *
  • {@code foo}
  • + *
  • {@code foo }
  • + *
+ * + *

The path to the specified node will not be prepended to the output, as there can theoretically be many + * ways to reach a given node. It will only give you paths relative to the specified node, not absolute from root.

+ * + * @param node target node to get child usage strings for + * @param source a custom "source" object, usually representing the originator of this command + * @param restricted if true, commands that the {@code source} cannot access will not be mentioned + * @return array of full usage strings under the target node + */ + public String[] getAllUsage(final CommandNode node, final S source, final boolean restricted) { + final ArrayList result = new ArrayList<>(); + getAllUsage(node, source, result, "", restricted); + return result.toArray(new String[result.size()]); + } + + private void getAllUsage(final CommandNode node, final S source, final ArrayList result, final String prefix, final boolean restricted) { + if (restricted && !node.canUse(source)) { + return; + } + + if (node.getCommand() != null) { + result.add(prefix); + } + + if (node.getRedirect() != null) { + final String redirect = node.getRedirect() == root ? "..." : "-> " + node.getRedirect().getUsageText(); + result.add(prefix.isEmpty() ? node.getUsageText() + ARGUMENT_SEPARATOR + redirect : prefix + ARGUMENT_SEPARATOR + redirect); + } else if (!node.getChildren().isEmpty()) { + for (final CommandNode child : node.getChildren()) { + getAllUsage(child, source, result, prefix.isEmpty() ? child.getUsageText() : prefix + ARGUMENT_SEPARATOR + child.getUsageText(), restricted); + } + } + } + + /** + * Gets the possible executable commands from a specified node. + * + *

You may use {@link #getRoot()} as a target to get usage data for the entire command tree.

+ * + *

The returned syntax will be in "smart" form: {@code }, {@code literal}, {@code [optional]} and {@code (either|or)}. + * These forms may be mixed and matched to provide as much information about the child nodes as it can, without being too verbose. + * For example, a required literal "foo" followed by an optional param "int" can be compressed into one string:

+ *
    + *
  • {@code foo []}
  • + *
+ * + *

The path to the specified node will not be prepended to the output, as there can theoretically be many + * ways to reach a given node. It will only give you paths relative to the specified node, not absolute from root.

+ * + *

The returned usage will be restricted to only commands that the provided {@code source} can use.

+ * + * @param node target node to get child usage strings for + * @param source a custom "source" object, usually representing the originator of this command + * @return array of full usage strings under the target node + */ + public Map, String> getSmartUsage(final CommandNode node, final S source) { + final Map, String> result = new LinkedHashMap<>(); + + final boolean optional = node.getCommand() != null; + for (final CommandNode child : node.getChildren()) { + final String usage = getSmartUsage(child, source, optional, false); + if (usage != null) { + result.put(child, usage); + } + } + return result; + } + + private String getSmartUsage(final CommandNode node, final S source, final boolean optional, final boolean deep) { + if (!node.canUse(source)) { + return null; + } + + final String self = optional ? USAGE_OPTIONAL_OPEN + node.getUsageText() + USAGE_OPTIONAL_CLOSE : node.getUsageText(); + final boolean childOptional = node.getCommand() != null; + final String open = childOptional ? USAGE_OPTIONAL_OPEN : USAGE_REQUIRED_OPEN; + final String close = childOptional ? USAGE_OPTIONAL_CLOSE : USAGE_REQUIRED_CLOSE; + + if (!deep) { + if (node.getRedirect() != null) { + final String redirect = node.getRedirect() == root ? "..." : "-> " + node.getRedirect().getUsageText(); + return self + ARGUMENT_SEPARATOR + redirect; + } else { + final Collection> children = node.getChildren().stream().filter(c -> c.canUse(source)).collect(Collectors.toList()); + if (children.size() == 1) { + final String usage = getSmartUsage(children.iterator().next(), source, childOptional, childOptional); + if (usage != null) { + return self + ARGUMENT_SEPARATOR + usage; + } + } else if (children.size() > 1) { + final Set childUsage = new LinkedHashSet<>(); + for (final CommandNode child : children) { + final String usage = getSmartUsage(child, source, childOptional, true); + if (usage != null) { + childUsage.add(usage); + } + } + if (childUsage.size() == 1) { + final String usage = childUsage.iterator().next(); + return self + ARGUMENT_SEPARATOR + (childOptional ? USAGE_OPTIONAL_OPEN + usage + USAGE_OPTIONAL_CLOSE : usage); + } else if (childUsage.size() > 1) { + final StringBuilder builder = new StringBuilder(open); + int count = 0; + for (final CommandNode child : children) { + if (count > 0) { + builder.append(USAGE_OR); + } + builder.append(child.getUsageText()); + count++; + } + if (count > 0) { + builder.append(close); + return self + ARGUMENT_SEPARATOR + builder.toString(); + } + } + } + } + } + + return self; + } + + /** + * Gets suggestions for a parsed input string on what comes next. + * + *

As it is ultimately up to custom argument types to provide suggestions, it may be an asynchronous operation, + * for example getting in-game data or player names etc. As such, this method returns a future and no guarantees + * are made to when or how the future completes.

+ * + *

The suggestions provided will be in the context of the end of the parsed input string, but may suggest + * new or replacement strings for earlier in the input string. For example, if the end of the string was + * {@code foobar} but an argument preferred it to be {@code minecraft:foobar}, it will suggest a replacement for that + * whole segment of the input.

+ * + * @param parse the result of a {@link #parse(StringReader, Object)} + * @return a future that will eventually resolve into a {@link Suggestions} object + */ + public CompletableFuture getCompletionSuggestions(final ParseResults parse) { + return getCompletionSuggestions(parse, parse.getReader().getTotalLength()); + } + + public CompletableFuture getCompletionSuggestions(final ParseResults parse, int cursor) { + final CommandContextBuilder context = parse.getContext(); + + final SuggestionContext nodeBeforeCursor = context.findSuggestionContext(cursor); + final CommandNode parent = nodeBeforeCursor.parent; + final int start = Math.min(nodeBeforeCursor.startPos, cursor); + + final String fullInput = parse.getReader().getString(); + final String truncatedInput = fullInput.substring(0, cursor); + final String truncatedInputLowerCase = truncatedInput.toLowerCase(Locale.ROOT); + @SuppressWarnings("unchecked") final CompletableFuture[] futures = new CompletableFuture[parent.getChildren().size()]; + int i = 0; + for (final CommandNode node : parent.getChildren()) { + CompletableFuture future = Suggestions.empty(); + try { + if (node.canUse(parse.getContext().getSource())) future = node.listSuggestions(context.build(truncatedInput), new SuggestionsBuilder(truncatedInput, truncatedInputLowerCase, start)); // CraftBukkit + } catch (final CommandSyntaxException ignored) { + } + futures[i++] = future; + } + + final CompletableFuture result = new CompletableFuture<>(); + CompletableFuture.allOf(futures).thenRun(() -> { + final List suggestions = new ArrayList<>(); + for (final CompletableFuture future : futures) { + suggestions.add(future.join()); + } + result.complete(Suggestions.merge(fullInput, suggestions)); + }); + + return result; + } + + /** + * Gets the root of this command tree. + * + *

This is often useful as a target of a {@link com.mojang.brigadier.builder.ArgumentBuilder#redirect(CommandNode)}, + * {@link #getAllUsage(CommandNode, Object, boolean)} or {@link #getSmartUsage(CommandNode, Object)}. + * You may also use it to clone the command tree via {@link #CommandDispatcher(RootCommandNode)}.

+ * + * @return root of the command tree + */ + public RootCommandNode getRoot() { + return root; + } + + /** + * Finds a valid path to a given node on the command tree. + * + *

There may theoretically be multiple paths to a node on the tree, especially with the use of forking or redirecting. + * As such, this method makes no guarantees about which path it finds. It will not look at forks or redirects, + * and find the first instance of the target node on the tree.

+ * + *

The only guarantee made is that for the same command tree and the same version of this library, the result of + * this method will always be a valid input for {@link #findNode(Collection)}, which should return the same node + * as provided to this method.

+ * + * @param target the target node you are finding a path for + * @return a path to the resulting node, or an empty list if it was not found + */ + public Collection getPath(final CommandNode target) { + final List>> nodes = new ArrayList<>(); + addPaths(root, nodes, new ArrayList<>()); + + for (final List> list : nodes) { + if (list.get(list.size() - 1) == target) { + final List result = new ArrayList<>(list.size()); + for (final CommandNode node : list) { + if (node != root) { + result.add(node.getName()); + } + } + return result; + } + } + + return Collections.emptyList(); + } + + /** + * Finds a node by its path + * + *

Paths may be generated with {@link #getPath(CommandNode)}, and are guaranteed (for the same tree, and the + * same version of this library) to always produce the same valid node by this method.

+ * + *

If a node could not be found at the specified path, then {@code null} will be returned.

+ * + * @param path a generated path to a node + * @return the node at the given path, or null if not found + */ + public CommandNode findNode(final Collection path) { + CommandNode node = root; + for (final String name : path) { + node = node.getChild(name); + if (node == null) { + return null; + } + } + return node; + } + + /** + * Scans the command tree for potential ambiguous commands. + * + *

This is a shortcut for {@link CommandNode#findAmbiguities(AmbiguityConsumer)} on {@link #getRoot()}.

+ * + *

Ambiguities are detected by testing every {@link CommandNode#getExamples()} on one node verses every sibling + * node. This is not fool proof, and relies a lot on the providers of the used argument types to give good examples.

+ * + * @param consumer a callback to be notified of potential ambiguities + */ + public void findAmbiguities(final AmbiguityConsumer consumer) { + root.findAmbiguities(consumer); + } + + private void addPaths(final CommandNode node, final List>> result, final List> parents) { + final List> current = new ArrayList<>(parents); + current.add(node); + result.add(current); + + for (final CommandNode child : node.getChildren()) { + addPaths(child, result, current); + } + } +} diff --git a/src/main/java/com/mojang/brigadier/tree/CommandNode.java b/src/main/java/com/mojang/brigadier/tree/CommandNode.java new file mode 100644 index 00000000..9be5c58f --- /dev/null +++ b/src/main/java/com/mojang/brigadier/tree/CommandNode.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +package com.mojang.brigadier.tree; + +// CHECKSTYLE:OFF +import com.mojang.brigadier.AmbiguityConsumer; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.RedirectModifier; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.builder.ArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.context.CommandContextBuilder; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.Predicate; + +import net.minecraft.commands.CommandListenerWrapper; // CraftBukkit + +public abstract class CommandNode implements Comparable> { + private final Map> children = new LinkedHashMap<>(); + private final Map> literals = new LinkedHashMap<>(); + private final Map> arguments = new LinkedHashMap<>(); + private final Predicate requirement; + private final CommandNode redirect; + private final RedirectModifier modifier; + private final boolean forks; + private Command command; + // CraftBukkit start + public void removeCommand(String name) { + children.remove(name); + literals.remove(name); + arguments.remove(name); + } + // CraftBukkit end + + protected CommandNode(final Command command, final Predicate requirement, final CommandNode redirect, final RedirectModifier modifier, final boolean forks) { + this.command = command; + this.requirement = requirement; + this.redirect = redirect; + this.modifier = modifier; + this.forks = forks; + } + + public Command getCommand() { + return command; + } + + public Collection> getChildren() { + return children.values(); + } + + public CommandNode getChild(final String name) { + return children.get(name); + } + + public CommandNode getRedirect() { + return redirect; + } + + public RedirectModifier getRedirectModifier() { + return modifier; + } + + // CraftBukkit start + public synchronized boolean canUse(final S source) { + if (source instanceof CommandListenerWrapper) { + try { + ((CommandListenerWrapper) source).currentCommand = this; + return requirement.test(source); + } finally { + ((CommandListenerWrapper) source).currentCommand = null; + } + } + // CraftBukkit end + return requirement.test(source); + } + + public void addChild(final CommandNode node) { + if (node instanceof RootCommandNode) { + throw new UnsupportedOperationException("Cannot add a RootCommandNode as a child to any other CommandNode"); + } + + final CommandNode child = children.get(node.getName()); + if (child != null) { + // We've found something to merge onto + if (node.getCommand() != null) { + child.command = node.getCommand(); + } + for (final CommandNode grandchild : node.getChildren()) { + child.addChild(grandchild); + } + } else { + children.put(node.getName(), node); + if (node instanceof LiteralCommandNode) { + literals.put(node.getName(), (LiteralCommandNode) node); + } else if (node instanceof ArgumentCommandNode) { + arguments.put(node.getName(), (ArgumentCommandNode) node); + } + } + } + + public void findAmbiguities(final AmbiguityConsumer consumer) { + Set matches = new HashSet<>(); + + for (final CommandNode child : children.values()) { + for (final CommandNode sibling : children.values()) { + if (child == sibling) { + continue; + } + + for (final String input : child.getExamples()) { + if (sibling.isValidInput(input)) { + matches.add(input); + } + } + + if (matches.size() > 0) { + consumer.ambiguous(this, child, sibling, matches); + matches = new HashSet<>(); + } + } + + child.findAmbiguities(consumer); + } + } + + protected abstract boolean isValidInput(final String input); + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (!(o instanceof CommandNode)) return false; + + final CommandNode that = (CommandNode) o; + + if (!children.equals(that.children)) return false; + if (command != null ? !command.equals(that.command) : that.command != null) return false; + + return true; + } + + @Override + public int hashCode() { + return 31 * children.hashCode() + (command != null ? command.hashCode() : 0); + } + + public Predicate getRequirement() { + return requirement; + } + + public abstract String getName(); + + public abstract String getUsageText(); + + public abstract void parse(StringReader reader, CommandContextBuilder contextBuilder) throws CommandSyntaxException; + + public abstract CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) throws CommandSyntaxException; + + public abstract ArgumentBuilder createBuilder(); + + protected abstract String getSortedKey(); + + public Collection> getRelevantNodes(final StringReader input) { + if (literals.size() > 0) { + final int cursor = input.getCursor(); + while (input.canRead() && input.peek() != ' ') { + input.skip(); + } + final String text = input.getString().substring(cursor, input.getCursor()); + input.setCursor(cursor); + final LiteralCommandNode literal = literals.get(text); + if (literal != null) { + return Collections.singleton(literal); + } else { + return arguments.values(); + } + } else { + return arguments.values(); + } + } + + @Override + public int compareTo(final CommandNode o) { + if (this instanceof LiteralCommandNode == o instanceof LiteralCommandNode) { + return getSortedKey().compareTo(o.getSortedKey()); + } + + return (o instanceof LiteralCommandNode) ? 1 : -1; + } + + public boolean isFork() { + return forks; + } + + public abstract Collection getExamples(); +} diff --git a/src/main/java/net/neoforged/neoforge/client/ClientHooks.java b/src/main/java/net/neoforged/neoforge/client/ClientHooks.java index 0132b8a8..a9472815 100644 --- a/src/main/java/net/neoforged/neoforge/client/ClientHooks.java +++ b/src/main/java/net/neoforged/neoforge/client/ClientHooks.java @@ -418,9 +418,9 @@ private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, i public static Vector4f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) { // Modify fog color depending on the fluid - FluidState state = level.getFluidState(camera.getBlockPosition()); + FluidState state = level.getFluidState(camera.getBlockPos()); Vector4f fluidFogColor = new Vector4f(fogRed, fogGreen, fogBlue, 1F); - if (camera.getPosition().y < (double) ((float) camera.getBlockPosition().getY() + state.getHeight(level, camera.getBlockPosition()))) + if (camera.getPosition().y < (double) ((float) camera.getBlockPos().getY() + state.getHeight(level, camera.getBlockPos()))) fluidFogColor = IClientFluidTypeExtensions.of(state).modifyFogColor(camera, partialTick, level, renderDistance, darkenWorldAmount, fluidFogColor); ViewportEvent.ComputeFogColor event = new ViewportEvent.ComputeFogColor(camera, partialTick, fluidFogColor.x(), fluidFogColor.y(), fluidFogColor.z()); @@ -432,8 +432,8 @@ public static Vector4f getFogColor(Camera camera, float partialTick, ClientLevel public static FogParameters onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, FogParameters fogParameters) { // Modify fog rendering depending on the fluid - FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPosition()); - if (camera.getPosition().y < (double) ((float) camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPosition()))) + FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPos()); + if (camera.getPosition().y < (double) ((float) camera.getBlockPos().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPos()))) fogParameters = IClientFluidTypeExtensions.of(state).modifyFogRender(camera, mode, renderDistance, partialTick, fogParameters); ViewportEvent.RenderFog event = new ViewportEvent.RenderFog(mode, type, camera, partialTick, fogParameters); diff --git a/src/main/java/org/bukkit/craftbukkit/CraftArt.java b/src/main/java/org/bukkit/craftbukkit/CraftArt.java index a4f3edb4..e67ec2ea 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftArt.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftArt.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.decoration.PaintingVariant; import org.bukkit.Art; @@ -13,7 +14,7 @@ public class CraftArt { public static Art minecraftToBukkit(PaintingVariant minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.PAINTING_VARIANT); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.PAINTING_VARIANT); Art bukkit = Registry.ART.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); @@ -22,7 +23,7 @@ public static Art minecraftToBukkit(PaintingVariant minecraft) { } public static Art minecraftHolderToBukkit(Holder minecraft) { - return CraftArt.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static PaintingVariant bukkitToMinecraft(Art bukkit) { @@ -35,9 +36,9 @@ public static PaintingVariant bukkitToMinecraft(Art bukkit) { public static Holder bukkitToMinecraftHolder(Art bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.PAINTING_VARIANT); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.PAINTING_VARIANT); - if (registry.wrapAsHolder(CraftArt.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftChunk.java b/src/main/java/org/bukkit/craftbukkit/CraftChunk.java index fd8a638a..3ae17396 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftChunk.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftChunk.java @@ -11,29 +11,31 @@ import java.util.function.Predicate; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.SectionPos; +import net.minecraft.core.IRegistry; +import net.minecraft.core.SectionPosition; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.thread.ProcessorMailbox; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.LightLayer; +import net.minecraft.nbt.DynamicOpsNBT; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.server.level.WorldServer; +import net.minecraft.util.thread.ConsecutiveExecutor; +import net.minecraft.world.level.ChunkCoordIntPair; +import net.minecraft.world.level.EnumSkyBlock; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.DataLayer; -import net.minecraft.world.level.chunk.ImposterProtoChunk; -import net.minecraft.world.level.chunk.LevelChunkSection; -import net.minecraft.world.level.chunk.PalettedContainer; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.chunk.ChunkSection; +import net.minecraft.world.level.chunk.DataPaletteBlock; +import net.minecraft.world.level.chunk.IChunkAccess; +import net.minecraft.world.level.chunk.NibbleArray; import net.minecraft.world.level.chunk.PalettedContainerRO; +import net.minecraft.world.level.chunk.ProtoChunkExtension; import net.minecraft.world.level.chunk.status.ChunkStatus; -import net.minecraft.world.level.chunk.storage.ChunkSerializer; import net.minecraft.world.level.chunk.storage.EntityStorage; +import net.minecraft.world.level.chunk.storage.SerializableChunkData; import net.minecraft.world.level.entity.PersistentEntitySectionManager; -import net.minecraft.world.level.levelgen.Heightmap; -import net.minecraft.world.level.levelgen.WorldgenRandom; +import net.minecraft.world.level.levelgen.HeightMap; +import net.minecraft.world.level.levelgen.SeededRandom; import net.minecraft.world.level.lighting.LevelLightEngine; import org.bukkit.Chunk; import org.bukkit.ChunkSnapshot; @@ -53,20 +55,20 @@ import org.bukkit.plugin.Plugin; public class CraftChunk implements Chunk { - private final ServerLevel worldServer; + private final WorldServer worldServer; private final int x; private final int z; - private static final PalettedContainer emptyBlockIDs = new PalettedContainer<>(net.minecraft.world.level.block.Block.BLOCK_STATE_REGISTRY, Blocks.AIR.defaultBlockState(), PalettedContainer.Strategy.SECTION_STATES); + private static final DataPaletteBlock emptyBlockIDs = new DataPaletteBlock<>(net.minecraft.world.level.block.Block.BLOCK_STATE_REGISTRY, Blocks.AIR.defaultBlockState(), DataPaletteBlock.d.SECTION_STATES); private static final byte[] FULL_LIGHT = new byte[2048]; private static final byte[] EMPTY_LIGHT = new byte[2048]; - public CraftChunk(net.minecraft.world.level.chunk.LevelChunk chunk) { - this.worldServer = chunk.r; - this.x = chunk.getPos().x; - this.z = chunk.getPos().z; + public CraftChunk(net.minecraft.world.level.chunk.Chunk chunk) { + worldServer = chunk.level; + x = chunk.getPos().x; + z = chunk.getPos().z; } - public CraftChunk(ServerLevel worldServer, int x, int z) { + public CraftChunk(WorldServer worldServer, int x, int z) { this.worldServer = worldServer; this.x = x; this.z = z; @@ -74,18 +76,18 @@ public CraftChunk(ServerLevel worldServer, int x, int z) { @Override public World getWorld() { - return this.worldServer.getWorld(); + return worldServer.getWorld(); } public CraftWorld getCraftWorld() { - return (CraftWorld) this.getWorld(); + return (CraftWorld) getWorld(); } - public ChunkAccess getHandle(ChunkStatus chunkStatus) { - ChunkAccess chunkAccess = this.worldServer.getChunk(this.x, this.z, chunkStatus); + public IChunkAccess getHandle(ChunkStatus chunkStatus) { + IChunkAccess chunkAccess = worldServer.getChunk(x, z, chunkStatus); // SPIGOT-7332: Get unwrapped extension - if (chunkAccess instanceof ImposterProtoChunk extension) { + if (chunkAccess instanceof ProtoChunkExtension extension) { return extension.getWrapped(); } @@ -94,42 +96,42 @@ public ChunkAccess getHandle(ChunkStatus chunkStatus) { @Override public int getX() { - return this.x; + return x; } @Override public int getZ() { - return this.z; + return z; } @Override public String toString() { - return "CraftChunk{" + "x=" + this.getX() + "z=" + this.getZ() + '}'; + return "CraftChunk{" + "x=" + getX() + "z=" + getZ() + '}'; } @Override public Block getBlock(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(this.worldServer.getMinBuildHeight(), this.worldServer.getMaxBuildHeight(), x, y, z); + validateChunkCoordinates(worldServer.getMinY(), worldServer.getMaxY(), x, y, z); - return new CraftBlock(this.worldServer, new BlockPos((this.x << 4) | x, y, (this.z << 4) | z)); + return new CraftBlock(worldServer, new BlockPos((this.x << 4) | x, y, (this.z << 4) | z)); } @Override public boolean isEntitiesLoaded() { - return this.getCraftWorld().getHandle().entityManager.areEntitiesLoaded(ChunkPos.asLong(this.x, this.z)); + return getCraftWorld().getHandle().entityManager.areEntitiesLoaded(ChunkCoordIntPair.asLong(x, z)); } @Override public Entity[] getEntities() { - if (!this.isLoaded()) { - this.getWorld().getChunkAt(this.x, this.z); // Transient load for this tick + if (!isLoaded()) { + getWorld().getChunkAt(x, z); // Transient load for this tick } - PersistentEntitySectionManager entityManager = this.getCraftWorld().getHandle().entityManager; - long pair = ChunkPos.asLong(this.x, this.z); + PersistentEntitySectionManager entityManager = getCraftWorld().getHandle().entityManager; + long pair = ChunkCoordIntPair.asLong(x, z); if (entityManager.areEntitiesLoaded(pair)) { - return entityManager.getEntities(new ChunkPos(this.x, this.z)).stream() + return entityManager.getEntities(new ChunkCoordIntPair(x, z)).stream() .map(net.minecraft.world.entity.Entity::getBukkitEntity) .filter(Objects::nonNull).toArray(Entity[]::new); } @@ -137,7 +139,7 @@ public Entity[] getEntities() { entityManager.ensureChunkQueuedForLoad(pair); // Start entity loading // SPIGOT-6772: Use entity mailbox and re-schedule entities if they get unloaded - ProcessorMailbox mailbox = ((EntityStorage) entityManager.permanentStorage).entityDeserializerQueue; + ConsecutiveExecutor mailbox = ((EntityStorage) entityManager.permanentStorage).entityDeserializerQueue; BooleanSupplier supplier = () -> { // only execute inbox if our entities are not present if (entityManager.areEntitiesLoaded(pair)) { @@ -167,23 +169,23 @@ public Entity[] getEntities() { } } - return entityManager.getEntities(new ChunkPos(this.x, this.z)).stream() + return entityManager.getEntities(new ChunkCoordIntPair(x, z)).stream() .map(net.minecraft.world.entity.Entity::getBukkitEntity) .filter(Objects::nonNull).toArray(Entity[]::new); } @Override public BlockState[] getTileEntities() { - if (!this.isLoaded()) { - this.getWorld().getChunkAt(this.x, this.z); // Transient load for this tick + if (!isLoaded()) { + getWorld().getChunkAt(x, z); // Transient load for this tick } int index = 0; - ChunkAccess chunk = this.getHandle(ChunkStatus.FULL); + IChunkAccess chunk = getHandle(ChunkStatus.FULL); BlockState[] entities = new BlockState[chunk.blockEntities.size()]; for (BlockPos position : chunk.blockEntities.keySet()) { - entities[index++] = this.worldServer.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()).getState(); + entities[index++] = worldServer.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()).getState(); } return entities; @@ -191,84 +193,84 @@ public BlockState[] getTileEntities() { @Override public boolean isGenerated() { - ChunkAccess chunk = this.getHandle(ChunkStatus.EMPTY); + IChunkAccess chunk = getHandle(ChunkStatus.EMPTY); return chunk.getPersistedStatus().isOrAfter(ChunkStatus.FULL); } @Override public boolean isLoaded() { - return this.getWorld().isChunkLoaded(this); + return getWorld().isChunkLoaded(this); } @Override public boolean load() { - return this.getWorld().loadChunk(this.getX(), this.getZ(), true); + return getWorld().loadChunk(getX(), getZ(), true); } @Override public boolean load(boolean generate) { - return this.getWorld().loadChunk(this.getX(), this.getZ(), generate); + return getWorld().loadChunk(getX(), getZ(), generate); } @Override public boolean unload() { - return this.getWorld().unloadChunk(this.getX(), this.getZ()); + return getWorld().unloadChunk(getX(), getZ()); } @Override public boolean isSlimeChunk() { // 987234911L is deterimined in EntitySlime when seeing if a slime can spawn in a chunk - return WorldgenRandom.seedSlimeChunk(this.getX(), this.getZ(), this.getWorld().getSeed(), this.worldServer.spigotConfig.slimeSeed).nextInt(10) == 0; + return SeededRandom.seedSlimeChunk(getX(), getZ(), getWorld().getSeed(), 987234911L).nextInt(10) == 0; } @Override public boolean unload(boolean save) { - return this.getWorld().unloadChunk(this.getX(), this.getZ(), save); + return getWorld().unloadChunk(getX(), getZ(), save); } @Override public boolean isForceLoaded() { - return this.getWorld().isChunkForceLoaded(this.getX(), this.getZ()); + return getWorld().isChunkForceLoaded(getX(), getZ()); } @Override public void setForceLoaded(boolean forced) { - this.getWorld().setChunkForceLoaded(this.getX(), this.getZ(), forced); + getWorld().setChunkForceLoaded(getX(), getZ(), forced); } @Override public boolean addPluginChunkTicket(Plugin plugin) { - return this.getWorld().addPluginChunkTicket(this.getX(), this.getZ(), plugin); + return getWorld().addPluginChunkTicket(getX(), getZ(), plugin); } @Override public boolean removePluginChunkTicket(Plugin plugin) { - return this.getWorld().removePluginChunkTicket(this.getX(), this.getZ(), plugin); + return getWorld().removePluginChunkTicket(getX(), getZ(), plugin); } @Override public Collection getPluginChunkTickets() { - return this.getWorld().getPluginChunkTickets(this.getX(), this.getZ()); + return getWorld().getPluginChunkTickets(getX(), getZ()); } @Override public long getInhabitedTime() { - return this.getHandle(ChunkStatus.EMPTY).getInhabitedTime(); + return getHandle(ChunkStatus.EMPTY).getInhabitedTime(); } @Override public void setInhabitedTime(long ticks) { Preconditions.checkArgument(ticks >= 0, "ticks cannot be negative"); - this.getHandle(ChunkStatus.STRUCTURE_STARTS).setInhabitedTime(ticks); + getHandle(ChunkStatus.STRUCTURE_STARTS).setInhabitedTime(ticks); } @Override public boolean contains(BlockData block) { Preconditions.checkArgument(block != null, "Block cannot be null"); - Predicate nms = Predicates.equalTo(((CraftBlockData) block).getState()); - for (LevelChunkSection section : this.getHandle(ChunkStatus.FULL).getSections()) { + Predicate nms = Predicates.equalTo(((CraftBlockData) block).getState()); + for (ChunkSection section : getHandle(ChunkStatus.FULL).getSections()) { if (section != null && section.getStates().maybeHas(nms)) { return true; } @@ -281,9 +283,9 @@ public boolean contains(BlockData block) { public boolean contains(Biome biome) { Preconditions.checkArgument(biome != null, "Biome cannot be null"); - ChunkAccess chunk = this.getHandle(ChunkStatus.BIOMES); - Predicate> nms = Predicates.equalTo(CraftBiome.bukkitToMinecraftHolder(biome)); - for (LevelChunkSection section : chunk.getSections()) { + IChunkAccess chunk = getHandle(ChunkStatus.BIOMES); + Predicate> nms = Predicates.equalTo(CraftBiome.bukkitToMinecraftHolder(biome)); + for (ChunkSection section : chunk.getSections()) { if (section != null && section.getBiomes().maybeHas(nms)) { return true; } @@ -294,71 +296,71 @@ public boolean contains(Biome biome) { @Override public ChunkSnapshot getChunkSnapshot() { - return this.getChunkSnapshot(true, false, false); + return getChunkSnapshot(true, false, false); } @Override public ChunkSnapshot getChunkSnapshot(boolean includeMaxBlockY, boolean includeBiome, boolean includeBiomeTempRain) { - ChunkAccess chunk = this.getHandle(ChunkStatus.FULL); + IChunkAccess chunk = getHandle(ChunkStatus.FULL); - LevelChunkSection[] cs = chunk.getSections(); - PalettedContainer[] sectionBlockIDs = new PalettedContainer[cs.length]; + ChunkSection[] cs = chunk.getSections(); + DataPaletteBlock[] sectionBlockIDs = new DataPaletteBlock[cs.length]; byte[][] sectionSkyLights = new byte[cs.length][]; byte[][] sectionEmitLights = new byte[cs.length][]; boolean[] sectionEmpty = new boolean[cs.length]; - PalettedContainerRO>[] biome = (includeBiome || includeBiomeTempRain) ? new PalettedContainer[cs.length] : null; + PalettedContainerRO>[] biome = (includeBiome || includeBiomeTempRain) ? new DataPaletteBlock[cs.length] : null; - Registry iregistry = this.worldServer.registryAccess().registryOrThrow(Registries.BIOME); - Codec>> biomeCodec = PalettedContainer.codecRO(iregistry.asHolderIdMap(), iregistry.holderByNameCodec(), PalettedContainer.Strategy.SECTION_BIOMES, iregistry.getHolderOrThrow(Biomes.PLAINS)); + IRegistry iregistry = worldServer.registryAccess().lookupOrThrow(Registries.BIOME); + Codec>> biomeCodec = DataPaletteBlock.codecRO(iregistry.asHolderIdMap(), iregistry.holderByNameCodec(), DataPaletteBlock.d.SECTION_BIOMES, iregistry.getOrThrow(Biomes.PLAINS)); for (int i = 0; i < cs.length; i++) { - CompoundTag data = new CompoundTag(); + NBTTagCompound data = new NBTTagCompound(); - data.put("block_states", ChunkSerializer.BLOCK_STATE_CODEC.encodeStart(NbtOps.INSTANCE, cs[i].getStates()).getOrThrow()); - sectionBlockIDs[i] = ChunkSerializer.BLOCK_STATE_CODEC.parse(NbtOps.INSTANCE, data.getCompound("block_states")).getOrThrow(ChunkSerializer.ChunkReadException::new); + data.put("block_states", SerializableChunkData.BLOCK_STATE_CODEC.encodeStart(DynamicOpsNBT.INSTANCE, cs[i].getStates()).getOrThrow()); + sectionBlockIDs[i] = SerializableChunkData.BLOCK_STATE_CODEC.parse(DynamicOpsNBT.INSTANCE, data.getCompound("block_states")).getOrThrow(SerializableChunkData.a::new); sectionEmpty[i] = cs[i].hasOnlyAir(); - LevelLightEngine lightengine = this.worldServer.getLightEngine(); - DataLayer skyLightArray = lightengine.getLayerListener(LightLayer.SKY).getDataLayerData(SectionPos.of(this.x, chunk.getSectionYFromSectionIndex(i), this.z)); // SPIGOT-7498: Convert section index + LevelLightEngine lightengine = worldServer.getLightEngine(); + NibbleArray skyLightArray = lightengine.getLayerListener(EnumSkyBlock.SKY).getDataLayerData(SectionPosition.of(x, chunk.getSectionYFromSectionIndex(i), z)); // SPIGOT-7498: Convert section index if (skyLightArray == null) { - sectionSkyLights[i] = this.worldServer.dimensionType().hasSkyLight() ? CraftChunk.FULL_LIGHT : CraftChunk.EMPTY_LIGHT; + sectionSkyLights[i] = worldServer.dimensionType().hasSkyLight() ? FULL_LIGHT : EMPTY_LIGHT; } else { sectionSkyLights[i] = new byte[2048]; System.arraycopy(skyLightArray.getData(), 0, sectionSkyLights[i], 0, 2048); } - DataLayer emitLightArray = lightengine.getLayerListener(LightLayer.BLOCK).getDataLayerData(SectionPos.of(this.x, chunk.getSectionYFromSectionIndex(i), this.z)); // SPIGOT-7498: Convert section index + NibbleArray emitLightArray = lightengine.getLayerListener(EnumSkyBlock.BLOCK).getDataLayerData(SectionPosition.of(x, chunk.getSectionYFromSectionIndex(i), z)); // SPIGOT-7498: Convert section index if (emitLightArray == null) { - sectionEmitLights[i] = CraftChunk.EMPTY_LIGHT; + sectionEmitLights[i] = EMPTY_LIGHT; } else { sectionEmitLights[i] = new byte[2048]; System.arraycopy(emitLightArray.getData(), 0, sectionEmitLights[i], 0, 2048); } if (biome != null) { - data.put("biomes", biomeCodec.encodeStart(NbtOps.INSTANCE, cs[i].getBiomes()).getOrThrow()); - biome[i] = biomeCodec.parse(NbtOps.INSTANCE, data.getCompound("biomes")).getOrThrow(ChunkSerializer.ChunkReadException::new); + data.put("biomes", biomeCodec.encodeStart(DynamicOpsNBT.INSTANCE, cs[i].getBiomes()).getOrThrow()); + biome[i] = biomeCodec.parse(DynamicOpsNBT.INSTANCE, data.getCompound("biomes")).getOrThrow(SerializableChunkData.a::new); } } - Heightmap hmap = null; + HeightMap hmap = null; if (includeMaxBlockY) { - hmap = new Heightmap(chunk, Heightmap.Types.MOTION_BLOCKING); - hmap.setRawData(chunk, Heightmap.Types.MOTION_BLOCKING, chunk.heightmaps.get(Heightmap.Types.MOTION_BLOCKING).getRawData()); + hmap = new HeightMap(chunk, HeightMap.Type.MOTION_BLOCKING); + hmap.setRawData(chunk, HeightMap.Type.MOTION_BLOCKING, chunk.heightmaps.get(HeightMap.Type.MOTION_BLOCKING).getRawData()); } - World world = this.getWorld(); - return new CraftChunkSnapshot(this.getX(), this.getZ(), chunk.getMinBuildHeight(), chunk.getMaxBuildHeight(), world.getName(), world.getFullTime(), sectionBlockIDs, sectionSkyLights, sectionEmitLights, sectionEmpty, hmap, iregistry, biome); + World world = getWorld(); + return new CraftChunkSnapshot(getX(), getZ(), chunk.getMinY(), chunk.getMaxY(), world.getSeaLevel(), world.getName(), world.getFullTime(), sectionBlockIDs, sectionSkyLights, sectionEmitLights, sectionEmpty, hmap, iregistry, biome); } @Override public PersistentDataContainer getPersistentDataContainer() { - return this.getHandle(ChunkStatus.STRUCTURE_STARTS).persistentDataContainer; + return getHandle(ChunkStatus.STRUCTURE_STARTS).persistentDataContainer; } @Override public LoadLevel getLoadLevel() { - net.minecraft.world.level.chunk.LevelChunk chunk = this.worldServer.getChunkIfLoaded(this.getX(), this.getZ()); + net.minecraft.world.level.chunk.Chunk chunk = worldServer.getChunkIfLoaded(getX(), getZ()); if (chunk == null) { return LoadLevel.UNLOADED; } @@ -367,12 +369,12 @@ public LoadLevel getLoadLevel() { @Override public Collection getStructures() { - return this.getCraftWorld().getStructures(this.getX(), this.getZ()); + return getCraftWorld().getStructures(getX(), getZ()); } @Override public Collection getStructures(Structure structure) { - return this.getCraftWorld().getStructures(this.getX(), this.getZ(), structure); + return getCraftWorld().getStructures(getX(), getZ(), structure); } @Override @@ -383,48 +385,48 @@ public Collection getPlayersSeeingChunk() { @Override public boolean equals(Object o) { if (this == o) return true; - if (o == null || this.getClass() != o.getClass()) return false; + if (o == null || getClass() != o.getClass()) return false; CraftChunk that = (CraftChunk) o; - if (this.x != that.x) return false; - if (this.z != that.z) return false; - return this.worldServer.equals(that.worldServer); + if (x != that.x) return false; + if (z != that.z) return false; + return worldServer.equals(that.worldServer); } @Override public int hashCode() { - int result = this.worldServer.hashCode(); - result = 31 * result + this.x; - result = 31 * result + this.z; + int result = worldServer.hashCode(); + result = 31 * result + x; + result = 31 * result + z; return result; } public static ChunkSnapshot getEmptyChunkSnapshot(int x, int z, CraftWorld world, boolean includeBiome, boolean includeBiomeTempRain) { - ChunkAccess actual = world.getHandle().getChunk(x, z, (includeBiome || includeBiomeTempRain) ? ChunkStatus.BIOMES : ChunkStatus.EMPTY); + IChunkAccess actual = world.getHandle().getChunk(x, z, (includeBiome || includeBiomeTempRain) ? ChunkStatus.BIOMES : ChunkStatus.EMPTY); /* Fill with empty data */ int hSection = actual.getSectionsCount(); - PalettedContainer[] blockIDs = new PalettedContainer[hSection]; + DataPaletteBlock[] blockIDs = new DataPaletteBlock[hSection]; byte[][] skyLight = new byte[hSection][]; byte[][] emitLight = new byte[hSection][]; boolean[] empty = new boolean[hSection]; - Registry iregistry = world.getHandle().registryAccess().registryOrThrow(Registries.BIOME); - PalettedContainer>[] biome = (includeBiome || includeBiomeTempRain) ? new PalettedContainer[hSection] : null; - Codec>> biomeCodec = PalettedContainer.codecRO(iregistry.asHolderIdMap(), iregistry.holderByNameCodec(), PalettedContainer.Strategy.SECTION_BIOMES, iregistry.getHolderOrThrow(Biomes.PLAINS)); + IRegistry iregistry = world.getHandle().registryAccess().lookupOrThrow(Registries.BIOME); + DataPaletteBlock>[] biome = (includeBiome || includeBiomeTempRain) ? new DataPaletteBlock[hSection] : null; + Codec>> biomeCodec = DataPaletteBlock.codecRO(iregistry.asHolderIdMap(), iregistry.holderByNameCodec(), DataPaletteBlock.d.SECTION_BIOMES, iregistry.getOrThrow(Biomes.PLAINS)); for (int i = 0; i < hSection; i++) { - blockIDs[i] = CraftChunk.emptyBlockIDs; - skyLight[i] = world.getHandle().dimensionType().hasSkyLight() ? CraftChunk.FULL_LIGHT : CraftChunk.EMPTY_LIGHT; - emitLight[i] = CraftChunk.EMPTY_LIGHT; + blockIDs[i] = emptyBlockIDs; + skyLight[i] = world.getHandle().dimensionType().hasSkyLight() ? FULL_LIGHT : EMPTY_LIGHT; + emitLight[i] = EMPTY_LIGHT; empty[i] = true; if (biome != null) { - biome[i] = (PalettedContainer>) biomeCodec.parse(NbtOps.INSTANCE, biomeCodec.encodeStart(NbtOps.INSTANCE, actual.getSection(i).getBiomes()).getOrThrow()).getOrThrow(ChunkSerializer.ChunkReadException::new); + biome[i] = (DataPaletteBlock>) biomeCodec.parse(DynamicOpsNBT.INSTANCE, biomeCodec.encodeStart(DynamicOpsNBT.INSTANCE, actual.getSection(i).getBiomes()).getOrThrow()).getOrThrow(SerializableChunkData.a::new); } } - return new CraftChunkSnapshot(x, z, world.getMinHeight(), world.getMaxHeight(), world.getName(), world.getFullTime(), blockIDs, skyLight, emitLight, empty, new Heightmap(actual, Heightmap.Types.MOTION_BLOCKING), iregistry, biome); + return new CraftChunkSnapshot(x, z, world.getMinHeight(), world.getMaxHeight(), world.getSeaLevel(), world.getName(), world.getFullTime(), blockIDs, skyLight, emitLight, empty, new HeightMap(actual, HeightMap.Type.MOTION_BLOCKING), iregistry, biome); } static void validateChunkCoordinates(int minY, int maxY, int x, int y, int z) { diff --git a/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java b/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java index f2ce97e4..3b832f22 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java @@ -5,11 +5,12 @@ import java.util.function.Predicate; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.PalettedContainer; +import net.minecraft.core.IRegistry; +import net.minecraft.world.level.biome.BiomeBase; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.chunk.DataPaletteBlock; import net.minecraft.world.level.chunk.PalettedContainerRO; -import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.HeightMap; import org.bukkit.ChunkSnapshot; import org.bukkit.Material; import org.bukkit.block.Biome; @@ -25,22 +26,23 @@ */ public class CraftChunkSnapshot implements ChunkSnapshot { private final int x, z; - private final int minHeight, maxHeight; + private final int minHeight, maxHeight, seaLevel; private final String worldname; - private final PalettedContainer[] blockids; + private final DataPaletteBlock[] blockids; private final byte[][] skylight; private final byte[][] emitlight; private final boolean[] empty; - private final Heightmap hmap; // Height map + private final HeightMap hmap; // Height map private final long captureFulltime; - private final Registry biomeRegistry; - private final PalettedContainerRO>[] biome; + private final IRegistry biomeRegistry; + private final PalettedContainerRO>[] biome; - CraftChunkSnapshot(int x, int z, int minHeight, int maxHeight, String wname, long wtime, PalettedContainer[] sectionBlockIDs, byte[][] sectionSkyLights, byte[][] sectionEmitLights, boolean[] sectionEmpty, Heightmap hmap, Registry biomeRegistry, PalettedContainerRO>[] biome) { + CraftChunkSnapshot(int x, int z, int minHeight, int maxHeight, int seaLevel, String wname, long wtime, DataPaletteBlock[] sectionBlockIDs, byte[][] sectionSkyLights, byte[][] sectionEmitLights, boolean[] sectionEmpty, HeightMap hmap, IRegistry biomeRegistry, PalettedContainerRO>[] biome) { this.x = x; this.z = z; this.minHeight = minHeight; this.maxHeight = maxHeight; + this.seaLevel = seaLevel; this.worldname = wname; this.captureFulltime = wtime; this.blockids = sectionBlockIDs; @@ -54,25 +56,25 @@ public class CraftChunkSnapshot implements ChunkSnapshot { @Override public int getX() { - return this.x; + return x; } @Override public int getZ() { - return this.z; + return z; } @Override public String getWorldName() { - return this.worldname; + return worldname; } @Override public boolean contains(BlockData block) { Preconditions.checkArgument(block != null, "Block cannot be null"); - Predicate nms = Predicates.equalTo(((CraftBlockData) block).getState()); - for (PalettedContainer palette : this.blockids) { + Predicate nms = Predicates.equalTo(((CraftBlockData) block).getState()); + for (DataPaletteBlock palette : blockids) { if (palette.maybeHas(nms)) { return true; } @@ -85,8 +87,8 @@ public boolean contains(BlockData block) { public boolean contains(Biome biome) { Preconditions.checkArgument(biome != null, "Biome cannot be null"); - Predicate> nms = Predicates.equalTo(CraftBiome.bukkitToMinecraftHolder(biome)); - for (PalettedContainerRO> palette : this.biome) { + Predicate> nms = Predicates.equalTo(CraftBiome.bukkitToMinecraftHolder(biome)); + for (PalettedContainerRO> palette : this.biome) { if (palette.maybeHas(nms)) { return true; } @@ -97,92 +99,92 @@ public boolean contains(Biome biome) { @Override public Material getBlockType(int x, int y, int z) { - this.validateChunkCoordinates(x, y, z); + validateChunkCoordinates(x, y, z); - return CraftBlockType.minecraftToBukkit(this.blockids[this.getSectionIndex(y)].get(x, y & 0xF, z).getBlock()); + return CraftBlockType.minecraftToBukkit(blockids[getSectionIndex(y)].get(x, y & 0xF, z).getBlock()); } @Override public final BlockData getBlockData(int x, int y, int z) { - this.validateChunkCoordinates(x, y, z); + validateChunkCoordinates(x, y, z); - return CraftBlockData.fromData(this.blockids[this.getSectionIndex(y)].get(x, y & 0xF, z)); + return CraftBlockData.fromData(blockids[getSectionIndex(y)].get(x, y & 0xF, z)); } @Override public final int getData(int x, int y, int z) { - this.validateChunkCoordinates(x, y, z); + validateChunkCoordinates(x, y, z); - return CraftMagicNumbers.toLegacyData(this.blockids[this.getSectionIndex(y)].get(x, y & 0xF, z)); + return CraftMagicNumbers.toLegacyData(blockids[getSectionIndex(y)].get(x, y & 0xF, z)); } @Override public final int getBlockSkyLight(int x, int y, int z) { - this.validateChunkCoordinates(x, y, z); + validateChunkCoordinates(x, y, z); int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); - return (this.skylight[this.getSectionIndex(y)][off] >> ((x & 1) << 2)) & 0xF; + return (skylight[getSectionIndex(y)][off] >> ((x & 1) << 2)) & 0xF; } @Override public final int getBlockEmittedLight(int x, int y, int z) { - this.validateChunkCoordinates(x, y, z); + validateChunkCoordinates(x, y, z); int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); - return (this.emitlight[this.getSectionIndex(y)][off] >> ((x & 1) << 2)) & 0xF; + return (emitlight[getSectionIndex(y)][off] >> ((x & 1) << 2)) & 0xF; } @Override public final int getHighestBlockYAt(int x, int z) { - Preconditions.checkState(this.hmap != null, "ChunkSnapshot created without height map. Please call getSnapshot with includeMaxblocky=true"); - this.validateChunkCoordinates(x, 0, z); + Preconditions.checkState(hmap != null, "ChunkSnapshot created without height map. Please call getSnapshot with includeMaxblocky=true"); + validateChunkCoordinates(x, 0, z); - return this.hmap.getHighestTaken(x, z); + return hmap.getHighestTaken(x, z); } @Override public final Biome getBiome(int x, int z) { - return this.getBiome(x, 0, z); + return getBiome(x, 0, z); } @Override public final Biome getBiome(int x, int y, int z) { - Preconditions.checkState(this.biome != null, "ChunkSnapshot created without biome. Please call getSnapshot with includeBiome=true"); - this.validateChunkCoordinates(x, y, z); + Preconditions.checkState(biome != null, "ChunkSnapshot created without biome. Please call getSnapshot with includeBiome=true"); + validateChunkCoordinates(x, y, z); - PalettedContainerRO> biome = this.biome[this.getSectionIndex(y)]; // SPIGOT-7188: Don't need to convert y to biome coordinate scale since it is bound to the block chunk section + PalettedContainerRO> biome = this.biome[getSectionIndex(y)]; // SPIGOT-7188: Don't need to convert y to biome coordinate scale since it is bound to the block chunk section return CraftBiome.minecraftHolderToBukkit(biome.get(x >> 2, (y & 0xF) >> 2, z >> 2)); } @Override public final double getRawBiomeTemperature(int x, int z) { - return this.getRawBiomeTemperature(x, 0, z); + return getRawBiomeTemperature(x, 0, z); } @Override public final double getRawBiomeTemperature(int x, int y, int z) { - Preconditions.checkState(this.biome != null, "ChunkSnapshot created without biome. Please call getSnapshot with includeBiome=true"); - this.validateChunkCoordinates(x, y, z); + Preconditions.checkState(biome != null, "ChunkSnapshot created without biome. Please call getSnapshot with includeBiome=true"); + validateChunkCoordinates(x, y, z); - PalettedContainerRO> biome = this.biome[this.getSectionIndex(y)]; // SPIGOT-7188: Don't need to convert y to biome coordinate scale since it is bound to the block chunk section - return biome.get(x >> 2, (y & 0xF) >> 2, z >> 2).value().getTemperature(new BlockPos((this.x << 4) | x, y, (this.z << 4) | z)); + PalettedContainerRO> biome = this.biome[getSectionIndex(y)]; // SPIGOT-7188: Don't need to convert y to biome coordinate scale since it is bound to the block chunk section + return biome.get(x >> 2, (y & 0xF) >> 2, z >> 2).value().getTemperature(new BlockPos((this.x << 4) | x, y, (this.z << 4) | z), seaLevel); } @Override public final long getCaptureFullTime() { - return this.captureFulltime; + return captureFulltime; } @Override public final boolean isSectionEmpty(int sy) { - return this.empty[sy]; + return empty[sy]; } private int getSectionIndex(int y) { - return (y - this.minHeight) >> 4; + return (y - minHeight) >> 4; } private void validateChunkCoordinates(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(this.minHeight, this.maxHeight, x, y, z); + CraftChunk.validateChunkCoordinates(minHeight, maxHeight, x, y, z); } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java b/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java index ae86c45c..e379616d 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java @@ -1,55 +1,56 @@ package org.bukkit.craftbukkit; import java.util.Locale; -import net.minecraft.world.InteractionHand; +import net.minecraft.world.EnumHand; +import net.minecraft.world.entity.EnumItemSlot; import net.minecraft.world.entity.EquipmentSlotGroup; import org.bukkit.inventory.EquipmentSlot; public class CraftEquipmentSlot { - private static final net.minecraft.world.entity.EquipmentSlot[] slots = new net.minecraft.world.entity.EquipmentSlot[EquipmentSlot.values().length]; - private static final EquipmentSlot[] enums = new EquipmentSlot[net.minecraft.world.entity.EquipmentSlot.values().length]; + private static final EnumItemSlot[] slots = new EnumItemSlot[EquipmentSlot.values().length]; + private static final EquipmentSlot[] enums = new EquipmentSlot[EnumItemSlot.values().length]; static { - set(EquipmentSlot.HAND, net.minecraft.world.entity.EquipmentSlot.MAINHAND); - set(EquipmentSlot.OFF_HAND, net.minecraft.world.entity.EquipmentSlot.OFFHAND); - set(EquipmentSlot.FEET, net.minecraft.world.entity.EquipmentSlot.FEET); - set(EquipmentSlot.LEGS, net.minecraft.world.entity.EquipmentSlot.LEGS); - set(EquipmentSlot.CHEST, net.minecraft.world.entity.EquipmentSlot.CHEST); - set(EquipmentSlot.HEAD, net.minecraft.world.entity.EquipmentSlot.HEAD); - set(EquipmentSlot.BODY, net.minecraft.world.entity.EquipmentSlot.BODY); + set(EquipmentSlot.HAND, EnumItemSlot.MAINHAND); + set(EquipmentSlot.OFF_HAND, EnumItemSlot.OFFHAND); + set(EquipmentSlot.FEET, EnumItemSlot.FEET); + set(EquipmentSlot.LEGS, EnumItemSlot.LEGS); + set(EquipmentSlot.CHEST, EnumItemSlot.CHEST); + set(EquipmentSlot.HEAD, EnumItemSlot.HEAD); + set(EquipmentSlot.BODY, EnumItemSlot.BODY); } - private static void set(EquipmentSlot type, net.minecraft.world.entity.EquipmentSlot value) { - CraftEquipmentSlot.slots[type.ordinal()] = value; - CraftEquipmentSlot.enums[value.ordinal()] = type; + private static void set(EquipmentSlot type, EnumItemSlot value) { + slots[type.ordinal()] = value; + enums[value.ordinal()] = type; } - public static EquipmentSlot getSlot(net.minecraft.world.entity.EquipmentSlot nms) { - return CraftEquipmentSlot.enums[nms.ordinal()]; + public static EquipmentSlot getSlot(EnumItemSlot nms) { + return enums[nms.ordinal()]; } public static org.bukkit.inventory.EquipmentSlotGroup getSlot(EquipmentSlotGroup nms) { return org.bukkit.inventory.EquipmentSlotGroup.getByName(nms.getSerializedName()); } - public static net.minecraft.world.entity.EquipmentSlot getNMS(EquipmentSlot slot) { - return CraftEquipmentSlot.slots[slot.ordinal()]; + public static EnumItemSlot getNMS(EquipmentSlot slot) { + return slots[slot.ordinal()]; } public static EquipmentSlotGroup getNMSGroup(org.bukkit.inventory.EquipmentSlotGroup slot) { return EquipmentSlotGroup.valueOf(slot.toString().toUpperCase(Locale.ROOT)); } - public static EquipmentSlot getHand(InteractionHand enumhand) { - return (enumhand == InteractionHand.MAIN_HAND) ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND; + public static EquipmentSlot getHand(EnumHand enumhand) { + return (enumhand == EnumHand.MAIN_HAND) ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND; } - public static InteractionHand getHand(EquipmentSlot hand) { + public static EnumHand getHand(EquipmentSlot hand) { if (hand == EquipmentSlot.HAND) { - return InteractionHand.MAIN_HAND; + return EnumHand.MAIN_HAND; } else if (hand == EquipmentSlot.OFF_HAND) { - return InteractionHand.OFF_HAND; + return EnumHand.OFF_HAND; } throw new IllegalArgumentException("EquipmentSlot." + hand + " is not a hand"); diff --git a/src/main/java/org/bukkit/craftbukkit/CraftExplosionResult.java b/src/main/java/org/bukkit/craftbukkit/CraftExplosionResult.java index 42e0b771..bbbb2f12 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftExplosionResult.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftExplosionResult.java @@ -8,7 +8,7 @@ public final class CraftExplosionResult { private CraftExplosionResult() {} - public static ExplosionResult toBukkit(Explosion.BlockInteraction effect) { + public static ExplosionResult toBukkit(Explosion.Effect effect) { Preconditions.checkArgument(effect != null, "explosion effect cannot be null"); switch (effect) { diff --git a/src/main/java/org/bukkit/craftbukkit/CraftFeatureFlag.java b/src/main/java/org/bukkit/craftbukkit/CraftFeatureFlag.java index da90e5c8..4622aa41 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftFeatureFlag.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftFeatureFlag.java @@ -2,7 +2,7 @@ import java.util.HashSet; import java.util.Set; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.MinecraftKey; import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.flag.FeatureFlags; import org.bukkit.FeatureFlag; @@ -15,7 +15,7 @@ public class CraftFeatureFlag implements FeatureFlag { private final NamespacedKey namespacedKey; private final net.minecraft.world.flag.FeatureFlag featureFlag; - public CraftFeatureFlag(ResourceLocation minecraftKey, net.minecraft.world.flag.FeatureFlag featureFlag) { + public CraftFeatureFlag(MinecraftKey minecraftKey, net.minecraft.world.flag.FeatureFlag featureFlag) { this.namespacedKey = CraftNamespacedKey.fromMinecraft(minecraftKey); this.featureFlag = featureFlag; } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftFluid.java b/src/main/java/org/bukkit/craftbukkit/CraftFluid.java index 0d4ed5f5..8157c81e 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftFluid.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftFluid.java @@ -1,17 +1,19 @@ package org.bukkit.craftbukkit; import com.google.common.base.Preconditions; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; +import net.minecraft.world.level.material.FluidType; import org.bukkit.Fluid; import org.bukkit.Registry; import org.bukkit.craftbukkit.util.CraftNamespacedKey; public class CraftFluid { - public static Fluid minecraftToBukkit(net.minecraft.world.level.material.Fluid minecraft) { + public static Fluid minecraftToBukkit(FluidType minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.FLUID); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.FLUID); Fluid bukkit = Registry.FLUID.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); @@ -19,7 +21,7 @@ public static Fluid minecraftToBukkit(net.minecraft.world.level.material.Fluid m return bukkit; } - public static net.minecraft.world.level.material.Fluid bukkitToMinecraft(Fluid bukkit) { + public static FluidType bukkitToMinecraft(Fluid bukkit) { Preconditions.checkArgument(bukkit != null); return CraftRegistry.getMinecraftRegistry(Registries.FLUID) diff --git a/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java b/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java index 2178d65f..1991614d 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java @@ -1,22 +1,22 @@ package org.bukkit.craftbukkit; -import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.RayTrace.FluidCollisionOption; import org.bukkit.FluidCollisionMode; public final class CraftFluidCollisionMode { private CraftFluidCollisionMode() {} - public static Fluid toNMS(FluidCollisionMode fluidCollisionMode) { + public static FluidCollisionOption toNMS(FluidCollisionMode fluidCollisionMode) { if (fluidCollisionMode == null) return null; switch (fluidCollisionMode) { case ALWAYS: - return Fluid.ANY; + return FluidCollisionOption.ANY; case SOURCE_ONLY: - return Fluid.SOURCE_ONLY; + return FluidCollisionOption.SOURCE_ONLY; case NEVER: - return Fluid.NONE; + return FluidCollisionOption.NONE; default: return null; } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftGameEvent.java b/src/main/java/org/bukkit/craftbukkit/CraftGameEvent.java index ac9b4328..33c07bc9 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftGameEvent.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftGameEvent.java @@ -27,13 +27,13 @@ public CraftGameEvent(NamespacedKey key, net.minecraft.world.level.gameevent.Gam @Override public net.minecraft.world.level.gameevent.GameEvent getHandle() { - return this.handle; + return handle; } @NotNull @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override @@ -46,16 +46,16 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((GameEvent) other).getKey()); + return getKey().equals(((GameEvent) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } @Override public String toString() { - return "CraftGameEvent{key=" + this.key + "}"; + return "CraftGameEvent{key=" + key + "}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftHeightMap.java b/src/main/java/org/bukkit/craftbukkit/CraftHeightMap.java index 8032f402..e635e085 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftHeightMap.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftHeightMap.java @@ -7,26 +7,26 @@ public final class CraftHeightMap { private CraftHeightMap() { } - public static net.minecraft.world.level.levelgen.Heightmap.Types toNMS(HeightMap bukkitHeightMap) { + public static net.minecraft.world.level.levelgen.HeightMap.Type toNMS(HeightMap bukkitHeightMap) { switch (bukkitHeightMap) { case MOTION_BLOCKING_NO_LEAVES: - return net.minecraft.world.level.levelgen.Heightmap.Types.MOTION_BLOCKING_NO_LEAVES; + return net.minecraft.world.level.levelgen.HeightMap.Type.MOTION_BLOCKING_NO_LEAVES; case OCEAN_FLOOR: - return net.minecraft.world.level.levelgen.Heightmap.Types.OCEAN_FLOOR; + return net.minecraft.world.level.levelgen.HeightMap.Type.OCEAN_FLOOR; case OCEAN_FLOOR_WG: - return net.minecraft.world.level.levelgen.Heightmap.Types.OCEAN_FLOOR_WG; + return net.minecraft.world.level.levelgen.HeightMap.Type.OCEAN_FLOOR_WG; case WORLD_SURFACE: - return net.minecraft.world.level.levelgen.Heightmap.Types.WORLD_SURFACE; + return net.minecraft.world.level.levelgen.HeightMap.Type.WORLD_SURFACE; case WORLD_SURFACE_WG: - return net.minecraft.world.level.levelgen.Heightmap.Types.WORLD_SURFACE_WG; + return net.minecraft.world.level.levelgen.HeightMap.Type.WORLD_SURFACE_WG; case MOTION_BLOCKING: - return net.minecraft.world.level.levelgen.Heightmap.Types.MOTION_BLOCKING; + return net.minecraft.world.level.levelgen.HeightMap.Type.MOTION_BLOCKING; default: - throw new EnumConstantNotPresentException(net.minecraft.world.level.levelgen.Heightmap.Types.class, bukkitHeightMap.name()); + throw new EnumConstantNotPresentException(net.minecraft.world.level.levelgen.HeightMap.Type.class, bukkitHeightMap.name()); } } - public static HeightMap fromNMS(net.minecraft.world.level.levelgen.Heightmap.Types nmsHeightMapType) { + public static HeightMap fromNMS(net.minecraft.world.level.levelgen.HeightMap.Type nmsHeightMapType) { switch (nmsHeightMapType) { case WORLD_SURFACE_WG: return HeightMap.WORLD_SURFACE_WG; diff --git a/src/main/java/org/bukkit/craftbukkit/CraftInput.java b/src/main/java/org/bukkit/craftbukkit/CraftInput.java new file mode 100644 index 00000000..ee71b85e --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/CraftInput.java @@ -0,0 +1,75 @@ +package org.bukkit.craftbukkit; + +import java.util.Objects; +import org.bukkit.Input; + +public class CraftInput implements Input { + + private final net.minecraft.world.entity.player.Input handle; + + public CraftInput(net.minecraft.world.entity.player.Input handle) { + this.handle = handle; + } + + @Override + public boolean isForward() { + return handle.forward(); + } + + @Override + public boolean isBackward() { + return handle.backward(); + } + + @Override + public boolean isLeft() { + return handle.left(); + } + + @Override + public boolean isRight() { + return handle.right(); + } + + @Override + public boolean isJump() { + return handle.jump(); + } + + @Override + public boolean isSneak() { + return handle.shift(); + } + + @Override + public boolean isSprint() { + return handle.sprint(); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 89 * hash + Objects.hashCode(this.handle); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftInput other = (CraftInput) obj; + return Objects.equals(this.handle, other.handle); + } + + @Override + public String toString() { + return "CraftInput{" + handle + '}'; + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java b/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java index ebde7e46..647b8d4a 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.contents.TranslatableContents; import org.bukkit.JukeboxSong; @@ -27,9 +28,9 @@ public static net.minecraft.world.item.JukeboxSong bukkitToMinecraft(JukeboxSong public static Holder bukkitToMinecraftHolder(JukeboxSong bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.JUKEBOX_SONG); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.JUKEBOX_SONG); - if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java b/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java index 85c7f302..f8de98e0 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java @@ -6,18 +6,19 @@ import java.util.List; import java.util.Random; import net.minecraft.core.registries.Registries; +import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.Container; +import net.minecraft.server.level.WorldServer; +import net.minecraft.util.context.ContextKey; +import net.minecraft.util.context.ContextKeySet; +import net.minecraft.world.IInventory; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.parameters.LootContextParam; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.level.storage.loot.LootTableInfo; +import net.minecraft.world.level.storage.loot.parameters.LootContextParameters; +import net.minecraft.world.phys.Vec3D; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; @@ -33,12 +34,12 @@ public class CraftLootTable implements org.bukkit.loot.LootTable { - public static org.bukkit.loot.LootTable minecraftToBukkit(ResourceLocation minecraft) { + public static org.bukkit.loot.LootTable minecraftToBukkit(MinecraftKey minecraft) { return (minecraft == null) ? null : Bukkit.getLootTable(CraftNamespacedKey.fromMinecraft(minecraft)); } public static org.bukkit.loot.LootTable minecraftToBukkit(ResourceKey minecraft) { - return (minecraft == null) ? null : Bukkit.getLootTable(CraftLootTable.minecraftToBukkitKey(minecraft)); + return (minecraft == null) ? null : Bukkit.getLootTable(minecraftToBukkitKey(minecraft)); } public static NamespacedKey minecraftToBukkitKey(ResourceKey minecraft) { @@ -46,7 +47,7 @@ public static NamespacedKey minecraftToBukkitKey(ResourceKey minecraf } public static ResourceKey bukkitToMinecraft(org.bukkit.loot.LootTable table) { - return (table == null) ? null : CraftLootTable.bukkitKeyToMinecraft(table.getKey()); + return (table == null) ? null : bukkitKeyToMinecraft(table.getKey()); } public static ResourceKey bukkitKeyToMinecraft(NamespacedKey key) { @@ -62,14 +63,14 @@ public CraftLootTable(NamespacedKey key, LootTable handle) { } public LootTable getHandle() { - return this.handle; + return handle; } @Override public Collection populateLoot(Random random, LootContext context) { Preconditions.checkArgument(context != null, "LootContext cannot be null"); - LootParams nmsContext = this.convertContext(context, random); - List nmsItems = this.handle.getRandomItems(nmsContext); + LootParams nmsContext = convertContext(context, random); + List nmsItems = handle.getRandomItems(nmsContext); Collection bukkit = new ArrayList<>(nmsItems.size()); for (net.minecraft.world.item.ItemStack item : nmsItems) { @@ -86,87 +87,87 @@ public Collection populateLoot(Random random, LootContext context) { public void fillInventory(Inventory inventory, Random random, LootContext context) { Preconditions.checkArgument(inventory != null, "Inventory cannot be null"); Preconditions.checkArgument(context != null, "LootContext cannot be null"); - LootParams nmsContext = this.convertContext(context, random); + LootParams nmsContext = convertContext(context, random); CraftInventory craftInventory = (CraftInventory) inventory; - Container handle = craftInventory.getInventory(); + IInventory handle = craftInventory.getInventory(); // TODO: When events are added, call event here w/ custom reason? - this.getHandle().fillInventory(handle, nmsContext, random.nextLong(), true); + getHandle().fillInventory(handle, nmsContext, random.nextLong(), true); } @Override public NamespacedKey getKey() { - return this.key; + return key; } private LootParams convertContext(LootContext context, Random random) { Preconditions.checkArgument(context != null, "LootContext cannot be null"); Location loc = context.getLocation(); Preconditions.checkArgument(loc.getWorld() != null, "LootContext.getLocation#getWorld cannot be null"); - ServerLevel handle = ((CraftWorld) loc.getWorld()).getHandle(); + WorldServer handle = ((CraftWorld) loc.getWorld()).getHandle(); - LootParams.Builder builder = new LootParams.Builder(handle); + LootParams.a builder = new LootParams.a(handle); if (random != null) { // builder = builder.withRandom(new RandomSourceWrapper(random)); } - this.setMaybe(builder, LootContextParams.ORIGIN, CraftLocation.toVec3D(loc)); - if (this.getHandle() != LootTable.EMPTY) { + setMaybe(builder, LootContextParameters.ORIGIN, CraftLocation.toVec3D(loc)); + if (getHandle() != LootTable.EMPTY) { // builder.luck(context.getLuck()); if (context.getLootedEntity() != null) { Entity nmsLootedEntity = ((CraftEntity) context.getLootedEntity()).getHandle(); - this.setMaybe(builder, LootContextParams.THIS_ENTITY, nmsLootedEntity); - this.setMaybe(builder, LootContextParams.DAMAGE_SOURCE, handle.damageSources().generic()); - this.setMaybe(builder, LootContextParams.ORIGIN, nmsLootedEntity.position()); + setMaybe(builder, LootContextParameters.THIS_ENTITY, nmsLootedEntity); + setMaybe(builder, LootContextParameters.DAMAGE_SOURCE, handle.damageSources().generic()); + setMaybe(builder, LootContextParameters.ORIGIN, nmsLootedEntity.position()); } if (context.getKiller() != null) { - Player nmsKiller = ((CraftHumanEntity) context.getKiller()).getHandle(); - this.setMaybe(builder, LootContextParams.ATTACKING_ENTITY, nmsKiller); + EntityHuman nmsKiller = ((CraftHumanEntity) context.getKiller()).getHandle(); + setMaybe(builder, LootContextParameters.ATTACKING_ENTITY, nmsKiller); // If there is a player killer, damage source should reflect that in case loot tables use that information - this.setMaybe(builder, LootContextParams.DAMAGE_SOURCE, handle.damageSources().playerAttack(nmsKiller)); - this.setMaybe(builder, LootContextParams.LAST_DAMAGE_PLAYER, nmsKiller); // SPIGOT-5603 - Set minecraft:killed_by_player - this.setMaybe(builder, LootContextParams.TOOL, nmsKiller.getUseItem()); // SPIGOT-6925 - Set minecraft:match_tool + setMaybe(builder, LootContextParameters.DAMAGE_SOURCE, handle.damageSources().playerAttack(nmsKiller)); + setMaybe(builder, LootContextParameters.LAST_DAMAGE_PLAYER, nmsKiller); // SPIGOT-5603 - Set minecraft:killed_by_player + setMaybe(builder, LootContextParameters.TOOL, nmsKiller.getUseItem()); // SPIGOT-6925 - Set minecraft:match_tool } } // SPIGOT-5603 - Avoid IllegalArgumentException in LootTableInfo#build() - LootContextParamSet.Builder nmsBuilder = new LootContextParamSet.Builder(); - for (LootContextParam param : this.getHandle().getParamSet().getRequired()) { + ContextKeySet.a nmsBuilder = new ContextKeySet.a(); + for (ContextKey param : getHandle().getParamSet().required()) { nmsBuilder.required(param); } - for (LootContextParam param : this.getHandle().getParamSet().getAllowed()) { - if (!this.getHandle().getParamSet().getRequired().contains(param)) { + for (ContextKey param : getHandle().getParamSet().allowed()) { + if (!getHandle().getParamSet().required().contains(param)) { nmsBuilder.optional(param); } } - return builder.create(this.getHandle().getParamSet()); + return builder.create(getHandle().getParamSet()); } - private void setMaybe(LootParams.Builder builder, LootContextParam param, T value) { - if (this.getHandle().getParamSet().getRequired().contains(param) || this.getHandle().getParamSet().getAllowed().contains(param)) { + private void setMaybe(LootParams.a builder, ContextKey param, T value) { + if (getHandle().getParamSet().required().contains(param) || getHandle().getParamSet().allowed().contains(param)) { builder.withParameter(param, value); } } - public static LootContext convertContext(net.minecraft.world.level.storage.loot.LootContext info) { - Vec3 position = info.getParamOrNull(LootContextParams.ORIGIN); + public static LootContext convertContext(LootTableInfo info) { + Vec3D position = info.getOptionalParameter(LootContextParameters.ORIGIN); if (position == null) { - position = info.getParamOrNull(LootContextParams.THIS_ENTITY).position(); // Every vanilla context has origin or this_entity, see LootContextParameterSets + position = info.getOptionalParameter(LootContextParameters.THIS_ENTITY).position(); // Every vanilla context has origin or this_entity, see LootContextParameterSets } Location location = CraftLocation.toBukkit(position, info.getLevel().getWorld()); LootContext.Builder contextBuilder = new LootContext.Builder(location); - if (info.hasParam(LootContextParams.ATTACKING_ENTITY)) { - CraftEntity killer = info.getParamOrNull(LootContextParams.ATTACKING_ENTITY).getBukkitEntity(); + if (info.hasParameter(LootContextParameters.ATTACKING_ENTITY)) { + CraftEntity killer = info.getOptionalParameter(LootContextParameters.ATTACKING_ENTITY).getBukkitEntity(); if (killer instanceof CraftHumanEntity) { contextBuilder.killer((CraftHumanEntity) killer); } } - if (info.hasParam(LootContextParams.THIS_ENTITY)) { - contextBuilder.lootedEntity(info.getParamOrNull(LootContextParams.THIS_ENTITY).getBukkitEntity()); + if (info.hasParameter(LootContextParameters.THIS_ENTITY)) { + contextBuilder.lootedEntity(info.getOptionalParameter(LootContextParameters.THIS_ENTITY).getBukkitEntity()); } contextBuilder.luck(info.getLuck()); @@ -175,7 +176,7 @@ public static LootContext convertContext(net.minecraft.world.level.storage.loot. @Override public String toString() { - return this.getKey().toString(); + return getKey().toString(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/CraftMusicInstrument.java b/src/main/java/org/bukkit/craftbukkit/CraftMusicInstrument.java index fa0a3f89..b6d151d3 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftMusicInstrument.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftMusicInstrument.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.world.item.Instrument; import org.bukkit.MusicInstrument; @@ -17,7 +18,7 @@ public static MusicInstrument minecraftToBukkit(Instrument minecraft) { } public static MusicInstrument minecraftHolderToBukkit(Holder minecraft) { - return CraftMusicInstrument.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static Instrument bukkitToMinecraft(MusicInstrument bukkit) { @@ -27,9 +28,9 @@ public static Instrument bukkitToMinecraft(MusicInstrument bukkit) { public static Holder bukkitToMinecraftHolder(MusicInstrument bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.INSTRUMENT); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.INSTRUMENT); - if (registry.wrapAsHolder(CraftMusicInstrument.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -59,13 +60,13 @@ public CraftMusicInstrument(NamespacedKey key, Instrument handle) { @Override public Instrument getHandle() { - return this.handle; + return handle; } @NotNull @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override @@ -78,16 +79,16 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((MusicInstrument) other).getKey()); + return getKey().equals(((MusicInstrument) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } @Override public String toString() { - return "CraftMusicInstrument{key=" + this.key + "}"; + return "CraftMusicInstrument{key=" + key + "}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java b/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java index 818df09e..a0076539 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java @@ -10,12 +10,12 @@ import java.util.Map; import java.util.UUID; import net.minecraft.core.GlobalPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.server.players.UserWhiteListEntry; -import net.minecraft.stats.ServerStatsCounter; -import net.minecraft.world.level.storage.PlayerDataStorage; +import net.minecraft.nbt.DynamicOpsNBT; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.server.players.WhiteListEntry; +import net.minecraft.stats.ServerStatisticManager; +import net.minecraft.world.level.storage.WorldNBTStorage; import org.bukkit.BanEntry; import org.bukkit.BanList; import org.bukkit.Bukkit; @@ -39,7 +39,7 @@ public class CraftOfflinePlayer implements OfflinePlayer, ConfigurationSerializable { private final GameProfile profile; private final CraftServer server; - private final PlayerDataStorage storage; + private final WorldNBTStorage storage; protected CraftOfflinePlayer(CraftServer server, GameProfile profile) { this.server = server; @@ -50,22 +50,22 @@ protected CraftOfflinePlayer(CraftServer server, GameProfile profile) { @Override public boolean isOnline() { - return this.getPlayer() != null; + return getPlayer() != null; } @Override public String getName() { - Player player = this.getPlayer(); + Player player = getPlayer(); if (player != null) { return player.getName(); } // This might not match lastKnownName but if not it should be more correct - if (!this.profile.getName().isEmpty()) { - return this.profile.getName(); + if (!profile.getName().isEmpty()) { + return profile.getName(); } - CompoundTag data = this.getBukkitData(); + NBTTagCompound data = getBukkitData(); if (data != null) { if (data.contains("lastKnownName")) { @@ -78,75 +78,75 @@ public String getName() { @Override public UUID getUniqueId() { - return this.profile.getId(); + return profile.getId(); } @Override public PlayerProfile getPlayerProfile() { - return new CraftPlayerProfile(this.profile); + return new CraftPlayerProfile(profile); } public Server getServer() { - return this.server; + return server; } @Override public boolean isOp() { - return this.server.getHandle().isOp(this.profile); + return server.getHandle().isOp(profile); } @Override public void setOp(boolean value) { - if (value == this.isOp()) { + if (value == isOp()) { return; } if (value) { - this.server.getHandle().op(this.profile); + server.getHandle().op(profile); } else { - this.server.getHandle().deop(this.profile); + server.getHandle().deop(profile); } } @Override public boolean isBanned() { - return ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).isBanned(this.getPlayerProfile()); + return ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).isBanned(getPlayerProfile()); } @Override public BanEntry ban(String reason, Date expires, String source) { - return ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).addBan(this.getPlayerProfile(), reason, expires, source); + return ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).addBan(getPlayerProfile(), reason, expires, source); } @Override public BanEntry ban(String reason, Instant expires, String source) { - return ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).addBan(this.getPlayerProfile(), reason, expires, source); + return ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).addBan(getPlayerProfile(), reason, expires, source); } @Override public BanEntry ban(String reason, Duration duration, String source) { - return ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).addBan(this.getPlayerProfile(), reason, duration, source); + return ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).addBan(getPlayerProfile(), reason, duration, source); } public void setBanned(boolean value) { if (value) { - ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).addBan(this.getPlayerProfile(), null, (Date) null, null); + ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).addBan(getPlayerProfile(), null, (Date) null, null); } else { - ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).pardon(this.getPlayerProfile()); + ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).pardon(getPlayerProfile()); } } @Override public boolean isWhitelisted() { - return this.server.getHandle().getWhiteList().isWhiteListed(this.profile); + return server.getHandle().getWhiteList().isWhiteListed(profile); } @Override public void setWhitelisted(boolean value) { if (value) { - this.server.getHandle().getWhiteList().add(new UserWhiteListEntry(this.profile)); + server.getHandle().getWhiteList().add(new WhiteListEntry(profile)); } else { - this.server.getHandle().getWhiteList().remove(this.profile); + server.getHandle().getWhiteList().remove(profile); } } @@ -154,7 +154,7 @@ public void setWhitelisted(boolean value) { public Map serialize() { Map result = new LinkedHashMap<>(); - result.put("UUID", this.profile.getId().toString()); + result.put("UUID", profile.getId().toString()); return result; } @@ -170,12 +170,12 @@ public static OfflinePlayer deserialize(Map args) { @Override public String toString() { - return this.getClass().getSimpleName() + "[UUID=" + this.profile.getId() + "]"; + return getClass().getSimpleName() + "[UUID=" + profile.getId() + "]"; } @Override public Player getPlayer() { - return this.server.getPlayer(this.getUniqueId()); + return server.getPlayer(getUniqueId()); } @Override @@ -198,16 +198,16 @@ public int hashCode() { return hash; } - private CompoundTag getData() { - return this.storage.load(this.profile.getName(), this.profile.getId().toString()).orElse(null); + private NBTTagCompound getData() { + return storage.load(profile.getName(), profile.getId().toString()).orElse(null); } - private CompoundTag getBukkitData() { - CompoundTag result = this.getData(); + private NBTTagCompound getBukkitData() { + NBTTagCompound result = getData(); if (result != null) { if (!result.contains("bukkit")) { - result.put("bukkit", new CompoundTag()); + result.put("bukkit", new NBTTagCompound()); } result = result.getCompound("bukkit"); } @@ -216,21 +216,21 @@ private CompoundTag getBukkitData() { } private File getDataFile() { - return new File(this.storage.getPlayerDir(), this.getUniqueId() + ".dat"); + return new File(storage.getPlayerDir(), getUniqueId() + ".dat"); } @Override public long getFirstPlayed() { - Player player = this.getPlayer(); + Player player = getPlayer(); if (player != null) return player.getFirstPlayed(); - CompoundTag data = this.getBukkitData(); + NBTTagCompound data = getBukkitData(); if (data != null) { if (data.contains("firstPlayed")) { return data.getLong("firstPlayed"); } else { - File file = this.getDataFile(); + File file = getDataFile(); return file.lastModified(); } } else { @@ -240,16 +240,16 @@ public long getFirstPlayed() { @Override public long getLastPlayed() { - Player player = this.getPlayer(); + Player player = getPlayer(); if (player != null) return player.getLastPlayed(); - CompoundTag data = this.getBukkitData(); + NBTTagCompound data = getBukkitData(); if (data != null) { if (data.contains("lastPlayed")) { return data.getLong("lastPlayed"); } else { - File file = this.getDataFile(); + File file = getDataFile(); return file.lastModified(); } } else { @@ -259,31 +259,31 @@ public long getLastPlayed() { @Override public boolean hasPlayedBefore() { - return this.getData() != null; + return getData() != null; } @Override public Location getLastDeathLocation() { - if (this.getData().contains("LastDeathLocation", 10)) { - return GlobalPos.CODEC.parse(NbtOps.INSTANCE, this.getData().get("LastDeathLocation")).result().map(CraftMemoryMapper::fromNms).orElse(null); + if (getData().contains("LastDeathLocation", 10)) { + return GlobalPos.CODEC.parse(DynamicOpsNBT.INSTANCE, getData().get("LastDeathLocation")).result().map(CraftMemoryMapper::fromNms).orElse(null); } return null; } @Override public Location getLocation() { - CompoundTag data = this.getData(); + NBTTagCompound data = getData(); if (data == null) { return null; } if (data.contains("Pos") && data.contains("Rotation")) { - ListTag position = (ListTag) data.get("Pos"); - ListTag rotation = (ListTag) data.get("Rotation"); + NBTTagList position = (NBTTagList) data.get("Pos"); + NBTTagList rotation = (NBTTagList) data.get("Rotation"); UUID uuid = new UUID(data.getLong("WorldUUIDMost"), data.getLong("WorldUUIDLeast")); - return new Location(this.server.getWorld(uuid), + return new Location(server.getWorld(uuid), position.getDouble(0), position.getDouble(1), position.getDouble(2), @@ -297,50 +297,50 @@ public Location getLocation() { @Override public Location getBedSpawnLocation() { - return this.getRespawnLocation(); + return getRespawnLocation(); } @Override public Location getRespawnLocation() { - CompoundTag data = this.getData(); + NBTTagCompound data = getData(); if (data == null) return null; if (data.contains("SpawnX") && data.contains("SpawnY") && data.contains("SpawnZ")) { String spawnWorld = data.getString("SpawnWorld"); if (spawnWorld.equals("")) { - spawnWorld = this.server.getWorlds().get(0).getName(); + spawnWorld = server.getWorlds().get(0).getName(); } - return new Location(this.server.getWorld(spawnWorld), data.getInt("SpawnX"), data.getInt("SpawnY"), data.getInt("SpawnZ")); + return new Location(server.getWorld(spawnWorld), data.getInt("SpawnX"), data.getInt("SpawnY"), data.getInt("SpawnZ")); } return null; } public void setMetadata(String metadataKey, MetadataValue metadataValue) { - this.server.getPlayerMetadata().setMetadata(this, metadataKey, metadataValue); + server.getPlayerMetadata().setMetadata(this, metadataKey, metadataValue); } public List getMetadata(String metadataKey) { - return this.server.getPlayerMetadata().getMetadata(this, metadataKey); + return server.getPlayerMetadata().getMetadata(this, metadataKey); } public boolean hasMetadata(String metadataKey) { - return this.server.getPlayerMetadata().hasMetadata(this, metadataKey); + return server.getPlayerMetadata().hasMetadata(this, metadataKey); } public void removeMetadata(String metadataKey, Plugin plugin) { - this.server.getPlayerMetadata().removeMetadata(this, metadataKey, plugin); + server.getPlayerMetadata().removeMetadata(this, metadataKey, plugin); } - private ServerStatsCounter getStatisticManager() { - return this.server.getHandle().getPlayerStats(this.getUniqueId(), this.getName()); + private ServerStatisticManager getStatisticManager() { + return server.getHandle().getPlayerStats(getUniqueId(), getName()); } @Override public void incrementStatistic(Statistic statistic) { - if (this.isOnline()) { - this.getPlayer().incrementStatistic(statistic); + if (isOnline()) { + getPlayer().incrementStatistic(statistic); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.incrementStatistic(manager, statistic, null); manager.save(); } @@ -348,10 +348,10 @@ public void incrementStatistic(Statistic statistic) { @Override public void decrementStatistic(Statistic statistic) { - if (this.isOnline()) { - this.getPlayer().decrementStatistic(statistic); + if (isOnline()) { + getPlayer().decrementStatistic(statistic); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.decrementStatistic(manager, statistic, null); manager.save(); } @@ -359,19 +359,19 @@ public void decrementStatistic(Statistic statistic) { @Override public int getStatistic(Statistic statistic) { - if (this.isOnline()) { - return this.getPlayer().getStatistic(statistic); + if (isOnline()) { + return getPlayer().getStatistic(statistic); } else { - return CraftStatistic.getStatistic(this.getStatisticManager(), statistic); + return CraftStatistic.getStatistic(getStatisticManager(), statistic); } } @Override public void incrementStatistic(Statistic statistic, int amount) { - if (this.isOnline()) { - this.getPlayer().incrementStatistic(statistic, amount); + if (isOnline()) { + getPlayer().incrementStatistic(statistic, amount); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.incrementStatistic(manager, statistic, amount, null); manager.save(); } @@ -379,10 +379,10 @@ public void incrementStatistic(Statistic statistic, int amount) { @Override public void decrementStatistic(Statistic statistic, int amount) { - if (this.isOnline()) { - this.getPlayer().decrementStatistic(statistic, amount); + if (isOnline()) { + getPlayer().decrementStatistic(statistic, amount); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.decrementStatistic(manager, statistic, amount, null); manager.save(); } @@ -390,10 +390,10 @@ public void decrementStatistic(Statistic statistic, int amount) { @Override public void setStatistic(Statistic statistic, int newValue) { - if (this.isOnline()) { - this.getPlayer().setStatistic(statistic, newValue); + if (isOnline()) { + getPlayer().setStatistic(statistic, newValue); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.setStatistic(manager, statistic, newValue, null); manager.save(); } @@ -401,10 +401,10 @@ public void setStatistic(Statistic statistic, int newValue) { @Override public void incrementStatistic(Statistic statistic, Material material) { - if (this.isOnline()) { - this.getPlayer().incrementStatistic(statistic, material); + if (isOnline()) { + getPlayer().incrementStatistic(statistic, material); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.incrementStatistic(manager, statistic, material, null); manager.save(); } @@ -412,10 +412,10 @@ public void incrementStatistic(Statistic statistic, Material material) { @Override public void decrementStatistic(Statistic statistic, Material material) { - if (this.isOnline()) { - this.getPlayer().decrementStatistic(statistic, material); + if (isOnline()) { + getPlayer().decrementStatistic(statistic, material); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.decrementStatistic(manager, statistic, material, null); manager.save(); } @@ -423,19 +423,19 @@ public void decrementStatistic(Statistic statistic, Material material) { @Override public int getStatistic(Statistic statistic, Material material) { - if (this.isOnline()) { - return this.getPlayer().getStatistic(statistic, material); + if (isOnline()) { + return getPlayer().getStatistic(statistic, material); } else { - return CraftStatistic.getStatistic(this.getStatisticManager(), statistic, material); + return CraftStatistic.getStatistic(getStatisticManager(), statistic, material); } } @Override public void incrementStatistic(Statistic statistic, Material material, int amount) { - if (this.isOnline()) { - this.getPlayer().incrementStatistic(statistic, material, amount); + if (isOnline()) { + getPlayer().incrementStatistic(statistic, material, amount); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.incrementStatistic(manager, statistic, material, amount, null); manager.save(); } @@ -443,10 +443,10 @@ public void incrementStatistic(Statistic statistic, Material material, int amoun @Override public void decrementStatistic(Statistic statistic, Material material, int amount) { - if (this.isOnline()) { - this.getPlayer().decrementStatistic(statistic, material, amount); + if (isOnline()) { + getPlayer().decrementStatistic(statistic, material, amount); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.decrementStatistic(manager, statistic, material, amount, null); manager.save(); } @@ -454,10 +454,10 @@ public void decrementStatistic(Statistic statistic, Material material, int amoun @Override public void setStatistic(Statistic statistic, Material material, int newValue) { - if (this.isOnline()) { - this.getPlayer().setStatistic(statistic, material, newValue); + if (isOnline()) { + getPlayer().setStatistic(statistic, material, newValue); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.setStatistic(manager, statistic, material, newValue, null); manager.save(); } @@ -465,10 +465,10 @@ public void setStatistic(Statistic statistic, Material material, int newValue) { @Override public void incrementStatistic(Statistic statistic, EntityType entityType) { - if (this.isOnline()) { - this.getPlayer().incrementStatistic(statistic, entityType); + if (isOnline()) { + getPlayer().incrementStatistic(statistic, entityType); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.incrementStatistic(manager, statistic, entityType, null); manager.save(); } @@ -476,10 +476,10 @@ public void incrementStatistic(Statistic statistic, EntityType entityType) { @Override public void decrementStatistic(Statistic statistic, EntityType entityType) { - if (this.isOnline()) { - this.getPlayer().decrementStatistic(statistic, entityType); + if (isOnline()) { + getPlayer().decrementStatistic(statistic, entityType); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.decrementStatistic(manager, statistic, entityType, null); manager.save(); } @@ -487,19 +487,19 @@ public void decrementStatistic(Statistic statistic, EntityType entityType) { @Override public int getStatistic(Statistic statistic, EntityType entityType) { - if (this.isOnline()) { - return this.getPlayer().getStatistic(statistic, entityType); + if (isOnline()) { + return getPlayer().getStatistic(statistic, entityType); } else { - return CraftStatistic.getStatistic(this.getStatisticManager(), statistic, entityType); + return CraftStatistic.getStatistic(getStatisticManager(), statistic, entityType); } } @Override public void incrementStatistic(Statistic statistic, EntityType entityType, int amount) { - if (this.isOnline()) { - this.getPlayer().incrementStatistic(statistic, entityType, amount); + if (isOnline()) { + getPlayer().incrementStatistic(statistic, entityType, amount); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.incrementStatistic(manager, statistic, entityType, amount, null); manager.save(); } @@ -507,10 +507,10 @@ public void incrementStatistic(Statistic statistic, EntityType entityType, int a @Override public void decrementStatistic(Statistic statistic, EntityType entityType, int amount) { - if (this.isOnline()) { - this.getPlayer().decrementStatistic(statistic, entityType, amount); + if (isOnline()) { + getPlayer().decrementStatistic(statistic, entityType, amount); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.decrementStatistic(manager, statistic, entityType, amount, null); manager.save(); } @@ -518,10 +518,10 @@ public void decrementStatistic(Statistic statistic, EntityType entityType, int a @Override public void setStatistic(Statistic statistic, EntityType entityType, int newValue) { - if (this.isOnline()) { - this.getPlayer().setStatistic(statistic, entityType, newValue); + if (isOnline()) { + getPlayer().setStatistic(statistic, entityType, newValue); } else { - ServerStatsCounter manager = this.getStatisticManager(); + ServerStatisticManager manager = getStatisticManager(); CraftStatistic.setStatistic(manager, statistic, entityType, newValue, null); manager.save(); } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftParticle.java b/src/main/java/org/bukkit/craftbukkit/CraftParticle.java index 2a07587f..69d3ef15 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftParticle.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftParticle.java @@ -4,19 +4,21 @@ import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; -import net.minecraft.core.particles.BlockParticleOption; +import net.minecraft.core.IRegistry; import net.minecraft.core.particles.ColorParticleOption; import net.minecraft.core.particles.DustColorTransitionOptions; -import net.minecraft.core.particles.DustParticleOptions; -import net.minecraft.core.particles.ItemParticleOption; -import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleParam; +import net.minecraft.core.particles.ParticleParamBlock; +import net.minecraft.core.particles.ParticleParamItem; +import net.minecraft.core.particles.ParticleParamRedstone; +import net.minecraft.core.particles.ParticleType; import net.minecraft.core.particles.SculkChargeParticleOptions; import net.minecraft.core.particles.ShriekParticleOption; -import net.minecraft.core.particles.SimpleParticleType; +import net.minecraft.core.particles.TargetColorParticleOption; import net.minecraft.core.particles.VibrationParticleOption; import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.gameevent.BlockPositionSource; +import net.minecraft.world.level.gameevent.BlockPosSource; import net.minecraft.world.level.gameevent.EntityPositionSource; import net.minecraft.world.level.gameevent.PositionSource; import org.bukkit.Color; @@ -36,16 +38,15 @@ import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; -import org.joml.Vector3f; public abstract class CraftParticle implements Keyed { private static final Registry> CRAFT_PARTICLE_REGISTRY = new CraftParticleRegistry(CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE)); - public static Particle minecraftToBukkit(net.minecraft.core.particles.ParticleType minecraft) { + public static Particle minecraftToBukkit(net.minecraft.core.particles.Particle minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry> registry = CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE); + IRegistry> registry = CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE); Particle bukkit = Registry.PARTICLE_TYPE.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); @@ -53,14 +54,14 @@ public static Particle minecraftToBukkit(net.minecraft.core.particles.ParticleTy return bukkit; } - public static net.minecraft.core.particles.ParticleType bukkitToMinecraft(Particle bukkit) { + public static net.minecraft.core.particles.Particle bukkitToMinecraft(Particle bukkit) { Preconditions.checkArgument(bukkit != null); return CraftRegistry.getMinecraftRegistry(Registries.PARTICLE_TYPE) .getOptional(CraftNamespacedKey.toMinecraft(bukkit.getKey())).orElseThrow(); } - public static ParticleOptions createParticleParam(Particle particle, D data) { + public static ParticleParam createParticleParam(Particle particle, D data) { Preconditions.checkArgument(particle != null, "particle cannot be null"); data = CraftParticle.convertLegacy(data); @@ -71,7 +72,7 @@ public static ParticleOptions createParticleParam(Particle particle, D data) Preconditions.checkArgument(particle.getDataType().isInstance(data), "data (%s) should be %s", data.getClass(), particle.getDataType()); } - CraftParticle craftParticle = (CraftParticle) CraftParticle.CRAFT_PARTICLE_REGISTRY.get(particle.getKey()); + CraftParticle craftParticle = (CraftParticle) CRAFT_PARTICLE_REGISTRY.get(particle.getKey()); Preconditions.checkArgument(craftParticle != null); @@ -87,76 +88,76 @@ public static T convertLegacy(T object) { } private final NamespacedKey key; - private final net.minecraft.core.particles.ParticleType particle; + private final net.minecraft.core.particles.Particle particle; private final Class clazz; - public CraftParticle(NamespacedKey key, net.minecraft.core.particles.ParticleType particle, Class clazz) { + public CraftParticle(NamespacedKey key, net.minecraft.core.particles.Particle particle, Class clazz) { this.key = key; this.particle = particle; this.clazz = clazz; } - public net.minecraft.core.particles.ParticleType getHandle() { - return this.particle; + public net.minecraft.core.particles.Particle getHandle() { + return particle; } - public abstract ParticleOptions createParticleParam(D data); + public abstract ParticleParam createParticleParam(D data); @Override public NamespacedKey getKey() { - return this.key; + return key; } - public static class CraftParticleRegistry extends CraftRegistry, net.minecraft.core.particles.ParticleType> { + public static class CraftParticleRegistry extends CraftRegistry, net.minecraft.core.particles.Particle> { - private static final Map, CraftParticle>> PARTICLE_MAP = new HashMap<>(); + private static final Map, CraftParticle>> PARTICLE_MAP = new HashMap<>(); - private static final BiFunction, CraftParticle> VOID_FUNCTION = (name, particle) -> new CraftParticle<>(name, particle, Void.class) { + private static final BiFunction, CraftParticle> VOID_FUNCTION = (name, particle) -> new CraftParticle<>(name, particle, Void.class) { @Override - public ParticleOptions createParticleParam(Void data) { - return (SimpleParticleType) this.getHandle(); + public ParticleParam createParticleParam(Void data) { + return (ParticleType) getHandle(); } }; static { - BiFunction, CraftParticle> dustOptionsFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.DustOptions.class) { + BiFunction, CraftParticle> dustOptionsFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.DustOptions.class) { @Override - public ParticleOptions createParticleParam(Particle.DustOptions data) { + public ParticleParam createParticleParam(Particle.DustOptions data) { Color color = data.getColor(); - return new DustParticleOptions(new Vector3f(color.getRed() / 255.0f, color.getGreen() / 255.0f, color.getBlue() / 255.0f), data.getSize()); + return new ParticleParamRedstone(color.asRGB(), data.getSize()); } }; - BiFunction, CraftParticle> itemStackFunction = (name, particle) -> new CraftParticle<>(name, particle, ItemStack.class) { + BiFunction, CraftParticle> itemStackFunction = (name, particle) -> new CraftParticle<>(name, particle, ItemStack.class) { @Override - public ParticleOptions createParticleParam(ItemStack data) { - return new ItemParticleOption((net.minecraft.core.particles.ParticleType) this.getHandle(), CraftItemStack.asNMSCopy(data)); + public ParticleParam createParticleParam(ItemStack data) { + return new ParticleParamItem((net.minecraft.core.particles.Particle) getHandle(), CraftItemStack.asNMSCopy(data)); } }; - BiFunction, CraftParticle> blockDataFunction = (name, particle) -> new CraftParticle<>(name, particle, BlockData.class) { + BiFunction, CraftParticle> blockDataFunction = (name, particle) -> new CraftParticle<>(name, particle, BlockData.class) { @Override - public ParticleOptions createParticleParam(BlockData data) { - return new BlockParticleOption((net.minecraft.core.particles.ParticleType) this.getHandle(), ((CraftBlockData) data).getState()); + public ParticleParam createParticleParam(BlockData data) { + return new ParticleParamBlock((net.minecraft.core.particles.Particle) getHandle(), ((CraftBlockData) data).getState()); } }; - BiFunction, CraftParticle> dustTransitionFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.DustTransition.class) { + BiFunction, CraftParticle> dustTransitionFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.DustTransition.class) { @Override - public ParticleOptions createParticleParam(Particle.DustTransition data) { + public ParticleParam createParticleParam(Particle.DustTransition data) { Color from = data.getColor(); Color to = data.getToColor(); - return new DustColorTransitionOptions(new Vector3f(from.getRed() / 255.0f, from.getGreen() / 255.0f, from.getBlue() / 255.0f), new Vector3f(to.getRed() / 255.0f, to.getGreen() / 255.0f, to.getBlue() / 255.0f), data.getSize()); + return new DustColorTransitionOptions(from.asRGB(), to.asRGB(), data.getSize()); } }; - BiFunction, CraftParticle> vibrationFunction = (name, particle) -> new CraftParticle<>(name, particle, Vibration.class) { + BiFunction, CraftParticle> vibrationFunction = (name, particle) -> new CraftParticle<>(name, particle, Vibration.class) { @Override - public ParticleOptions createParticleParam(Vibration data) { + public ParticleParam createParticleParam(Vibration data) { PositionSource source; if (data.getDestination() instanceof Vibration.Destination.BlockDestination) { Location destination = ((Vibration.Destination.BlockDestination) data.getDestination()).getLocation(); - source = new BlockPositionSource(CraftLocation.toBlockPosition(destination)); + source = new BlockPosSource(CraftLocation.toBlockPos(destination)); } else if (data.getDestination() instanceof Vibration.Destination.EntityDestination) { Entity destination = ((CraftEntity) ((Vibration.Destination.EntityDestination) data.getDestination()).getEntity()).getHandle(); source = new EntityPositionSource(destination, destination.getEyeHeight()); @@ -168,24 +169,31 @@ public ParticleOptions createParticleParam(Vibration data) { } }; - BiFunction, CraftParticle> floatFunction = (name, particle) -> new CraftParticle<>(name, particle, Float.class) { + BiFunction, CraftParticle> floatFunction = (name, particle) -> new CraftParticle<>(name, particle, Float.class) { @Override - public ParticleOptions createParticleParam(Float data) { + public ParticleParam createParticleParam(Float data) { return new SculkChargeParticleOptions(data); } }; - BiFunction, CraftParticle> integerFunction = (name, particle) -> new CraftParticle<>(name, particle, Integer.class) { + BiFunction, CraftParticle> integerFunction = (name, particle) -> new CraftParticle<>(name, particle, Integer.class) { @Override - public ParticleOptions createParticleParam(Integer data) { + public ParticleParam createParticleParam(Integer data) { return new ShriekParticleOption(data); } }; - BiFunction, CraftParticle> colorFunction = (name, particle) -> new CraftParticle<>(name, particle, Color.class) { + BiFunction, CraftParticle> colorFunction = (name, particle) -> new CraftParticle<>(name, particle, Color.class) { @Override - public ParticleOptions createParticleParam(Color color) { - return ColorParticleOption.create((net.minecraft.core.particles.ParticleType) particle, color.asARGB()); + public ParticleParam createParticleParam(Color color) { + return ColorParticleOption.create((net.minecraft.core.particles.Particle) particle, color.asARGB()); + } + }; + + BiFunction, CraftParticle> targetColorFunction = (name, particle) -> new CraftParticle<>(name, particle, Particle.TargetColor.class) { + @Override + public ParticleParam createParticleParam(Particle.TargetColor data) { + return new TargetColorParticleOption(CraftLocation.toVec3D(data.getTarget()), data.getColor().asRGB()); } }; @@ -200,23 +208,25 @@ public ParticleOptions createParticleParam(Color color) { add("block_marker", blockDataFunction); add("entity_effect", colorFunction); add("dust_pillar", blockDataFunction); + add("block_crumble", blockDataFunction); + add("trail", targetColorFunction); } - private static void add(String name, BiFunction, CraftParticle> function) { - CraftParticleRegistry.PARTICLE_MAP.put(NamespacedKey.fromString(name), function); + private static void add(String name, BiFunction, CraftParticle> function) { + PARTICLE_MAP.put(NamespacedKey.fromString(name), function); } - public CraftParticleRegistry(net.minecraft.core.Registry> minecraftRegistry) { + public CraftParticleRegistry(IRegistry> minecraftRegistry) { super(CraftParticle.class, minecraftRegistry, null, FieldRename.PARTICLE_TYPE_RENAME); } @Override - public CraftParticle createBukkit(NamespacedKey namespacedKey, net.minecraft.core.particles.ParticleType particle) { + public CraftParticle createBukkit(NamespacedKey namespacedKey, net.minecraft.core.particles.Particle particle) { if (particle == null) { return null; } - BiFunction, CraftParticle> function = CraftParticleRegistry.PARTICLE_MAP.getOrDefault(namespacedKey, CraftParticleRegistry.VOID_FUNCTION); + BiFunction, CraftParticle> function = PARTICLE_MAP.getOrDefault(namespacedKey, VOID_FUNCTION); return function.apply(namespacedKey, particle); } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftRaid.java b/src/main/java/org/bukkit/craftbukkit/CraftRaid.java index b8ce1c1c..434494b7 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftRaid.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftRaid.java @@ -8,7 +8,8 @@ import java.util.UUID; import java.util.function.Function; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; +import net.minecraft.world.entity.raid.EntityRaider; +import net.minecraft.world.level.World; import org.bukkit.Location; import org.bukkit.Raid; import org.bukkit.Raid.RaidStatus; @@ -25,40 +26,40 @@ public CraftRaid(net.minecraft.world.entity.raid.Raid handle) { @Override public boolean isStarted() { - return this.handle.isStarted(); + return handle.isStarted(); } @Override public long getActiveTicks() { - return this.handle.ticksActive; + return handle.ticksActive; } @Override public int getBadOmenLevel() { - return this.handle.raidOmenLevel; + return handle.raidOmenLevel; } @Override public void setBadOmenLevel(int badOmenLevel) { - int max = this.handle.getMaxRaidOmenLevel(); + int max = handle.getMaxRaidOmenLevel(); Preconditions.checkArgument(0 <= badOmenLevel && badOmenLevel <= max, "Bad Omen level must be between 0 and %s", max); - this.handle.raidOmenLevel = badOmenLevel; + handle.raidOmenLevel = badOmenLevel; } @Override public Location getLocation() { - BlockPos pos = this.handle.getCenter(); - Level world = this.handle.getLevel(); + BlockPos pos = handle.getCenter(); + World world = handle.getLevel(); return CraftLocation.toBukkit(pos, world.getWorld()); } @Override public RaidStatus getStatus() { - if (this.handle.isStopped()) { + if (handle.isStopped()) { return RaidStatus.STOPPED; - } else if (this.handle.isVictory()) { + } else if (handle.isVictory()) { return RaidStatus.VICTORY; - } else if (this.handle.isLoss()) { + } else if (handle.isLoss()) { return RaidStatus.LOSS; } else { return RaidStatus.ONGOING; @@ -67,40 +68,40 @@ public RaidStatus getStatus() { @Override public int getSpawnedGroups() { - return this.handle.getGroupsSpawned(); + return handle.getGroupsSpawned(); } @Override public int getTotalGroups() { - return this.handle.numGroups + (this.handle.raidOmenLevel > 1 ? 1 : 0); + return handle.numGroups + (handle.raidOmenLevel > 1 ? 1 : 0); } @Override public int getTotalWaves() { - return this.handle.numGroups; + return handle.numGroups; } @Override public float getTotalHealth() { - return this.handle.getHealthOfLivingRaiders(); + return handle.getHealthOfLivingRaiders(); } @Override public Set getHeroes() { - return Collections.unmodifiableSet(this.handle.heroesOfTheVillage); + return Collections.unmodifiableSet(handle.heroesOfTheVillage); } @Override public List getRaiders() { - return this.handle.getRaiders().stream().map(new Function() { + return handle.getRaiders().stream().map(new Function() { @Override - public Raider apply(net.minecraft.world.entity.raid.Raider entityRaider) { + public Raider apply(EntityRaider entityRaider) { return (Raider) entityRaider.getBukkitEntity(); } }).collect(ImmutableList.toImmutableList()); } public net.minecraft.world.entity.raid.Raid getHandle() { - return this.handle; + return handle; } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java b/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java index f7dde8fd..a0905765 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java @@ -13,15 +13,18 @@ import net.minecraft.data.worldgen.features.TreeFeatures; import net.minecraft.resources.ResourceKey; import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.entity.SpawnGroupData; -import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.entity.EntityInsentient; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.GroupDataEntity; +import net.minecraft.world.entity.projectile.EntityPotion; +import net.minecraft.world.level.GeneratorAccessSeed; +import net.minecraft.world.level.biome.BiomeBase; +import net.minecraft.world.level.block.BlockChorusFlower; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.ChorusFlowerBlock; +import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.portal.DimensionTransition; +import net.minecraft.world.level.levelgen.feature.WorldGenFeatureConfigured; +import net.minecraft.world.level.portal.TeleportTransition; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.RegionAccessor; @@ -61,123 +64,123 @@ public abstract class CraftRegionAccessor implements RegionAccessor { - public abstract WorldGenLevel getHandle(); + public abstract GeneratorAccessSeed getHandle(); public boolean isNormalWorld() { - return this.getHandle() instanceof net.minecraft.server.level.ServerLevel; + return getHandle() instanceof net.minecraft.server.level.WorldServer; } @Override public Biome getBiome(Location location) { - return this.getBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return getBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public Biome getBiome(int x, int y, int z) { - return CraftBiome.minecraftHolderToBukkit(this.getHandle().getNoiseBiome(x >> 2, y >> 2, z >> 2)); + return CraftBiome.minecraftHolderToBukkit(getHandle().getNoiseBiome(x >> 2, y >> 2, z >> 2)); } @Override public void setBiome(Location location, Biome biome) { - this.setBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ(), biome); + setBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ(), biome); } @Override public void setBiome(int x, int y, int z, Biome biome) { Preconditions.checkArgument(biome != Biome.CUSTOM, "Cannot set the biome to %s", biome); - Holder biomeBase = CraftBiome.bukkitToMinecraftHolder(biome); - this.setBiome(x, y, z, biomeBase); + Holder biomeBase = CraftBiome.bukkitToMinecraftHolder(biome); + setBiome(x, y, z, biomeBase); } - public abstract void setBiome(int x, int y, int z, Holder biomeBase); + public abstract void setBiome(int x, int y, int z, Holder biomeBase); @Override public BlockState getBlockState(Location location) { - return this.getBlockState(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return getBlockState(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public BlockState getBlockState(int x, int y, int z) { - return CraftBlock.at(this.getHandle(), new BlockPos(x, y, z)).getState(); + return CraftBlock.at(getHandle(), new BlockPos(x, y, z)).getState(); } @Override public BlockData getBlockData(Location location) { - return this.getBlockData(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return getBlockData(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public BlockData getBlockData(int x, int y, int z) { - return CraftBlockData.fromData(this.getData(x, y, z)); + return CraftBlockData.fromData(getData(x, y, z)); } @Override public Material getType(Location location) { - return this.getType(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return getType(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public Material getType(int x, int y, int z) { - return CraftBlockType.minecraftToBukkit(this.getData(x, y, z).getBlock()); + return CraftBlockType.minecraftToBukkit(getData(x, y, z).getBlock()); } - private net.minecraft.world.level.block.state.BlockState getData(int x, int y, int z) { - return this.getHandle().getBlockState(new BlockPos(x, y, z)); + private IBlockData getData(int x, int y, int z) { + return getHandle().getBlockState(new BlockPos(x, y, z)); } @Override public void setBlockData(Location location, BlockData blockData) { - this.setBlockData(location.getBlockX(), location.getBlockY(), location.getBlockZ(), blockData); + setBlockData(location.getBlockX(), location.getBlockY(), location.getBlockZ(), blockData); } @Override public void setBlockData(int x, int y, int z, BlockData blockData) { - WorldGenLevel world = this.getHandle(); + GeneratorAccessSeed world = getHandle(); BlockPos pos = new BlockPos(x, y, z); - net.minecraft.world.level.block.state.BlockState old = this.getHandle().getBlockState(pos); + IBlockData old = getHandle().getBlockState(pos); CraftBlock.setTypeAndData(world, pos, old, ((CraftBlockData) blockData).getState(), true); } @Override public void setType(Location location, Material material) { - this.setType(location.getBlockX(), location.getBlockY(), location.getBlockZ(), material); + setType(location.getBlockX(), location.getBlockY(), location.getBlockZ(), material); } @Override public void setType(int x, int y, int z, Material material) { - this.setBlockData(x, y, z, material.createBlockData()); + setBlockData(x, y, z, material.createBlockData()); } @Override public int getHighestBlockYAt(int x, int z) { - return this.getHighestBlockYAt(x, z, org.bukkit.HeightMap.MOTION_BLOCKING); + return getHighestBlockYAt(x, z, org.bukkit.HeightMap.MOTION_BLOCKING); } @Override public int getHighestBlockYAt(Location location) { - return this.getHighestBlockYAt(location.getBlockX(), location.getBlockZ()); + return getHighestBlockYAt(location.getBlockX(), location.getBlockZ()); } @Override public int getHighestBlockYAt(int x, int z, org.bukkit.HeightMap heightMap) { - return this.getHandle().getHeight(CraftHeightMap.toNMS(heightMap), x, z); + return getHandle().getHeight(CraftHeightMap.toNMS(heightMap), x, z); } @Override public int getHighestBlockYAt(Location location, org.bukkit.HeightMap heightMap) { - return this.getHighestBlockYAt(location.getBlockX(), location.getBlockZ(), heightMap); + return getHighestBlockYAt(location.getBlockX(), location.getBlockZ(), heightMap); } @Override public boolean generateTree(Location location, Random random, TreeType treeType) { - BlockPos pos = CraftLocation.toBlockPosition(location); - return this.generateTree(this.getHandle(), this.getHandle().getMinecraftWorld().getChunkSource().getGenerator(), pos, new RandomSourceWrapper(random), treeType); + BlockPos pos = CraftLocation.toBlockPos(location); + return generateTree(getHandle(), getHandle().getMinecraftWorld().getChunkSource().getGenerator(), pos, new RandomSourceWrapper(random), treeType); } @Override public boolean generateTree(Location location, Random random, TreeType treeType, Consumer consumer) { - return this.generateTree(location, random, treeType, (consumer == null) ? null : (block) -> { + return generateTree(location, random, treeType, (consumer == null) ? null : (block) -> { consumer.accept(block); return true; }); @@ -185,9 +188,9 @@ public boolean generateTree(Location location, Random random, TreeType treeType, @Override public boolean generateTree(Location location, Random random, TreeType treeType, Predicate predicate) { - BlockPos pos = CraftLocation.toBlockPosition(location); - BlockStateListPopulator populator = new BlockStateListPopulator(this.getHandle()); - boolean result = this.generateTree(populator, this.getHandle().getMinecraftWorld().getChunkSource().getGenerator(), pos, new RandomSourceWrapper(random), treeType); + BlockPos pos = CraftLocation.toBlockPos(location); + BlockStateListPopulator populator = new BlockStateListPopulator(getHandle()); + boolean result = generateTree(populator, getHandle().getMinecraftWorld().getChunkSource().getGenerator(), pos, new RandomSourceWrapper(random), treeType); populator.refreshTiles(); for (BlockState blockState : populator.getList()) { @@ -199,8 +202,8 @@ public boolean generateTree(Location location, Random random, TreeType treeType, return result; } - public boolean generateTree(WorldGenLevel access, ChunkGenerator chunkGenerator, BlockPos pos, RandomSource random, TreeType treeType) { - ResourceKey> gen; + public boolean generateTree(GeneratorAccessSeed access, ChunkGenerator chunkGenerator, BlockPos pos, RandomSource random, TreeType treeType) { + ResourceKey> gen; switch (treeType) { case BIG_TREE: gen = TreeFeatures.FANCY_OAK; @@ -251,7 +254,7 @@ public boolean generateTree(WorldGenLevel access, ChunkGenerator chunkGenerator, gen = TreeFeatures.SUPER_BIRCH_BEES_0002; break; case CHORUS_PLANT: - ((ChorusFlowerBlock) Blocks.CHORUS_FLOWER).generatePlant(access, pos, random, 8); + ((BlockChorusFlower) Blocks.CHORUS_FLOWER).generatePlant(access, pos, random, 8); return true; case CRIMSON_FUNGUS: gen = TreeFeatures.CRIMSON_FUNGUS_PLANTED; @@ -277,29 +280,29 @@ public boolean generateTree(WorldGenLevel access, ChunkGenerator chunkGenerator, break; } - Holder> holder = access.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).getHolder(gen).orElse(null); + Holder> holder = access.registryAccess().lookupOrThrow(Registries.CONFIGURED_FEATURE).get(gen).orElse(null); return (holder != null) ? holder.value().place(access, chunkGenerator, random, pos) : false; } @Override public Entity spawnEntity(Location location, EntityType entityType) { - return this.spawn(location, entityType.getEntityClass()); + return spawn(location, entityType.getEntityClass()); } @Override public Entity spawnEntity(Location loc, EntityType type, boolean randomizeData) { - return this.spawn(loc, type.getEntityClass(), null, CreatureSpawnEvent.SpawnReason.CUSTOM, randomizeData); + return spawn(loc, type.getEntityClass(), null, CreatureSpawnEvent.SpawnReason.CUSTOM, randomizeData); } @Override public List getEntities() { List list = new ArrayList(); - this.getNMSEntities().forEach(entity -> { + getNMSEntities().forEach(entity -> { Entity bukkitEntity = entity.getBukkitEntity(); // Assuming that bukkitEntity isn't null - if (bukkitEntity != null && (!this.isNormalWorld() || bukkitEntity.isValid())) { + if (bukkitEntity != null && (!isNormalWorld() || bukkitEntity.isValid())) { list.add(bukkitEntity); } }); @@ -311,11 +314,11 @@ public List getEntities() { public List getLivingEntities() { List list = new ArrayList(); - this.getNMSEntities().forEach(entity -> { + getNMSEntities().forEach(entity -> { Entity bukkitEntity = entity.getBukkitEntity(); // Assuming that bukkitEntity isn't null - if (bukkitEntity != null && bukkitEntity instanceof LivingEntity && (!this.isNormalWorld() || bukkitEntity.isValid())) { + if (bukkitEntity != null && bukkitEntity instanceof LivingEntity && (!isNormalWorld() || bukkitEntity.isValid())) { list.add((LivingEntity) bukkitEntity); } }); @@ -328,7 +331,7 @@ public List getLivingEntities() { public Collection getEntitiesByClass(Class clazz) { Collection list = new ArrayList(); - this.getNMSEntities().forEach(entity -> { + getNMSEntities().forEach(entity -> { Entity bukkitEntity = entity.getBukkitEntity(); if (bukkitEntity == null) { @@ -337,7 +340,7 @@ public Collection getEntitiesByClass(Class clazz) { Class bukkitClass = bukkitEntity.getClass(); - if (clazz.isAssignableFrom(bukkitClass) && (!this.isNormalWorld() || bukkitEntity.isValid())) { + if (clazz.isAssignableFrom(bukkitClass) && (!isNormalWorld() || bukkitEntity.isValid())) { list.add((T) bukkitEntity); } }); @@ -349,7 +352,7 @@ public Collection getEntitiesByClass(Class clazz) { public Collection getEntitiesByClasses(Class... classes) { Collection list = new ArrayList(); - this.getNMSEntities().forEach(entity -> { + getNMSEntities().forEach(entity -> { Entity bukkitEntity = entity.getBukkitEntity(); if (bukkitEntity == null) { @@ -360,7 +363,7 @@ public Collection getEntitiesByClasses(Class... classes) { for (Class clazz : classes) { if (clazz.isAssignableFrom(bukkitClass)) { - if (!this.isNormalWorld() || bukkitEntity.isValid()) { + if (!isNormalWorld() || bukkitEntity.isValid()) { list.add(bukkitEntity); } break; @@ -376,9 +379,9 @@ public Collection getEntitiesByClasses(Class... classes) { @Override @SuppressWarnings("unchecked") public T createEntity(Location location, Class clazz) throws IllegalArgumentException { - net.minecraft.world.entity.Entity entity = this.createEntity(location, clazz, true); + net.minecraft.world.entity.Entity entity = createEntity(location, clazz, true); - if (!this.isNormalWorld()) { + if (!isNormalWorld()) { entity.generation = true; } @@ -387,27 +390,27 @@ public T createEntity(Location location, Class clazz) thro @Override public T spawn(Location location, Class clazz) throws IllegalArgumentException { - return this.spawn(location, clazz, null, CreatureSpawnEvent.SpawnReason.CUSTOM); + return spawn(location, clazz, null, CreatureSpawnEvent.SpawnReason.CUSTOM); } @Override public T spawn(Location location, Class clazz, Consumer function) throws IllegalArgumentException { - return this.spawn(location, clazz, function, CreatureSpawnEvent.SpawnReason.CUSTOM); + return spawn(location, clazz, function, CreatureSpawnEvent.SpawnReason.CUSTOM); } @Override public T spawn(Location location, Class clazz, boolean randomizeData, Consumer function) throws IllegalArgumentException { - return this.spawn(location, clazz, function, CreatureSpawnEvent.SpawnReason.CUSTOM, randomizeData); + return spawn(location, clazz, function, CreatureSpawnEvent.SpawnReason.CUSTOM, randomizeData); } public T spawn(Location location, Class clazz, Consumer function, CreatureSpawnEvent.SpawnReason reason) throws IllegalArgumentException { - return this.spawn(location, clazz, function, reason, true); + return spawn(location, clazz, function, reason, true); } public T spawn(Location location, Class clazz, Consumer function, CreatureSpawnEvent.SpawnReason reason, boolean randomizeData) throws IllegalArgumentException { - net.minecraft.world.entity.Entity entity = this.createEntity(location, clazz, randomizeData); + net.minecraft.world.entity.Entity entity = createEntity(location, clazz, randomizeData); - return this.addEntity(entity, reason, function, randomizeData); + return addEntity(entity, reason, function, randomizeData); } @Override @@ -415,28 +418,28 @@ public T spawn(Location location, Class clazz, Consumer T addEntity(T entity) { Preconditions.checkArgument(!entity.isInWorld(), "Entity has already been added to a world"); net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); - if (nmsEntity.level() != this.getHandle().getLevel()) { - nmsEntity = nmsEntity.changeDimension(new DimensionTransition(getHandle().getLevel(), nmsEntity, DimensionTransition.DO_NOTHING)); + if (nmsEntity.level() != getHandle().getLevel()) { + nmsEntity = nmsEntity.teleport(new TeleportTransition(getHandle().getLevel(), nmsEntity, TeleportTransition.DO_NOTHING)); } - this.addEntityWithPassengers(nmsEntity, CreatureSpawnEvent.SpawnReason.CUSTOM); + addEntityWithPassengers(nmsEntity, CreatureSpawnEvent.SpawnReason.CUSTOM); return (T) nmsEntity.getBukkitEntity(); } @SuppressWarnings("unchecked") public T addEntity(net.minecraft.world.entity.Entity entity, CreatureSpawnEvent.SpawnReason reason) throws IllegalArgumentException { - return this.addEntity(entity, reason, null, true); + return addEntity(entity, reason, null, true); } @SuppressWarnings("unchecked") public T addEntity(net.minecraft.world.entity.Entity entity, CreatureSpawnEvent.SpawnReason reason, Consumer function, boolean randomizeData) throws IllegalArgumentException { Preconditions.checkArgument(entity != null, "Cannot spawn null entity"); - if (randomizeData && entity instanceof Mob) { - ((Mob) entity).finalizeSpawn(this.getHandle(), this.getHandle().getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.COMMAND, (SpawnGroupData) null); + if (randomizeData && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).finalizeSpawn(getHandle(), getHandle().getCurrentDifficultyAt(entity.blockPosition()), EntitySpawnReason.COMMAND, (GroupDataEntity) null); } - if (!this.isNormalWorld()) { + if (!isNormalWorld()) { entity.generation = true; } @@ -444,7 +447,7 @@ public T addEntity(net.minecraft.world.entity.Entity entity, function.accept((T) entity.getBukkitEntity()); } - this.addEntityToWorld(entity, reason); + addEntityToWorld(entity, reason); return (T) entity.getBukkitEntity(); } @@ -454,7 +457,7 @@ public T addEntity(net.minecraft.world.entity.Entity entity, @SuppressWarnings("unchecked") public net.minecraft.world.entity.Entity makeEntity(Location location, Class clazz) throws IllegalArgumentException { - return this.createEntity(location, clazz, true); + return createEntity(location, clazz, true); } @SuppressWarnings("unchecked") @@ -472,7 +475,7 @@ public net.minecraft.world.entity.Entity createEntity(Location location, Class ((net.minecraft.world.entity.projectile.ThrownPotion) other).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); + runOld = other -> ((EntityPotion) other).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); } else if (clazz == Minecart.class) { clazz = RideableMinecart.class; } else if (clazz == SizedFireball.class) { @@ -496,11 +499,11 @@ public net.minecraft.world.entity.Entity createEntity(Location location, Class implements Registry { - private static final BiFunction NONE = (namespacedKey, apiVersion) -> namespacedKey; - private static RegistryAccess registry; + private static IRegistryCustom registry; - public static void setMinecraftRegistry(RegistryAccess registry) { + public static void setMinecraftRegistry(IRegistryCustom registry) { Preconditions.checkState(CraftRegistry.registry == null, "Registry already set"); CraftRegistry.registry = registry; } - public static RegistryAccess getMinecraftRegistry() { + public static IRegistryCustom getMinecraftRegistry() { return registry; } - public static net.minecraft.core.Registry getMinecraftRegistry(ResourceKey> key) { - return getMinecraftRegistry().registryOrThrow(key); + public static IRegistry getMinecraftRegistry(ResourceKey> key) { + return getMinecraftRegistry().lookupOrThrow(key); } /** @@ -85,10 +85,10 @@ public static net.minecraft.core.Registry getMinecraftRegistry(ResourceKe * @param bukkitRegistry the bukkit registry to use * @return the bukkit representation of the minecraft value */ - public static B minecraftToBukkit(M minecraft, ResourceKey> registryKey, Registry bukkitRegistry) { + public static B minecraftToBukkit(M minecraft, ResourceKey> registryKey, Registry bukkitRegistry) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(registryKey); + IRegistry registry = CraftRegistry.getMinecraftRegistry(registryKey); B bukkit = bukkitRegistry.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft) .orElseThrow(() -> new IllegalStateException(String.format("Cannot convert '%s' to bukkit representation, since it is not registered.", minecraft))).location())); @@ -110,12 +110,12 @@ public static M bukkitToMinecraft(B bukkit) { return ((Handleable) bukkit).getHandle(); } - public static Holder bukkitToMinecraftHolder(B bukkit, ResourceKey> registryKey) { + public static Holder bukkitToMinecraftHolder(B bukkit, ResourceKey> registryKey) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(registryKey); + IRegistry registry = CraftRegistry.getMinecraftRegistry(registryKey); - if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -130,66 +130,66 @@ public static Holder bukkitToMinecraftHolder(B bukkit, R * @param registryHolder the minecraft registry holder * @return the bukkit registry of the provided class */ - public static Registry createRegistry(Class bukkitClass, RegistryAccess registryHolder) { + public static Registry createRegistry(Class bukkitClass, IRegistryCustom registryHolder) { if (bukkitClass == Enchantment.class) { - return new CraftRegistry<>(Enchantment.class, registryHolder.registryOrThrow(Registries.ENCHANTMENT), CraftEnchantment::new, FieldRename.ENCHANTMENT_RENAME); + return new CraftRegistry<>(Enchantment.class, registryHolder.lookupOrThrow(Registries.ENCHANTMENT), CraftEnchantment::new, FieldRename.ENCHANTMENT_RENAME); } if (bukkitClass == GameEvent.class) { - return new CraftRegistry<>(GameEvent.class, registryHolder.registryOrThrow(Registries.GAME_EVENT), CraftGameEvent::new, FieldRename.NONE); + return new CraftRegistry<>(GameEvent.class, registryHolder.lookupOrThrow(Registries.GAME_EVENT), CraftGameEvent::new, FieldRename.NONE); } if (bukkitClass == MusicInstrument.class) { - return new CraftRegistry<>(MusicInstrument.class, registryHolder.registryOrThrow(Registries.INSTRUMENT), CraftMusicInstrument::new, FieldRename.NONE); + return new CraftRegistry<>(MusicInstrument.class, registryHolder.lookupOrThrow(Registries.INSTRUMENT), CraftMusicInstrument::new, FieldRename.NONE); } - if (bukkitClass == org.bukkit.inventory.MenuType.class) { - return new CraftRegistry<>(org.bukkit.inventory.MenuType.class, registryHolder.registryOrThrow(Registries.MENU), CraftMenuType::new, FieldRename.NONE); + if (bukkitClass == MenuType.class) { + return new CraftRegistry<>(MenuType.class, registryHolder.lookupOrThrow(Registries.MENU), CraftMenuType::new, FieldRename.NONE); } if (bukkitClass == PotionEffectType.class) { - return new CraftRegistry<>(PotionEffectType.class, registryHolder.registryOrThrow(Registries.MOB_EFFECT), CraftPotionEffectType::new, FieldRename.NONE); + return new CraftRegistry<>(PotionEffectType.class, registryHolder.lookupOrThrow(Registries.MOB_EFFECT), CraftPotionEffectType::new, FieldRename.NONE); } if (bukkitClass == Structure.class) { - return new CraftRegistry<>(Structure.class, registryHolder.registryOrThrow(Registries.STRUCTURE), CraftStructure::new, FieldRename.NONE); + return new CraftRegistry<>(Structure.class, registryHolder.lookupOrThrow(Registries.STRUCTURE), CraftStructure::new, FieldRename.NONE); } if (bukkitClass == StructureType.class) { - return new CraftRegistry<>(StructureType.class, registryHolder.registryOrThrow(Registries.STRUCTURE_TYPE), CraftStructureType::new, FieldRename.NONE); + return new CraftRegistry<>(StructureType.class, registryHolder.lookupOrThrow(Registries.STRUCTURE_TYPE), CraftStructureType::new, FieldRename.NONE); } if (bukkitClass == Villager.Type.class) { - return new CraftRegistry<>(Villager.Type.class, registryHolder.registryOrThrow(Registries.VILLAGER_TYPE), CraftVillager.CraftType::new, FieldRename.NONE); + return new CraftRegistry<>(Villager.Type.class, registryHolder.lookupOrThrow(Registries.VILLAGER_TYPE), CraftVillager.CraftType::new, FieldRename.NONE); } if (bukkitClass == Villager.Profession.class) { - return new CraftRegistry<>(Villager.Profession.class, registryHolder.registryOrThrow(Registries.VILLAGER_PROFESSION), CraftVillager.CraftProfession::new, FieldRename.NONE); + return new CraftRegistry<>(Villager.Profession.class, registryHolder.lookupOrThrow(Registries.VILLAGER_PROFESSION), CraftVillager.CraftProfession::new, FieldRename.NONE); } if (bukkitClass == TrimMaterial.class) { - return new CraftRegistry<>(TrimMaterial.class, registryHolder.registryOrThrow(Registries.TRIM_MATERIAL), CraftTrimMaterial::new, FieldRename.NONE); + return new CraftRegistry<>(TrimMaterial.class, registryHolder.lookupOrThrow(Registries.TRIM_MATERIAL), CraftTrimMaterial::new, FieldRename.NONE); } if (bukkitClass == TrimPattern.class) { - return new CraftRegistry<>(TrimPattern.class, registryHolder.registryOrThrow(Registries.TRIM_PATTERN), CraftTrimPattern::new, FieldRename.NONE); + return new CraftRegistry<>(TrimPattern.class, registryHolder.lookupOrThrow(Registries.TRIM_PATTERN), CraftTrimPattern::new, FieldRename.NONE); } if (bukkitClass == DamageType.class) { - return new CraftRegistry<>(DamageType.class, registryHolder.registryOrThrow(Registries.DAMAGE_TYPE), CraftDamageType::new, FieldRename.NONE); + return new CraftRegistry<>(DamageType.class, registryHolder.lookupOrThrow(Registries.DAMAGE_TYPE), CraftDamageType::new, FieldRename.NONE); } if (bukkitClass == JukeboxSong.class) { - return new CraftRegistry<>(JukeboxSong.class, registryHolder.registryOrThrow(Registries.JUKEBOX_SONG), CraftJukeboxSong::new, FieldRename.NONE); + return new CraftRegistry<>(JukeboxSong.class, registryHolder.lookupOrThrow(Registries.JUKEBOX_SONG), CraftJukeboxSong::new, FieldRename.NONE); } if (bukkitClass == Wolf.Variant.class) { - return new CraftRegistry<>(Wolf.Variant.class, registryHolder.registryOrThrow(Registries.WOLF_VARIANT), CraftWolf.CraftVariant::new, FieldRename.NONE); + return new CraftRegistry<>(Wolf.Variant.class, registryHolder.lookupOrThrow(Registries.WOLF_VARIANT), CraftWolf.CraftVariant::new, FieldRename.NONE); } if (bukkitClass == BlockType.class) { - return new CraftRegistry<>(BlockType.class, registryHolder.registryOrThrow(Registries.BLOCK), CraftBlockType::new, FieldRename.NONE); + return new CraftRegistry<>(BlockType.class, registryHolder.lookupOrThrow(Registries.BLOCK), CraftBlockType::new, FieldRename.NONE); } if (bukkitClass == ItemType.class) { - return new CraftRegistry<>(ItemType.class, registryHolder.registryOrThrow(Registries.ITEM), CraftItemType::new, FieldRename.NONE); + return new CraftRegistry<>(ItemType.class, registryHolder.lookupOrThrow(Registries.ITEM), CraftItemType::new, FieldRename.NONE); } if (bukkitClass == Frog.Variant.class) { - return new CraftRegistry<>(Frog.Variant.class, registryHolder.registryOrThrow(Registries.FROG_VARIANT), CraftFrog.CraftVariant::new, FieldRename.NONE); + return new CraftRegistry<>(Frog.Variant.class, registryHolder.lookupOrThrow(Registries.FROG_VARIANT), CraftFrog.CraftVariant::new, FieldRename.NONE); } if (bukkitClass == Cat.Type.class) { - return new CraftRegistry<>(Cat.Type.class, registryHolder.registryOrThrow(Registries.CAT_VARIANT), CraftCat.CraftType::new, FieldRename.NONE); + return new CraftRegistry<>(Cat.Type.class, registryHolder.lookupOrThrow(Registries.CAT_VARIANT), CraftCat.CraftType::new, FieldRename.NONE); } if (bukkitClass == MapCursor.Type.class) { - return new CraftRegistry<>(MapCursor.Type.class, registryHolder.registryOrThrow(Registries.MAP_DECORATION_TYPE), CraftMapCursor.CraftType::new, FieldRename.NONE); + return new CraftRegistry<>(MapCursor.Type.class, registryHolder.lookupOrThrow(Registries.MAP_DECORATION_TYPE), CraftMapCursor.CraftType::new, FieldRename.NONE); } if (bukkitClass == PatternType.class) { - return new CraftRegistry<>(PatternType.class, registryHolder.registryOrThrow(Registries.BANNER_PATTERN), CraftPatternType::new, FieldRename.NONE); + return new CraftRegistry<>(PatternType.class, registryHolder.lookupOrThrow(Registries.BANNER_PATTERN), CraftPatternType::new, FieldRename.NONE); } return null; @@ -225,12 +225,12 @@ public static B get(Registry bukkit, NamespacedKey namespac private final Class bukkitClass; private final Map cache = new HashMap<>(); - private final net.minecraft.core.Registry minecraftRegistry; + private final IRegistry minecraftRegistry; private final BiFunction minecraftToBukkit; private final BiFunction updater; private boolean init; - public CraftRegistry(Class bukkitClass, net.minecraft.core.Registry minecraftRegistry, BiFunction minecraftToBukkit, BiFunction updater) { + public CraftRegistry(Class bukkitClass, IRegistry minecraftRegistry, BiFunction minecraftToBukkit, BiFunction updater) { this.bukkitClass = bukkitClass; this.minecraftRegistry = minecraftRegistry; this.minecraftToBukkit = minecraftToBukkit; @@ -279,6 +279,16 @@ public B get(NamespacedKey namespacedKey) { return bukkit; } + @NotNull + @Override + public B getOrThrow(@NotNull NamespacedKey namespacedKey) { + B object = get(namespacedKey); + + Preconditions.checkArgument(object != null, "No %s registry entry found for key %s.", minecraftRegistry.key(), namespacedKey); + + return object; + } + @NotNull @Override public Stream stream() { diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java index 186963d1..d496815a 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java @@ -16,7 +16,6 @@ import com.mojang.serialization.Dynamic; import com.mojang.serialization.Lifecycle; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; @@ -46,74 +45,77 @@ import javax.imageio.ImageIO; import jline.console.ConsoleReader; import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.commands.CommandDispatcher; +import net.minecraft.commands.CommandListenerWrapper; +import net.minecraft.commands.arguments.ArgumentEntity; import net.minecraft.core.BlockPos; -import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.IRegistry; +import net.minecraft.core.IRegistryCustom; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.NbtException; import net.minecraft.nbt.ReportedNbtException; +import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.ConsoleInput; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.ServerCommand; import net.minecraft.server.WorldLoader; -import net.minecraft.server.bossevents.CustomBossEvent; -import net.minecraft.server.commands.ReloadCommand; +import net.minecraft.server.bossevents.BossBattleCustom; +import net.minecraft.server.commands.CommandReload; import net.minecraft.server.dedicated.DedicatedPlayerList; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.server.dedicated.DedicatedServerProperties; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.dedicated.DedicatedServerSettings; +import net.minecraft.server.level.EntityPlayer; import net.minecraft.server.level.TicketType; -import net.minecraft.server.players.IpBanListEntry; +import net.minecraft.server.level.WorldServer; +import net.minecraft.server.players.GameProfileBanEntry; +import net.minecraft.server.players.IpBanEntry; +import net.minecraft.server.players.OpListEntry; import net.minecraft.server.players.PlayerList; -import net.minecraft.server.players.ServerOpListEntry; -import net.minecraft.server.players.UserBanListEntry; -import net.minecraft.server.players.UserWhiteListEntry; +import net.minecraft.server.players.WhiteListEntry; import net.minecraft.tags.TagKey; -import net.minecraft.util.GsonHelper; -import net.minecraft.util.datafix.DataFixers; -import net.minecraft.world.Difficulty; -import net.minecraft.world.entity.EntityType; +import net.minecraft.util.ChatDeserializer; +import net.minecraft.util.datafix.DataConverterRegistry; +import net.minecraft.world.EnumDifficulty; +import net.minecraft.world.damagesource.DamageType; +import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.entity.ai.village.VillageSiege; -import net.minecraft.world.entity.npc.CatSpawner; -import net.minecraft.world.entity.npc.WanderingTraderSpawner; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.inventory.CraftingMenu; -import net.minecraft.world.inventory.ResultContainer; +import net.minecraft.world.entity.npc.MobSpawnerCat; +import net.minecraft.world.entity.npc.MobSpawnerTrader; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.ContainerWorkbench; +import net.minecraft.world.inventory.InventoryCraftResult; +import net.minecraft.world.inventory.InventoryCrafting; import net.minecraft.world.inventory.TransientCraftingContainer; import net.minecraft.world.item.Item; -import net.minecraft.world.item.MapItem; -import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.ItemWorldMap; +import net.minecraft.world.item.crafting.RecipeCrafting; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.item.crafting.RepairItemRecipe; -import net.minecraft.world.level.CustomSpawner; +import net.minecraft.world.item.crafting.RecipeRepair; +import net.minecraft.world.item.crafting.Recipes; +import net.minecraft.world.level.EnumGamemode; import net.minecraft.world.level.GameRules; -import net.minecraft.world.level.GameType; -import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.MobSpawner; +import net.minecraft.world.level.WorldSettings; import net.minecraft.world.level.biome.BiomeManager; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.PatrolSpawner; -import net.minecraft.world.level.levelgen.PhantomSpawner; +import net.minecraft.world.level.dimension.WorldDimension; +import net.minecraft.world.level.levelgen.MobSpawnerPatrol; +import net.minecraft.world.level.levelgen.MobSpawnerPhantom; import net.minecraft.world.level.levelgen.WorldDimensions; import net.minecraft.world.level.levelgen.WorldOptions; -import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.FluidType; import net.minecraft.world.level.saveddata.maps.MapId; -import net.minecraft.world.level.saveddata.maps.MapItemSavedData; +import net.minecraft.world.level.saveddata.maps.WorldMap; +import net.minecraft.world.level.storage.Convertable; import net.minecraft.world.level.storage.LevelDataAndDimensions; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.PlayerDataStorage; -import net.minecraft.world.level.storage.PrimaryLevelData; +import net.minecraft.world.level.storage.WorldDataServer; +import net.minecraft.world.level.storage.WorldNBTStorage; import net.minecraft.world.level.validation.ContentValidationException; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.Vec3D; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -178,6 +180,7 @@ import org.bukkit.craftbukkit.inventory.CraftSmithingTrimRecipe; import org.bukkit.craftbukkit.inventory.CraftSmokingRecipe; import org.bukkit.craftbukkit.inventory.CraftStonecuttingRecipe; +import org.bukkit.craftbukkit.inventory.CraftTransmuteRecipe; import org.bukkit.craftbukkit.inventory.RecipeIterator; import org.bukkit.craftbukkit.inventory.util.CraftInventoryCreator; import org.bukkit.craftbukkit.map.CraftMapColorCache; @@ -194,6 +197,7 @@ import org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager; import org.bukkit.craftbukkit.structure.CraftStructureManager; import org.bukkit.craftbukkit.tag.CraftBlockTag; +import org.bukkit.craftbukkit.tag.CraftDamageTag; import org.bukkit.craftbukkit.tag.CraftEntityTag; import org.bukkit.craftbukkit.tag.CraftFluidTag; import org.bukkit.craftbukkit.tag.CraftItemTag; @@ -213,6 +217,7 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerChatTabCompleteEvent; import org.bukkit.event.server.BroadcastMessageEvent; +import org.bukkit.event.server.ServerLoadEvent; import org.bukkit.event.server.TabCompleteEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; @@ -237,6 +242,7 @@ import org.bukkit.inventory.SmithingTrimRecipe; import org.bukkit.inventory.SmokingRecipe; import org.bukkit.inventory.StonecuttingRecipe; +import org.bukkit.inventory.TransmuteRecipe; import org.bukkit.loot.LootTable; import org.bukkit.map.MapPalette; import org.bukkit.map.MapView; @@ -254,19 +260,18 @@ import org.bukkit.plugin.messaging.Messenger; import org.bukkit.plugin.messaging.StandardMessenger; import org.bukkit.profile.PlayerProfile; +import org.bukkit.scheduler.BukkitWorker; import org.bukkit.scoreboard.Criteria; import org.bukkit.structure.StructureManager; import org.bukkit.util.StringUtil; import org.bukkit.util.permissions.DefaultPermissions; -import com.mohistmc.org.yaml.snakeyaml .LoaderOptions; -import com.mohistmc.org.yaml.snakeyaml .Yaml; -import com.mohistmc.org.yaml.snakeyaml .constructor.SafeConstructor; -import com.mohistmc.org.yaml.snakeyaml .error.MarkedYAMLException; - -import net.md_5.bungee.api.chat.BaseComponent; // Spigot +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.error.MarkedYAMLException; public final class CraftServer implements Server { - private final String serverName = "Mohist"; + private final String serverName = "CraftBukkit"; private final String serverVersion; private final String bukkitVersion = Versioning.getBukkitVersion(); private final Logger logger = Logger.getLogger("Minecraft"); @@ -275,12 +280,11 @@ public final class CraftServer implements Server { private final CraftCommandMap commandMap = new CraftCommandMap(this); private final SimpleHelpMap helpMap = new SimpleHelpMap(this); private final StandardMessenger messenger = new StandardMessenger(); - private final SimplePluginManager pluginManager = new SimplePluginManager(this, this.commandMap); + private final SimplePluginManager pluginManager = new SimplePluginManager(this, commandMap); private final StructureManager structureManager; protected final DedicatedServer console; protected final DedicatedPlayerList playerList; private final Map worlds = new LinkedHashMap(); - private final Map worldsByUUID = new Object2ObjectLinkedOpenHashMap<>(); // MultiPaper - optimize getWorld(UUID) private final Map, Registry> registries = new HashMap<>(); private YamlConfiguration configuration; private YamlConfiguration commandsConfiguration; @@ -316,13 +320,13 @@ public final class CraftServer implements Server { public CraftServer(DedicatedServer console, PlayerList playerList) { this.console = console; this.playerList = (DedicatedPlayerList) playerList; - this.playerView = Collections.unmodifiableList(Lists.transform(playerList.players, new Function() { + this.playerView = Collections.unmodifiableList(Lists.transform(playerList.players, new Function() { @Override - public CraftPlayer apply(ServerPlayer player) { + public CraftPlayer apply(EntityPlayer player) { return player.getBukkitEntity(); } })); - this.serverVersion = Mohist.versionInfo.mohist(); + this.serverVersion = CraftServer.class.getPackage().getImplementationVersion(); this.structureManager = new CraftStructureManager(console.getStructureManager(), console.registryAccess()); this.dataPackManager = new CraftDataPackManager(this.getServer().getPackRepository()); this.serverTickManager = new CraftServerTickManager(console.tickRateManager()); @@ -332,32 +336,30 @@ public CraftPlayer apply(ServerPlayer player) { CraftRegistry.setMinecraftRegistry(console.registryAccess()); - ForgeInjectBukkit.init(); - if (!Main.useConsole) { - this.getLogger().info("Console input is disabled due to --noconsole command argument"); + getLogger().info("Console input is disabled due to --noconsole command argument"); } - this.configuration = YamlConfiguration.loadConfiguration(this.getConfigFile()); - this.configuration.options().copyDefaults(true); - this.configuration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("configurations/bukkit.yml"), Charsets.UTF_8))); + configuration = YamlConfiguration.loadConfiguration(getConfigFile()); + configuration.options().copyDefaults(true); + configuration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/bukkit.yml"), Charsets.UTF_8))); ConfigurationSection legacyAlias = null; - if (!this.configuration.isString("aliases")) { - legacyAlias = this.configuration.getConfigurationSection("aliases"); - this.configuration.set("aliases", "now-in-commands.yml"); + if (!configuration.isString("aliases")) { + legacyAlias = configuration.getConfigurationSection("aliases"); + configuration.set("aliases", "now-in-commands.yml"); } - this.saveConfig(); - if (this.getCommandsConfigFile().isFile()) { + saveConfig(); + if (getCommandsConfigFile().isFile()) { legacyAlias = null; } - this.commandsConfiguration = YamlConfiguration.loadConfiguration(this.getCommandsConfigFile()); - this.commandsConfiguration.options().copyDefaults(true); - this.commandsConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("configurations/commands.yml"), Charsets.UTF_8))); - this.saveCommandsConfig(); + commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); + commandsConfiguration.options().copyDefaults(true); + commandsConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/commands.yml"), Charsets.UTF_8))); + saveCommandsConfig(); // Migrate aliases from old file and add previously implicit $1- to pass all arguments if (legacyAlias != null) { - ConfigurationSection aliases = this.commandsConfiguration.createSection("aliases"); + ConfigurationSection aliases = commandsConfiguration.createSection("aliases"); for (String key : legacyAlias.getKeys(false)) { ArrayList commands = new ArrayList(); @@ -373,57 +375,58 @@ public CraftPlayer apply(ServerPlayer player) { } } - this.saveCommandsConfig(); - this.overrideAllCommandBlockCommands = this.commandsConfiguration.getStringList("command-block-overrides").contains("*"); - this.ignoreVanillaPermissions = this.commandsConfiguration.getBoolean("ignore-vanilla-permissions"); - this.pluginManager.useTimings(this.configuration.getBoolean("settings.plugin-profiling")); - this.overrideSpawnLimits(); - console.autosavePeriod = this.configuration.getInt("ticks-per.autosave"); - this.warningState = WarningState.value(this.configuration.getString("settings.deprecated-verbose")); - TicketType.PLUGIN.timeout = this.configuration.getInt("chunk-gc.period-in-ticks"); - this.minimumAPI = ApiVersion.getOrCreateVersion(this.configuration.getString("settings.minimum-api")); - this.loadIcon(); + saveCommandsConfig(); + overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*"); + ignoreVanillaPermissions = commandsConfiguration.getBoolean("ignore-vanilla-permissions"); + pluginManager.useTimings(configuration.getBoolean("settings.plugin-profiling")); + overrideSpawnLimits(); + console.autosavePeriod = configuration.getInt("ticks-per.autosave"); + warningState = WarningState.value(configuration.getString("settings.deprecated-verbose")); + TicketType.PLUGIN.timeout = configuration.getInt("chunk-gc.period-in-ticks"); + minimumAPI = ApiVersion.getOrCreateVersion(configuration.getString("settings.minimum-api")); + loadIcon(); loadCompatibilities(); + CraftMagicNumbers.INSTANCE.getCommodore().updateReroute(activeCompatibilities::contains); // Set map color cache - if (this.configuration.getBoolean("settings.use-map-color-cache")) { - MapPalette.setMapColorCache(new CraftMapColorCache(this.logger)); + if (configuration.getBoolean("settings.use-map-color-cache")) { + MapPalette.setMapColorCache(new CraftMapColorCache(logger)); } } public boolean getCommandBlockOverride(String command) { - return this.overrideAllCommandBlockCommands || this.commandsConfiguration.getStringList("command-block-overrides").contains(command); + return overrideAllCommandBlockCommands || commandsConfiguration.getStringList("command-block-overrides").contains(command); } private File getConfigFile() { - return (File) this.console.options.valueOf("bukkit-settings"); + return (File) console.options.valueOf("bukkit-settings"); } private File getCommandsConfigFile() { - return (File) this.console.options.valueOf("commands-settings"); + return (File) console.options.valueOf("commands-settings"); } private void overrideSpawnLimits() { for (SpawnCategory spawnCategory : SpawnCategory.values()) { if (CraftSpawnCategory.isValidForLimits(spawnCategory)) { - this.spawnCategoryLimit.put(spawnCategory, this.configuration.getInt(CraftSpawnCategory.getConfigNameSpawnLimit(spawnCategory))); + spawnCategoryLimit.put(spawnCategory, configuration.getInt(CraftSpawnCategory.getConfigNameSpawnLimit(spawnCategory))); } } } private void saveConfig() { try { - this.configuration.save(this.getConfigFile()); + configuration.save(getConfigFile()); } catch (IOException ex) { - Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + this.getConfigFile(), ex); + Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + getConfigFile(), ex); } } private void saveCommandsConfig() { try { - this.commandsConfiguration.save(this.getCommandsConfigFile()); + commandsConfiguration.save(getCommandsConfigFile()); } catch (IOException ex) { - Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + this.getCommandsConfigFile(), ex); + Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + getCommandsConfigFile(), ex); } } @@ -455,12 +458,12 @@ private void loadCompatibilities() { } public void loadPlugins() { - this.pluginManager.registerInterface(JavaPluginLoader.class); + pluginManager.registerInterface(JavaPluginLoader.class); - File pluginFolder = (File) this.console.options.valueOf("plugins"); + File pluginFolder = (File) console.options.valueOf("plugins"); if (pluginFolder.exists()) { - Plugin[] plugins = this.pluginManager.loadPlugins(pluginFolder); + Plugin[] plugins = pluginManager.loadPlugins(pluginFolder); for (Plugin plugin : plugins) { try { String message = String.format("Loading %s", plugin.getDescription().getFullName()); @@ -477,71 +480,58 @@ public void loadPlugins() { public void enablePlugins(PluginLoadOrder type) { if (type == PluginLoadOrder.STARTUP) { - this.helpMap.clear(); - this.helpMap.initializeGeneralTopics(); + helpMap.clear(); + helpMap.initializeGeneralTopics(); } - Plugin[] plugins = this.pluginManager.getPlugins(); + Plugin[] plugins = pluginManager.getPlugins(); for (Plugin plugin : plugins) { if ((!plugin.isEnabled()) && (plugin.getDescription().getLoad() == type)) { - this.enablePlugin(plugin); + enablePlugin(plugin); } } if (type == PluginLoadOrder.POSTWORLD) { - MohistPlugin.init(this); // Mohist init mohist plugins - // Spigot start - Allow vanilla commands to be forced to be the main command - this.setVanillaCommands(true); - this.commandMap.setFallbackCommands(); - this.setVanillaCommands(false); - // Spigot end - this.commandMap.registerServerAliases(); + commandMap.setFallbackCommands(); + setVanillaCommands(); + commandMap.registerServerAliases(); DefaultPermissions.registerCorePermissions(); CraftDefaultPermissions.registerCorePermissions(); - this.loadCustomPermissions(); - this.helpMap.initializeCommands(); - this.syncCommands(); + loadCustomPermissions(); + helpMap.initializeCommands(); + syncCommands(); } } public void disablePlugins() { - this.pluginManager.disablePlugins(); + pluginManager.disablePlugins(); } - private void setVanillaCommands(boolean first) { // Spigot - Commands dispatcher = this.console.vanillaCommandDispatcher; + private void setVanillaCommands() { + CommandDispatcher dispatcher = console.vanillaCommandDispatcher; // Build a list of all Vanilla commands and create wrappers - for (CommandNode cmd : dispatcher.getDispatcher().getRoot().getChildren()) { - // Spigot start - VanillaCommandWrapper wrapper = new VanillaCommandWrapper(dispatcher, cmd); - if (org.spigotmc.SpigotConfig.replaceCommands.contains( wrapper.getName() ) ) { - if (first) { - this.commandMap.register("minecraft", wrapper); - } - } else if (!first) { - this.commandMap.register("minecraft", wrapper); - } - // Spigot end + for (CommandNode cmd : dispatcher.getDispatcher().getRoot().getChildren()) { + commandMap.register("minecraft", new VanillaCommandWrapper(dispatcher, cmd)); } } public void syncCommands() { // Clear existing commands - Commands dispatcher = this.console.resources.managers().commands = new Commands(); + CommandDispatcher dispatcher = console.resources.managers().commands = new CommandDispatcher(); // Register all commands, vanilla ones will be using the old dispatcher references - for (Map.Entry entry : this.commandMap.getKnownCommands().entrySet()) { + for (Map.Entry entry : commandMap.getKnownCommands().entrySet()) { String label = entry.getKey(); Command command = entry.getValue(); if (command instanceof VanillaCommandWrapper) { - LiteralCommandNode node = (LiteralCommandNode) ((VanillaCommandWrapper) command).vanillaCommand; + LiteralCommandNode node = (LiteralCommandNode) ((VanillaCommandWrapper) command).vanillaCommand; if (!node.getLiteral().equals(label)) { - LiteralCommandNode clone = new LiteralCommandNode(label, node.getCommand(), node.getRequirement(), node.getRedirect(), node.getRedirectModifier(), node.isFork()); + LiteralCommandNode clone = new LiteralCommandNode(label, node.getCommand(), node.getRequirement(), node.getRedirect(), node.getRedirectModifier(), node.isFork()); - for (CommandNode child : node.getChildren()) { + for (CommandNode child : node.getChildren()) { clone.addChild(child); } node = clone; @@ -554,7 +544,7 @@ public void syncCommands() { } // Refresh commands - for (ServerPlayer player : this.getHandle().players) { + for (EntityPlayer player : getHandle().players) { dispatcher.sendCommands(player); } } @@ -565,14 +555,14 @@ private void enablePlugin(Plugin plugin) { for (Permission perm : perms) { try { - this.pluginManager.addPermission(perm, false); + pluginManager.addPermission(perm, false); } catch (IllegalArgumentException ex) { - this.getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex); + getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex); } } - this.pluginManager.dirtyPermissibles(); + pluginManager.dirtyPermissibles(); - this.pluginManager.enablePlugin(plugin); + pluginManager.enablePlugin(plugin); } catch (Throwable ex) { Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, ex.getMessage() + " loading " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); } @@ -580,17 +570,17 @@ private void enablePlugin(Plugin plugin) { @Override public String getName() { - return this.serverName; + return serverName; } @Override public String getVersion() { - return this.serverVersion + " (MC: " + this.console.getServerVersion() + ")"; + return serverVersion + " (MC: " + console.getServerVersion() + ")"; } @Override public String getBukkitVersion() { - return this.bukkitVersion; + return bukkitVersion; } @Override @@ -603,16 +593,16 @@ public List getOnlinePlayers() { public Player getPlayer(final String name) { Preconditions.checkArgument(name != null, "name cannot be null"); - Player found = this.getPlayerExact(name); + Player found = getPlayerExact(name); // Try for an exact match first. if (found != null) { return found; } - String lowerName = name.toLowerCase(java.util.Locale.ENGLISH); + String lowerName = name.toLowerCase(Locale.ROOT); int delta = Integer.MAX_VALUE; - for (Player player : this.getOnlinePlayers()) { - if (player.getName().toLowerCase(java.util.Locale.ENGLISH).startsWith(lowerName)) { + for (Player player : getOnlinePlayers()) { + if (player.getName().toLowerCase(Locale.ROOT).startsWith(lowerName)) { int curDelta = Math.abs(player.getName().length() - lowerName.length()); if (curDelta < delta) { found = player; @@ -629,7 +619,7 @@ public Player getPlayer(final String name) { public Player getPlayerExact(String name) { Preconditions.checkArgument(name != null, "name cannot be null"); - ServerPlayer player = this.playerList.getPlayerByName(name); + EntityPlayer player = playerList.getPlayerByName(name); return (player != null) ? player.getBukkitEntity() : null; } @@ -637,7 +627,7 @@ public Player getPlayerExact(String name) { public Player getPlayer(UUID id) { Preconditions.checkArgument(id != null, "UUID id cannot be null"); - ServerPlayer player = this.playerList.getPlayer(id); + EntityPlayer player = playerList.getPlayer(id); if (player != null) { return player.getBukkitEntity(); } @@ -647,7 +637,7 @@ public Player getPlayer(UUID id) { @Override public int broadcastMessage(String message) { - return this.broadcast(message, BROADCAST_CHANNEL_USERS); + return broadcast(message, BROADCAST_CHANNEL_USERS); } @Override @@ -666,7 +656,7 @@ public List matchPlayer(String partialName) { matchedPlayers.add(iterPlayer); break; } - if (iterPlayerName.toLowerCase(java.util.Locale.ENGLISH).contains(partialName.toLowerCase(java.util.Locale.ENGLISH))) { + if (iterPlayerName.toLowerCase(Locale.ROOT).contains(partialName.toLowerCase(Locale.ROOT))) { // Partial match matchedPlayers.add(iterPlayer); } @@ -677,14 +667,14 @@ public List matchPlayer(String partialName) { @Override public int getMaxPlayers() { - return this.playerList.getMaxPlayers(); + return playerList.getMaxPlayers(); } @Override public void setMaxPlayers(int maxPlayers) { Preconditions.checkArgument(maxPlayers >= 0, "maxPlayers must be >= 0"); - this.playerList.maxPlayers = maxPlayers; + playerList.maxPlayers = maxPlayers; } // NOTE: These are dependent on the corresponding call in MinecraftServer @@ -810,54 +800,48 @@ public String getUpdateFolder() { @Override public File getUpdateFolderFile() { - return new File((File) this.console.options.valueOf("plugins"), this.configuration.getString("settings.update-folder", "update")); + return new File((File) console.options.valueOf("plugins"), this.configuration.getString("settings.update-folder", "update")); } @Override public long getConnectionThrottle() { - // Spigot Start - Automatically set connection throttle for bungee configurations - if (org.spigotmc.SpigotConfig.bungee) { - return -1; - } else { - return this.configuration.getInt("settings.connection-throttle"); - } - // Spigot End + return this.configuration.getInt("settings.connection-throttle"); } @Override @Deprecated public int getTicksPerAnimalSpawns() { - return this.getTicksPerSpawns(SpawnCategory.ANIMAL); + return getTicksPerSpawns(SpawnCategory.ANIMAL); } @Override @Deprecated public int getTicksPerMonsterSpawns() { - return this.getTicksPerSpawns(SpawnCategory.MONSTER); + return getTicksPerSpawns(SpawnCategory.MONSTER); } @Override @Deprecated public int getTicksPerWaterSpawns() { - return this.getTicksPerSpawns(SpawnCategory.WATER_ANIMAL); + return getTicksPerSpawns(SpawnCategory.WATER_ANIMAL); } @Override @Deprecated public int getTicksPerWaterAmbientSpawns() { - return this.getTicksPerSpawns(SpawnCategory.WATER_AMBIENT); + return getTicksPerSpawns(SpawnCategory.WATER_AMBIENT); } @Override @Deprecated public int getTicksPerWaterUndergroundCreatureSpawns() { - return this.getTicksPerSpawns(SpawnCategory.WATER_UNDERGROUND_CREATURE); + return getTicksPerSpawns(SpawnCategory.WATER_UNDERGROUND_CREATURE); } @Override @Deprecated public int getTicksPerAmbientSpawns() { - return this.getTicksPerSpawns(SpawnCategory.AMBIENT); + return getTicksPerSpawns(SpawnCategory.AMBIENT); } @Override @@ -869,34 +853,30 @@ public int getTicksPerSpawns(SpawnCategory spawnCategory) { @Override public PluginManager getPluginManager() { - return this.pluginManager; + return pluginManager; } @Override public CraftScheduler getScheduler() { - return this.scheduler; + return scheduler; } @Override public ServicesManager getServicesManager() { - return this.servicesManager; + return servicesManager; } @Override public List getWorlds() { - return new ArrayList(this.worlds.values()); - } - - public Set getWorldsByName() { - return new HashSet<>(worlds.keySet()); + return new ArrayList(worlds.values()); } public DedicatedPlayerList getHandle() { - return this.playerList; + return playerList; } // NOTE: Should only be called from DedicatedServer.ah() - public boolean dispatchServerCommand(CommandSender sender, ConsoleInput serverCommand) { + public boolean dispatchServerCommand(CommandSender sender, ServerCommand serverCommand) { if (sender instanceof Conversable) { Conversable conversable = (Conversable) sender; @@ -907,9 +887,9 @@ public boolean dispatchServerCommand(CommandSender sender, ConsoleInput serverCo } try { this.playerCommandState = true; - return this.dispatchCommand(sender, serverCommand.msg); + return dispatchCommand(sender, serverCommand.msg); } catch (Exception ex) { - this.getLogger().log(Level.WARNING, "Unexpected exception while parsing console command \"" + serverCommand.msg + '"', ex); + getLogger().log(Level.WARNING, "Unexpected exception while parsing console command \"" + serverCommand.msg + '"', ex); return false; } finally { this.playerCommandState = false; @@ -920,46 +900,121 @@ public boolean dispatchServerCommand(CommandSender sender, ConsoleInput serverCo public boolean dispatchCommand(CommandSender sender, String commandLine) { Preconditions.checkArgument(sender != null, "sender cannot be null"); Preconditions.checkArgument(commandLine != null, "commandLine cannot be null"); - org.spigotmc.AsyncCatcher.catchOp("command dispatch"); // Spigot - if (this.commandMap.dispatch(sender, commandLine)) { + if (commandMap.dispatch(sender, commandLine)) { return true; } - // Spigot start - if (!org.spigotmc.SpigotConfig.unknownCommandMessage.isEmpty()) { - sender.sendMessage(org.spigotmc.SpigotConfig.unknownCommandMessage); + if (sender instanceof Player) { + sender.sendMessage("Unknown command. Type \"/help\" for help."); + } else { + sender.sendMessage("Unknown command. Type \"help\" for help."); } - // Spigot end return false; } @Override public void reload() { - Youer.LOGGER.warn("For your server security, Bukkit reloading is not supported by Mohist."); + reloadCount++; + configuration = YamlConfiguration.loadConfiguration(getConfigFile()); + commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); + + console.settings = new DedicatedServerSettings(console.options); + DedicatedServerProperties config = console.settings.getProperties(); + + console.setPvpAllowed(config.pvp); + console.setFlightAllowed(config.allowFlight); + console.setMotd(config.motd); + overrideSpawnLimits(); + warningState = WarningState.value(configuration.getString("settings.deprecated-verbose")); + TicketType.PLUGIN.timeout = configuration.getInt("chunk-gc.period-in-ticks"); + minimumAPI = ApiVersion.getOrCreateVersion(configuration.getString("settings.minimum-api")); + printSaveWarning = false; + console.autosavePeriod = configuration.getInt("ticks-per.autosave"); + loadIcon(); + loadCompatibilities(); + CraftMagicNumbers.INSTANCE.getCommodore().updateReroute(activeCompatibilities::contains); + + try { + playerList.getIpBans().load(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Failed to load banned-ips.json, " + ex.getMessage()); + } + try { + playerList.getBans().load(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Failed to load banned-players.json, " + ex.getMessage()); + } + + for (WorldServer world : console.getAllLevels()) { + world.serverLevelData.setDifficulty(config.difficulty); + world.setSpawnSettings(config.spawnMonsters); + + for (SpawnCategory spawnCategory : SpawnCategory.values()) { + if (CraftSpawnCategory.isValidForLimits(spawnCategory)) { + long ticksPerCategorySpawn = this.getTicksPerSpawns(spawnCategory); + if (ticksPerCategorySpawn < 0) { + world.ticksPerSpawnCategory.put(spawnCategory, CraftSpawnCategory.getDefaultTicksPerSpawn(spawnCategory)); + } else { + world.ticksPerSpawnCategory.put(spawnCategory, ticksPerCategorySpawn); + } + } + } + } + + pluginManager.clearPlugins(); + commandMap.clearCommands(); + reloadData(); + overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*"); + ignoreVanillaPermissions = commandsConfiguration.getBoolean("ignore-vanilla-permissions"); + + int pollCount = 0; + + // Wait for at most 2.5 seconds for plugins to close their threads + while (pollCount < 50 && getScheduler().getActiveWorkers().size() > 0) { + try { + Thread.sleep(50); + } catch (InterruptedException e) {} + pollCount++; + } + + List overdueWorkers = getScheduler().getActiveWorkers(); + for (BukkitWorker worker : overdueWorkers) { + Plugin plugin = worker.getOwner(); + getLogger().log(Level.SEVERE, String.format( + "Nag author(s): '%s' of '%s' about the following: %s", + plugin.getDescription().getAuthors(), + plugin.getDescription().getFullName(), + "This plugin is not properly shutting down its async tasks when it is being reloaded. This may cause conflicts with the newly loaded version of the plugin" + )); + } + loadPlugins(); + enablePlugins(PluginLoadOrder.STARTUP); + enablePlugins(PluginLoadOrder.POSTWORLD); + getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.RELOAD)); } @Override public void reloadData() { - ReloadCommand.reload(this.console); + CommandReload.reload(console); } private void loadIcon() { - this.icon = new CraftIconCache(null); + icon = new CraftIconCache(null); try { final File file = new File(new File("."), "server-icon.png"); if (file.isFile()) { - this.icon = CraftServer.loadServerIcon0(file); + icon = loadServerIcon0(file); } } catch (Exception ex) { - this.getLogger().log(Level.WARNING, "Couldn't load server icon", ex); + getLogger().log(Level.WARNING, "Couldn't load server icon", ex); } } @SuppressWarnings({ "unchecked", "finally" }) private void loadCustomPermissions() { - File file = new File(this.configuration.getString("settings.permissions-file")); + File file = new File(configuration.getString("settings.permissions-file")); FileInputStream stream; try { @@ -975,12 +1030,12 @@ private void loadCustomPermissions() { Map> perms; try { - perms = (Map>) this.yaml.load(stream); + perms = (Map>) yaml.load(stream); } catch (MarkedYAMLException ex) { - this.getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML: " + ex.toString()); + getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML: " + ex.toString()); return; } catch (Throwable ex) { - this.getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML.", ex); + getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML.", ex); return; } finally { try { @@ -989,7 +1044,7 @@ private void loadCustomPermissions() { } if (perms == null) { - this.getLogger().log(Level.INFO, "Server permissions file " + file + " is empty, ignoring it"); + getLogger().log(Level.INFO, "Server permissions file " + file + " is empty, ignoring it"); return; } @@ -997,16 +1052,16 @@ private void loadCustomPermissions() { for (Permission perm : permsList) { try { - this.pluginManager.addPermission(perm); + pluginManager.addPermission(perm); } catch (IllegalArgumentException ex) { - this.getLogger().log(Level.SEVERE, "Permission in " + file + " was already defined", ex); + getLogger().log(Level.SEVERE, "Permission in " + file + " was already defined", ex); } } } @Override public String toString() { - return "CraftServer{" + "serverName=" + this.serverName + ",serverVersion=" + this.serverVersion + ",minecraftVersion=" + this.console.getServerVersion() + '}'; + return "CraftServer{" + "serverName=" + serverName + ",serverVersion=" + serverVersion + ",minecraftVersion=" + console.getServerVersion() + '}'; } public World createWorld(String name, World.Environment environment) { @@ -1027,16 +1082,15 @@ public World createWorld(String name, Environment environment, long seed, ChunkG @Override public World createWorld(WorldCreator creator) { - Preconditions.checkState(this.console.getAllLevels().iterator().hasNext(), "Cannot create additional worlds on STARTUP"); + Preconditions.checkState(console.getAllLevels().iterator().hasNext(), "Cannot create additional worlds on STARTUP"); Preconditions.checkArgument(creator != null, "WorldCreator cannot be null"); - Level2LevelStem.initPluginWorld.set(true); // Mohist + String name = creator.name(); ChunkGenerator generator = creator.generator(); BiomeProvider biomeProvider = creator.biomeProvider(); - File folder = new File(this.getWorldContainer(), name); - World world = this.getWorld(name); - Level2LevelStem.bukkit = folder; - Level2LevelStem.bukkit_name = name; + File folder = new File(getWorldContainer(), name); + World world = getWorld(name); + if (world != null) { return world; } @@ -1046,31 +1100,44 @@ public World createWorld(WorldCreator creator) { } if (generator == null) { - generator = this.getGenerator(name); + generator = getGenerator(name); } if (biomeProvider == null) { - biomeProvider = this.getBiomeProvider(name); + biomeProvider = getBiomeProvider(name); } - ResourceKey actualDimension = ForgeInjectBukkit.environment0.get(creator.environment()); + ResourceKey actualDimension; + switch (creator.environment()) { + case NORMAL: + actualDimension = WorldDimension.OVERWORLD; + break; + case NETHER: + actualDimension = WorldDimension.NETHER; + break; + case THE_END: + actualDimension = WorldDimension.END; + break; + default: + throw new IllegalArgumentException("Illegal dimension (" + creator.environment() + ")"); + } - LevelStorageSource.LevelStorageAccess worldSession; + Convertable.ConversionSession worldSession; try { - worldSession = LevelStorageSource.createDefault(this.getWorldContainer().toPath()).validateAndCreateAccess(name, actualDimension); + worldSession = Convertable.createDefault(getWorldContainer().toPath()).validateAndCreateAccess(name, actualDimension); } catch (IOException | ContentValidationException ex) { throw new RuntimeException(ex); } Dynamic dynamic; if (worldSession.hasWorldData()) { - net.minecraft.world.level.storage.LevelSummary worldinfo; + net.minecraft.world.level.storage.WorldInfo worldinfo; try { dynamic = worldSession.getDataTag(); worldinfo = worldSession.getSummary(dynamic); } catch (NbtException | ReportedNbtException | IOException ioexception) { - LevelStorageSource.LevelDirectory convertable_b = worldSession.getLevelDirectory(); + Convertable.b convertable_b = worldSession.getLevelDirectory(); MinecraftServer.LOGGER.warn("Failed to load world data from {}", convertable_b.dataFile(), ioexception); MinecraftServer.LOGGER.info("Attempting to use fallback"); @@ -1102,91 +1169,85 @@ public World createWorld(WorldCreator creator) { boolean hardcore = creator.hardcore(); - PrimaryLevelData worlddata; - WorldLoader.DataLoadContext worldloader_a = this.console.worldLoader; - RegistryAccess.Frozen iregistrycustom_dimension = worldloader_a.datapackDimensions(); - net.minecraft.core.Registry iregistry = iregistrycustom_dimension.registryOrThrow(Registries.LEVEL_STEM); + WorldDataServer worlddata; + WorldLoader.a worldloader_a = console.worldLoader; + IRegistryCustom.Dimension iregistrycustom_dimension = worldloader_a.datapackDimensions(); + IRegistry iregistry = iregistrycustom_dimension.lookupOrThrow(Registries.LEVEL_STEM); if (dynamic != null) { - LevelDataAndDimensions leveldataanddimensions = LevelStorageSource.getLevelDataAndDimensions(dynamic, worldloader_a.dataConfiguration(), iregistry, worldloader_a.datapackWorldgen()); + LevelDataAndDimensions leveldataanddimensions = Convertable.getLevelDataAndDimensions(dynamic, worldloader_a.dataConfiguration(), iregistry, worldloader_a.datapackWorldgen()); - worlddata = (PrimaryLevelData) leveldataanddimensions.worldData(); + worlddata = (WorldDataServer) leveldataanddimensions.worldData(); iregistrycustom_dimension = leveldataanddimensions.dimensions().dimensionsRegistryAccess(); } else { - LevelSettings worldsettings; + WorldSettings worldsettings; WorldOptions worldoptions = new WorldOptions(creator.seed(), creator.generateStructures(), false); WorldDimensions worlddimensions; - DedicatedServerProperties.WorldDimensionData properties = new DedicatedServerProperties.WorldDimensionData(GsonHelper.parse((creator.generatorSettings().isEmpty()) ? "{}" : creator.generatorSettings()), creator.type().name().toLowerCase(Locale.ROOT)); + DedicatedServerProperties.WorldDimensionData properties = new DedicatedServerProperties.WorldDimensionData(ChatDeserializer.parse((creator.generatorSettings().isEmpty()) ? "{}" : creator.generatorSettings()), creator.type().name().toLowerCase(Locale.ROOT)); - worldsettings = new LevelSettings(name, GameType.byId(this.getDefaultGameMode().getValue()), hardcore, Difficulty.EASY, false, new GameRules(), worldloader_a.dataConfiguration()); + worldsettings = new WorldSettings(name, EnumGamemode.byId(getDefaultGameMode().getValue()), hardcore, EnumDifficulty.EASY, false, new GameRules(worldloader_a.dataConfiguration().enabledFeatures()), worldloader_a.dataConfiguration()); worlddimensions = properties.create(worldloader_a.datapackWorldgen()); - WorldDimensions.Complete worlddimensions_b = worlddimensions.bake(iregistry); + WorldDimensions.b worlddimensions_b = worlddimensions.bake(iregistry); Lifecycle lifecycle = worlddimensions_b.lifecycle().add(worldloader_a.datapackWorldgen().allRegistriesLifecycle()); - worlddata = new PrimaryLevelData(worldsettings, worldoptions, worlddimensions_b.specialWorldProperty(), lifecycle); + worlddata = new WorldDataServer(worldsettings, worldoptions, worlddimensions_b.specialWorldProperty(), lifecycle); iregistrycustom_dimension = worlddimensions_b.dimensionsRegistryAccess(); } - iregistry = iregistrycustom_dimension.registryOrThrow(Registries.LEVEL_STEM); + iregistry = iregistrycustom_dimension.lookupOrThrow(Registries.LEVEL_STEM); worlddata.customDimensions = iregistry; worlddata.checkName(name); - worlddata.setModdedInfo(this.console.getServerModName(), this.console.getModdedStatus().shouldReportAsModified()); + worlddata.setModdedInfo(console.getServerModName(), console.getModdedStatus().shouldReportAsModified()); - if (this.console.options.has("forceUpgrade")) { - net.minecraft.server.Main.forceUpgrade(worldSession, DataFixers.getDataFixer(), this.console.options.has("eraseCache"), () -> true, iregistrycustom_dimension, this.console.options.has("recreateRegionFiles")); + if (console.options.has("forceUpgrade")) { + net.minecraft.server.Main.forceUpgrade(worldSession, DataConverterRegistry.getDataFixer(), console.options.has("eraseCache"), () -> true, iregistrycustom_dimension, console.options.has("recreateRegionFiles")); } long j = BiomeManager.obfuscateSeed(creator.seed()); - List list = ImmutableList.of(new PhantomSpawner(), new PatrolSpawner(), new CatSpawner(), new VillageSiege(), new WanderingTraderSpawner(worlddata)); - LevelStem worlddimension = iregistry.get(actualDimension); + List list = ImmutableList.of(new MobSpawnerPhantom(), new MobSpawnerPatrol(), new MobSpawnerCat(), new VillageSiege(), new MobSpawnerTrader(worlddata)); + WorldDimension worlddimension = iregistry.getValue(actualDimension); WorldInfo worldInfo = new CraftWorldInfo(worlddata, worldSession, creator.environment(), worlddimension.type().value()); if (biomeProvider == null && generator != null) { biomeProvider = generator.getDefaultBiomeProvider(worldInfo); } - ResourceKey worldKey; + ResourceKey worldKey; String levelName = this.getServer().getProperties().levelName; if (name.equals(levelName + "_nether")) { - worldKey = net.minecraft.world.level.Level.NETHER; + worldKey = net.minecraft.world.level.World.NETHER; } else if (name.equals(levelName + "_the_end")) { - worldKey = net.minecraft.world.level.Level.END; + worldKey = net.minecraft.world.level.World.END; } else { - worldKey = ResourceKey.create(Registries.DIMENSION, ResourceLocation.withDefaultNamespace(name.toLowerCase(java.util.Locale.ENGLISH))); + worldKey = ResourceKey.create(Registries.DIMENSION, MinecraftKey.withDefaultNamespace(name.toLowerCase(Locale.ROOT))); } // If set to not keep spawn in memory (changed from default) then adjust rule accordingly if (!creator.keepSpawnInMemory()) { worlddata.getGameRules().getRule(GameRules.RULE_SPAWN_CHUNK_RADIUS).set(0, null); } - net.minecraft.world.level.Level.craftWorldData(generator, creator.environment(), biomeProvider); // TODO MOHIST - ServerLevel internal = new ServerLevel(this.console, this.console.executor, worldSession, worlddata, worldKey, worlddimension, this.getServer().progressListenerFactory.create(worlddata.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS)), - worlddata.isDebugWorld(), j, creator.environment() == Environment.NORMAL ? list : ImmutableList.of(), true, this.console.overworld().getRandomSequences()); + WorldServer internal = (WorldServer) new WorldServer(console, console.executor, worldSession, worlddata, worldKey, worlddimension, getServer().progressListenerFactory.create(worlddata.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS)), + worlddata.isDebugWorld(), j, creator.environment() == Environment.NORMAL ? list : ImmutableList.of(), true, console.overworld().getRandomSequences(), creator.environment(), generator, biomeProvider); - name = name.contains("DIM") ? name : name.toLowerCase(java.util.Locale.ENGLISH); - if (!(worlds.containsKey(name))) { - Level2LevelStem.initPluginWorld.set(false); // Mohist + if (!(worlds.containsKey(name.toLowerCase(Locale.ROOT)))) { return null; } - this.console.initWorld(internal, worlddata, worlddata, worlddata.worldGenOptions()); + console.initWorld(internal, worlddata, worlddata, worlddata.worldGenOptions()); - internal.setSpawnSettings(true, true); - this.console.addLevel(internal); + internal.setSpawnSettings(true); + console.addLevel(internal); - this.getServer().prepareLevels(internal.getChunkSource().chunkMap.progressListener, internal); + getServer().prepareLevels(internal.getChunkSource().chunkMap.progressListener, internal); internal.entityManager.tick(); // SPIGOT-6526: Load pending entities so they are available to the API - this.pluginManager.callEvent(new WorldLoadEvent(internal.getWorld())); - World world1 = internal.getWorld(); - world1.setBukkit(true); - Level2LevelStem.reloadAndInit(world1); - return world1; + pluginManager.callEvent(new WorldLoadEvent(internal.getWorld())); + return internal.getWorld(); } @Override public boolean unloadWorld(String name, boolean save) { - return this.unloadWorld(this.getWorld(name), save); + return unloadWorld(getWorld(name), save); } @Override @@ -1195,13 +1256,13 @@ public boolean unloadWorld(World world, boolean save) { return false; } - ServerLevel handle = ((CraftWorld) world).getHandle(); + WorldServer handle = ((CraftWorld) world).getHandle(); - if (this.console.getLevel(handle.dimension()) == null) { + if (console.getLevel(handle.dimension()) == null) { return false; } - if (handle.dimension() == net.minecraft.world.level.Level.OVERWORLD) { + if (handle.dimension() == net.minecraft.world.level.World.OVERWORLD) { return false; } @@ -1210,7 +1271,7 @@ public boolean unloadWorld(World world, boolean save) { } WorldUnloadEvent e = new WorldUnloadEvent(handle.getWorld()); - this.pluginManager.callEvent(e); + pluginManager.callEvent(e); if (e.isCancelled()) { return false; @@ -1225,39 +1286,28 @@ public boolean unloadWorld(World world, boolean save) { handle.entityManager.close(save); // SPIGOT-6722: close entityManager handle.convertable.close(); } catch (Exception ex) { - this.getLogger().log(Level.SEVERE, null, ex); + getLogger().log(Level.SEVERE, null, ex); } - this.worlds.remove(world.getName().toLowerCase(java.util.Locale.ENGLISH)); - this.console.removeLevel(handle); + worlds.remove(world.getName().toLowerCase(Locale.ROOT)); + console.removeLevel(handle); return true; } - public void removeWorld(ServerLevel world) { - if (world == null) { - return; - } - String worldname = world.getWorld().getName().contains("DIM") ? world.getWorld().getName() :world.getWorld().getName().toLowerCase(java.util.Locale.ENGLISH); - this.worlds.remove(worldname); - Level2LevelStem.plugin_worlds.remove(worldname); - } - public DedicatedServer getServer() { - return this.console; + return console; } @Override public World getWorld(String name) { Preconditions.checkArgument(name != null, "name cannot be null"); - String worldname = name.contains("DIM") ? name : name.toLowerCase(java.util.Locale.ENGLISH); - return worlds.get(worldname); + return worlds.get(name.toLowerCase(Locale.ROOT)); } @Override public World getWorld(UUID uid) { - if (true) return this.worldsByUUID.get(uid); - for (World world : this.worlds.values()) { + for (World world : worlds.values()) { if (world.getUID().equals(uid)) { return world; } @@ -1267,13 +1317,11 @@ public World getWorld(UUID uid) { public void addWorld(World world) { // Check if a World already exists with the UID. - if (this.getWorld(world.getUID()) != null) { + if (getWorld(world.getUID()) != null) { System.out.println("World " + world.getName() + " is a duplicate of another world and has been prevented from loading. Please delete the uid.dat file from " + world.getName() + "'s world directory if you want to be able to load the duplicate world."); return; } - this.worldsByUUID.put(world.getUID(), world); // MultiPaper - optimize getWorld(UUID) - String worldname = world.getName().contains("DIM") ? world.getName() : world.getName().toLowerCase(java.util.Locale.ENGLISH); - worlds.put(worldname, world); + worlds.put(world.getName().toLowerCase(Locale.ROOT), world); } @Override @@ -1283,12 +1331,16 @@ public WorldBorder createWorldBorder() { @Override public Logger getLogger() { - return this.logger; + return logger; + } + + public ConsoleReader getReader() { + return console.reader; } @Override public PluginCommand getPluginCommand(String name) { - Command command = this.commandMap.getCommand(name); + Command command = commandMap.getCommand(name); if (command instanceof PluginCommand) { return (PluginCommand) command; @@ -1299,8 +1351,8 @@ public PluginCommand getPluginCommand(String name) { @Override public void savePlayers() { - this.checkSaveState(); - this.playerList.saveAll(); + checkSaveState(); + playerList.saveAll(); } @Override @@ -1327,6 +1379,8 @@ public boolean addRecipe(Recipe recipe) { toAdd = CraftSmithingTransformRecipe.fromBukkitRecipe((SmithingTransformRecipe) recipe); } else if (recipe instanceof SmithingTrimRecipe) { toAdd = CraftSmithingTrimRecipe.fromBukkitRecipe((SmithingTrimRecipe) recipe); + } else if (recipe instanceof TransmuteRecipe) { + toAdd = CraftTransmuteRecipe.fromBukkitRecipe((TransmuteRecipe) recipe); } else if (recipe instanceof ComplexRecipe) { throw new UnsupportedOperationException("Cannot add custom complex recipe"); } else { @@ -1342,7 +1396,7 @@ public List getRecipesFor(ItemStack result) { Preconditions.checkArgument(result != null, "ItemStack cannot be null"); List results = new ArrayList(); - Iterator iter = this.recipeIterator(); + Iterator iter = recipeIterator(); while (iter.hasNext()) { Recipe recipe = iter.next(); ItemStack stack = recipe.getResult(); @@ -1360,39 +1414,39 @@ public List getRecipesFor(ItemStack result) { public Recipe getRecipe(NamespacedKey recipeKey) { Preconditions.checkArgument(recipeKey != null, "NamespacedKey recipeKey cannot be null"); - return this.getServer().getRecipeManager().byKey(CraftNamespacedKey.toMinecraft(recipeKey)).map(RecipeHolder::toBukkitRecipe).orElse(null); + return getServer().getRecipeManager().byKey(CraftRecipe.toMinecraft(recipeKey)).map(RecipeHolder::toBukkitRecipe).orElse(null); } - private CraftingContainer createInventoryCrafting() { + private InventoryCrafting createInventoryCrafting() { // Create a players Crafting Inventory - AbstractContainerMenu container = new AbstractContainerMenu(null, -1) { + Container container = new Container(null, -1) { @Override public InventoryView getBukkitView() { return null; } @Override - public boolean stillValid(net.minecraft.world.entity.player.Player player) { + public boolean stillValid(EntityHuman entityhuman) { return false; } @Override - public net.minecraft.world.item.ItemStack quickMoveStack(net.minecraft.world.entity.player.Player player, int slot) { + public net.minecraft.world.item.ItemStack quickMoveStack(EntityHuman entityhuman, int i) { return net.minecraft.world.item.ItemStack.EMPTY; } }; - CraftingContainer inventoryCrafting = new TransientCraftingContainer(container, 3, 3); + InventoryCrafting inventoryCrafting = new TransientCraftingContainer(container, 3, 3); return inventoryCrafting; } @Override public Recipe getCraftingRecipe(ItemStack[] craftingMatrix, World world) { - return this.getNMSRecipe(craftingMatrix, this.createInventoryCrafting(), (CraftWorld) world).map(RecipeHolder::toBukkitRecipe).orElse(null); + return getNMSRecipe(craftingMatrix, createInventoryCrafting(), (CraftWorld) world).map(RecipeHolder::toBukkitRecipe).orElse(null); } @Override public ItemStack craftItem(ItemStack[] craftingMatrix, World world, Player player) { - return this.craftItemResult(craftingMatrix, world, player).getResult(); + return craftItemResult(craftingMatrix, world, player).getResult(); } @Override @@ -1404,31 +1458,31 @@ public ItemCraftResult craftItemResult(ItemStack[] craftingMatrix, World world, CraftPlayer craftPlayer = (CraftPlayer) player; // Create a players Crafting Inventory and get the recipe - CraftingMenu container = new CraftingMenu(-1, craftPlayer.getHandle().getInventory()); - CraftingContainer inventoryCrafting = container.craftSlots; - ResultContainer craftResult = container.resultSlots; + ContainerWorkbench container = new ContainerWorkbench(-1, craftPlayer.getHandle().getInventory()); + InventoryCrafting inventoryCrafting = container.craftSlots; + InventoryCraftResult craftResult = container.resultSlots; - Optional> recipe = this.getNMSRecipe(craftingMatrix, inventoryCrafting, craftWorld); + Optional> recipe = getNMSRecipe(craftingMatrix, inventoryCrafting, craftWorld); // Generate the resulting ItemStack from the Crafting Matrix net.minecraft.world.item.ItemStack itemstack = net.minecraft.world.item.ItemStack.EMPTY; if (recipe.isPresent()) { - RecipeHolder recipeCrafting = recipe.get(); - if (craftResult.setRecipeUsed(craftWorld.getHandle(), craftPlayer.getHandle(), recipeCrafting)) { + RecipeHolder recipeCrafting = recipe.get(); + if (craftResult.setRecipeUsed(craftPlayer.getHandle(), recipeCrafting)) { itemstack = recipeCrafting.value().assemble(inventoryCrafting.asCraftInput(), craftWorld.getHandle().registryAccess()); } } // Call Bukkit event to check for matrix/result changes. - net.minecraft.world.item.ItemStack result = CraftEventFactory.callPreCraftEvent(inventoryCrafting, craftResult, itemstack, container.getBukkitView(), recipe.map(RecipeHolder::value).orElse(null) instanceof RepairItemRecipe); + net.minecraft.world.item.ItemStack result = CraftEventFactory.callPreCraftEvent(inventoryCrafting, craftResult, itemstack, container.getBukkitView(), recipe.map(RecipeHolder::value).orElse(null) instanceof RecipeRepair); - return this.createItemCraftResult(CraftItemStack.asBukkitCopy(result), inventoryCrafting, craftWorld.getHandle()); + return createItemCraftResult(recipe, CraftItemStack.asBukkitCopy(result), inventoryCrafting, craftWorld.getHandle()); } @Override public ItemStack craftItem(ItemStack[] craftingMatrix, World world) { - return this.craftItemResult(craftingMatrix, world).getResult(); + return craftItemResult(craftingMatrix, world).getResult(); } @Override @@ -1438,9 +1492,9 @@ public ItemCraftResult craftItemResult(ItemStack[] craftingMatrix, World world) CraftWorld craftWorld = (CraftWorld) world; // Create a players Crafting Inventory and get the recipe - CraftingContainer inventoryCrafting = this.createInventoryCrafting(); + InventoryCrafting inventoryCrafting = createInventoryCrafting(); - Optional> recipe = this.getNMSRecipe(craftingMatrix, inventoryCrafting, craftWorld); + Optional> recipe = getNMSRecipe(craftingMatrix, inventoryCrafting, craftWorld); // Generate the resulting ItemStack from the Crafting Matrix net.minecraft.world.item.ItemStack itemStack = net.minecraft.world.item.ItemStack.EMPTY; @@ -1449,34 +1503,34 @@ public ItemCraftResult craftItemResult(ItemStack[] craftingMatrix, World world) itemStack = recipe.get().value().assemble(inventoryCrafting.asCraftInput(), craftWorld.getHandle().registryAccess()); } - return this.createItemCraftResult(CraftItemStack.asBukkitCopy(itemStack), inventoryCrafting, craftWorld.getHandle()); + return createItemCraftResult(recipe, CraftItemStack.asBukkitCopy(itemStack), inventoryCrafting, craftWorld.getHandle()); } - private CraftItemCraftResult createItemCraftResult(ItemStack itemStack, CraftingContainer inventoryCrafting, ServerLevel worldServer) { + private CraftItemCraftResult createItemCraftResult(Optional> recipe, ItemStack itemStack, InventoryCrafting inventoryCrafting, WorldServer worldServer) { CraftItemCraftResult craftItemResult = new CraftItemCraftResult(itemStack); - NonNullList remainingItems = this.getServer().getRecipeManager().getRemainingItemsFor(RecipeType.CRAFTING, inventoryCrafting.asCraftInput(), worldServer); - - // Set the resulting matrix items and overflow items - for (int i = 0; i < remainingItems.size(); ++i) { - net.minecraft.world.item.ItemStack itemstack1 = inventoryCrafting.getItem(i); - net.minecraft.world.item.ItemStack itemstack2 = (net.minecraft.world.item.ItemStack) remainingItems.get(i); - - if (!itemstack1.isEmpty()) { - inventoryCrafting.removeItem(i, 1); - itemstack1 = inventoryCrafting.getItem(i); - } + recipe.map((holder) -> holder.value().getRemainingItems(inventoryCrafting.asCraftInput())).ifPresent((remainingItems) -> { + // Set the resulting matrix items and overflow items + for (int i = 0; i < remainingItems.size(); ++i) { + net.minecraft.world.item.ItemStack itemstack1 = inventoryCrafting.getItem(i); + net.minecraft.world.item.ItemStack itemstack2 = (net.minecraft.world.item.ItemStack) remainingItems.get(i); + + if (!itemstack1.isEmpty()) { + inventoryCrafting.removeItem(i, 1); + itemstack1 = inventoryCrafting.getItem(i); + } - if (!itemstack2.isEmpty()) { - if (itemstack1.isEmpty()) { - inventoryCrafting.setItem(i, itemstack2); - } else if (net.minecraft.world.item.ItemStack.isSameItemSameComponents(itemstack1, itemstack2)) { - itemstack2.grow(itemstack1.getCount()); - inventoryCrafting.setItem(i, itemstack2); - } else { - craftItemResult.getOverflowItems().add(CraftItemStack.asBukkitCopy(itemstack2)); + if (!itemstack2.isEmpty()) { + if (itemstack1.isEmpty()) { + inventoryCrafting.setItem(i, itemstack2); + } else if (net.minecraft.world.item.ItemStack.isSameItemSameComponents(itemstack1, itemstack2)) { + itemstack2.grow(itemstack1.getCount()); + inventoryCrafting.setItem(i, itemstack2); + } else { + craftItemResult.getOverflowItems().add(CraftItemStack.asBukkitCopy(itemstack2)); + } } } - } + }); for (int i = 0; i < inventoryCrafting.getContents().size(); i++) { craftItemResult.setResultMatrix(i, CraftItemStack.asBukkitCopy(inventoryCrafting.getItem(i))); @@ -1485,7 +1539,7 @@ private CraftItemCraftResult createItemCraftResult(ItemStack itemStack, Crafting return craftItemResult; } - private Optional> getNMSRecipe(ItemStack[] craftingMatrix, CraftingContainer inventoryCrafting, CraftWorld world) { + private Optional> getNMSRecipe(ItemStack[] craftingMatrix, InventoryCrafting inventoryCrafting, CraftWorld world) { Preconditions.checkArgument(craftingMatrix != null, "craftingMatrix must not be null"); Preconditions.checkArgument(craftingMatrix.length == 9, "craftingMatrix must be an array of length 9"); Preconditions.checkArgument(world != null, "world must not be null"); @@ -1494,7 +1548,7 @@ private Optional> getNMSRecipe(ItemStack[] crafting inventoryCrafting.setItem(i, CraftItemStack.asNMSCopy(craftingMatrix[i])); } - return this.getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, inventoryCrafting.asCraftInput(), world.getHandle()); + return getServer().getRecipeManager().getRecipeFor(Recipes.CRAFTING, inventoryCrafting.asCraftInput(), world.getHandle()); } @Override @@ -1504,25 +1558,24 @@ public Iterator recipeIterator() { @Override public void clearRecipes() { - this.console.getRecipeManager().clearRecipes(); + console.getRecipeManager().clearRecipes(); } @Override public void resetRecipes() { - this.reloadData(); // Not ideal but hard to reload a subset of a resource pack + reloadData(); // Not ideal but hard to reload a subset of a resource pack } @Override public boolean removeRecipe(NamespacedKey recipeKey) { Preconditions.checkArgument(recipeKey != null, "recipeKey == null"); - ResourceLocation mcKey = CraftNamespacedKey.toMinecraft(recipeKey); - return this.getServer().getRecipeManager().removeRecipe(mcKey); + return getServer().getRecipeManager().removeRecipe(CraftRecipe.toMinecraft(recipeKey)); } @Override public Map getCommandAliases() { - ConfigurationSection section = this.commandsConfiguration.getConfigurationSection("aliases"); + ConfigurationSection section = commandsConfiguration.getConfigurationSection("aliases"); Map result = new LinkedHashMap(); if (section != null) { @@ -1543,17 +1596,17 @@ public Map getCommandAliases() { } public void removeBukkitSpawnRadius() { - this.configuration.set("settings.spawn-radius", null); - this.saveConfig(); + configuration.set("settings.spawn-radius", null); + saveConfig(); } public int getBukkitSpawnRadius() { - return this.configuration.getInt("settings.spawn-radius", -1); + return configuration.getInt("settings.spawn-radius", -1); } @Override public String getShutdownMessage() { - return this.configuration.getString("settings.shutdown-message"); + return configuration.getString("settings.shutdown-message"); } @Override @@ -1563,8 +1616,8 @@ public int getSpawnRadius() { @Override public void setSpawnRadius(int value) { - this.configuration.set("settings.spawn-radius", value); - this.saveConfig(); + configuration.set("settings.spawn-radius", value); + saveConfig(); } @Override @@ -1584,26 +1637,26 @@ public boolean isAcceptingTransfers() { @Override public boolean getHideOnlinePlayers() { - return this.console.hidesOnlinePlayers(); + return console.hidesOnlinePlayers(); } @Override public boolean getOnlineMode() { - return this.console.usesAuthentication(); + return console.usesAuthentication(); } @Override public boolean getAllowFlight() { - return this.console.isFlightAllowed(); + return console.isFlightAllowed(); } @Override public boolean isHardcore() { - return this.console.isHardcore(); + return console.isHardcore(); } public ChunkGenerator getGenerator(String world) { - ConfigurationSection section = this.configuration.getConfigurationSection("worlds"); + ConfigurationSection section = configuration.getConfigurationSection("worlds"); ChunkGenerator result = null; if (section != null) { @@ -1615,17 +1668,17 @@ public ChunkGenerator getGenerator(String world) { if ((name != null) && (!name.equals(""))) { String[] split = name.split(":", 2); String id = (split.length > 1) ? split[1] : null; - Plugin plugin = this.pluginManager.getPlugin(split[0]); + Plugin plugin = pluginManager.getPlugin(split[0]); if (plugin == null) { - this.getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + split[0] + "' does not exist"); + getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + split[0] + "' does not exist"); } else if (!plugin.isEnabled()) { - this.getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled yet (is it load:STARTUP?)"); + getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled yet (is it load:STARTUP?)"); } else { try { result = plugin.getDefaultWorldGenerator(world, id); if (result == null) { - this.getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' lacks a default world generator"); + getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' lacks a default world generator"); } } catch (Throwable t) { plugin.getLogger().log(Level.SEVERE, "Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName(), t); @@ -1639,7 +1692,7 @@ public ChunkGenerator getGenerator(String world) { } public BiomeProvider getBiomeProvider(String world) { - ConfigurationSection section = this.configuration.getConfigurationSection("worlds"); + ConfigurationSection section = configuration.getConfigurationSection("worlds"); BiomeProvider result = null; if (section != null) { @@ -1651,17 +1704,17 @@ public BiomeProvider getBiomeProvider(String world) { if ((name != null) && (!name.equals(""))) { String[] split = name.split(":", 2); String id = (split.length > 1) ? split[1] : null; - Plugin plugin = this.pluginManager.getPlugin(split[0]); + Plugin plugin = pluginManager.getPlugin(split[0]); if (plugin == null) { - this.getLogger().severe("Could not set biome provider for default world '" + world + "': Plugin '" + split[0] + "' does not exist"); + getLogger().severe("Could not set biome provider for default world '" + world + "': Plugin '" + split[0] + "' does not exist"); } else if (!plugin.isEnabled()) { - this.getLogger().severe("Could not set biome provider for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled yet (is it load:STARTUP?)"); + getLogger().severe("Could not set biome provider for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled yet (is it load:STARTUP?)"); } else { try { result = plugin.getDefaultBiomeProvider(world, id); if (result == null) { - this.getLogger().severe("Could not set biome provider for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' lacks a default world biome provider"); + getLogger().severe("Could not set biome provider for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' lacks a default world biome provider"); } } catch (Throwable t) { plugin.getLogger().log(Level.SEVERE, "Could not set biome provider for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName(), t); @@ -1677,7 +1730,7 @@ public BiomeProvider getBiomeProvider(String world) { @Override @Deprecated public CraftMapView getMap(int id) { - MapItemSavedData worldmap = this.console.getLevel(net.minecraft.world.level.Level.OVERWORLD).getMapData(new MapId(id)); + WorldMap worldmap = console.getLevel(net.minecraft.world.level.World.OVERWORLD).getMapData(new MapId(id)); if (worldmap == null) { return null; } @@ -1688,10 +1741,10 @@ public CraftMapView getMap(int id) { public CraftMapView createMap(World world) { Preconditions.checkArgument(world != null, "World cannot be null"); - net.minecraft.world.level.Level minecraftWorld = ((CraftWorld) world).getHandle(); + net.minecraft.world.level.World minecraftWorld = ((CraftWorld) world).getHandle(); // creates a new map at world spawn with the scale of 3, with out tracking position and unlimited tracking BlockPos spawn = minecraftWorld.getLevelData().getSpawnPos(); - MapId newId = MapItem.createNewSavedData(minecraftWorld, spawn.getX(), spawn.getZ(), 3, false, false, minecraftWorld.dimension()); + MapId newId = ItemWorldMap.createNewSavedData(minecraftWorld, spawn.getX(), spawn.getZ(), 3, false, false, minecraftWorld.dimension()); return minecraftWorld.getMapData(newId).mapView; } @@ -1706,35 +1759,35 @@ public ItemStack createExplorerMap(World world, Location location, StructureType Preconditions.checkArgument(structureType != null, "StructureType cannot be null"); Preconditions.checkArgument(structureType.getMapIcon() != null, "Cannot create explorer maps for StructureType %s", structureType.getName()); - ServerLevel worldServer = ((CraftWorld) world).getHandle(); + WorldServer worldServer = ((CraftWorld) world).getHandle(); Location structureLocation = world.locateNearestStructure(location, structureType, radius, findUnexplored); - BlockPos structurePosition = CraftLocation.toBlockPosition(structureLocation); + BlockPos structurePosition = CraftLocation.toBlockPos(structureLocation); // Create map with trackPlayer = true, unlimitedTracking = true - net.minecraft.world.item.ItemStack stack = MapItem.create(worldServer, structurePosition.getX(), structurePosition.getZ(), MapView.Scale.NORMAL.getValue(), true, true); - MapItem.renderBiomePreviewMap(worldServer, stack); + net.minecraft.world.item.ItemStack stack = ItemWorldMap.create(worldServer, structurePosition.getX(), structurePosition.getZ(), MapView.Scale.NORMAL.getValue(), true, true); + ItemWorldMap.renderBiomePreviewMap(worldServer, stack); // "+" map ID taken from EntityVillager - MapItem.getSavedData(stack, worldServer).addTargetDecoration(stack, structurePosition, "+", CraftMapCursor.CraftType.bukkitToMinecraftHolder(structureType.getMapIcon())); + ItemWorldMap.getSavedData(stack, worldServer).addTargetDecoration(stack, structurePosition, "+", CraftMapCursor.CraftType.bukkitToMinecraftHolder(structureType.getMapIcon())); return CraftItemStack.asBukkitCopy(stack); } @Override public void shutdown() { - this.console.halt(false); + console.halt(false); } @Override public int broadcast(String message, String permission) { Set recipients = new HashSet<>(); - for (Permissible permissible : this.getPluginManager().getPermissionSubscriptions(permission)) { + for (Permissible permissible : getPluginManager().getPermissionSubscriptions(permission)) { if (permissible instanceof CommandSender && permissible.hasPermission(permission)) { recipients.add((CommandSender) permissible); } } BroadcastMessageEvent broadcastMessageEvent = new BroadcastMessageEvent(!Bukkit.isPrimaryThread(), message, recipients); - this.getPluginManager().callEvent(broadcastMessageEvent); + getPluginManager().callEvent(broadcastMessageEvent); if (broadcastMessageEvent.isCancelled()) { return 0; @@ -1755,24 +1808,24 @@ public OfflinePlayer getOfflinePlayer(String name) { Preconditions.checkArgument(name != null, "name cannot be null"); Preconditions.checkArgument(!name.isBlank(), "name cannot be empty"); - OfflinePlayer result = this.getPlayerExact(name); + OfflinePlayer result = getPlayerExact(name); if (result == null) { GameProfile profile = null; // Only fetch an online UUID in online mode - if (this.getOnlineMode() || org.spigotmc.SpigotConfig.bungee) { // Spigot: bungee = online mode, for now. + if (getOnlineMode()) { // This is potentially blocking :( - profile = this.console.getProfileCache().get(name).orElse(null); + profile = console.getProfileCache().get(name).orElse(null); } if (profile == null) { // Make an OfflinePlayer using an offline mode UUID since the name has no profile - result = this.getOfflinePlayer(new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name)); + result = getOfflinePlayer(new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name)); } else { // Use the GameProfile even when we get a UUID so we ensure we still have a name - result = this.getOfflinePlayer(profile); + result = getOfflinePlayer(profile); } } else { - this.offlinePlayers.remove(result.getUniqueId()); + offlinePlayers.remove(result.getUniqueId()); } return result; @@ -1782,15 +1835,15 @@ public OfflinePlayer getOfflinePlayer(String name) { public OfflinePlayer getOfflinePlayer(UUID id) { Preconditions.checkArgument(id != null, "UUID id cannot be null"); - OfflinePlayer result = this.getPlayer(id); + OfflinePlayer result = getPlayer(id); if (result == null) { - result = this.offlinePlayers.get(id); + result = offlinePlayers.get(id); if (result == null) { result = new CraftOfflinePlayer(this, new GameProfile(id, "")); - this.offlinePlayers.put(id, result); + offlinePlayers.put(id, result); } } else { - this.offlinePlayers.remove(id); + offlinePlayers.remove(id); } return result; @@ -1813,14 +1866,14 @@ public PlayerProfile createPlayerProfile(String name) { public OfflinePlayer getOfflinePlayer(GameProfile profile) { OfflinePlayer player = new CraftOfflinePlayer(this, profile); - this.offlinePlayers.put(profile.getId(), player); + offlinePlayers.put(profile.getId(), player); return player; } @Override @SuppressWarnings("unchecked") public Set getIPBans() { - return this.playerList.getIpBans().getEntries().stream().map(IpBanListEntry::getUser).collect(Collectors.toSet()); + return playerList.getIpBans().getEntries().stream().map(IpBanEntry::getUser).collect(Collectors.toSet()); } @Override @@ -1855,8 +1908,8 @@ public void unbanIP(InetAddress address) { public Set getBannedPlayers() { Set result = new HashSet(); - for (UserBanListEntry entry : this.playerList.getBans().getEntries()) { - result.add(this.getOfflinePlayer(entry.getUser())); + for (GameProfileBanEntry entry : playerList.getBans().getEntries()) { + result.add(getOfflinePlayer(entry.getUser())); } return result; @@ -1874,26 +1927,26 @@ public > T getBanList(BanList.Type type) { @Override public void setWhitelist(boolean value) { - this.playerList.setUsingWhiteList(value); - this.console.storeUsingWhiteList(value); + playerList.setUsingWhiteList(value); + console.storeUsingWhiteList(value); } @Override public boolean isWhitelistEnforced() { - return this.console.isEnforceWhitelist(); + return console.isEnforceWhitelist(); } @Override public void setWhitelistEnforced(boolean value) { - this.console.setEnforceWhitelist(value); + console.setEnforceWhitelist(value); } @Override public Set getWhitelistedPlayers() { Set result = new LinkedHashSet(); - for (UserWhiteListEntry entry : this.playerList.getWhiteList().getEntries()) { - result.add(this.getOfflinePlayer(entry.getUser())); + for (WhiteListEntry entry : playerList.getWhiteList().getEntries()) { + result.add(getOfflinePlayer(entry.getUser())); } return result; @@ -1903,8 +1956,8 @@ public Set getWhitelistedPlayers() { public Set getOperators() { Set result = new HashSet(); - for (ServerOpListEntry entry : this.playerList.getOps().getEntries()) { - result.add(this.getOfflinePlayer(entry.getUser())); + for (OpListEntry entry : playerList.getOps().getEntries()) { + result.add(getOfflinePlayer(entry.getUser())); } return result; @@ -1912,74 +1965,74 @@ public Set getOperators() { @Override public void reloadWhitelist() { - this.playerList.reloadWhiteList(); + playerList.reloadWhiteList(); } @Override public GameMode getDefaultGameMode() { - return GameMode.getByValue(this.console.getLevel(net.minecraft.world.level.Level.OVERWORLD).serverLevelData.getGameType().getId()); + return GameMode.getByValue(console.getLevel(net.minecraft.world.level.World.OVERWORLD).serverLevelData.getGameType().getId()); } @Override public void setDefaultGameMode(GameMode mode) { Preconditions.checkArgument(mode != null, "GameMode cannot be null"); - for (World world : this.getWorlds()) { - ((CraftWorld) world).getHandle().serverLevelData.setGameType(GameType.byId(mode.getValue())); + for (World world : getWorlds()) { + ((CraftWorld) world).getHandle().serverLevelData.setGameType(EnumGamemode.byId(mode.getValue())); } } @Override public ConsoleCommandSender getConsoleSender() { - return this.console.console; + return console.console; } public EntityMetadataStore getEntityMetadata() { - return this.entityMetadata; + return entityMetadata; } public PlayerMetadataStore getPlayerMetadata() { - return this.playerMetadata; + return playerMetadata; } public WorldMetadataStore getWorldMetadata() { - return this.worldMetadata; + return worldMetadata; } @Override public File getWorldContainer() { - return this.getServer().storageSource.getDimensionPath(net.minecraft.world.level.Level.OVERWORLD).getParent().toFile(); + return this.getServer().storageSource.getDimensionPath(net.minecraft.world.level.World.OVERWORLD).getParent().toFile(); } @Override public OfflinePlayer[] getOfflinePlayers() { - PlayerDataStorage storage = this.console.playerDataStorage; + WorldNBTStorage storage = console.playerDataStorage; String[] files = storage.getPlayerDir().list(new DatFileFilter()); Set players = new HashSet(); for (String file : files) { try { - players.add(this.getOfflinePlayer(UUID.fromString(file.substring(0, file.length() - 4)))); + players.add(getOfflinePlayer(UUID.fromString(file.substring(0, file.length() - 4)))); } catch (IllegalArgumentException ex) { // Who knows what is in this directory, just ignore invalid files } } - players.addAll(this.getOnlinePlayers()); + players.addAll(getOnlinePlayers()); return players.toArray(new OfflinePlayer[players.size()]); } @Override public Messenger getMessenger() { - return this.messenger; + return messenger; } @Override public void sendPluginMessage(Plugin source, String channel, byte[] message) { - StandardMessenger.validatePluginMessage(this.getMessenger(), source, channel, message); + StandardMessenger.validatePluginMessage(getMessenger(), source, channel, message); - for (Player player : this.getOnlinePlayers()) { + for (Player player : getOnlinePlayers()) { player.sendPluginMessage(source, channel, message); } } @@ -1988,7 +2041,7 @@ public void sendPluginMessage(Plugin source, String channel, byte[] message) { public Set getListeningPluginChannels() { Set result = new HashSet(); - for (Player player : this.getOnlinePlayers()) { + for (Player player : getOnlinePlayers()) { result.addAll(player.getListeningPluginChannels()); } @@ -2034,67 +2087,67 @@ public int getMaxChainedNeighborUpdates() { @Override public HelpMap getHelpMap() { - return this.helpMap; + return helpMap; } public SimpleCommandMap getCommandMap() { - return this.commandMap; + return commandMap; } @Override @Deprecated public int getMonsterSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.MONSTER); + return getSpawnLimit(SpawnCategory.MONSTER); } @Override @Deprecated public int getAnimalSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.ANIMAL); + return getSpawnLimit(SpawnCategory.ANIMAL); } @Override @Deprecated public int getWaterAnimalSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.WATER_ANIMAL); + return getSpawnLimit(SpawnCategory.WATER_ANIMAL); } @Override @Deprecated public int getWaterAmbientSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.WATER_AMBIENT); + return getSpawnLimit(SpawnCategory.WATER_AMBIENT); } @Override @Deprecated public int getWaterUndergroundCreatureSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.WATER_UNDERGROUND_CREATURE); + return getSpawnLimit(SpawnCategory.WATER_UNDERGROUND_CREATURE); } @Override @Deprecated public int getAmbientSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.AMBIENT); + return getSpawnLimit(SpawnCategory.AMBIENT); } @Override public int getSpawnLimit(SpawnCategory spawnCategory) { - return this.spawnCategoryLimit.getOrDefault(spawnCategory, -1); + return spawnCategoryLimit.getOrDefault(spawnCategory, -1); } @Override public boolean isPrimaryThread() { - return Thread.currentThread().equals(this.console.serverThread) || this.console.hasStopped() || !org.spigotmc.AsyncCatcher.enabled; // All bets are off if we have shut down (e.g. due to watchdog) + return Thread.currentThread().equals(console.serverThread) || console.hasStopped(); // All bets are off if we have shut down (e.g. due to watchdog) } @Override public String getMotd() { - return this.console.getMotd(); + return console.getMotd(); } @Override public void setMotd(String motd) { - this.console.setMotd(motd); + console.setMotd(motd); } @Override @@ -2104,10 +2157,10 @@ public ServerLinks getServerLinks() { @Override public WarningState getWarningState() { - return this.warningState; + return warningState; } - public List tabComplete(CommandSender sender, String message, ServerLevel world, Vec3 pos, boolean forceCommand) { + public List tabComplete(CommandSender sender, String message, WorldServer world, Vec3D pos, boolean forceCommand) { if (!(sender instanceof Player)) { return ImmutableList.of(); } @@ -2115,25 +2168,18 @@ public List tabComplete(CommandSender sender, String message, ServerLeve List offers; Player player = (Player) sender; if (message.startsWith("/") || forceCommand) { - offers = this.tabCompleteCommand(player, message, world, pos); + offers = tabCompleteCommand(player, message, world, pos); } else { - offers = this.tabCompleteChat(player, message); + offers = tabCompleteChat(player, message); } TabCompleteEvent tabEvent = new TabCompleteEvent(player, message, offers); - this.getPluginManager().callEvent(tabEvent); + getPluginManager().callEvent(tabEvent); return tabEvent.isCancelled() ? Collections.EMPTY_LIST : tabEvent.getCompletions(); } - public List tabCompleteCommand(Player player, String message, ServerLevel world, Vec3 pos) { - // Spigot Start - if ( (org.spigotmc.SpigotConfig.tabComplete < 0 || message.length() <= org.spigotmc.SpigotConfig.tabComplete) && !message.contains( " " ) ) - { - return ImmutableList.of(); - } - // Spigot End - + public List tabCompleteCommand(Player player, String message, WorldServer world, Vec3D pos) { List completions = null; try { if (message.startsWith("/")) { @@ -2141,13 +2187,13 @@ public List tabCompleteCommand(Player player, String message, ServerLeve message = message.substring(1); } if (pos == null) { - completions = this.getCommandMap().tabComplete(player, message); + completions = getCommandMap().tabComplete(player, message); } else { - completions = this.getCommandMap().tabComplete(player, message, CraftLocation.toBukkit(pos, world.getWorld())); + completions = getCommandMap().tabComplete(player, message, CraftLocation.toBukkit(pos, world.getWorld())); } } catch (CommandException ex) { player.sendMessage(ChatColor.RED + "An internal error occurred while attempting to tab-complete this command"); - this.getLogger().log(Level.SEVERE, "Exception when " + player.getName() + " attempted to tab complete " + message, ex); + getLogger().log(Level.SEVERE, "Exception when " + player.getName() + " attempted to tab complete " + message, ex); } return completions == null ? ImmutableList.of() : completions; @@ -2157,12 +2203,12 @@ public List tabCompleteChat(Player player, String message) { List completions = new ArrayList(); PlayerChatTabCompleteEvent event = new PlayerChatTabCompleteEvent(player, message, completions); String token = event.getLastToken(); - for (Player p : this.getOnlinePlayers()) { + for (Player p : getOnlinePlayers()) { if (player.canSee(p) && StringUtil.startsWithIgnoreCase(p.getName(), token)) { completions.add(p.getName()); } } - this.pluginManager.callEvent(event); + pluginManager.callEvent(event); Iterator it = completions.iterator(); while (it.hasNext()) { @@ -2188,7 +2234,7 @@ public CraftEntityFactory getEntityFactory() { @Override public CraftScoreboardManager getScoreboardManager() { - return this.scoreboardManager; + return scoreboardManager; } @Override @@ -2201,29 +2247,29 @@ public void checkSaveState() { return; } this.printSaveWarning = true; - this.getLogger().log(Level.WARNING, "A manual (plugin-induced) save has been detected while server is configured to auto-save. This may affect performance.", this.warningState == WarningState.ON ? new Throwable() : null); + getLogger().log(Level.WARNING, "A manual (plugin-induced) save has been detected while server is configured to auto-save. This may affect performance.", warningState == WarningState.ON ? new Throwable() : null); } @Override public CraftIconCache getServerIcon() { - return this.icon; + return icon; } @Override public CraftIconCache loadServerIcon(File file) throws Exception { Preconditions.checkArgument(file != null, "File cannot be null"); Preconditions.checkArgument(file.isFile(), "File (%s) is not a valid file", file); - return CraftServer.loadServerIcon0(file); + return loadServerIcon0(file); } static CraftIconCache loadServerIcon0(File file) throws Exception { - return CraftServer.loadServerIcon0(ImageIO.read(file)); + return loadServerIcon0(ImageIO.read(file)); } @Override public CraftIconCache loadServerIcon(BufferedImage image) throws Exception { Preconditions.checkArgument(image != null, "BufferedImage image cannot be null"); - return CraftServer.loadServerIcon0(image); + return loadServerIcon0(image); } static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception { @@ -2238,19 +2284,19 @@ static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception { @Override public void setIdleTimeout(int threshold) { - this.console.setPlayerIdleTimeout(threshold); + console.setPlayerIdleTimeout(threshold); } @Override public int getIdleTimeout() { - return this.console.getPlayerIdleTimeout(); + return console.getPlayerIdleTimeout(); } @Override public ChunkGenerator.ChunkData createChunkData(World world) { Preconditions.checkArgument(world != null, "World cannot be null"); - ServerLevel handle = ((CraftWorld) world).getHandle(); - return new OldCraftChunkData(world.getMinHeight(), world.getMaxHeight(), handle.registryAccess().registryOrThrow(Registries.BIOME)); + WorldServer handle = ((CraftWorld) world).getHandle(); + return new OldCraftChunkData(world.getMinHeight(), world.getMaxHeight(), handle.registryAccess().lookupOrThrow(Registries.BIOME)); } @Override @@ -2264,7 +2310,7 @@ public KeyedBossBar createBossBar(NamespacedKey key, String title, BarColor barC Preconditions.checkArgument(barColor != null, "BarColor key cannot be null"); Preconditions.checkArgument(barStyle != null, "BarStyle key cannot be null"); - CustomBossEvent bossBattleCustom = this.getServer().getCustomBossEvents().create(CraftNamespacedKey.toMinecraft(key), CraftChatMessage.fromString(title, true)[0]); + BossBattleCustom bossBattleCustom = getServer().getCustomBossEvents().create(CraftNamespacedKey.toMinecraft(key), CraftChatMessage.fromString(title, true)[0]); CraftKeyedBossbar craftKeyedBossbar = new CraftKeyedBossbar(bossBattleCustom); craftKeyedBossbar.setColor(barColor); craftKeyedBossbar.setStyle(barStyle); @@ -2280,9 +2326,9 @@ public KeyedBossBar createBossBar(NamespacedKey key, String title, BarColor barC @Override public Iterator getBossBars() { - return Iterators.unmodifiableIterator(Iterators.transform(this.getServer().getCustomBossEvents().getEvents().iterator(), new Function() { + return Iterators.unmodifiableIterator(Iterators.transform(getServer().getCustomBossEvents().getEvents().iterator(), new Function() { @Override - public org.bukkit.boss.KeyedBossBar apply(CustomBossEvent bossBattleCustom) { + public org.bukkit.boss.KeyedBossBar apply(BossBattleCustom bossBattleCustom) { return bossBattleCustom.getBukkitEntity(); } })); @@ -2291,7 +2337,7 @@ public org.bukkit.boss.KeyedBossBar apply(CustomBossEvent bossBattleCustom) { @Override public KeyedBossBar getBossBar(NamespacedKey key) { Preconditions.checkArgument(key != null, "key"); - net.minecraft.server.bossevents.CustomBossEvent bossBattleCustom = this.getServer().getCustomBossEvents().get(CraftNamespacedKey.toMinecraft(key)); + net.minecraft.server.bossevents.BossBattleCustom bossBattleCustom = getServer().getCustomBossEvents().get(CraftNamespacedKey.toMinecraft(key)); return (bossBattleCustom == null) ? null : bossBattleCustom.getBukkitEntity(); } @@ -2299,8 +2345,8 @@ public KeyedBossBar getBossBar(NamespacedKey key) { @Override public boolean removeBossBar(NamespacedKey key) { Preconditions.checkArgument(key != null, "key"); - net.minecraft.server.bossevents.CustomBossEvents bossBattleCustomData = this.getServer().getCustomBossEvents(); - net.minecraft.server.bossevents.CustomBossEvent bossBattleCustom = bossBattleCustomData.get(CraftNamespacedKey.toMinecraft(key)); + net.minecraft.server.bossevents.BossBattleCustomData bossBattleCustomData = getServer().getCustomBossEvents(); + net.minecraft.server.bossevents.BossBattleCustom bossBattleCustom = bossBattleCustomData.get(CraftNamespacedKey.toMinecraft(key)); if (bossBattleCustom != null) { bossBattleCustomData.remove(bossBattleCustom); @@ -2314,7 +2360,7 @@ public boolean removeBossBar(NamespacedKey key) { public Entity getEntity(UUID uuid) { Preconditions.checkArgument(uuid != null, "UUID id cannot be null"); - for (ServerLevel world : this.getServer().getAllLevels()) { + for (WorldServer world : getServer().getAllLevels()) { net.minecraft.world.entity.Entity entity = world.getEntity(uuid); if (entity != null) { return entity.getBukkitEntity(); @@ -2328,13 +2374,13 @@ public Entity getEntity(UUID uuid) { public org.bukkit.advancement.Advancement getAdvancement(NamespacedKey key) { Preconditions.checkArgument(key != null, "NamespacedKey key cannot be null"); - AdvancementHolder advancement = this.console.getAdvancements().get(CraftNamespacedKey.toMinecraft(key)); + AdvancementHolder advancement = console.getAdvancements().get(CraftNamespacedKey.toMinecraft(key)); return (advancement == null) ? null : advancement.toBukkit(); } @Override public Iterator advancementIterator() { - return Iterators.unmodifiableIterator(Iterators.transform(this.console.getAdvancements().getAllAdvancements().iterator(), new Function() { + return Iterators.unmodifiableIterator(Iterators.transform(console.getAdvancements().getAllAdvancements().iterator(), new Function() { @Override public org.bukkit.advancement.Advancement apply(AdvancementHolder advancement) { return advancement.toBukkit(); @@ -2346,12 +2392,12 @@ public org.bukkit.advancement.Advancement apply(AdvancementHolder advancement) { public BlockData createBlockData(org.bukkit.Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); - return this.createBlockData(material, (String) null); + return createBlockData(material, (String) null); } @Override public BlockData createBlockData(org.bukkit.Material material, Consumer consumer) { - BlockData data = this.createBlockData(material); + BlockData data = createBlockData(material); if (consumer != null) { consumer.accept(data); @@ -2364,7 +2410,7 @@ public BlockData createBlockData(org.bukkit.Material material, Consumer org.bukkit.Tag getTag(String registry, NamespacedKey Preconditions.checkArgument(registry != null, "registry cannot be null"); Preconditions.checkArgument(tag != null, "NamespacedKey tag cannot be null"); Preconditions.checkArgument(clazz != null, "Class clazz cannot be null"); - ResourceLocation key = CraftNamespacedKey.toMinecraft(tag); + MinecraftKey key = CraftNamespacedKey.toMinecraft(tag); switch (registry) { case org.bukkit.Tag.REGISTRY_BLOCKS -> { Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace (%s) must have material type", clazz.getName()); TagKey blockTagKey = TagKey.create(Registries.BLOCK, key); - if (BuiltInRegistries.BLOCK.getTag(blockTagKey).isPresent()) { + if (BuiltInRegistries.BLOCK.get(blockTagKey).isPresent()) { return (org.bukkit.Tag) new CraftBlockTag(BuiltInRegistries.BLOCK, blockTagKey); } } case org.bukkit.Tag.REGISTRY_ITEMS -> { Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace (%s) must have material type", clazz.getName()); TagKey itemTagKey = TagKey.create(Registries.ITEM, key); - if (BuiltInRegistries.ITEM.getTag(itemTagKey).isPresent()) { + if (BuiltInRegistries.ITEM.get(itemTagKey).isPresent()) { return (org.bukkit.Tag) new CraftItemTag(BuiltInRegistries.ITEM, itemTagKey); } } case org.bukkit.Tag.REGISTRY_FLUIDS -> { Preconditions.checkArgument(clazz == org.bukkit.Fluid.class, "Fluid namespace (%s) must have fluid type", clazz.getName()); - TagKey fluidTagKey = TagKey.create(Registries.FLUID, key); - if (BuiltInRegistries.FLUID.getTag(fluidTagKey).isPresent()) { + TagKey fluidTagKey = TagKey.create(Registries.FLUID, key); + if (BuiltInRegistries.FLUID.get(fluidTagKey).isPresent()) { return (org.bukkit.Tag) new CraftFluidTag(BuiltInRegistries.FLUID, fluidTagKey); } } case org.bukkit.Tag.REGISTRY_ENTITY_TYPES -> { Preconditions.checkArgument(clazz == org.bukkit.entity.EntityType.class, "Entity type namespace (%s) must have entity type", clazz.getName()); - TagKey> entityTagKey = TagKey.create(Registries.ENTITY_TYPE, key); - if (BuiltInRegistries.ENTITY_TYPE.getTag(entityTagKey).isPresent()) { + TagKey> entityTagKey = TagKey.create(Registries.ENTITY_TYPE, key); + if (BuiltInRegistries.ENTITY_TYPE.get(entityTagKey).isPresent()) { return (org.bukkit.Tag) new CraftEntityTag(BuiltInRegistries.ENTITY_TYPE, entityTagKey); } } + case org.bukkit.tag.DamageTypeTags.REGISTRY_DAMAGE_TYPES -> { + Preconditions.checkArgument(clazz == org.bukkit.damage.DamageType.class, "Damage type namespace (%s) must have damage type", clazz.getName()); + TagKey damageTagKey = TagKey.create(Registries.DAMAGE_TYPE, key); + IRegistry damageRegistry = CraftRegistry.getMinecraftRegistry(Registries.DAMAGE_TYPE); + if (damageRegistry.get(damageTagKey).isPresent()) { + return (org.bukkit.Tag) new CraftDamageTag(damageRegistry, damageTagKey); + } + } default -> throw new IllegalArgumentException(); } @@ -2425,23 +2479,28 @@ public Iterable> getTags(String registry, Cl switch (registry) { case org.bukkit.Tag.REGISTRY_BLOCKS -> { Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace (%s) must have material type", clazz.getName()); - net.minecraft.core.Registry blockTags = BuiltInRegistries.BLOCK; - return blockTags.getTags().map(pair -> (org.bukkit.Tag) new CraftBlockTag(blockTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); + IRegistry blockTags = BuiltInRegistries.BLOCK; + return blockTags.getTags().map(pair -> (org.bukkit.Tag) new CraftBlockTag(blockTags, pair.key())).collect(ImmutableList.toImmutableList()); } case org.bukkit.Tag.REGISTRY_ITEMS -> { Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace (%s) must have material type", clazz.getName()); - net.minecraft.core.Registry itemTags = BuiltInRegistries.ITEM; - return itemTags.getTags().map(pair -> (org.bukkit.Tag) new CraftItemTag(itemTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); + IRegistry itemTags = BuiltInRegistries.ITEM; + return itemTags.getTags().map(pair -> (org.bukkit.Tag) new CraftItemTag(itemTags, pair.key())).collect(ImmutableList.toImmutableList()); } case org.bukkit.Tag.REGISTRY_FLUIDS -> { Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Fluid namespace (%s) must have fluid type", clazz.getName()); - net.minecraft.core.Registry fluidTags = BuiltInRegistries.FLUID; - return fluidTags.getTags().map(pair -> (org.bukkit.Tag) new CraftFluidTag(fluidTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); + IRegistry fluidTags = BuiltInRegistries.FLUID; + return fluidTags.getTags().map(pair -> (org.bukkit.Tag) new CraftFluidTag(fluidTags, pair.key())).collect(ImmutableList.toImmutableList()); } case org.bukkit.Tag.REGISTRY_ENTITY_TYPES -> { Preconditions.checkArgument(clazz == org.bukkit.entity.EntityType.class, "Entity type namespace (%s) must have entity type", clazz.getName()); - net.minecraft.core.Registry> entityTags = BuiltInRegistries.ENTITY_TYPE; - return entityTags.getTags().map(pair -> (org.bukkit.Tag) new CraftEntityTag(entityTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); + IRegistry> entityTags = BuiltInRegistries.ENTITY_TYPE; + return entityTags.getTags().map(pair -> (org.bukkit.Tag) new CraftEntityTag(entityTags, pair.key())).collect(ImmutableList.toImmutableList()); + } + case org.bukkit.tag.DamageTypeTags.REGISTRY_DAMAGE_TYPES -> { + Preconditions.checkArgument(clazz == org.bukkit.damage.DamageType.class, "Damage type namespace (%s) must have damage type", clazz.getName()); + IRegistry damageTags = CraftRegistry.getMinecraftRegistry(Registries.DAMAGE_TYPE); + return damageTags.getTags().map(pair -> (org.bukkit.Tag) new CraftDamageTag(damageTags, pair.key())).collect(ImmutableList.toImmutableList()); } default -> throw new IllegalArgumentException(); } @@ -2451,7 +2510,7 @@ public Iterable> getTags(String registry, Cl public LootTable getLootTable(NamespacedKey key) { Preconditions.checkArgument(key != null, "NamespacedKey key cannot be null"); - ReloadableServerRegistries.Holder registry = this.getServer().reloadableRegistries(); + ReloadableServerRegistries.a registry = getServer().reloadableRegistries(); return registry.lookup().lookup(Registries.LOOT_TABLE) .flatMap((lookup) -> lookup.get(CraftLootTable.bukkitKeyToMinecraft(key))) .map((holder) -> new CraftLootTable(key, holder.value())) @@ -2463,7 +2522,7 @@ public List selectEntities(CommandSender sender, String selector) { Preconditions.checkArgument(selector != null, "selector cannot be null"); Preconditions.checkArgument(sender != null, "CommandSender sender cannot be null"); - EntityArgument arg = EntityArgument.entities(); + ArgumentEntity arg = ArgumentEntity.entities(); List nms; try { @@ -2479,12 +2538,12 @@ public List selectEntities(CommandSender sender, String selector) { @Override public StructureManager getStructureManager() { - return this.structureManager; + return structureManager; } @Override public Registry getRegistry(Class aClass) { - return (Registry) this.registries.computeIfAbsent(aClass, key -> CraftRegistry.createRegistry(aClass, this.console.registryAccess())); + return (Registry) registries.computeIfAbsent(aClass, key -> CraftRegistry.createRegistry(aClass, console.registryAccess())); } @Deprecated @@ -2492,40 +2551,4 @@ public Registry getRegistry(Class aClass) { public UnsafeValues getUnsafe() { return CraftMagicNumbers.INSTANCE; } - - // Spigot start - private final org.bukkit.Server.Spigot spigot = new org.bukkit.Server.Spigot() - { - - @Override - public YamlConfiguration getConfig() - { - return org.spigotmc.SpigotConfig.config; - } - - @Override - public void restart() { - org.spigotmc.RestartCommand.restart(); - } - - @Override - public void broadcast(BaseComponent component) { - for (Player player : CraftServer.this.getOnlinePlayers()) { - player.spigot().sendMessage(component); - } - } - - @Override - public void broadcast(BaseComponent... components) { - for (Player player : CraftServer.this.getOnlinePlayers()) { - player.spigot().sendMessage(components); - } - } - }; - - public org.bukkit.Server.Spigot spigot() - { - return this.spigot; - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServerTickManager.java b/src/main/java/org/bukkit/craftbukkit/CraftServerTickManager.java index cdc55d07..7fca09c2 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftServerTickManager.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftServerTickManager.java @@ -16,78 +16,78 @@ final class CraftServerTickManager implements ServerTickManager { @Override public boolean isRunningNormally() { - return this.manager.runsNormally(); + return manager.runsNormally(); } @Override public boolean isStepping() { - return this.manager.isSteppingForward(); + return manager.isSteppingForward(); } @Override public boolean isSprinting() { - return this.manager.isSprinting(); + return manager.isSprinting(); } @Override public boolean isFrozen() { - return this.manager.isFrozen(); + return manager.isFrozen(); } @Override public float getTickRate() { - return this.manager.tickrate(); + return manager.tickrate(); } @Override public void setTickRate(final float tickRate) { Preconditions.checkArgument(tickRate >= 1.0F && tickRate <= 10_000.0F, "The given tick rate must not be less than 1.0 or greater than 10,000.0"); - this.manager.setTickRate(tickRate); + manager.setTickRate(tickRate); } @Override public void setFrozen(final boolean frozen) { if (frozen) { - if (this.manager.isSprinting()) { - this.manager.stopSprinting(); + if (manager.isSprinting()) { + manager.stopSprinting(); } - if (this.manager.isSteppingForward()) { - this.manager.stopStepping(); + if (manager.isSteppingForward()) { + manager.stopStepping(); } } - this.manager.setFrozen(frozen); + manager.setFrozen(frozen); } @Override public boolean stepGameIfFrozen(final int ticks) { - return this.manager.stepGameIfPaused(ticks); + return manager.stepGameIfPaused(ticks); } @Override public boolean stopStepping() { - return this.manager.stopStepping(); + return manager.stopStepping(); } @Override public boolean requestGameToSprint(final int ticks) { - return this.manager.requestGameToSprint(ticks); + return manager.requestGameToSprint(ticks); } @Override public boolean stopSprinting() { - return this.manager.stopSprinting(); + return manager.stopSprinting(); } @Override public boolean isFrozen(final Entity entity) { Preconditions.checkArgument(entity != null, "The given entity must not be null"); - return this.manager.isEntityFrozen(((CraftEntity) entity).getHandle()); + return manager.isEntityFrozen(((CraftEntity) entity).getHandle()); } @Override public int getFrozenTicksToRun() { - return this.manager.frozenTicksToRun(); + return manager.frozenTicksToRun(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftSound.java b/src/main/java/org/bukkit/craftbukkit/CraftSound.java index 260a738d..db0d2acc 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftSound.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftSound.java @@ -2,18 +2,19 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; -import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundEffect; import org.bukkit.Registry; import org.bukkit.Sound; import org.bukkit.craftbukkit.util.CraftNamespacedKey; public class CraftSound { - public static Sound minecraftToBukkit(SoundEvent minecraft) { + public static Sound minecraftToBukkit(SoundEffect minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.SOUND_EVENT); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.SOUND_EVENT); Sound bukkit = Registry.SOUNDS.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); @@ -21,19 +22,19 @@ public static Sound minecraftToBukkit(SoundEvent minecraft) { return bukkit; } - public static SoundEvent bukkitToMinecraft(Sound bukkit) { + public static SoundEffect bukkitToMinecraft(Sound bukkit) { Preconditions.checkArgument(bukkit != null); return CraftRegistry.getMinecraftRegistry(Registries.SOUND_EVENT) .getOptional(CraftNamespacedKey.toMinecraft(bukkit.getKey())).orElseThrow(); } - public static Holder bukkitToMinecraftHolder(Sound bukkit) { + public static Holder bukkitToMinecraftHolder(Sound bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.SOUND_EVENT); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.SOUND_EVENT); - if (registry.wrapAsHolder(CraftSound.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftSoundGroup.java b/src/main/java/org/bukkit/craftbukkit/CraftSoundGroup.java index c61612e5..3859fc6b 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftSoundGroup.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftSoundGroup.java @@ -1,59 +1,59 @@ package org.bukkit.craftbukkit; import java.util.HashMap; -import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.SoundEffectType; import org.bukkit.Sound; import org.bukkit.SoundGroup; public class CraftSoundGroup implements SoundGroup { - private final net.minecraft.world.level.block.SoundType handle; - private static final HashMap SOUND_GROUPS = new HashMap<>(); + private final net.minecraft.world.level.block.SoundEffectType handle; + private static final HashMap SOUND_GROUPS = new HashMap<>(); - public static SoundGroup getSoundGroup(SoundType soundEffectType) { - return CraftSoundGroup.SOUND_GROUPS.computeIfAbsent(soundEffectType, CraftSoundGroup::new); + public static SoundGroup getSoundGroup(SoundEffectType soundEffectType) { + return SOUND_GROUPS.computeIfAbsent(soundEffectType, CraftSoundGroup::new); } - private CraftSoundGroup(net.minecraft.world.level.block.SoundType soundEffectType) { + private CraftSoundGroup(net.minecraft.world.level.block.SoundEffectType soundEffectType) { this.handle = soundEffectType; } - public net.minecraft.world.level.block.SoundType getHandle() { - return this.handle; + public net.minecraft.world.level.block.SoundEffectType getHandle() { + return handle; } @Override public float getVolume() { - return this.getHandle().getVolume(); + return getHandle().getVolume(); } @Override public float getPitch() { - return this.getHandle().getPitch(); + return getHandle().getPitch(); } @Override public Sound getBreakSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getBreakSound()); + return CraftSound.minecraftToBukkit(getHandle().breakSound); } @Override public Sound getStepSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getStepSound()); + return CraftSound.minecraftToBukkit(getHandle().getStepSound()); } @Override public Sound getPlaceSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getPlaceSound()); + return CraftSound.minecraftToBukkit(getHandle().getPlaceSound()); } @Override public Sound getHitSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getHitSound()); + return CraftSound.minecraftToBukkit(getHandle().hitSound); } @Override public Sound getFallSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getFallSound()); + return CraftSound.minecraftToBukkit(getHandle().getFallSound()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java b/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java index ccee1f63..a1318890 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java @@ -3,12 +3,13 @@ import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.stats.ServerStatsCounter; -import net.minecraft.stats.Stats; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.stats.ServerStatisticManager; +import net.minecraft.stats.StatisticList; +import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import org.bukkit.Material; @@ -20,95 +21,95 @@ import org.bukkit.entity.EntityType; public enum CraftStatistic { - DAMAGE_DEALT(Stats.DAMAGE_DEALT), - DAMAGE_TAKEN(Stats.DAMAGE_TAKEN), - DEATHS(Stats.DEATHS), - MOB_KILLS(Stats.MOB_KILLS), - PLAYER_KILLS(Stats.PLAYER_KILLS), - FISH_CAUGHT(Stats.FISH_CAUGHT), - ANIMALS_BRED(Stats.ANIMALS_BRED), - LEAVE_GAME(Stats.LEAVE_GAME), - JUMP(Stats.JUMP), - DROP_COUNT(Stats.DROP), - DROP(ResourceLocation.withDefaultNamespace("dropped")), - PICKUP(ResourceLocation.withDefaultNamespace("picked_up")), - PLAY_ONE_MINUTE(Stats.PLAY_TIME), - TOTAL_WORLD_TIME(Stats.TOTAL_WORLD_TIME), - WALK_ONE_CM(Stats.WALK_ONE_CM), - WALK_ON_WATER_ONE_CM(Stats.WALK_ON_WATER_ONE_CM), - FALL_ONE_CM(Stats.FALL_ONE_CM), - SNEAK_TIME(Stats.CROUCH_TIME), - CLIMB_ONE_CM(Stats.CLIMB_ONE_CM), - FLY_ONE_CM(Stats.FLY_ONE_CM), - WALK_UNDER_WATER_ONE_CM(Stats.WALK_UNDER_WATER_ONE_CM), - MINECART_ONE_CM(Stats.MINECART_ONE_CM), - BOAT_ONE_CM(Stats.BOAT_ONE_CM), - PIG_ONE_CM(Stats.PIG_ONE_CM), - HORSE_ONE_CM(Stats.HORSE_ONE_CM), - SPRINT_ONE_CM(Stats.SPRINT_ONE_CM), - CROUCH_ONE_CM(Stats.CROUCH_ONE_CM), - AVIATE_ONE_CM(Stats.AVIATE_ONE_CM), - MINE_BLOCK(ResourceLocation.withDefaultNamespace("mined")), - USE_ITEM(ResourceLocation.withDefaultNamespace("used")), - BREAK_ITEM(ResourceLocation.withDefaultNamespace("broken")), - CRAFT_ITEM(ResourceLocation.withDefaultNamespace("crafted")), - KILL_ENTITY(ResourceLocation.withDefaultNamespace("killed")), - ENTITY_KILLED_BY(ResourceLocation.withDefaultNamespace("killed_by")), - TIME_SINCE_DEATH(Stats.TIME_SINCE_DEATH), - TALKED_TO_VILLAGER(Stats.TALKED_TO_VILLAGER), - TRADED_WITH_VILLAGER(Stats.TRADED_WITH_VILLAGER), - CAKE_SLICES_EATEN(Stats.EAT_CAKE_SLICE), - CAULDRON_FILLED(Stats.FILL_CAULDRON), - CAULDRON_USED(Stats.USE_CAULDRON), - ARMOR_CLEANED(Stats.CLEAN_ARMOR), - BANNER_CLEANED(Stats.CLEAN_BANNER), - BREWINGSTAND_INTERACTION(Stats.INTERACT_WITH_BREWINGSTAND), - BEACON_INTERACTION(Stats.INTERACT_WITH_BEACON), - DROPPER_INSPECTED(Stats.INSPECT_DROPPER), - HOPPER_INSPECTED(Stats.INSPECT_HOPPER), - DISPENSER_INSPECTED(Stats.INSPECT_DISPENSER), - NOTEBLOCK_PLAYED(Stats.PLAY_NOTEBLOCK), - NOTEBLOCK_TUNED(Stats.TUNE_NOTEBLOCK), - FLOWER_POTTED(Stats.POT_FLOWER), - TRAPPED_CHEST_TRIGGERED(Stats.TRIGGER_TRAPPED_CHEST), - ENDERCHEST_OPENED(Stats.OPEN_ENDERCHEST), - ITEM_ENCHANTED(Stats.ENCHANT_ITEM), - RECORD_PLAYED(Stats.PLAY_RECORD), - FURNACE_INTERACTION(Stats.INTERACT_WITH_FURNACE), - CRAFTING_TABLE_INTERACTION(Stats.INTERACT_WITH_CRAFTING_TABLE), - CHEST_OPENED(Stats.OPEN_CHEST), - SLEEP_IN_BED(Stats.SLEEP_IN_BED), - SHULKER_BOX_OPENED(Stats.OPEN_SHULKER_BOX), - TIME_SINCE_REST(Stats.TIME_SINCE_REST), - SWIM_ONE_CM(Stats.SWIM_ONE_CM), - DAMAGE_DEALT_ABSORBED(Stats.DAMAGE_DEALT_ABSORBED), - DAMAGE_DEALT_RESISTED(Stats.DAMAGE_DEALT_RESISTED), - DAMAGE_BLOCKED_BY_SHIELD(Stats.DAMAGE_BLOCKED_BY_SHIELD), - DAMAGE_ABSORBED(Stats.DAMAGE_ABSORBED), - DAMAGE_RESISTED(Stats.DAMAGE_RESISTED), - CLEAN_SHULKER_BOX(Stats.CLEAN_SHULKER_BOX), - OPEN_BARREL(Stats.OPEN_BARREL), - INTERACT_WITH_BLAST_FURNACE(Stats.INTERACT_WITH_BLAST_FURNACE), - INTERACT_WITH_SMOKER(Stats.INTERACT_WITH_SMOKER), - INTERACT_WITH_LECTERN(Stats.INTERACT_WITH_LECTERN), - INTERACT_WITH_CAMPFIRE(Stats.INTERACT_WITH_CAMPFIRE), - INTERACT_WITH_CARTOGRAPHY_TABLE(Stats.INTERACT_WITH_CARTOGRAPHY_TABLE), - INTERACT_WITH_LOOM(Stats.INTERACT_WITH_LOOM), - INTERACT_WITH_STONECUTTER(Stats.INTERACT_WITH_STONECUTTER), - BELL_RING(Stats.BELL_RING), - RAID_TRIGGER(Stats.RAID_TRIGGER), - RAID_WIN(Stats.RAID_WIN), - INTERACT_WITH_ANVIL(Stats.INTERACT_WITH_ANVIL), - INTERACT_WITH_GRINDSTONE(Stats.INTERACT_WITH_GRINDSTONE), - TARGET_HIT(Stats.TARGET_HIT), - INTERACT_WITH_SMITHING_TABLE(Stats.INTERACT_WITH_SMITHING_TABLE), - STRIDER_ONE_CM(Stats.STRIDER_ONE_CM); - private final ResourceLocation minecraftKey; + DAMAGE_DEALT(StatisticList.DAMAGE_DEALT), + DAMAGE_TAKEN(StatisticList.DAMAGE_TAKEN), + DEATHS(StatisticList.DEATHS), + MOB_KILLS(StatisticList.MOB_KILLS), + PLAYER_KILLS(StatisticList.PLAYER_KILLS), + FISH_CAUGHT(StatisticList.FISH_CAUGHT), + ANIMALS_BRED(StatisticList.ANIMALS_BRED), + LEAVE_GAME(StatisticList.LEAVE_GAME), + JUMP(StatisticList.JUMP), + DROP_COUNT(StatisticList.DROP), + DROP(MinecraftKey.withDefaultNamespace("dropped")), + PICKUP(MinecraftKey.withDefaultNamespace("picked_up")), + PLAY_ONE_MINUTE(StatisticList.PLAY_TIME), + TOTAL_WORLD_TIME(StatisticList.TOTAL_WORLD_TIME), + WALK_ONE_CM(StatisticList.WALK_ONE_CM), + WALK_ON_WATER_ONE_CM(StatisticList.WALK_ON_WATER_ONE_CM), + FALL_ONE_CM(StatisticList.FALL_ONE_CM), + SNEAK_TIME(StatisticList.CROUCH_TIME), + CLIMB_ONE_CM(StatisticList.CLIMB_ONE_CM), + FLY_ONE_CM(StatisticList.FLY_ONE_CM), + WALK_UNDER_WATER_ONE_CM(StatisticList.WALK_UNDER_WATER_ONE_CM), + MINECART_ONE_CM(StatisticList.MINECART_ONE_CM), + BOAT_ONE_CM(StatisticList.BOAT_ONE_CM), + PIG_ONE_CM(StatisticList.PIG_ONE_CM), + HORSE_ONE_CM(StatisticList.HORSE_ONE_CM), + SPRINT_ONE_CM(StatisticList.SPRINT_ONE_CM), + CROUCH_ONE_CM(StatisticList.CROUCH_ONE_CM), + AVIATE_ONE_CM(StatisticList.AVIATE_ONE_CM), + MINE_BLOCK(MinecraftKey.withDefaultNamespace("mined")), + USE_ITEM(MinecraftKey.withDefaultNamespace("used")), + BREAK_ITEM(MinecraftKey.withDefaultNamespace("broken")), + CRAFT_ITEM(MinecraftKey.withDefaultNamespace("crafted")), + KILL_ENTITY(MinecraftKey.withDefaultNamespace("killed")), + ENTITY_KILLED_BY(MinecraftKey.withDefaultNamespace("killed_by")), + TIME_SINCE_DEATH(StatisticList.TIME_SINCE_DEATH), + TALKED_TO_VILLAGER(StatisticList.TALKED_TO_VILLAGER), + TRADED_WITH_VILLAGER(StatisticList.TRADED_WITH_VILLAGER), + CAKE_SLICES_EATEN(StatisticList.EAT_CAKE_SLICE), + CAULDRON_FILLED(StatisticList.FILL_CAULDRON), + CAULDRON_USED(StatisticList.USE_CAULDRON), + ARMOR_CLEANED(StatisticList.CLEAN_ARMOR), + BANNER_CLEANED(StatisticList.CLEAN_BANNER), + BREWINGSTAND_INTERACTION(StatisticList.INTERACT_WITH_BREWINGSTAND), + BEACON_INTERACTION(StatisticList.INTERACT_WITH_BEACON), + DROPPER_INSPECTED(StatisticList.INSPECT_DROPPER), + HOPPER_INSPECTED(StatisticList.INSPECT_HOPPER), + DISPENSER_INSPECTED(StatisticList.INSPECT_DISPENSER), + NOTEBLOCK_PLAYED(StatisticList.PLAY_NOTEBLOCK), + NOTEBLOCK_TUNED(StatisticList.TUNE_NOTEBLOCK), + FLOWER_POTTED(StatisticList.POT_FLOWER), + TRAPPED_CHEST_TRIGGERED(StatisticList.TRIGGER_TRAPPED_CHEST), + ENDERCHEST_OPENED(StatisticList.OPEN_ENDERCHEST), + ITEM_ENCHANTED(StatisticList.ENCHANT_ITEM), + RECORD_PLAYED(StatisticList.PLAY_RECORD), + FURNACE_INTERACTION(StatisticList.INTERACT_WITH_FURNACE), + CRAFTING_TABLE_INTERACTION(StatisticList.INTERACT_WITH_CRAFTING_TABLE), + CHEST_OPENED(StatisticList.OPEN_CHEST), + SLEEP_IN_BED(StatisticList.SLEEP_IN_BED), + SHULKER_BOX_OPENED(StatisticList.OPEN_SHULKER_BOX), + TIME_SINCE_REST(StatisticList.TIME_SINCE_REST), + SWIM_ONE_CM(StatisticList.SWIM_ONE_CM), + DAMAGE_DEALT_ABSORBED(StatisticList.DAMAGE_DEALT_ABSORBED), + DAMAGE_DEALT_RESISTED(StatisticList.DAMAGE_DEALT_RESISTED), + DAMAGE_BLOCKED_BY_SHIELD(StatisticList.DAMAGE_BLOCKED_BY_SHIELD), + DAMAGE_ABSORBED(StatisticList.DAMAGE_ABSORBED), + DAMAGE_RESISTED(StatisticList.DAMAGE_RESISTED), + CLEAN_SHULKER_BOX(StatisticList.CLEAN_SHULKER_BOX), + OPEN_BARREL(StatisticList.OPEN_BARREL), + INTERACT_WITH_BLAST_FURNACE(StatisticList.INTERACT_WITH_BLAST_FURNACE), + INTERACT_WITH_SMOKER(StatisticList.INTERACT_WITH_SMOKER), + INTERACT_WITH_LECTERN(StatisticList.INTERACT_WITH_LECTERN), + INTERACT_WITH_CAMPFIRE(StatisticList.INTERACT_WITH_CAMPFIRE), + INTERACT_WITH_CARTOGRAPHY_TABLE(StatisticList.INTERACT_WITH_CARTOGRAPHY_TABLE), + INTERACT_WITH_LOOM(StatisticList.INTERACT_WITH_LOOM), + INTERACT_WITH_STONECUTTER(StatisticList.INTERACT_WITH_STONECUTTER), + BELL_RING(StatisticList.BELL_RING), + RAID_TRIGGER(StatisticList.RAID_TRIGGER), + RAID_WIN(StatisticList.RAID_WIN), + INTERACT_WITH_ANVIL(StatisticList.INTERACT_WITH_ANVIL), + INTERACT_WITH_GRINDSTONE(StatisticList.INTERACT_WITH_GRINDSTONE), + TARGET_HIT(StatisticList.TARGET_HIT), + INTERACT_WITH_SMITHING_TABLE(StatisticList.INTERACT_WITH_SMITHING_TABLE), + STRIDER_ONE_CM(StatisticList.STRIDER_ONE_CM); + private final MinecraftKey minecraftKey; private final org.bukkit.Statistic bukkit; - private static final BiMap statistics; + private static final BiMap statistics; static { - ImmutableBiMap.Builder statisticBuilder = ImmutableBiMap.builder(); + ImmutableBiMap.Builder statisticBuilder = ImmutableBiMap.builder(); for (CraftStatistic statistic : CraftStatistic.values()) { statisticBuilder.put(statistic.minecraftKey, statistic.bukkit); } @@ -116,53 +117,53 @@ public enum CraftStatistic { statistics = statisticBuilder.build(); } - private CraftStatistic(ResourceLocation minecraftKey) { + private CraftStatistic(MinecraftKey minecraftKey) { this.minecraftKey = minecraftKey; this.bukkit = org.bukkit.Statistic.valueOf(this.name()); - Preconditions.checkState(this.bukkit != null, "Bukkit statistic %s does not exist", this.name()); + Preconditions.checkState(bukkit != null, "Bukkit statistic %s does not exist", this.name()); } - public static org.bukkit.Statistic getBukkitStatistic(net.minecraft.stats.Stat statistic) { + public static org.bukkit.Statistic getBukkitStatistic(net.minecraft.stats.Statistic statistic) { Preconditions.checkArgument(statistic != null, "NMS Statistic cannot be null"); - Registry statRegistry = statistic.getType().getRegistry(); - ResourceLocation nmsKey = BuiltInRegistries.STAT_TYPE.getKey(statistic.getType()); + IRegistry statRegistry = statistic.getType().getRegistry(); + MinecraftKey nmsKey = BuiltInRegistries.STAT_TYPE.getKey(statistic.getType()); if (statRegistry == BuiltInRegistries.CUSTOM_STAT) { - nmsKey = (ResourceLocation) statistic.getValue(); + nmsKey = (MinecraftKey) statistic.getValue(); } return statistics.get(nmsKey); } - public static net.minecraft.stats.Stat getNMSStatistic(org.bukkit.Statistic bukkit) { + public static net.minecraft.stats.Statistic getNMSStatistic(org.bukkit.Statistic bukkit) { Preconditions.checkArgument(bukkit.getType() == Statistic.Type.UNTYPED, "This method only accepts untyped statistics"); - net.minecraft.stats.Stat nms = Stats.CUSTOM.get(statistics.inverse().get(bukkit)); + net.minecraft.stats.Statistic nms = StatisticList.CUSTOM.get(statistics.inverse().get(bukkit)); Preconditions.checkArgument(nms != null, "NMS Statistic %s does not exist", bukkit); return nms; } - public static net.minecraft.stats.Stat getMaterialStatistic(org.bukkit.Statistic stat, Material material) { + public static net.minecraft.stats.Statistic getMaterialStatistic(org.bukkit.Statistic stat, Material material) { try { if (stat == Statistic.MINE_BLOCK) { - return Stats.BLOCK_MINED.get(CraftBlockType.bukkitToMinecraft(material)); + return StatisticList.BLOCK_MINED.get(CraftBlockType.bukkitToMinecraft(material)); } if (stat == Statistic.CRAFT_ITEM) { - return Stats.ITEM_CRAFTED.get(CraftItemType.bukkitToMinecraft(material)); + return StatisticList.ITEM_CRAFTED.get(CraftItemType.bukkitToMinecraft(material)); } if (stat == Statistic.USE_ITEM) { - return Stats.ITEM_USED.get(CraftItemType.bukkitToMinecraft(material)); + return StatisticList.ITEM_USED.get(CraftItemType.bukkitToMinecraft(material)); } if (stat == Statistic.BREAK_ITEM) { - return Stats.ITEM_BROKEN.get(CraftItemType.bukkitToMinecraft(material)); + return StatisticList.ITEM_BROKEN.get(CraftItemType.bukkitToMinecraft(material)); } if (stat == Statistic.PICKUP) { - return Stats.ITEM_PICKED_UP.get(CraftItemType.bukkitToMinecraft(material)); + return StatisticList.ITEM_PICKED_UP.get(CraftItemType.bukkitToMinecraft(material)); } if (stat == Statistic.DROP) { - return Stats.ITEM_DROPPED.get(CraftItemType.bukkitToMinecraft(material)); + return StatisticList.ITEM_DROPPED.get(CraftItemType.bukkitToMinecraft(material)); } } catch (ArrayIndexOutOfBoundsException e) { return null; @@ -170,27 +171,27 @@ public static net.minecraft.stats.Stat getMaterialStatistic(org.bukkit.Statistic return null; } - public static net.minecraft.stats.Stat getEntityStatistic(org.bukkit.Statistic stat, EntityType entity) { + public static net.minecraft.stats.Statistic getEntityStatistic(org.bukkit.Statistic stat, EntityType entity) { Preconditions.checkArgument(entity != null, "EntityType cannot be null"); if (entity.getName() != null) { - net.minecraft.world.entity.EntityType nmsEntity = CraftEntityType.bukkitToMinecraft(entity); + EntityTypes nmsEntity = CraftEntityType.bukkitToMinecraft(entity); if (stat == org.bukkit.Statistic.KILL_ENTITY) { - return net.minecraft.stats.Stats.ENTITY_KILLED.get(nmsEntity); + return net.minecraft.stats.StatisticList.ENTITY_KILLED.get(nmsEntity); } if (stat == org.bukkit.Statistic.ENTITY_KILLED_BY) { - return net.minecraft.stats.Stats.ENTITY_KILLED_BY.get(nmsEntity); + return net.minecraft.stats.StatisticList.ENTITY_KILLED_BY.get(nmsEntity); } } return null; } - public static EntityType getEntityTypeFromStatistic(net.minecraft.stats.Stat> statistic) { + public static EntityType getEntityTypeFromStatistic(net.minecraft.stats.Statistic> statistic) { Preconditions.checkArgument(statistic != null, "NMS Statistic cannot be null"); return CraftEntityType.minecraftToBukkit(statistic.getValue()); } - public static Material getMaterialFromStatistic(net.minecraft.stats.Stat statistic) { + public static Material getMaterialFromStatistic(net.minecraft.stats.Statistic statistic) { if (statistic.getValue() instanceof Item statisticItemValue) { return CraftItemType.minecraftToBukkit(statisticItemValue); } @@ -200,35 +201,35 @@ public static Material getMaterialFromStatistic(net.minecraft.stats.Stat stat return null; } - public static void incrementStatistic(ServerStatsCounter manager, Statistic statistic, ServerPlayer player) { + public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityPlayer player) { incrementStatistic(manager, statistic, 1, player); } - public static void decrementStatistic(ServerStatsCounter manager, Statistic statistic, ServerPlayer player) { + public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityPlayer player) { decrementStatistic(manager, statistic, 1, player); } - public static int getStatistic(ServerStatsCounter manager, Statistic statistic) { + public static int getStatistic(ServerStatisticManager manager, Statistic statistic) { Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); Preconditions.checkArgument(statistic.getType() == Type.UNTYPED, "Must supply additional parameter for this statistic"); return manager.getValue(CraftStatistic.getNMSStatistic(statistic)); } - public static void incrementStatistic(ServerStatsCounter manager, Statistic statistic, int amount, ServerPlayer player) { + public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, int amount, EntityPlayer player) { Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, getStatistic(manager, statistic) + amount, player); } - public static void decrementStatistic(ServerStatsCounter manager, Statistic statistic, int amount, ServerPlayer player) { + public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, int amount, EntityPlayer player) { Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, getStatistic(manager, statistic) - amount, player); } - public static void setStatistic(ServerStatsCounter manager, Statistic statistic, int newValue, ServerPlayer player) { + public static void setStatistic(ServerStatisticManager manager, Statistic statistic, int newValue, EntityPlayer player) { Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); Preconditions.checkArgument(statistic.getType() == Type.UNTYPED, "Must supply additional parameter for this statistic"); Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0"); - net.minecraft.stats.Stat nmsStatistic = CraftStatistic.getNMSStatistic(statistic); + net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getNMSStatistic(statistic); manager.setValue(null, nmsStatistic, newValue); // Update scoreboards @@ -239,39 +240,39 @@ public static void setStatistic(ServerStatsCounter manager, Statistic statistic, } } - public static void incrementStatistic(ServerStatsCounter manager, Statistic statistic, Material material, ServerPlayer player) { + public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, EntityPlayer player) { incrementStatistic(manager, statistic, material, 1, player); } - public static void decrementStatistic(ServerStatsCounter manager, Statistic statistic, Material material, ServerPlayer player) { + public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, EntityPlayer player) { decrementStatistic(manager, statistic, material, 1, player); } - public static int getStatistic(ServerStatsCounter manager, Statistic statistic, Material material) { + public static int getStatistic(ServerStatisticManager manager, Statistic statistic, Material material) { Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null"); Preconditions.checkArgument(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter"); - net.minecraft.stats.Stat nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); + net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); Preconditions.checkArgument(nmsStatistic != null, "The supplied Material %s does not have a corresponding statistic", material); return manager.getValue(nmsStatistic); } - public static void incrementStatistic(ServerStatsCounter manager, Statistic statistic, Material material, int amount, ServerPlayer player) { + public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int amount, EntityPlayer player) { Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, material, getStatistic(manager, statistic, material) + amount, player); } - public static void decrementStatistic(ServerStatsCounter manager, Statistic statistic, Material material, int amount, ServerPlayer player) { + public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int amount, EntityPlayer player) { Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, material, getStatistic(manager, statistic, material) - amount, player); } - public static void setStatistic(ServerStatsCounter manager, Statistic statistic, Material material, int newValue, ServerPlayer player) { + public static void setStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int newValue, EntityPlayer player) { Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null"); Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0"); Preconditions.checkArgument(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter"); - net.minecraft.stats.Stat nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); + net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); Preconditions.checkArgument(nmsStatistic != null, "The supplied Material %s does not have a corresponding statistic", material); manager.setValue(null, nmsStatistic, newValue); @@ -283,39 +284,39 @@ public static void setStatistic(ServerStatsCounter manager, Statistic statistic, } } - public static void incrementStatistic(ServerStatsCounter manager, Statistic statistic, EntityType entityType, ServerPlayer player) { + public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, EntityPlayer player) { incrementStatistic(manager, statistic, entityType, 1, player); } - public static void decrementStatistic(ServerStatsCounter manager, Statistic statistic, EntityType entityType, ServerPlayer player) { + public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, EntityPlayer player) { decrementStatistic(manager, statistic, entityType, 1, player); } - public static int getStatistic(ServerStatsCounter manager, Statistic statistic, EntityType entityType) { + public static int getStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType) { Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); Preconditions.checkArgument(entityType != null, "EntityType cannot be null"); Preconditions.checkArgument(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); - net.minecraft.stats.Stat nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); + net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); Preconditions.checkArgument(nmsStatistic != null, "The supplied EntityType %s does not have a corresponding statistic", entityType); return manager.getValue(nmsStatistic); } - public static void incrementStatistic(ServerStatsCounter manager, Statistic statistic, EntityType entityType, int amount, ServerPlayer player) { + public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int amount, EntityPlayer player) { Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, entityType, getStatistic(manager, statistic, entityType) + amount, player); } - public static void decrementStatistic(ServerStatsCounter manager, Statistic statistic, EntityType entityType, int amount, ServerPlayer player) { + public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int amount, EntityPlayer player) { Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, entityType, getStatistic(manager, statistic, entityType) - amount, player); } - public static void setStatistic(ServerStatsCounter manager, Statistic statistic, EntityType entityType, int newValue, ServerPlayer player) { + public static void setStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int newValue, EntityPlayer player) { Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); Preconditions.checkArgument(entityType != null, "EntityType cannot be null"); Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0"); Preconditions.checkArgument(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); - net.minecraft.stats.Stat nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); + net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); Preconditions.checkArgument(nmsStatistic != null, "The supplied EntityType %s does not have a corresponding statistic", entityType); manager.setValue(null, nmsStatistic, newValue); diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java index f3a62874..c913c853 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java @@ -27,44 +27,53 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; +import net.minecraft.core.IRegistry; +import net.minecraft.core.particles.Particles; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; -import net.minecraft.network.protocol.game.ClientboundLevelEventPacket; -import net.minecraft.network.protocol.game.ClientboundSetTimePacket; -import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; -import net.minecraft.network.protocol.game.ClientboundSoundPacket; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ChunkHolder; -import net.minecraft.server.level.ChunkMap; -import net.minecraft.server.level.DistanceManager; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.network.protocol.game.PacketPlayOutEntitySound; +import net.minecraft.network.protocol.game.PacketPlayOutNamedSoundEffect; +import net.minecraft.network.protocol.game.PacketPlayOutUpdateTime; +import net.minecraft.network.protocol.game.PacketPlayOutWorldEvent; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.server.level.ChunkMapDistance; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.server.level.PlayerChunk; +import net.minecraft.server.level.PlayerChunkMap; import net.minecraft.server.level.Ticket; import net.minecraft.server.level.TicketType; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; -import net.minecraft.util.SortedArraySet; +import net.minecraft.server.level.WorldServer; +import net.minecraft.sounds.SoundCategory; +import net.minecraft.sounds.SoundEffect; +import net.minecraft.sounds.SoundEffects; +import net.minecraft.util.ArraySetSorted; import net.minecraft.util.Unit; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.LightningBolt; -import net.minecraft.world.entity.item.FallingBlockEntity; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.raid.Raids; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.ClipContext; +import net.minecraft.world.EnumDifficulty; +import net.minecraft.world.entity.EntityLightning; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.item.EntityFallingBlock; +import net.minecraft.world.entity.item.EntityItem; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.entity.projectile.EntityArrow; +import net.minecraft.world.entity.raid.PersistentRaid; +import net.minecraft.world.level.ChunkCoordIntPair; +import net.minecraft.world.level.Explosion; import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.RayTrace; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.Climate; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ImposterProtoChunk; +import net.minecraft.world.level.chunk.IChunkAccess; +import net.minecraft.world.level.chunk.ProtoChunkExtension; import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.levelgen.structure.StructureStart; -import net.minecraft.world.level.storage.LevelResource; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.HitResult; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.level.storage.SavedFile; +import net.minecraft.world.phys.AxisAlignedBB; +import net.minecraft.world.phys.MovingObjectPosition; +import net.minecraft.world.phys.Vec3D; +import net.minecraft.world.phys.shapes.VoxelShapeCollision; import org.bukkit.BlockChangeDelegate; import org.bukkit.Bukkit; import org.bukkit.Chunk; @@ -152,7 +161,7 @@ public class CraftWorld extends CraftRegionAccessor implements World { public static final int CUSTOM_DIMENSION_OFFSET = 10; private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry(); - private final ServerLevel world; + private final WorldServer world; private WorldBorder worldBorder; private Environment environment; private final CraftServer server = (CraftServer) Bukkit.getServer(); @@ -161,27 +170,27 @@ public class CraftWorld extends CraftRegionAccessor implements World { private final List populators = new ArrayList(); private final BlockMetadataStore blockMetadata = new BlockMetadataStore(this); private final Object2IntOpenHashMap spawnCategoryLimit = new Object2IntOpenHashMap<>(); - private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(CraftWorld.DATA_TYPE_REGISTRY); + private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(DATA_TYPE_REGISTRY); private static final Random rand = new Random(); - public CraftWorld(ServerLevel world, ChunkGenerator gen, BiomeProvider biomeProvider, Environment env) { + public CraftWorld(WorldServer world, ChunkGenerator gen, BiomeProvider biomeProvider, Environment env) { this.world = world; this.generator = gen; this.biomeProvider = biomeProvider; - this.environment = env; + environment = env; } @Override public Block getBlockAt(int x, int y, int z) { - return CraftBlock.at(this.world, new BlockPos(x, y, z)); + return CraftBlock.at(world, new BlockPos(x, y, z)); } @Override public Location getSpawnLocation() { - BlockPos spawn = this.world.getSharedSpawnPos(); - float yaw = this.world.getSharedSpawnAngle(); + BlockPos spawn = world.getSharedSpawnPos(); + float yaw = world.getSharedSpawnAngle(); return CraftLocation.toBukkit(spawn, this, yaw, 0); } @@ -189,18 +198,18 @@ public Location getSpawnLocation() { public boolean setSpawnLocation(Location location) { Preconditions.checkArgument(location != null, "location"); - return this.equals(location.getWorld()) ? this.setSpawnLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getYaw()) : false; + return equals(location.getWorld()) ? setSpawnLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getYaw()) : false; } @Override public boolean setSpawnLocation(int x, int y, int z, float angle) { try { - Location previousLocation = this.getSpawnLocation(); - this.world.levelData.setSpawn(new BlockPos(x, y, z), angle); + Location previousLocation = getSpawnLocation(); + world.levelData.setSpawn(new BlockPos(x, y, z), angle); // Notify anyone who's listening. SpawnChangeEvent event = new SpawnChangeEvent(this, previousLocation); - this.server.getPluginManager().callEvent(event); + server.getPluginManager().callEvent(event); return true; } catch (Exception e) { @@ -210,12 +219,12 @@ public boolean setSpawnLocation(int x, int y, int z, float angle) { @Override public boolean setSpawnLocation(int x, int y, int z) { - return this.setSpawnLocation(x, y, z, 0.0F); + return setSpawnLocation(x, y, z, 0.0F); } @Override public Chunk getChunkAt(int x, int z) { - net.minecraft.world.level.chunk.LevelChunk chunk = (net.minecraft.world.level.chunk.LevelChunk) this.world.getChunk(x, z, ChunkStatus.FULL, true); + net.minecraft.world.level.chunk.Chunk chunk = (net.minecraft.world.level.chunk.Chunk) this.world.getChunk(x, z, ChunkStatus.FULL, true); return new CraftChunk(chunk); } @@ -223,28 +232,28 @@ public Chunk getChunkAt(int x, int z) { @Override public Chunk getChunkAt(int x, int z, boolean generate) { if (generate) { - return this.getChunkAt(x, z); + return getChunkAt(x, z); } - return new CraftChunk(this.getHandle(), x, z); + return new CraftChunk(getHandle(), x, z); } @Override public Chunk getChunkAt(Block block) { Preconditions.checkArgument(block != null, "null block"); - return this.getChunkAt(block.getX() >> 4, block.getZ() >> 4); + return getChunkAt(block.getX() >> 4, block.getZ() >> 4); } @Override public boolean isChunkLoaded(int x, int z) { - return this.world.getChunkSource().isChunkLoaded(x, z); + return world.getChunkSource().isChunkLoaded(x, z); } @Override public boolean isChunkGenerated(int x, int z) { try { - return this.isChunkLoaded(x, z) || this.world.getChunkSource().chunkMap.read(new ChunkPos(x, z)).get().isPresent(); + return isChunkLoaded(x, z) || world.getChunkSource().chunkMap.read(new ChunkCoordIntPair(x, z)).get().isPresent(); } catch (InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } @@ -252,57 +261,56 @@ public boolean isChunkGenerated(int x, int z) { @Override public Chunk[] getLoadedChunks() { - Long2ObjectLinkedOpenHashMap chunks = this.world.getChunkSource().chunkMap.visibleChunkMap; - return chunks.values().stream().map(ChunkHolder::getFullChunkNow).filter(Objects::nonNull).map(CraftChunk::new).toArray(Chunk[]::new); + Long2ObjectLinkedOpenHashMap chunks = world.getChunkSource().chunkMap.visibleChunkMap; + return chunks.values().stream().map(PlayerChunk::getFullChunkNow).filter(Objects::nonNull).map(CraftChunk::new).toArray(Chunk[]::new); } @Override public void loadChunk(int x, int z) { - this.loadChunk(x, z, true); + loadChunk(x, z, true); } @Override public boolean unloadChunk(Chunk chunk) { - return this.unloadChunk(chunk.getX(), chunk.getZ()); + return unloadChunk(chunk.getX(), chunk.getZ()); } @Override public boolean unloadChunk(int x, int z) { - return this.unloadChunk(x, z, true); + return unloadChunk(x, z, true); } @Override public boolean unloadChunk(int x, int z, boolean save) { - return this.unloadChunk0(x, z, save); + return unloadChunk0(x, z, save); } @Override public boolean unloadChunkRequest(int x, int z) { - org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot - if (this.isChunkLoaded(x, z)) { - this.world.getChunkSource().removeRegionTicket(TicketType.PLUGIN, new ChunkPos(x, z), 1, Unit.INSTANCE); + if (isChunkLoaded(x, z)) { + world.getChunkSource().removeRegionTicket(TicketType.PLUGIN, new ChunkCoordIntPair(x, z), 1, Unit.INSTANCE); } return true; } private boolean unloadChunk0(int x, int z, boolean save) { - org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot - if (!this.isChunkLoaded(x, z)) { + if (!isChunkLoaded(x, z)) { return true; } - net.minecraft.world.level.chunk.LevelChunk chunk = this.world.getChunk(x, z); + net.minecraft.world.level.chunk.Chunk chunk = world.getChunk(x, z); - chunk.setUnsaved(!save); // Use method call to account for persistentDataContainer - this.unloadChunkRequest(x, z); + if (!save) { + chunk.tryMarkSaved(); // Use method call to account for persistentDataContainer + } + unloadChunkRequest(x, z); - this.world.getChunkSource().purgeUnload(); - return !this.isChunkLoaded(x, z); + world.getChunkSource().purgeUnload(); + return !isChunkLoaded(x, z); } @Override public boolean regenerateChunk(int x, int z) { - org.spigotmc.AsyncCatcher.catchOp("chunk regenerate"); // Spigot throw new UnsupportedOperationException("Not supported in this Minecraft version! Unless you can fix it, this is not a bug :)"); /* if (!unloadChunk0(x, z, false)) { @@ -328,16 +336,16 @@ public boolean regenerateChunk(int x, int z) { @Override public boolean refreshChunk(int x, int z) { - ChunkHolder playerChunk = this.world.getChunkSource().chunkMap.visibleChunkMap.get(ChunkPos.asLong(x, z)); + PlayerChunk playerChunk = world.getChunkSource().chunkMap.visibleChunkMap.get(ChunkCoordIntPair.asLong(x, z)); if (playerChunk == null) return false; playerChunk.getTickingChunkFuture().thenAccept(either -> { either.ifSuccess(chunk -> { - List playersInRange = playerChunk.playerProvider.getPlayers(playerChunk.getPos(), false); + List playersInRange = playerChunk.playerProvider.getPlayers(playerChunk.getPos(), false); if (playersInRange.isEmpty()) return; - ClientboundLevelChunkWithLightPacket refreshPacket = new ClientboundLevelChunkWithLightPacket(chunk, this.world.getLightEngine(), null, null); - for (ServerPlayer player : playersInRange) { + ClientboundLevelChunkWithLightPacket refreshPacket = new ClientboundLevelChunkWithLightPacket(chunk, world.getLightEngine(), null, null); + for (EntityPlayer player : playersInRange) { if (player.connection == null) continue; player.connection.send(refreshPacket); @@ -361,7 +369,7 @@ public Collection getPlayersSeeingChunk(int x, int z) { return Collections.emptySet(); } - List players = world.getChunkSource().chunkMap.getPlayers(new ChunkPos(x, z), false); + List players = world.getChunkSource().chunkMap.getPlayers(new ChunkCoordIntPair(x, z), false); if (players.isEmpty()) { return Collections.emptySet(); @@ -369,28 +377,27 @@ public Collection getPlayersSeeingChunk(int x, int z) { return players.stream() .filter(Objects::nonNull) - .map(ServerPlayer::getBukkitEntity) + .map(EntityPlayer::getBukkitEntity) .collect(Collectors.toUnmodifiableSet()); } @Override public boolean isChunkInUse(int x, int z) { - return this.isChunkLoaded(x, z); + return isChunkLoaded(x, z); } @Override public boolean loadChunk(int x, int z, boolean generate) { - org.spigotmc.AsyncCatcher.catchOp("chunk load"); // Spigot - ChunkAccess chunk = this.world.getChunkSource().getChunk(x, z, generate ? ChunkStatus.FULL : ChunkStatus.EMPTY, true); + IChunkAccess chunk = world.getChunkSource().getChunk(x, z, generate ? ChunkStatus.FULL : ChunkStatus.EMPTY, true); // If generate = false, but the chunk already exists, we will get this back. - if (chunk instanceof ImposterProtoChunk) { + if (chunk instanceof ProtoChunkExtension) { // We then cycle through again to get the full chunk immediately, rather than after the ticket addition - chunk = this.world.getChunkSource().getChunk(x, z, ChunkStatus.FULL, true); + chunk = world.getChunkSource().getChunk(x, z, ChunkStatus.FULL, true); } - if (chunk instanceof net.minecraft.world.level.chunk.LevelChunk) { - this.world.getChunkSource().addRegionTicket(TicketType.PLUGIN, new ChunkPos(x, z), 1, Unit.INSTANCE); + if (chunk instanceof net.minecraft.world.level.chunk.Chunk) { + world.getChunkSource().addRegionTicket(TicketType.PLUGIN, new ChunkCoordIntPair(x, z), 1, Unit.INSTANCE); return true; } @@ -401,14 +408,14 @@ public boolean loadChunk(int x, int z, boolean generate) { public boolean isChunkLoaded(Chunk chunk) { Preconditions.checkArgument(chunk != null, "null chunk"); - return this.isChunkLoaded(chunk.getX(), chunk.getZ()); + return isChunkLoaded(chunk.getX(), chunk.getZ()); } @Override public void loadChunk(Chunk chunk) { Preconditions.checkArgument(chunk != null, "null chunk"); - this.loadChunk(chunk.getX(), chunk.getZ()); + loadChunk(chunk.getX(), chunk.getZ()); } @Override @@ -416,9 +423,9 @@ public boolean addPluginChunkTicket(int x, int z, Plugin plugin) { Preconditions.checkArgument(plugin != null, "null plugin"); Preconditions.checkArgument(plugin.isEnabled(), "plugin is not enabled"); - DistanceManager chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; + ChunkMapDistance chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; - if (chunkDistanceManager.addRegionTicketAtDistance(TicketType.PLUGIN_TICKET, new ChunkPos(x, z), 2, plugin)) { // keep in-line with force loading, add at level 31 + if (chunkDistanceManager.addRegionTicketAtDistance(TicketType.PLUGIN_TICKET, new ChunkCoordIntPair(x, z), 2, plugin)) { // keep in-line with force loading, add at level 31 this.getChunkAt(x, z); // ensure loaded return true; } @@ -430,22 +437,22 @@ public boolean addPluginChunkTicket(int x, int z, Plugin plugin) { public boolean removePluginChunkTicket(int x, int z, Plugin plugin) { Preconditions.checkNotNull(plugin, "null plugin"); - DistanceManager chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; - return chunkDistanceManager.removeRegionTicketAtDistance(TicketType.PLUGIN_TICKET, new ChunkPos(x, z), 2, plugin); // keep in-line with force loading, remove at level 31 + ChunkMapDistance chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; + return chunkDistanceManager.removeRegionTicketAtDistance(TicketType.PLUGIN_TICKET, new ChunkCoordIntPair(x, z), 2, plugin); // keep in-line with force loading, remove at level 31 } @Override public void removePluginChunkTickets(Plugin plugin) { Preconditions.checkNotNull(plugin, "null plugin"); - DistanceManager chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; + ChunkMapDistance chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; chunkDistanceManager.removeAllTicketsFor(TicketType.PLUGIN_TICKET, 31, plugin); // keep in-line with force loading, remove at level 31 } @Override public Collection getPluginChunkTickets(int x, int z) { - DistanceManager chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; - SortedArraySet> tickets = chunkDistanceManager.tickets.get(ChunkPos.asLong(x, z)); + ChunkMapDistance chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; + ArraySetSorted> tickets = chunkDistanceManager.tickets.get(ChunkCoordIntPair.asLong(x, z)); if (tickets == null) { return Collections.emptyList(); @@ -464,11 +471,11 @@ public Collection getPluginChunkTickets(int x, int z) { @Override public Map> getPluginChunkTickets() { Map> ret = new HashMap<>(); - DistanceManager chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; + ChunkMapDistance chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager; - for (Long2ObjectMap.Entry>> chunkTickets : chunkDistanceManager.tickets.long2ObjectEntrySet()) { + for (Long2ObjectMap.Entry>> chunkTickets : chunkDistanceManager.tickets.long2ObjectEntrySet()) { long chunkKey = chunkTickets.getLongKey(); - SortedArraySet> tickets = chunkTickets.getValue(); + ArraySetSorted> tickets = chunkTickets.getValue(); Chunk chunk = null; for (Ticket ticket : tickets) { @@ -477,7 +484,7 @@ public Map> getPluginChunkTickets() { } if (chunk == null) { - chunk = this.getChunkAt(ChunkPos.getX(chunkKey), ChunkPos.getZ(chunkKey)); + chunk = this.getChunkAt(ChunkCoordIntPair.getX(chunkKey), ChunkCoordIntPair.getZ(chunkKey)); } ret.computeIfAbsent((Plugin) ticket.key, (key) -> ImmutableList.builder()).add(chunk); @@ -499,7 +506,7 @@ public Collection getIntersectingChunks(@NotNull BoundingBox boundingBox) for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { - chunks.add(this.getChunkAt(x, z, false)); + chunks.add(getChunkAt(x, z, false)); } } @@ -508,32 +515,32 @@ public Collection getIntersectingChunks(@NotNull BoundingBox boundingBox) @Override public boolean isChunkForceLoaded(int x, int z) { - return this.getHandle().getForcedChunks().contains(ChunkPos.asLong(x, z)); + return getHandle().getForcedChunks().contains(ChunkCoordIntPair.asLong(x, z)); } @Override public void setChunkForceLoaded(int x, int z, boolean forced) { - this.getHandle().setChunkForced(x, z, forced); + getHandle().setChunkForced(x, z, forced); } @Override public Collection getForceLoadedChunks() { Set chunks = new HashSet<>(); - for (long coord : this.getHandle().getForcedChunks()) { - chunks.add(this.getChunkAt(ChunkPos.getX(coord), ChunkPos.getZ(coord))); + for (long coord : getHandle().getForcedChunks()) { + chunks.add(getChunkAt(ChunkCoordIntPair.getX(coord), ChunkCoordIntPair.getZ(coord))); } return Collections.unmodifiableCollection(chunks); } - public ServerLevel getHandle() { - return this.world; + public WorldServer getHandle() { + return world; } @Override public org.bukkit.entity.Item dropItem(Location loc, ItemStack item) { - return this.dropItem(loc, item, null); + return dropItem(loc, item, null); } @Override @@ -541,19 +548,19 @@ public org.bukkit.entity.Item dropItem(Location loc, ItemStack item, Consumer T spawnArrow(Location loc, Vector velocity, flo Preconditions.checkArgument(velocity != null, "Vector cannot be null"); Preconditions.checkArgument(clazz != null, "clazz Entity for the arrow cannot be null"); - net.minecraft.world.entity.projectile.AbstractArrow arrow; + EntityArrow arrow; if (TippedArrow.class.isAssignableFrom(clazz)) { - arrow = EntityType.ARROW.create(this.world); + arrow = EntityTypes.ARROW.create(world, EntitySpawnReason.COMMAND); ((Arrow) arrow.getBukkitEntity()).setBasePotionType(PotionType.WATER); } else if (SpectralArrow.class.isAssignableFrom(clazz)) { - arrow = EntityType.SPECTRAL_ARROW.create(this.world); + arrow = EntityTypes.SPECTRAL_ARROW.create(world, EntitySpawnReason.COMMAND); } else if (Trident.class.isAssignableFrom(clazz)) { - arrow = EntityType.TRIDENT.create(this.world); + arrow = EntityTypes.TRIDENT.create(world, EntitySpawnReason.COMMAND); } else { - arrow = EntityType.ARROW.create(this.world); + arrow = EntityTypes.ARROW.create(world, EntitySpawnReason.COMMAND); } arrow.moveTo(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch()); arrow.shoot(velocity.getX(), velocity.getY(), velocity.getZ(), speed, spread); - this.world.addFreshEntity(arrow); + world.addFreshEntity(arrow); return (T) arrow.getBukkitEntity(); } @Override public LightningStrike strikeLightning(Location loc) { - return this.strikeLightning0(loc, false); + return strikeLightning0(loc, false); } @Override public LightningStrike strikeLightningEffect(Location loc) { - return this.strikeLightning0(loc, true); + return strikeLightning0(loc, true); } private LightningStrike strikeLightning0(Location loc, boolean isVisual) { Preconditions.checkArgument(loc != null, "Location cannot be null"); - LightningBolt lightning = EntityType.LIGHTNING_BOLT.create(this.world); + EntityLightning lightning = EntityTypes.LIGHTNING_BOLT.create(world, EntitySpawnReason.COMMAND); lightning.moveTo(loc.getX(), loc.getY(), loc.getZ()); lightning.setVisualOnly(isVisual); - this.world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM); + world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM); return (LightningStrike) lightning.getBukkitEntity(); } @Override public boolean generateTree(Location loc, TreeType type) { - return this.generateTree(loc, CraftWorld.rand, type); + return generateTree(loc, rand, type); } @Override public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) { - this.world.captureTreeGeneration = true; - this.world.captureBlockStates = true; - boolean grownTree = this.generateTree(loc, type); - this.world.captureBlockStates = false; - this.world.captureTreeGeneration = false; + world.captureTreeGeneration = true; + world.captureBlockStates = true; + boolean grownTree = generateTree(loc, type); + world.captureBlockStates = false; + world.captureTreeGeneration = false; if (grownTree) { // Copy block data to delegate - for (BlockState blockstate : this.world.capturedBlockStates.values()) { + for (BlockState blockstate : world.capturedBlockStates.values()) { BlockPos position = ((CraftBlockState) blockstate).getPosition(); - net.minecraft.world.level.block.state.BlockState oldBlock = this.world.getBlockState(position); + net.minecraft.world.level.block.state.IBlockData oldBlock = world.getBlockState(position); int flag = ((CraftBlockState) blockstate).getFlag(); delegate.setBlockData(blockstate.getX(), blockstate.getY(), blockstate.getZ(), blockstate.getBlockData()); - net.minecraft.world.level.block.state.BlockState newBlock = this.world.getBlockState(position); - this.world.notifyAndUpdatePhysics(position, null, oldBlock, newBlock, newBlock, flag, 512); + net.minecraft.world.level.block.state.IBlockData newBlock = world.getBlockState(position); + world.notifyAndUpdatePhysics(position, null, oldBlock, newBlock, newBlock, flag, 512); } - this.world.capturedBlockStates.clear(); + world.capturedBlockStates.clear(); return true; } else { - this.world.capturedBlockStates.clear(); + world.capturedBlockStates.clear(); return false; } } @Override public String getName() { - world.K.checkName(world.name); - return world.name; + return world.serverLevelData.getLevelName(); } @Override public UUID getUID() { - return this.world.uuid; + return world.uuid; } @Override public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(this.world.dimension().location()); + return CraftNamespacedKey.fromMinecraft(world.dimension().location()); } @Override public String toString() { - return "CraftWorld{name=" + this.getName() + '}'; + return "CraftWorld{name=" + getName() + '}'; } @Override public long getTime() { - long time = this.getFullTime() % 24000; + long time = getFullTime() % 24000; if (time < 0) time += 24000; return time; } @Override public void setTime(long time) { - long margin = (time - this.getFullTime()) % 24000; + long margin = (time - getFullTime()) % 24000; if (margin < 0) margin += 24000; - this.setFullTime(this.getFullTime() + margin); + setFullTime(getFullTime() + margin); } @Override public long getFullTime() { - return this.world.getDayTime(); + return world.getDayTime(); } @Override public void setFullTime(long time) { // Notify anyone who's listening - TimeSkipEvent event = new TimeSkipEvent(this, TimeSkipEvent.SkipReason.CUSTOM, time - this.world.getDayTime()); - this.server.getPluginManager().callEvent(event); + TimeSkipEvent event = new TimeSkipEvent(this, TimeSkipEvent.SkipReason.CUSTOM, time - world.getDayTime()); + server.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } - this.world.setDayTime(this.world.getDayTime() + event.getSkipAmount()); + world.setDayTime(world.getDayTime() + event.getSkipAmount()); // Forces the client to update to the new time immediately - for (Player p : this.getPlayers()) { + for (Player p : getPlayers()) { CraftPlayer cp = (CraftPlayer) p; if (cp.getHandle().connection == null) continue; - cp.getHandle().connection.send(new ClientboundSetTimePacket(cp.getHandle().level().getGameTime(), cp.getHandle().getPlayerTime(), cp.getHandle().level().getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); + cp.getHandle().connection.send(new PacketPlayOutUpdateTime(cp.getHandle().level().getGameTime(), cp.getHandle().getPlayerTime(), cp.getHandle().serverLevel().getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); } } @Override public long getGameTime() { - return this.world.levelData.getGameTime(); + return world.levelData.getGameTime(); } @Override public boolean createExplosion(double x, double y, double z, float power) { - return this.createExplosion(x, y, z, power, false, true); + return createExplosion(x, y, z, power, false, true); } @Override public boolean createExplosion(double x, double y, double z, float power, boolean setFire) { - return this.createExplosion(x, y, z, power, setFire, true); + return createExplosion(x, y, z, power, setFire, true); } @Override public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { - return this.createExplosion(x, y, z, power, setFire, breakBlocks, null); + return createExplosion(x, y, z, power, setFire, breakBlocks, null); } @Override public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) { - net.minecraft.world.level.Level.ExplosionInteraction explosionType; + net.minecraft.world.level.World.a explosionType; if (!breakBlocks) { - explosionType = net.minecraft.world.level.Level.ExplosionInteraction.NONE; // Don't break blocks + explosionType = net.minecraft.world.level.World.a.NONE; // Don't break blocks } else if (source == null) { - explosionType = net.minecraft.world.level.Level.ExplosionInteraction.STANDARD; // Break blocks, don't decay drops + explosionType = net.minecraft.world.level.World.a.STANDARD; // Break blocks, don't decay drops } else { - explosionType = net.minecraft.world.level.Level.ExplosionInteraction.MOB; // Respect mobGriefing gamerule + explosionType = net.minecraft.world.level.World.a.MOB; // Respect mobGriefing gamerule } - return !this.world.explode(source == null ? null : ((CraftEntity) source).getHandle(), x, y, z, power, setFire, explosionType).wasCanceled; + net.minecraft.world.entity.Entity entity = (source == null) ? null : ((CraftEntity) source).getHandle(); + return !world.explode0(entity, Explosion.getDefaultDamageSource(world, entity), null, x, y, z, power, setFire, explosionType, Particles.EXPLOSION, Particles.EXPLOSION_EMITTER, SoundEffects.GENERIC_EXPLODE).wasCanceled; } @Override public boolean createExplosion(Location loc, float power) { - return this.createExplosion(loc, power, false); + return createExplosion(loc, power, false); } @Override public boolean createExplosion(Location loc, float power, boolean setFire) { - return this.createExplosion(loc, power, setFire, true); + return createExplosion(loc, power, setFire, true); } @Override public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks) { - return this.createExplosion(loc, power, setFire, breakBlocks, null); + return createExplosion(loc, power, setFire, breakBlocks, null); } @Override @@ -760,139 +767,139 @@ public boolean createExplosion(Location loc, float power, boolean setFire, boole Preconditions.checkArgument(loc != null, "Location is null"); Preconditions.checkArgument(this.equals(loc.getWorld()), "Location not in world"); - return this.createExplosion(loc.getX(), loc.getY(), loc.getZ(), power, setFire, breakBlocks, source); + return createExplosion(loc.getX(), loc.getY(), loc.getZ(), power, setFire, breakBlocks, source); } @Override public Environment getEnvironment() { - return this.environment; + return environment; } @Override public Block getBlockAt(Location location) { - return this.getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public Chunk getChunkAt(Location location) { - return this.getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4); + return getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4); } @Override public ChunkGenerator getGenerator() { - return this.generator; + return generator; } @Override public BiomeProvider getBiomeProvider() { - return this.biomeProvider; + return biomeProvider; } @Override public List getPopulators() { - return this.populators; + return populators; } @NotNull @Override public T spawn(@NotNull Location location, @NotNull Class clazz, @NotNull SpawnReason spawnReason, boolean randomizeData, @Nullable Consumer function) throws IllegalArgumentException { Preconditions.checkArgument(spawnReason != null, "Spawn reason cannot be null"); - return this.spawn(location, clazz, function, spawnReason, randomizeData); + return spawn(location, clazz, function, spawnReason, randomizeData); } @Override public Block getHighestBlockAt(int x, int z) { - return this.getBlockAt(x, this.getHighestBlockYAt(x, z), z); + return getBlockAt(x, getHighestBlockYAt(x, z), z); } @Override public Block getHighestBlockAt(Location location) { - return this.getHighestBlockAt(location.getBlockX(), location.getBlockZ()); + return getHighestBlockAt(location.getBlockX(), location.getBlockZ()); } @Override public int getHighestBlockYAt(int x, int z, org.bukkit.HeightMap heightMap) { // Transient load for this tick - return this.world.getChunk(x >> 4, z >> 4).getHeight(CraftHeightMap.toNMS(heightMap), x, z); + return world.getChunk(x >> 4, z >> 4).getHeight(CraftHeightMap.toNMS(heightMap), x, z); } @Override public Block getHighestBlockAt(int x, int z, org.bukkit.HeightMap heightMap) { - return this.getBlockAt(x, this.getHighestBlockYAt(x, z, heightMap), z); + return getBlockAt(x, getHighestBlockYAt(x, z, heightMap), z); } @Override public Block getHighestBlockAt(Location location, org.bukkit.HeightMap heightMap) { - return this.getHighestBlockAt(location.getBlockX(), location.getBlockZ(), heightMap); + return getHighestBlockAt(location.getBlockX(), location.getBlockZ(), heightMap); } @Override public Biome getBiome(int x, int z) { - return this.getBiome(x, 0, z); + return getBiome(x, 0, z); } @Override public void setBiome(int x, int z, Biome bio) { - for (int y = this.getMinHeight(); y < this.getMaxHeight(); y++) { - this.setBiome(x, y, z, bio); + for (int y = getMinHeight(); y < getMaxHeight(); y++) { + setBiome(x, y, z, bio); } } @Override - public void setBiome(int x, int y, int z, Holder bb) { + public void setBiome(int x, int y, int z, Holder bb) { BlockPos pos = new BlockPos(x, 0, z); if (this.world.hasChunkAt(pos)) { - net.minecraft.world.level.chunk.LevelChunk chunk = this.world.getChunkAt(pos); + net.minecraft.world.level.chunk.Chunk chunk = this.world.getChunkAt(pos); if (chunk != null) { chunk.setBiome(x >> 2, y >> 2, z >> 2, bb); - chunk.setUnsaved(true); // SPIGOT-2890 + chunk.markUnsaved(); // SPIGOT-2890 } } } @Override public double getTemperature(int x, int z) { - return this.getTemperature(x, 0, z); + return getTemperature(x, 0, z); } @Override public double getTemperature(int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); - return this.world.getNoiseBiome(x >> 2, y >> 2, z >> 2).value().getTemperature(pos); + return this.world.getNoiseBiome(x >> 2, y >> 2, z >> 2).value().getTemperature(pos, this.world.getSeaLevel()); } @Override public double getHumidity(int x, int z) { - return this.getHumidity(x, 0, z); + return getHumidity(x, 0, z); } @Override public double getHumidity(int x, int y, int z) { - return this.world.getNoiseBiome(x >> 2, y >> 2, z >> 2).value().i.downfall(); + return this.world.getNoiseBiome(x >> 2, y >> 2, z >> 2).value().climateSettings.downfall(); } @Override @SuppressWarnings("unchecked") @Deprecated public Collection getEntitiesByClass(Class... classes) { - return (Collection) this.getEntitiesByClasses(classes); + return (Collection) getEntitiesByClasses(classes); } @Override public Iterable getNMSEntities() { - return this.getHandle().getEntities().getAll(); + return getHandle().getEntities().getAll(); } @Override public void addEntityToWorld(net.minecraft.world.entity.Entity entity, SpawnReason reason) { - this.getHandle().addFreshEntity(entity, reason); + getHandle().addFreshEntity(entity, reason); } @Override public void addEntityWithPassengers(net.minecraft.world.entity.Entity entity, SpawnReason reason) { - this.getHandle().tryAddFreshEntityWithPassengers(entity, reason); + getHandle().tryAddFreshEntityWithPassengers(entity, reason); } @Override @@ -916,11 +923,10 @@ public Collection getNearbyEntities(BoundingBox boundingBox) { @Override public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) { - org.spigotmc.AsyncCatcher.catchOp("getNearbyEntities"); // Spigot Preconditions.checkArgument(boundingBox != null, "BoundingBox cannot be null"); - AABB bb = new AABB(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ()); - List entityList = this.getHandle().getEntities((net.minecraft.world.entity.Entity) null, bb, Predicates.alwaysTrue()); + AxisAlignedBB bb = new AxisAlignedBB(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ()); + List entityList = getHandle().getEntities((net.minecraft.world.entity.Entity) null, bb, Predicates.alwaysTrue()); List bukkitEntityList = new ArrayList(entityList.size()); for (net.minecraft.world.entity.Entity entity : entityList) { @@ -1017,9 +1023,9 @@ public RayTraceResult rayTraceBlocks(Location start, Vector direction, double ma } Vector dir = direction.clone().normalize().multiply(maxDistance); - Vec3 startPos = CraftLocation.toVec3D(start); - Vec3 endPos = startPos.add(dir.getX(), dir.getY(), dir.getZ()); - HitResult nmsHitResult = this.getHandle().clip(new ClipContext(startPos, endPos, ignorePassableBlocks ? ClipContext.Block.COLLIDER : ClipContext.Block.OUTLINE, CraftFluidCollisionMode.toNMS(fluidCollisionMode), CollisionContext.empty())); + Vec3D startPos = CraftLocation.toVec3D(start); + Vec3D endPos = startPos.add(dir.getX(), dir.getY(), dir.getZ()); + MovingObjectPosition nmsHitResult = this.getHandle().clip(new RayTrace(startPos, endPos, ignorePassableBlocks ? RayTrace.BlockCollisionOption.COLLIDER : RayTrace.BlockCollisionOption.OUTLINE, CraftFluidCollisionMode.toNMS(fluidCollisionMode), VoxelShapeCollision.empty())); return CraftRayTraceResult.fromNMS(this, nmsHitResult); } @@ -1056,9 +1062,9 @@ public RayTraceResult rayTrace(Location start, Vector direction, double maxDista @Override public List getPlayers() { - List list = new ArrayList(this.world.players().size()); + List list = new ArrayList(world.players().size()); - for (net.minecraft.world.entity.player.Player human : this.world.players()) { + for (EntityHuman human : world.players()) { HumanEntity bukkitEntity = human.getBukkitEntity(); if ((bukkitEntity != null) && (bukkitEntity instanceof Player)) { @@ -1071,29 +1077,28 @@ public List getPlayers() { @Override public void save() { - org.spigotmc.AsyncCatcher.catchOp("world save"); // Spigot this.server.checkSaveState(); - boolean oldSave = this.world.noSave; + boolean oldSave = world.noSave; - this.world.noSave = false; - this.world.save(null, false, false); + world.noSave = false; + world.save(null, false, false); - this.world.noSave = oldSave; + world.noSave = oldSave; } @Override public boolean isAutoSave() { - return !this.world.noSave; + return !world.noSave; } @Override public void setAutoSave(boolean value) { - this.world.noSave = !value; + world.noSave = !value; } @Override public void setDifficulty(Difficulty difficulty) { - this.getHandle().K.setDifficulty(net.minecraft.world.Difficulty.byId(difficulty.getValue())); + this.getHandle().serverLevelData.setDifficulty(EnumDifficulty.byId(difficulty.getValue())); } @Override @@ -1103,60 +1108,60 @@ public Difficulty getDifficulty() { @Override public int getViewDistance() { - return this.world.getChunkSource().chunkMap.serverViewDistance; + return world.getChunkSource().chunkMap.serverViewDistance; } @Override public int getSimulationDistance() { - return this.world.getChunkSource().chunkMap.getDistanceManager().simulationDistance; + return world.getChunkSource().chunkMap.getDistanceManager().simulationDistance; } public BlockMetadataStore getBlockMetadata() { - return this.blockMetadata; + return blockMetadata; } @Override public boolean hasStorm() { - return this.world.levelData.isRaining(); + return world.levelData.isRaining(); } @Override public void setStorm(boolean hasStorm) { - this.world.levelData.setRaining(hasStorm); - this.setWeatherDuration(0); // Reset weather duration (legacy behaviour) - this.setClearWeatherDuration(0); // Reset clear weather duration (reset "/weather clear" commands) + world.levelData.setRaining(hasStorm); + setWeatherDuration(0); // Reset weather duration (legacy behaviour) + setClearWeatherDuration(0); // Reset clear weather duration (reset "/weather clear" commands) } @Override public int getWeatherDuration() { - return this.world.serverLevelData.getRainTime(); + return world.serverLevelData.getRainTime(); } @Override public void setWeatherDuration(int duration) { - this.world.serverLevelData.setRainTime(duration); + world.serverLevelData.setRainTime(duration); } @Override public boolean isThundering() { - return this.world.levelData.isThundering(); + return world.levelData.isThundering(); } @Override public void setThundering(boolean thundering) { - this.world.serverLevelData.setThundering(thundering); - this.setThunderDuration(0); // Reset weather duration (legacy behaviour) - this.setClearWeatherDuration(0); // Reset clear weather duration (reset "/weather clear" commands) + world.serverLevelData.setThundering(thundering); + setThunderDuration(0); // Reset weather duration (legacy behaviour) + setClearWeatherDuration(0); // Reset clear weather duration (reset "/weather clear" commands) } @Override public int getThunderDuration() { - return this.world.serverLevelData.getThunderTime(); + return world.serverLevelData.getThunderTime(); } @Override public void setThunderDuration(int duration) { - this.world.serverLevelData.setThunderTime(duration); + world.serverLevelData.setThunderTime(duration); } @Override @@ -1166,41 +1171,41 @@ public boolean isClearWeather() { @Override public void setClearWeatherDuration(int duration) { - this.world.serverLevelData.setClearWeatherTime(duration); + world.serverLevelData.setClearWeatherTime(duration); } @Override public int getClearWeatherDuration() { - return this.world.serverLevelData.getClearWeatherTime(); + return world.serverLevelData.getClearWeatherTime(); } @Override public long getSeed() { - return this.world.getSeed(); + return world.getSeed(); } @Override public boolean getPVP() { - return this.world.pvpMode; + return world.pvpMode; } @Override public void setPVP(boolean pvp) { - this.world.pvpMode = pvp; + world.pvpMode = pvp; } public void playEffect(Player player, Effect effect, int data) { - this.playEffect(player.getLocation(), effect, data, 0); + playEffect(player.getLocation(), effect, data, 0); } @Override public void playEffect(Location location, Effect effect, int data) { - this.playEffect(location, effect, data, 64); + playEffect(location, effect, data, 64); } @Override public void playEffect(Location loc, Effect effect, T data) { - this.playEffect(loc, effect, data, 64); + playEffect(loc, effect, data, 64); } @Override @@ -1214,7 +1219,7 @@ public void playEffect(Location loc, Effect effect, T data, int radius) { } int datavalue = CraftEffect.getDataValue(effect, data); - this.playEffect(loc, effect, datavalue, radius); + playEffect(loc, effect, datavalue, radius); } @Override @@ -1223,11 +1228,11 @@ public void playEffect(Location location, Effect effect, int data, int radius) { Preconditions.checkArgument(location != null, "Location cannot be null"); Preconditions.checkArgument(location.getWorld() != null, "World of Location cannot be null"); int packetData = effect.getId(); - ClientboundLevelEventPacket packet = new ClientboundLevelEventPacket(packetData, CraftLocation.toBlockPosition(location), data, false); + PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, CraftLocation.toBlockPos(location), data, false); int distance; radius *= radius; - for (Player player : this.getPlayers()) { + for (Player player : getPlayers()) { if (((CraftPlayer) player).getHandle().connection == null) continue; if (!location.getWorld().equals(player.getWorld())) continue; @@ -1241,7 +1246,7 @@ public void playEffect(Location location, Effect effect, int data, int radius) { @Override public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException { Preconditions.checkArgument(data != null, "MaterialData cannot be null"); - return this.spawnFallingBlock(location, data.getItemType(), data.getData()); + return spawnFallingBlock(location, data.getItemType(), data.getData()); } @Override @@ -1250,7 +1255,7 @@ public FallingBlock spawnFallingBlock(Location location, org.bukkit.Material mat Preconditions.checkArgument(material != null, "Material cannot be null"); Preconditions.checkArgument(material.isBlock(), "Material.%s must be a block", material); - FallingBlockEntity entity = FallingBlockEntity.fall(this.world, BlockPos.containing(location.getX(), location.getY(), location.getZ()), CraftBlockType.bukkitToMinecraft(material).defaultBlockState(), SpawnReason.CUSTOM); + EntityFallingBlock entity = EntityFallingBlock.fall(world, BlockPos.containing(location.getX(), location.getY(), location.getZ()), CraftBlockType.bukkitToMinecraft(material).defaultBlockState(), SpawnReason.CUSTOM); return (FallingBlock) entity.getBukkitEntity(); } @@ -1259,7 +1264,7 @@ public FallingBlock spawnFallingBlock(Location location, BlockData data) throws Preconditions.checkArgument(location != null, "Location cannot be null"); Preconditions.checkArgument(data != null, "BlockData cannot be null"); - FallingBlockEntity entity = FallingBlockEntity.fall(this.world, BlockPos.containing(location.getX(), location.getY(), location.getZ()), ((CraftBlockData) data).getState(), SpawnReason.CUSTOM); + EntityFallingBlock entity = EntityFallingBlock.fall(world, BlockPos.containing(location.getX(), location.getY(), location.getZ()), ((CraftBlockData) data).getState(), SpawnReason.CUSTOM); return (FallingBlock) entity.getBukkitEntity(); } @@ -1270,96 +1275,96 @@ public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, b @Override public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) { - this.world.setSpawnSettings(allowMonsters, allowAnimals); + world.getChunkSource().setSpawnSettings(allowMonsters, allowAnimals); } @Override public boolean getAllowAnimals() { - return this.world.getChunkSource().spawnFriendlies; + return world.getChunkSource().spawnFriendlies; } @Override public boolean getAllowMonsters() { - return this.world.getChunkSource().spawnEnemies; + return world.getChunkSource().spawnEnemies; } @Override public int getMinHeight() { - return this.world.getMinBuildHeight(); + return world.getMinY(); } @Override public int getMaxHeight() { - return this.world.getMaxBuildHeight(); + return world.getMaxY(); } @Override public int getLogicalHeight() { - return this.world.dimensionType().logicalHeight(); + return world.dimensionType().logicalHeight(); } @Override public boolean isNatural() { - return this.world.dimensionType().natural(); + return world.dimensionType().natural(); } @Override public boolean isBedWorks() { - return this.world.dimensionType().bedWorks(); + return world.dimensionType().bedWorks(); } @Override public boolean hasSkyLight() { - return this.world.dimensionType().hasSkyLight(); + return world.dimensionType().hasSkyLight(); } @Override public boolean hasCeiling() { - return this.world.dimensionType().hasCeiling(); + return world.dimensionType().hasCeiling(); } @Override public boolean isPiglinSafe() { - return this.world.dimensionType().piglinSafe(); + return world.dimensionType().piglinSafe(); } @Override public boolean isRespawnAnchorWorks() { - return this.world.dimensionType().respawnAnchorWorks(); + return world.dimensionType().respawnAnchorWorks(); } @Override public boolean hasRaids() { - return this.world.dimensionType().hasRaids(); + return world.dimensionType().hasRaids(); } @Override public boolean isUltraWarm() { - return this.world.dimensionType().ultraWarm(); + return world.dimensionType().ultraWarm(); } @Override public int getSeaLevel() { - return this.world.getSeaLevel(); + return world.getSeaLevel(); } @Override public boolean getKeepSpawnInMemory() { - return this.getGameRuleValue(GameRule.SPAWN_RADIUS) > 0; + return getGameRuleValue(GameRule.SPAWN_CHUNK_RADIUS) > 0; } @Override public void setKeepSpawnInMemory(boolean keepLoaded) { if (keepLoaded) { - this.setGameRule(GameRule.SPAWN_CHUNK_RADIUS, this.getGameRuleDefault(GameRule.SPAWN_CHUNK_RADIUS)); + setGameRule(GameRule.SPAWN_CHUNK_RADIUS, getGameRuleDefault(GameRule.SPAWN_CHUNK_RADIUS)); } else { - this.setGameRule(GameRule.SPAWN_CHUNK_RADIUS, 0); + setGameRule(GameRule.SPAWN_CHUNK_RADIUS, 0); } } @Override public int hashCode() { - return this.getUID().hashCode(); + return getUID().hashCode(); } @Override @@ -1367,7 +1372,7 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (this.getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } @@ -1378,14 +1383,14 @@ public boolean equals(Object obj) { @Override public File getWorldFolder() { - return this.world.convertable.getLevelPath(LevelResource.ROOT).toFile().getParentFile(); + return world.convertable.getLevelPath(SavedFile.ROOT).toFile().getParentFile(); } @Override public void sendPluginMessage(Plugin source, String channel, byte[] message) { - StandardMessenger.validatePluginMessage(this.server.getMessenger(), source, channel, message); + StandardMessenger.validatePluginMessage(server.getMessenger(), source, channel, message); - for (Player player : this.getPlayers()) { + for (Player player : getPlayers()) { player.sendPluginMessage(source, channel, message); } } @@ -1394,7 +1399,7 @@ public void sendPluginMessage(Plugin source, String channel, byte[] message) { public Set getListeningPluginChannels() { Set result = new HashSet(); - for (Player player : this.getPlayers()) { + for (Player player : getPlayers()) { result.addAll(player.getListeningPluginChannels()); } @@ -1403,94 +1408,94 @@ public Set getListeningPluginChannels() { @Override public org.bukkit.WorldType getWorldType() { - return this.world.isFlat() ? org.bukkit.WorldType.FLAT : org.bukkit.WorldType.NORMAL; + return world.isFlat() ? org.bukkit.WorldType.FLAT : org.bukkit.WorldType.NORMAL; } @Override public boolean canGenerateStructures() { - return this.world.K.worldGenOptions().generateStructures(); + return world.serverLevelData.worldGenOptions().generateStructures(); } @Override public boolean isHardcore() { - return this.world.getLevelData().isHardcore(); + return world.getLevelData().isHardcore(); } @Override public void setHardcore(boolean hardcore) { - this.world.K.settings.hardcore = hardcore; + world.serverLevelData.settings.hardcore = hardcore; } @Override @Deprecated public long getTicksPerAnimalSpawns() { - return this.getTicksPerSpawns(SpawnCategory.ANIMAL); + return getTicksPerSpawns(SpawnCategory.ANIMAL); } @Override @Deprecated public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) { - this.setTicksPerSpawns(SpawnCategory.ANIMAL, ticksPerAnimalSpawns); + setTicksPerSpawns(SpawnCategory.ANIMAL, ticksPerAnimalSpawns); } @Override @Deprecated public long getTicksPerMonsterSpawns() { - return this.getTicksPerSpawns(SpawnCategory.MONSTER); + return getTicksPerSpawns(SpawnCategory.MONSTER); } @Override @Deprecated public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) { - this.setTicksPerSpawns(SpawnCategory.MONSTER, ticksPerMonsterSpawns); + setTicksPerSpawns(SpawnCategory.MONSTER, ticksPerMonsterSpawns); } @Override @Deprecated public long getTicksPerWaterSpawns() { - return this.getTicksPerSpawns(SpawnCategory.WATER_ANIMAL); + return getTicksPerSpawns(SpawnCategory.WATER_ANIMAL); } @Override @Deprecated public void setTicksPerWaterSpawns(int ticksPerWaterSpawns) { - this.setTicksPerSpawns(SpawnCategory.WATER_ANIMAL, ticksPerWaterSpawns); + setTicksPerSpawns(SpawnCategory.WATER_ANIMAL, ticksPerWaterSpawns); } @Override @Deprecated public long getTicksPerWaterAmbientSpawns() { - return this.getTicksPerSpawns(SpawnCategory.WATER_AMBIENT); + return getTicksPerSpawns(SpawnCategory.WATER_AMBIENT); } @Override @Deprecated public void setTicksPerWaterAmbientSpawns(int ticksPerWaterAmbientSpawns) { - this.setTicksPerSpawns(SpawnCategory.WATER_AMBIENT, ticksPerWaterAmbientSpawns); + setTicksPerSpawns(SpawnCategory.WATER_AMBIENT, ticksPerWaterAmbientSpawns); } @Override @Deprecated public long getTicksPerWaterUndergroundCreatureSpawns() { - return this.getTicksPerSpawns(SpawnCategory.WATER_UNDERGROUND_CREATURE); + return getTicksPerSpawns(SpawnCategory.WATER_UNDERGROUND_CREATURE); } @Override @Deprecated public void setTicksPerWaterUndergroundCreatureSpawns(int ticksPerWaterUndergroundCreatureSpawns) { - this.setTicksPerSpawns(SpawnCategory.WATER_UNDERGROUND_CREATURE, ticksPerWaterUndergroundCreatureSpawns); + setTicksPerSpawns(SpawnCategory.WATER_UNDERGROUND_CREATURE, ticksPerWaterUndergroundCreatureSpawns); } @Override @Deprecated public long getTicksPerAmbientSpawns() { - return this.getTicksPerSpawns(SpawnCategory.AMBIENT); + return getTicksPerSpawns(SpawnCategory.AMBIENT); } @Override @Deprecated public void setTicksPerAmbientSpawns(int ticksPerAmbientSpawns) { - this.setTicksPerSpawns(SpawnCategory.AMBIENT, ticksPerAmbientSpawns); + setTicksPerSpawns(SpawnCategory.AMBIENT, ticksPerAmbientSpawns); } @Override @@ -1498,7 +1503,7 @@ public void setTicksPerSpawns(SpawnCategory spawnCategory, int ticksPerCategoryS Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); - this.world.ticksPerSpawnCategory.put(spawnCategory, (long) ticksPerCategorySpawn); + world.ticksPerSpawnCategory.put(spawnCategory, (long) ticksPerCategorySpawn); } @Override @@ -1506,99 +1511,99 @@ public long getTicksPerSpawns(SpawnCategory spawnCategory) { Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); - return this.world.ticksPerSpawnCategory.getLong(spawnCategory); + return world.ticksPerSpawnCategory.getLong(spawnCategory); } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - this.server.getWorldMetadata().setMetadata(this, metadataKey, newMetadataValue); + server.getWorldMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List getMetadata(String metadataKey) { - return this.server.getWorldMetadata().getMetadata(this, metadataKey); + return server.getWorldMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { - return this.server.getWorldMetadata().hasMetadata(this, metadataKey); + return server.getWorldMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { - this.server.getWorldMetadata().removeMetadata(this, metadataKey, owningPlugin); + server.getWorldMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override @Deprecated public int getMonsterSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.MONSTER); + return getSpawnLimit(SpawnCategory.MONSTER); } @Override @Deprecated public void setMonsterSpawnLimit(int limit) { - this.setSpawnLimit(SpawnCategory.MONSTER, limit); + setSpawnLimit(SpawnCategory.MONSTER, limit); } @Override @Deprecated public int getAnimalSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.ANIMAL); + return getSpawnLimit(SpawnCategory.ANIMAL); } @Override @Deprecated public void setAnimalSpawnLimit(int limit) { - this.setSpawnLimit(SpawnCategory.ANIMAL, limit); + setSpawnLimit(SpawnCategory.ANIMAL, limit); } @Override @Deprecated public int getWaterAnimalSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.WATER_ANIMAL); + return getSpawnLimit(SpawnCategory.WATER_ANIMAL); } @Override @Deprecated public void setWaterAnimalSpawnLimit(int limit) { - this.setSpawnLimit(SpawnCategory.WATER_ANIMAL, limit); + setSpawnLimit(SpawnCategory.WATER_ANIMAL, limit); } @Override @Deprecated public int getWaterAmbientSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.WATER_AMBIENT); + return getSpawnLimit(SpawnCategory.WATER_AMBIENT); } @Override @Deprecated public void setWaterAmbientSpawnLimit(int limit) { - this.setSpawnLimit(SpawnCategory.WATER_AMBIENT, limit); + setSpawnLimit(SpawnCategory.WATER_AMBIENT, limit); } @Override @Deprecated public int getWaterUndergroundCreatureSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.WATER_UNDERGROUND_CREATURE); + return getSpawnLimit(SpawnCategory.WATER_UNDERGROUND_CREATURE); } @Override @Deprecated public void setWaterUndergroundCreatureSpawnLimit(int limit) { - this.setSpawnLimit(SpawnCategory.WATER_UNDERGROUND_CREATURE, limit); + setSpawnLimit(SpawnCategory.WATER_UNDERGROUND_CREATURE, limit); } @Override @Deprecated public int getAmbientSpawnLimit() { - return this.getSpawnLimit(SpawnCategory.AMBIENT); + return getSpawnLimit(SpawnCategory.AMBIENT); } @Override @Deprecated public void setAmbientSpawnLimit(int limit) { - this.setSpawnLimit(SpawnCategory.AMBIENT, limit); + setSpawnLimit(SpawnCategory.AMBIENT, limit); } @Override @@ -1606,9 +1611,9 @@ public int getSpawnLimit(SpawnCategory spawnCategory) { Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); - int limit = this.spawnCategoryLimit.getOrDefault(spawnCategory, -1); + int limit = spawnCategoryLimit.getOrDefault(spawnCategory, -1); if (limit < 0) { - limit = this.server.getSpawnLimit(spawnCategory); + limit = server.getSpawnLimit(spawnCategory); } return limit; } @@ -1618,32 +1623,32 @@ public void setSpawnLimit(SpawnCategory spawnCategory, int limit) { Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); - this.spawnCategoryLimit.put(spawnCategory, limit); + spawnCategoryLimit.put(spawnCategory, limit); } @Override public void playNote(@NotNull Location loc, @NotNull Instrument instrument, @NotNull Note note) { - this.playSound(loc, instrument.getSound(), org.bukkit.SoundCategory.RECORDS, 3f, note.getPitch()); + playSound(loc, instrument.getSound(), org.bukkit.SoundCategory.RECORDS, 3f, note.getPitch()); } @Override public void playSound(Location loc, Sound sound, float volume, float pitch) { - this.playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(Location loc, String sound, float volume, float pitch) { - this.playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(loc, sound, category, volume, pitch, this.getHandle().random.nextLong());; + playSound(loc, sound, category, volume, pitch, getHandle().random.nextLong());; } @Override public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(loc, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(loc, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override @@ -1654,7 +1659,7 @@ public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory catego double y = loc.getY(); double z = loc.getZ(); - this.getHandle().playSeededSound(null, x, y, z, CraftSound.bukkitToMinecraft(sound), SoundSource.valueOf(category.name()), volume, pitch, seed); + getHandle().playSeededSound(null, x, y, z, CraftSound.bukkitToMinecraft(sound), SoundCategory.valueOf(category.name()), volume, pitch, seed); } @Override @@ -1665,36 +1670,36 @@ public void playSound(Location loc, String sound, org.bukkit.SoundCategory categ double y = loc.getY(); double z = loc.getZ(); - ClientboundSoundPacket packet = new ClientboundSoundPacket(Holder.direct(SoundEvent.createVariableRangeEvent(ResourceLocation.parse(sound))), SoundSource.valueOf(category.name()), x, y, z, volume, pitch, seed); - this.world.getServer().getPlayerList().broadcast(null, x, y, z, volume > 1.0F ? 16.0F * volume : 16.0D, this.world.dimension(), packet); + PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(Holder.direct(SoundEffect.createVariableRangeEvent(MinecraftKey.parse(sound))), SoundCategory.valueOf(category.name()), x, y, z, volume, pitch, seed); + world.getServer().getPlayerList().broadcast(null, x, y, z, volume > 1.0F ? 16.0F * volume : 16.0D, this.world.dimension(), packet); } @Override public void playSound(Entity entity, Sound sound, float volume, float pitch) { - this.playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(Entity entity, String sound, float volume, float pitch) { - this.playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(Entity entity, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(entity, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(entity, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override public void playSound(Entity entity, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(entity, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(entity, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override public void playSound(Entity entity, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch, long seed) { if (!(entity instanceof CraftEntity craftEntity) || entity.getWorld() != this || sound == null || category == null) return; - ClientboundSoundEntityPacket packet = new ClientboundSoundEntityPacket(CraftSound.bukkitToMinecraftHolder(sound), net.minecraft.sounds.SoundSource.valueOf(category.name()), craftEntity.getHandle(), volume, pitch, seed); - ChunkMap.TrackedEntity entityTracker = this.getHandle().getChunkSource().chunkMap.entityMap.get(entity.getEntityId()); + PacketPlayOutEntitySound packet = new PacketPlayOutEntitySound(CraftSound.bukkitToMinecraftHolder(sound), net.minecraft.sounds.SoundCategory.valueOf(category.name()), craftEntity.getHandle(), volume, pitch, seed); + PlayerChunkMap.EntityTracker entityTracker = getHandle().getChunkSource().chunkMap.entityMap.get(entity.getEntityId()); if (entityTracker != null) { entityTracker.broadcastAndSend(packet); } @@ -1704,45 +1709,48 @@ public void playSound(Entity entity, Sound sound, org.bukkit.SoundCategory categ public void playSound(Entity entity, String sound, org.bukkit.SoundCategory category, float volume, float pitch, long seed) { if (!(entity instanceof CraftEntity craftEntity) || entity.getWorld() != this || sound == null || category == null) return; - ClientboundSoundEntityPacket packet = new ClientboundSoundEntityPacket(Holder.direct(SoundEvent.createVariableRangeEvent(ResourceLocation.parse(sound))), net.minecraft.sounds.SoundSource.valueOf(category.name()), craftEntity.getHandle(), volume, pitch, seed); - ChunkMap.TrackedEntity entityTracker = this.getHandle().getChunkSource().chunkMap.entityMap.get(entity.getEntityId()); + PacketPlayOutEntitySound packet = new PacketPlayOutEntitySound(Holder.direct(SoundEffect.createVariableRangeEvent(MinecraftKey.parse(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), craftEntity.getHandle(), volume, pitch, seed); + PlayerChunkMap.EntityTracker entityTracker = getHandle().getChunkSource().chunkMap.entityMap.get(entity.getEntityId()); if (entityTracker != null) { entityTracker.broadcastAndSend(packet); } } - private static Map> gamerules; - public static synchronized Map> getGameRulesNMS() { - if (CraftWorld.gamerules != null) { - return CraftWorld.gamerules; + private Map> gamerules; + public synchronized Map> getGameRulesNMS() { + if (gamerules != null) { + return gamerules; } - Map> gamerules = new HashMap<>(); - GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { + return this.gamerules = getGameRulesNMS(getHandle().getGameRules()); + } + + public static Map> getGameRulesNMS(GameRules gameRules) { + Map> gamerules = new HashMap<>(); + gameRules.visitGameRuleTypes(new GameRules.GameRuleVisitor() { @Override - public > void visit(GameRules.Key key, GameRules.Type type) { - gamerules.put(key.getId(), key); + public > void visit(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { + gamerules.put(gamerules_gamerulekey.getId(), gamerules_gamerulekey); } }); - - return CraftWorld.gamerules = gamerules; + return gamerules; } - private static Map> gameruleDefinitions; - public static synchronized Map> getGameRuleDefinitions() { - if (CraftWorld.gameruleDefinitions != null) { - return CraftWorld.gameruleDefinitions; + private Map> gameruleDefinitions; + public synchronized Map> getGameRuleDefinitions() { + if (gameruleDefinitions != null) { + return gameruleDefinitions; } - Map> gameruleDefinitions = new HashMap<>(); - GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { + Map> gameruleDefinitions = new HashMap<>(); + getHandle().getGameRules().visitGameRuleTypes(new GameRules.GameRuleVisitor() { @Override - public > void visit(GameRules.Key key, GameRules.Type type) { - gameruleDefinitions.put(key.getId(), type); + public > void visit(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { + gameruleDefinitions.put(gamerules_gamerulekey.getId(), gamerules_gameruledefinition); } }); - return CraftWorld.gameruleDefinitions = gameruleDefinitions; + return this.gameruleDefinitions = gameruleDefinitions; } @Override @@ -1752,7 +1760,7 @@ public String getGameRuleValue(String rule) { return null; } - GameRules.Value value = this.getHandle().getGameRules().getRule(CraftWorld.getGameRulesNMS().get(rule)); + GameRules.GameRuleValue value = getHandle().getGameRules().getRule(getGameRulesNMS().get(rule)); return value != null ? value.toString() : ""; } @@ -1761,36 +1769,36 @@ public boolean setGameRuleValue(String rule, String value) { // No null values allowed if (rule == null || value == null) return false; - if (!this.isGameRule(rule)) return false; + if (!isGameRule(rule)) return false; - GameRules.Value handle = this.getHandle().getGameRules().getRule(CraftWorld.getGameRulesNMS().get(rule)); + GameRules.GameRuleValue handle = getHandle().getGameRules().getRule(getGameRulesNMS().get(rule)); handle.deserialize(value); - handle.onChanged(this.getHandle()); + handle.onChanged(getHandle()); return true; } @Override public String[] getGameRules() { - return CraftWorld.getGameRulesNMS().keySet().toArray(new String[CraftWorld.getGameRulesNMS().size()]); + return getGameRulesNMS().keySet().toArray(new String[getGameRulesNMS().size()]); } @Override public boolean isGameRule(String rule) { Preconditions.checkArgument(rule != null, "String rule cannot be null"); Preconditions.checkArgument(!rule.isEmpty(), "String rule cannot be empty"); - return CraftWorld.getGameRulesNMS().containsKey(rule); + return getGameRulesNMS().containsKey(rule); } @Override public T getGameRuleValue(GameRule rule) { Preconditions.checkArgument(rule != null, "GameRule cannot be null"); - return this.convert(rule, this.getHandle().getGameRules().getRule(CraftWorld.getGameRulesNMS().get(rule.getName()))); + return convert(rule, getHandle().getGameRules().getRule(getGameRulesNMS().get(rule.getName()))); } @Override public T getGameRuleDefault(GameRule rule) { Preconditions.checkArgument(rule != null, "GameRule cannot be null"); - return this.convert(rule, CraftWorld.getGameRuleDefinitions().get(rule.getName()).createRule()); + return convert(rule, getGameRuleDefinitions().get(rule.getName()).createRule()); } @Override @@ -1798,22 +1806,22 @@ public boolean setGameRule(GameRule rule, T newValue) { Preconditions.checkArgument(rule != null, "GameRule cannot be null"); Preconditions.checkArgument(newValue != null, "GameRule value cannot be null"); - if (!this.isGameRule(rule.getName())) return false; + if (!isGameRule(rule.getName())) return false; - GameRules.Value handle = this.getHandle().getGameRules().getRule(CraftWorld.getGameRulesNMS().get(rule.getName())); + GameRules.GameRuleValue handle = getHandle().getGameRules().getRule(getGameRulesNMS().get(rule.getName())); handle.deserialize(newValue.toString()); - handle.onChanged(this.getHandle()); + handle.onChanged(getHandle()); return true; } - private T convert(GameRule rule, GameRules.Value value) { + private T convert(GameRule rule, GameRules.GameRuleValue value) { if (value == null) { return null; } - if (value instanceof GameRules.BooleanValue) { - return rule.getType().cast(((GameRules.BooleanValue) value).get()); - } else if (value instanceof GameRules.IntegerValue) { + if (value instanceof GameRules.GameRuleBoolean) { + return rule.getType().cast(((GameRules.GameRuleBoolean) value).get()); + } else if (value instanceof GameRules.GameRuleInt) { return rule.getType().cast(value.getCommandResult()); } else { throw new IllegalArgumentException("Invalid GameRule type (" + value + ") for GameRule " + rule.getName()); @@ -1831,72 +1839,72 @@ public WorldBorder getWorldBorder() { @Override public void spawnParticle(Particle particle, Location location, int count) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count) { - this.spawnParticle(particle, x, y, z, count, null); + spawnParticle(particle, x, y, z, count, null); } @Override public void spawnParticle(Particle particle, Location location, int count, T data) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, data); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, data); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { - this.spawnParticle(particle, x, y, z, count, 0, 0, 0, data); + spawnParticle(particle, x, y, z, count, 0, 0, 0, data); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, null); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, null); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, 1, data); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, 1, data); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data, false); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data, false); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data, force); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data, force); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - this.getHandle().sendParticles( + getHandle().sendParticles( null, // Sender CraftParticle.createParticleParam(particle, data), // Particle x, y, z, // Position @@ -1905,6 +1913,7 @@ public void spawnParticle(Particle particle, double x, double y, double z, i extra, // Speed? force ); + } @Deprecated @@ -1914,41 +1923,41 @@ public Location locateNearestStructure(Location origin, org.bukkit.StructureType // Manually map the mess of the old StructureType to the new StructureType and normal Structure if (org.bukkit.StructureType.MINESHAFT == structureType) { - result = this.locateNearestStructure(origin, StructureType.MINESHAFT, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.MINESHAFT, radius, findUnexplored); } else if (org.bukkit.StructureType.VILLAGE == structureType) { - result = this.locateNearestStructure(origin, List.of(Structure.VILLAGE_DESERT, Structure.VILLAGE_PLAINS, Structure.VILLAGE_SAVANNA, Structure.VILLAGE_SNOWY, Structure.VILLAGE_TAIGA), radius, findUnexplored); + result = locateNearestStructure(origin, List.of(Structure.VILLAGE_DESERT, Structure.VILLAGE_PLAINS, Structure.VILLAGE_SAVANNA, Structure.VILLAGE_SNOWY, Structure.VILLAGE_TAIGA), radius, findUnexplored); } else if (org.bukkit.StructureType.NETHER_FORTRESS == structureType) { - result = this.locateNearestStructure(origin, StructureType.FORTRESS, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.FORTRESS, radius, findUnexplored); } else if (org.bukkit.StructureType.STRONGHOLD == structureType) { - result = this.locateNearestStructure(origin, StructureType.STRONGHOLD, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.STRONGHOLD, radius, findUnexplored); } else if (org.bukkit.StructureType.JUNGLE_PYRAMID == structureType) { - result = this.locateNearestStructure(origin, StructureType.JUNGLE_TEMPLE, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.JUNGLE_TEMPLE, radius, findUnexplored); } else if (org.bukkit.StructureType.OCEAN_RUIN == structureType) { - result = this.locateNearestStructure(origin, StructureType.OCEAN_RUIN, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.OCEAN_RUIN, radius, findUnexplored); } else if (org.bukkit.StructureType.DESERT_PYRAMID == structureType) { - result = this.locateNearestStructure(origin, StructureType.DESERT_PYRAMID, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.DESERT_PYRAMID, radius, findUnexplored); } else if (org.bukkit.StructureType.IGLOO == structureType) { - result = this.locateNearestStructure(origin, StructureType.IGLOO, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.IGLOO, radius, findUnexplored); } else if (org.bukkit.StructureType.SWAMP_HUT == structureType) { - result = this.locateNearestStructure(origin, StructureType.SWAMP_HUT, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.SWAMP_HUT, radius, findUnexplored); } else if (org.bukkit.StructureType.OCEAN_MONUMENT == structureType) { - result = this.locateNearestStructure(origin, StructureType.OCEAN_MONUMENT, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.OCEAN_MONUMENT, radius, findUnexplored); } else if (org.bukkit.StructureType.END_CITY == structureType) { - result = this.locateNearestStructure(origin, StructureType.END_CITY, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.END_CITY, radius, findUnexplored); } else if (org.bukkit.StructureType.WOODLAND_MANSION == structureType) { - result = this.locateNearestStructure(origin, StructureType.WOODLAND_MANSION, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.WOODLAND_MANSION, radius, findUnexplored); } else if (org.bukkit.StructureType.BURIED_TREASURE == structureType) { - result = this.locateNearestStructure(origin, StructureType.BURIED_TREASURE, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.BURIED_TREASURE, radius, findUnexplored); } else if (org.bukkit.StructureType.SHIPWRECK == structureType) { - result = this.locateNearestStructure(origin, StructureType.SHIPWRECK, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.SHIPWRECK, radius, findUnexplored); } else if (org.bukkit.StructureType.PILLAGER_OUTPOST == structureType) { - result = this.locateNearestStructure(origin, Structure.PILLAGER_OUTPOST, radius, findUnexplored); + result = locateNearestStructure(origin, Structure.PILLAGER_OUTPOST, radius, findUnexplored); } else if (org.bukkit.StructureType.NETHER_FOSSIL == structureType) { - result = this.locateNearestStructure(origin, StructureType.NETHER_FOSSIL, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.NETHER_FOSSIL, radius, findUnexplored); } else if (org.bukkit.StructureType.RUINED_PORTAL == structureType) { - result = this.locateNearestStructure(origin, StructureType.RUINED_PORTAL, radius, findUnexplored); + result = locateNearestStructure(origin, StructureType.RUINED_PORTAL, radius, findUnexplored); } else if (org.bukkit.StructureType.BASTION_REMNANT == structureType) { - result = this.locateNearestStructure(origin, Structure.BASTION_REMNANT, radius, findUnexplored); + result = locateNearestStructure(origin, Structure.BASTION_REMNANT, radius, findUnexplored); } return (result == null) ? null : result.getLocation(); @@ -1963,12 +1972,12 @@ public StructureSearchResult locateNearestStructure(Location origin, StructureTy } } - return this.locateNearestStructure(origin, structures, radius, findUnexplored); + return locateNearestStructure(origin, structures, radius, findUnexplored); } @Override public StructureSearchResult locateNearestStructure(Location origin, Structure structure, int radius, boolean findUnexplored) { - return this.locateNearestStructure(origin, List.of(structure), radius, findUnexplored); + return locateNearestStructure(origin, List.of(structure), radius, findUnexplored); } public StructureSearchResult locateNearestStructure(Location origin, List structures, int radius, boolean findUnexplored) { @@ -1979,7 +1988,7 @@ public StructureSearchResult locateNearestStructure(Location origin, List> found = this.getHandle().getChunkSource().getGenerator().findNearestMapStructure(this.getHandle(), HolderSet.direct(holders), originPos, radius, findUnexplored); + Pair> found = getHandle().getChunkSource().getGenerator().findNearestMapStructure(getHandle(), HolderSet.direct(holders), originPos, radius, findUnexplored); if (found == null) { return null; } @@ -1989,21 +1998,21 @@ public StructureSearchResult locateNearestStructure(Location origin, List> holders = new HashSet<>(); + Set> holders = new HashSet<>(); for (Biome biome : biomes) { holders.add(CraftBiome.bukkitToMinecraftHolder(biome)); } - Climate.Sampler sampler = this.getHandle().getChunkSource().randomState().sampler(); + Climate.Sampler sampler = getHandle().getChunkSource().randomState().sampler(); // The given predicate is evaluated once at the start of the search, so performance isn't a large concern. - Pair> found = this.getHandle().getChunkSource().getGenerator().getBiomeSource().findClosestBiome3d(originPos, radius, horizontalInterval, verticalInterval, holders::contains, sampler, this.getHandle()); + Pair> found = getHandle().getChunkSource().getGenerator().getBiomeSource().findClosestBiome3d(originPos, radius, horizontalInterval, verticalInterval, holders::contains, sampler, getHandle()); if (found == null) { return null; } @@ -2016,40 +2025,40 @@ public Raid locateNearestRaid(Location location, int radius) { Preconditions.checkArgument(location != null, "Location cannot be null"); Preconditions.checkArgument(radius >= 0, "Radius value (%s) cannot be negative", radius); - Raids persistentRaid = this.world.getRaids(); - net.minecraft.world.entity.raid.Raid raid = persistentRaid.getNearbyRaid(CraftLocation.toBlockPosition(location), radius * radius); + PersistentRaid persistentRaid = world.getRaids(); + net.minecraft.world.entity.raid.Raid raid = persistentRaid.getNearbyRaid(CraftLocation.toBlockPos(location), radius * radius); return (raid == null) ? null : new CraftRaid(raid); } @Override public List getRaids() { - Raids persistentRaid = this.world.getRaids(); + PersistentRaid persistentRaid = world.getRaids(); return persistentRaid.raidMap.values().stream().map(CraftRaid::new).collect(Collectors.toList()); } @Override public DragonBattle getEnderDragonBattle() { - return (this.getHandle().getDragonFight() == null) ? null : new CraftDragonBattle(this.getHandle().getDragonFight()); + return (getHandle().getDragonFight() == null) ? null : new CraftDragonBattle(getHandle().getDragonFight()); } @Override public Collection getStructures(int x, int z) { - return this.getStructures(x, z, struct -> true); + return getStructures(x, z, struct -> true); } @Override public Collection getStructures(int x, int z, Structure structure) { Preconditions.checkArgument(structure != null, "Structure cannot be null"); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.STRUCTURE); - ResourceLocation key = registry.getKey(CraftStructure.bukkitToMinecraft(structure)); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.STRUCTURE); + MinecraftKey key = registry.getKey(CraftStructure.bukkitToMinecraft(structure)); - return this.getStructures(x, z, struct -> registry.getKey(struct).equals(key)); + return getStructures(x, z, struct -> registry.getKey(struct).equals(key)); } private List getStructures(int x, int z, Predicate predicate) { List structures = new ArrayList<>(); - for (StructureStart start : this.getHandle().structureManager().startsForStructure(new ChunkPos(x, z), predicate)) { + for (StructureStart start : getHandle().structureManager().startsForStructure(new ChunkCoordIntPair(x, z), predicate)) { structures.add(new CraftGeneratedStructure(start)); } @@ -2058,7 +2067,7 @@ private List getStructures(int x, int z, Predicate getFeatureFlags() { return CraftFeatureFlag.getFromNMS(this.getHandle().enabledFeatures()).stream().map(FeatureFlag.class::cast).collect(Collectors.toUnmodifiableSet()); } - public void storeBukkitValues(CompoundTag c) { + public void storeBukkitValues(NBTTagCompound c) { if (!this.persistentDataContainer.isEmpty()) { c.put("BukkitValues", this.persistentDataContainer.toTagCompound()); } } - public void readBukkitValues(Tag c) { - if (c instanceof CompoundTag) { - this.persistentDataContainer.putAll((CompoundTag) c); - } - } - - // Spigot start - private final org.bukkit.World.Spigot spigot = new org.bukkit.World.Spigot() - { - - @Override - public LightningStrike strikeLightning(Location loc, boolean isSilent) - { - return CraftWorld.this.strikeLightning(loc); - } - - @Override - public LightningStrike strikeLightningEffect(Location loc, boolean isSilent) - { - return CraftWorld.this.strikeLightningEffect(loc); - } - }; - - public org.bukkit.World.Spigot spigot() - { - return this.spigot; - } - // Spigot end - - // Mohist start - private boolean isbukkit = false; - @Override - public boolean isBukkit() { - return isbukkit; - } - - @Override - public void setBukkit(boolean b) { - isbukkit = b; - } - - @Override - public boolean isMods() { - String path = getWorldFolder().getAbsolutePath().replaceAll("\\\\", "/"); - return !isBukkit() && path.contains("/world/dimensions/"); - } - - @Override - public String getModid() { - String path = getWorldFolder().getAbsolutePath().replaceAll("\\\\", "/"); - String modName = ""; - if(path.contains("/world/dimensions/")) { - modName = path.split("/world/dimensions/")[1].split("/")[0]; + public void readBukkitValues(NBTBase c) { + if (c instanceof NBTTagCompound) { + this.persistentDataContainer.putAll((NBTTagCompound) c); } - return modName; } - // Mohist end } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java b/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java index 1fe5ae16..bbc6c55e 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java @@ -24,7 +24,7 @@ public CraftWorldBorder(net.minecraft.world.level.border.WorldBorder handle) { @Override public World getWorld() { - return this.world; + return world; } @Override @@ -44,7 +44,7 @@ public void setSize(double newSize) { @Override public void setSize(double newSize, long time) { - this.setSize(Math.min(this.getMaxSize(), Math.max(1.0D, newSize)), TimeUnit.SECONDS, Math.min(9223372036854775L, Math.max(0L, time))); + setSize(Math.min(getMaxSize(), Math.max(1.0D, newSize)), TimeUnit.SECONDS, Math.min(9223372036854775L, Math.max(0L, time))); } @Override @@ -125,7 +125,7 @@ public void setWarningDistance(int distance) { public boolean isInside(Location location) { Preconditions.checkArgument(location != null, "location cannot be null"); - return (this.world == null || location.getWorld().equals(this.world)) && this.handle.isWithinBounds(BlockPos.containing(location.getX(), location.getY(), location.getZ())); + return (world == null || location.getWorld().equals(this.world)) && this.handle.isWithinBounds(BlockPos.containing(location.getX(), location.getY(), location.getZ())); } @Override @@ -139,10 +139,10 @@ public double getMaxCenterCoordinate() { } public net.minecraft.world.level.border.WorldBorder getHandle() { - return this.handle; + return handle; } public boolean isVirtual() { - return this.world == null; + return world == null; } } diff --git a/src/main/java/org/bukkit/craftbukkit/Main.java b/src/main/java/org/bukkit/craftbukkit/Main.java index dee87ffc..5c9f3073 100644 --- a/src/main/java/org/bukkit/craftbukkit/Main.java +++ b/src/main/java/org/bukkit/craftbukkit/Main.java @@ -23,125 +23,117 @@ public static void main(String[] args) { // Todo: Installation script OptionParser parser = new OptionParser() { { - this.acceptsAll(Main.asList("?", "help"), "Show the help"); + acceptsAll(asList("?", "help"), "Show the help"); - this.acceptsAll(Main.asList("c", "config"), "Properties file to use") + acceptsAll(asList("c", "config"), "Properties file to use") .withRequiredArg() .ofType(File.class) .defaultsTo(new File("server.properties")) .describedAs("Properties file"); - this.acceptsAll(Main.asList("P", "plugins"), "Plugin directory to use") + acceptsAll(asList("P", "plugins"), "Plugin directory to use") .withRequiredArg() .ofType(File.class) .defaultsTo(new File("plugins")) .describedAs("Plugin directory"); - this.acceptsAll(Main.asList("h", "host", "server-ip"), "Host to listen on") + acceptsAll(asList("h", "host", "server-ip"), "Host to listen on") .withRequiredArg() .ofType(String.class) .describedAs("Hostname or IP"); - this.acceptsAll(Main.asList("W", "world-dir", "universe", "world-container"), "World container") + acceptsAll(asList("W", "world-dir", "universe", "world-container"), "World container") .withRequiredArg() .ofType(File.class) .defaultsTo(new File(".")) .describedAs("Directory containing worlds"); - this.acceptsAll(Main.asList("w", "world", "level-name"), "World name") + acceptsAll(asList("w", "world", "level-name"), "World name") .withRequiredArg() .ofType(String.class) .describedAs("World name"); - this.acceptsAll(Main.asList("p", "port", "server-port"), "Port to listen on") + acceptsAll(asList("p", "port", "server-port"), "Port to listen on") .withRequiredArg() .ofType(Integer.class) .describedAs("Port"); - this.accepts("serverId", "Server ID") + accepts("serverId", "Server ID") .withRequiredArg(); - this.accepts("jfrProfile", "Enable JFR profiling"); + accepts("jfrProfile", "Enable JFR profiling"); - this.accepts("pidFile", "pid File") + accepts("pidFile", "pid File") .withRequiredArg() .withValuesConvertedBy(new PathConverter()); - this.acceptsAll(Main.asList("o", "online-mode"), "Whether to use online authentication") + acceptsAll(asList("o", "online-mode"), "Whether to use online authentication") .withRequiredArg() .ofType(Boolean.class) .describedAs("Authentication"); - this.acceptsAll(Main.asList("s", "size", "max-players"), "Maximum amount of players") + acceptsAll(asList("s", "size", "max-players"), "Maximum amount of players") .withRequiredArg() .ofType(Integer.class) .describedAs("Server size"); - this.acceptsAll(Main.asList("d", "date-format"), "Format of the date to display in the console (for log entries)") + acceptsAll(asList("d", "date-format"), "Format of the date to display in the console (for log entries)") .withRequiredArg() .ofType(SimpleDateFormat.class) .describedAs("Log date format"); - this.acceptsAll(Main.asList("log-pattern"), "Specfies the log filename pattern") + acceptsAll(asList("log-pattern"), "Specfies the log filename pattern") .withRequiredArg() .ofType(String.class) .defaultsTo("server.log") .describedAs("Log filename"); - this.acceptsAll(Main.asList("log-limit"), "Limits the maximum size of the log file (0 = unlimited)") + acceptsAll(asList("log-limit"), "Limits the maximum size of the log file (0 = unlimited)") .withRequiredArg() .ofType(Integer.class) .defaultsTo(0) .describedAs("Max log size"); - this.acceptsAll(Main.asList("log-count"), "Specified how many log files to cycle through") + acceptsAll(asList("log-count"), "Specified how many log files to cycle through") .withRequiredArg() .ofType(Integer.class) .defaultsTo(1) .describedAs("Log count"); - this.acceptsAll(Main.asList("log-append"), "Whether to append to the log file") + acceptsAll(asList("log-append"), "Whether to append to the log file") .withRequiredArg() .ofType(Boolean.class) .defaultsTo(true) .describedAs("Log append"); - this.acceptsAll(Main.asList("log-strip-color"), "Strips color codes from log file"); + acceptsAll(asList("log-strip-color"), "Strips color codes from log file"); - this.acceptsAll(Main.asList("b", "bukkit-settings"), "File for bukkit settings") + acceptsAll(asList("b", "bukkit-settings"), "File for bukkit settings") .withRequiredArg() .ofType(File.class) .defaultsTo(new File("bukkit.yml")) .describedAs("Yml file"); - this.acceptsAll(Main.asList("C", "commands-settings"), "File for command settings") + acceptsAll(asList("C", "commands-settings"), "File for command settings") .withRequiredArg() .ofType(File.class) .defaultsTo(new File("commands.yml")) .describedAs("Yml file"); - this.acceptsAll(Main.asList("forceUpgrade"), "Whether to force a world upgrade"); - this.acceptsAll(Main.asList("eraseCache"), "Whether to force cache erase during world upgrade"); - this.acceptsAll(Main.asList("recreateRegionFiles"), "Whether to recreate region files during world upgrade"); - this.acceptsAll(Main.asList("nogui"), "Disables the graphical console"); + acceptsAll(asList("forceUpgrade"), "Whether to force a world upgrade"); + acceptsAll(asList("eraseCache"), "Whether to force cache erase during world upgrade"); + acceptsAll(asList("recreateRegionFiles"), "Whether to recreate region files during world upgrade"); + acceptsAll(asList("nogui"), "Disables the graphical console"); - this.acceptsAll(Main.asList("nojline"), "Disables jline and emulates the vanilla console"); + acceptsAll(asList("nojline"), "Disables jline and emulates the vanilla console"); - this.acceptsAll(Main.asList("noconsole"), "Disables the console"); + acceptsAll(asList("noconsole"), "Disables the console"); - this.acceptsAll(Main.asList("v", "version"), "Show the CraftBukkit Version"); + acceptsAll(asList("v", "version"), "Show the CraftBukkit Version"); - this.acceptsAll(Main.asList("demo"), "Demo mode"); + acceptsAll(asList("demo"), "Demo mode"); - this.acceptsAll(Main.asList("initSettings"), "Only create configuration files and then exit"); // SPIGOT-5761: Add initSettings option - - // Spigot Start - this.acceptsAll(Main.asList("S", "spigot-settings"), "File for spigot settings") - .withRequiredArg() - .ofType(File.class) - .defaultsTo(new File("spigot.yml")) - .describedAs("Yml file"); - // Spigot End + acceptsAll(asList("initSettings"), "Only create configuration files and then exit"); // SPIGOT-5761: Add initSettings option } }; @@ -170,19 +162,8 @@ public static void main(String[] args) { } float javaVersion = Float.parseFloat(System.getProperty("java.class.version")); - if (javaVersion < 61.0) { - System.err.println("Unsupported Java detected (" + javaVersion + "). This version of Minecraft requires at least Java 17. Check your Java version with the command 'java -version'."); - return; - } - if (javaVersion > 66.0) { - System.err.println("Unsupported Java detected (" + javaVersion + "). Only up to Java 22 is supported."); - return; - } - String javaVersionName = System.getProperty("java.version"); - // J2SE SDK/JRE Version String Naming Convention - boolean isPreRelease = javaVersionName.contains("-"); - if (isPreRelease && javaVersion == 61.0) { - System.err.println("Unsupported Java detected (" + javaVersionName + "). You are running an outdated, pre-release version. Only general availability versions of Java are supported. Please update your Java version."); + if (javaVersion > 67.0) { + System.err.println("Unsupported Java detected (" + javaVersion + "). Only up to Java 23 is supported."); return; } @@ -191,14 +172,14 @@ public static void main(String[] args) { String jline_UnsupportedTerminal = new String(new char[]{'j', 'l', 'i', 'n', 'e', '.', 'U', 'n', 's', 'u', 'p', 'p', 'o', 'r', 't', 'e', 'd', 'T', 'e', 'r', 'm', 'i', 'n', 'a', 'l'}); String jline_terminal = new String(new char[]{'j', 'l', 'i', 'n', 'e', '.', 't', 'e', 'r', 'm', 'i', 'n', 'a', 'l'}); - Main.useJline = !(jline_UnsupportedTerminal).equals(System.getProperty(jline_terminal)); + useJline = !(jline_UnsupportedTerminal).equals(System.getProperty(jline_terminal)); if (options.has("nojline")) { System.setProperty("user.language", "en"); - Main.useJline = false; + useJline = false; } - if (Main.useJline) { + if (useJline) { AnsiConsole.systemInstall(); } else { // This ensures the terminal literal will always match the jline implementation @@ -206,7 +187,7 @@ public static void main(String[] args) { } if (options.has("noconsole")) { - Main.useConsole = false; + useConsole = false; } if (Main.class.getPackage().getImplementationVendor() != null && System.getProperty("IReallyKnowWhatIAmDoingISwear") == null) { @@ -223,6 +204,7 @@ public static void main(String[] args) { } System.out.println("Loading libraries, please wait..."); + net.minecraft.server.Main.main(options); } catch (Throwable t) { t.printStackTrace(); } diff --git a/src/main/java/org/bukkit/craftbukkit/SpigotTimings.java b/src/main/java/org/bukkit/craftbukkit/SpigotTimings.java deleted file mode 100644 index b0ffa23f..00000000 --- a/src/main/java/org/bukkit/craftbukkit/SpigotTimings.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.util.HashMap; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.storage.PrimaryLevelData; -import org.bukkit.craftbukkit.scheduler.CraftTask; -import org.bukkit.plugin.java.JavaPluginLoader; -import org.bukkit.scheduler.BukkitTask; -import org.spigotmc.CustomTimingsHandler; - -public class SpigotTimings { - - public static final CustomTimingsHandler serverTickTimer = new CustomTimingsHandler("** Full Server Tick"); - public static final CustomTimingsHandler playerListTimer = new CustomTimingsHandler("Player List"); - public static final CustomTimingsHandler commandFunctionsTimer = new CustomTimingsHandler("Command Functions"); - public static final CustomTimingsHandler connectionTimer = new CustomTimingsHandler("Connection Handler"); - public static final CustomTimingsHandler playerConnectionTimer = new CustomTimingsHandler("** PlayerConnection"); - public static final CustomTimingsHandler tickablesTimer = new CustomTimingsHandler("Tickables"); - public static final CustomTimingsHandler schedulerTimer = new CustomTimingsHandler("Scheduler"); - public static final CustomTimingsHandler timeUpdateTimer = new CustomTimingsHandler("Time Update"); - public static final CustomTimingsHandler serverCommandTimer = new CustomTimingsHandler("Server Command"); - public static final CustomTimingsHandler worldSaveTimer = new CustomTimingsHandler("World Save"); - - public static final CustomTimingsHandler entityMoveTimer = new CustomTimingsHandler("** entityMove"); - public static final CustomTimingsHandler tickEntityTimer = new CustomTimingsHandler("** tickEntity"); - public static final CustomTimingsHandler activatedEntityTimer = new CustomTimingsHandler("** activatedTickEntity"); - public static final CustomTimingsHandler tickTileEntityTimer = new CustomTimingsHandler("** tickTileEntity"); - - public static final CustomTimingsHandler timerEntityBaseTick = new CustomTimingsHandler("** livingEntityBaseTick"); - public static final CustomTimingsHandler timerEntityAI = new CustomTimingsHandler("** livingEntityAI"); - public static final CustomTimingsHandler timerEntityAICollision = new CustomTimingsHandler("** livingEntityAICollision"); - public static final CustomTimingsHandler timerEntityAIMove = new CustomTimingsHandler("** livingEntityAIMove"); - public static final CustomTimingsHandler timerEntityTickRest = new CustomTimingsHandler("** livingEntityTickRest"); - - public static final CustomTimingsHandler processQueueTimer = new CustomTimingsHandler("processQueue"); - public static final CustomTimingsHandler schedulerSyncTimer = new CustomTimingsHandler("** Scheduler - Sync Tasks", JavaPluginLoader.pluginParentTimer); - - public static final CustomTimingsHandler playerCommandTimer = new CustomTimingsHandler("** playerCommand"); - - public static final CustomTimingsHandler entityActivationCheckTimer = new CustomTimingsHandler("entityActivationCheck"); - public static final CustomTimingsHandler checkIfActiveTimer = new CustomTimingsHandler("** checkIfActive"); - - public static final HashMap entityTypeTimingMap = new HashMap(); - public static final HashMap tileEntityTypeTimingMap = new HashMap(); - public static final HashMap pluginTaskTimingMap = new HashMap(); - - /** - * Gets a timer associated with a plugins tasks. - * @param task - * @param period - * @return - */ - public static CustomTimingsHandler getPluginTaskTimings(BukkitTask task, long period) { - if (!task.isSync()) { - return null; - } - String plugin; - final CraftTask ctask = (CraftTask) task; - - if (task.getOwner() != null) { - plugin = task.getOwner().getDescription().getFullName(); - } else { - plugin = "Unknown"; - } - String taskname = ctask.getTaskName(); - - String name = "Task: " + plugin + " Runnable: " + taskname; - if (period > 0) { - name += "(interval:" + period + ")"; - } else { - name += "(Single)"; - } - CustomTimingsHandler result = SpigotTimings.pluginTaskTimingMap.get(name); - if (result == null) { - result = new CustomTimingsHandler(name, SpigotTimings.schedulerSyncTimer); - SpigotTimings.pluginTaskTimingMap.put(name, result); - } - return result; - } - - /** - * Get a named timer for the specified entity type to track type specific timings. - * @param entity - * @return - */ - public static CustomTimingsHandler getEntityTimings(Entity entity) { - String entityType = entity.getClass().getName(); - CustomTimingsHandler result = SpigotTimings.entityTypeTimingMap.get(entityType); - if (result == null) { - result = new CustomTimingsHandler("** tickEntity - " + entity.getClass().getSimpleName(), SpigotTimings.activatedEntityTimer); - SpigotTimings.entityTypeTimingMap.put(entityType, result); - } - return result; - } - - /** - * Get a named timer for the specified tile entity type to track type specific timings. - * @param entity - * @return - */ - public static CustomTimingsHandler getTileEntityTimings(BlockEntity entity) { - String entityType = entity.getClass().getName(); - CustomTimingsHandler result = SpigotTimings.tileEntityTypeTimingMap.get(entityType); - if (result == null) { - result = new CustomTimingsHandler("** tickTileEntity - " + entity.getClass().getSimpleName(), SpigotTimings.tickTileEntityTimer); - SpigotTimings.tileEntityTypeTimingMap.put(entityType, result); - } - return result; - } - - /** - * Set of timers per world, to track world specific timings. - */ - public static class WorldTimingsHandler { - public final CustomTimingsHandler mobSpawn; - public final CustomTimingsHandler doChunkUnload; - public final CustomTimingsHandler doTickPending; - public final CustomTimingsHandler doTickTiles; - public final CustomTimingsHandler doChunkMap; - public final CustomTimingsHandler doSounds; - public final CustomTimingsHandler entityTick; - public final CustomTimingsHandler tileEntityTick; - public final CustomTimingsHandler tileEntityPending; - public final CustomTimingsHandler tracker; - public final CustomTimingsHandler doTick; - public final CustomTimingsHandler tickEntities; - - public final CustomTimingsHandler syncChunkLoadTimer; - public final CustomTimingsHandler syncChunkLoadStructuresTimer; - public final CustomTimingsHandler syncChunkLoadEntitiesTimer; - public final CustomTimingsHandler syncChunkLoadTileEntitiesTimer; - public final CustomTimingsHandler syncChunkLoadTileTicksTimer; - public final CustomTimingsHandler syncChunkLoadPostTimer; - - public WorldTimingsHandler(Level server) { - String name = ((PrimaryLevelData) server.levelData).getLevelName() + " - "; - - this.mobSpawn = new CustomTimingsHandler("** " + name + "mobSpawn"); - this.doChunkUnload = new CustomTimingsHandler("** " + name + "doChunkUnload"); - this.doTickPending = new CustomTimingsHandler("** " + name + "doTickPending"); - this.doTickTiles = new CustomTimingsHandler("** " + name + "doTickTiles"); - this.doChunkMap = new CustomTimingsHandler("** " + name + "doChunkMap"); - this.doSounds = new CustomTimingsHandler("** " + name + "doSounds"); - this.entityTick = new CustomTimingsHandler("** " + name + "entityTick"); - this.tileEntityTick = new CustomTimingsHandler("** " + name + "tileEntityTick"); - this.tileEntityPending = new CustomTimingsHandler("** " + name + "tileEntityPending"); - - this.syncChunkLoadTimer = new CustomTimingsHandler("** " + name + "syncChunkLoad"); - this.syncChunkLoadStructuresTimer = new CustomTimingsHandler("** " + name + "chunkLoad - Structures"); - this.syncChunkLoadEntitiesTimer = new CustomTimingsHandler("** " + name + "chunkLoad - Entities"); - this.syncChunkLoadTileEntitiesTimer = new CustomTimingsHandler("** " + name + "chunkLoad - TileEntities"); - this.syncChunkLoadTileTicksTimer = new CustomTimingsHandler("** " + name + "chunkLoad - TileTicks"); - this.syncChunkLoadPostTimer = new CustomTimingsHandler("** " + name + "chunkLoad - Post"); - - - this.tracker = new CustomTimingsHandler(name + "tracker"); - this.doTick = new CustomTimingsHandler(name + "doTick"); - this.tickEntities = new CustomTimingsHandler(name + "tickEntities"); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java index 52baf818..472d910a 100644 --- a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java +++ b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java @@ -16,25 +16,25 @@ public CraftAdvancement(AdvancementHolder handle) { } public AdvancementHolder getHandle() { - return this.handle; + return handle; } @Override public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(this.handle.id()); + return CraftNamespacedKey.fromMinecraft(handle.id()); } @Override public Collection getCriteria() { - return Collections.unmodifiableCollection(this.handle.value().criteria().keySet()); + return Collections.unmodifiableCollection(handle.value().criteria().keySet()); } @Override public AdvancementDisplay getDisplay() { - if (this.handle.value().display().isEmpty()) { + if (handle.value().display().isEmpty()) { return null; } - return new CraftAdvancementDisplay(this.handle.value().display().get()); + return new CraftAdvancementDisplay(handle.value().display().get()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementDisplay.java b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementDisplay.java index 8ca86852..7756e2ff 100644 --- a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementDisplay.java +++ b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementDisplay.java @@ -15,51 +15,51 @@ public CraftAdvancementDisplay(DisplayInfo handle) { } public DisplayInfo getHandle() { - return this.handle; + return handle; } @Override public String getTitle() { - return CraftChatMessage.fromComponent(this.handle.getTitle()); + return CraftChatMessage.fromComponent(handle.getTitle()); } @Override public String getDescription() { - return CraftChatMessage.fromComponent(this.handle.getDescription()); + return CraftChatMessage.fromComponent(handle.getDescription()); } @Override public ItemStack getIcon() { - return CraftItemStack.asBukkitCopy(this.handle.getIcon()); + return CraftItemStack.asBukkitCopy(handle.getIcon()); } @Override public boolean shouldShowToast() { - return this.handle.shouldShowToast(); + return handle.shouldShowToast(); } @Override public boolean shouldAnnounceChat() { - return this.handle.shouldAnnounceChat(); + return handle.shouldAnnounceChat(); } @Override public boolean isHidden() { - return this.handle.isHidden(); + return handle.isHidden(); } @Override public float getX() { - return this.handle.getX(); + return handle.getX(); } @Override public float getY() { - return this.handle.getY(); + return handle.getY(); } @Override public AdvancementDisplayType getType() { - return AdvancementDisplayType.values()[this.handle.getType().ordinal()]; + return AdvancementDisplayType.values()[handle.getType().ordinal()]; } } diff --git a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java index aeb04a65..bb6c4223 100644 --- a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java +++ b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java @@ -15,7 +15,7 @@ public class CraftAdvancementProgress implements AdvancementProgress { private final PlayerAdvancements playerData; private final net.minecraft.advancements.AdvancementProgress handle; - public CraftAdvancementProgress(CraftAdvancement advancement, PlayerAdvancements player, net.minecraft.advancements.AdvancementProgress handle) { + public CraftAdvancementProgress(CraftAdvancement advancement, PlayerAdvancements player, net.minecraft.advancements.AdvancementProgress handle) { this.advancement = advancement; this.playerData = player; this.handle = handle; @@ -23,37 +23,37 @@ public CraftAdvancementProgress(CraftAdvancement advancement, PlayerAdvancements @Override public Advancement getAdvancement() { - return this.advancement; + return advancement; } @Override public boolean isDone() { - return this.handle.isDone(); + return handle.isDone(); } @Override public boolean awardCriteria(String criteria) { - return this.playerData.award(this.advancement.getHandle(), criteria); + return playerData.award(advancement.getHandle(), criteria); } @Override public boolean revokeCriteria(String criteria) { - return this.playerData.revoke(this.advancement.getHandle(), criteria); + return playerData.revoke(advancement.getHandle(), criteria); } @Override public Date getDateAwarded(String criteria) { - CriterionProgress criterion = this.handle.getCriterion(criteria); + CriterionProgress criterion = handle.getCriterion(criteria); return (criterion == null) ? null : Date.from(criterion.getObtained()); } @Override public Collection getRemainingCriteria() { - return Collections.unmodifiableCollection(Lists.newArrayList(this.handle.getRemainingCriteria())); + return Collections.unmodifiableCollection(Lists.newArrayList(handle.getRemainingCriteria())); } @Override public Collection getAwardedCriteria() { - return Collections.unmodifiableCollection(Lists.newArrayList(this.handle.getCompletedCriteria())); + return Collections.unmodifiableCollection(Lists.newArrayList(handle.getCompletedCriteria())); } } diff --git a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttribute.java b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttribute.java index cc97638e..19c3a4e5 100644 --- a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttribute.java +++ b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttribute.java @@ -3,7 +3,9 @@ import com.google.common.base.Preconditions; import java.util.Locale; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; +import net.minecraft.world.entity.ai.attributes.AttributeBase; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.attribute.Attribute; @@ -26,7 +28,7 @@ public static Attribute minecraftToBukkit(net.minecraft.world.entity.ai.attribut } public static Attribute minecraftHolderToBukkit(Holder minecraft) { - return CraftAttribute.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static Attribute stringToBukkit(String string) { @@ -54,7 +56,7 @@ public static Holder bukkitT net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.ATTRIBUTE); - if (registry.wrapAsHolder(CraftAttribute.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { return holder; } diff --git a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java index de0eba19..82076cb7 100644 --- a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java +++ b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java @@ -12,34 +12,34 @@ public class CraftAttributeInstance implements AttributeInstance { - private final net.minecraft.world.entity.ai.attributes.AttributeInstance handle; + private final net.minecraft.world.entity.ai.attributes.AttributeModifiable handle; private final Attribute attribute; - public CraftAttributeInstance(net.minecraft.world.entity.ai.attributes.AttributeInstance handle, Attribute attribute) { + public CraftAttributeInstance(net.minecraft.world.entity.ai.attributes.AttributeModifiable handle, Attribute attribute) { this.handle = handle; this.attribute = attribute; } @Override public Attribute getAttribute() { - return this.attribute; + return attribute; } @Override public double getBaseValue() { - return this.handle.getBaseValue(); + return handle.getBaseValue(); } @Override public void setBaseValue(double d) { - this.handle.setBaseValue(d); + handle.setBaseValue(d); } @Override public Collection getModifiers() { List result = new ArrayList(); - for (net.minecraft.world.entity.ai.attributes.AttributeModifier nms : this.handle.getModifiers()) { - result.add(CraftAttributeInstance.convert(nms)); + for (net.minecraft.world.entity.ai.attributes.AttributeModifier nms : handle.getModifiers()) { + result.add(convert(nms)); } return result; @@ -48,23 +48,23 @@ public Collection getModifiers() { @Override public void addModifier(AttributeModifier modifier) { Preconditions.checkArgument(modifier != null, "modifier"); - this.handle.addPermanentModifier(CraftAttributeInstance.convert(modifier)); + handle.addPermanentModifier(convert(modifier)); } @Override public void removeModifier(AttributeModifier modifier) { Preconditions.checkArgument(modifier != null, "modifier"); - this.handle.removeModifier(CraftAttributeInstance.convert(modifier)); + handle.removeModifier(convert(modifier)); } @Override public double getValue() { - return this.handle.getValue(); + return handle.getValue(); } @Override public double getDefaultValue() { - return this.handle.getAttribute().value().getDefaultValue(); + return handle.getAttribute().value().getDefaultValue(); } public static net.minecraft.world.entity.ai.attributes.AttributeModifier convert(AttributeModifier bukkit) { diff --git a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java index de40e522..063bcf5f 100644 --- a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java +++ b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java @@ -1,23 +1,23 @@ package org.bukkit.craftbukkit.attribute; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.ai.attributes.AttributeMap; +import net.minecraft.world.entity.ai.attributes.AttributeMapBase; import org.bukkit.attribute.Attributable; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; public class CraftAttributeMap implements Attributable { - private final AttributeMap handle; + private final AttributeMapBase handle; - public CraftAttributeMap(AttributeMap handle) { + public CraftAttributeMap(AttributeMapBase handle) { this.handle = handle; } @Override public AttributeInstance getAttribute(Attribute attribute) { Preconditions.checkArgument(attribute != null, "attribute"); - net.minecraft.world.entity.ai.attributes.AttributeInstance nms = this.handle.getInstance(CraftAttribute.bukkitToMinecraftHolder(attribute)); + net.minecraft.world.entity.ai.attributes.AttributeModifiable nms = handle.getInstance(CraftAttribute.bukkitToMinecraftHolder(attribute)); return (nms == null) ? null : new CraftAttributeInstance(nms, attribute); } diff --git a/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanEntry.java b/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanEntry.java index 847da7f8..e6d6689d 100644 --- a/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanEntry.java +++ b/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanEntry.java @@ -4,8 +4,8 @@ import java.net.InetAddress; import java.time.Instant; import java.util.Date; +import net.minecraft.server.players.IpBanEntry; import net.minecraft.server.players.IpBanList; -import net.minecraft.server.players.IpBanListEntry; import org.bukkit.BanEntry; public final class CraftIpBanEntry implements BanEntry { @@ -17,7 +17,7 @@ public final class CraftIpBanEntry implements BanEntry { private Date expiration; private String reason; - public CraftIpBanEntry(String target, IpBanListEntry entry, IpBanList list) { + public CraftIpBanEntry(String target, IpBanEntry entry, IpBanList list) { this.list = list; this.target = target; this.created = entry.getCreated() != null ? new Date(entry.getCreated().getTime()) : null; @@ -63,7 +63,7 @@ public Date getExpiration() { @Override public void setExpiration(Date expiration) { - if (expiration != null && expiration.getTime() == CraftIpBanEntry.minorDate.getTime()) { + if (expiration != null && expiration.getTime() == minorDate.getTime()) { expiration = null; // Forces "forever" } @@ -82,12 +82,12 @@ public void setReason(String reason) { @Override public void save() { - IpBanListEntry entry = new IpBanListEntry(this.target, this.created, this.source, this.expiration, this.reason); + IpBanEntry entry = new IpBanEntry(this.target, this.created, this.source, this.expiration, this.reason); this.list.add(entry); } @Override public void remove() { - this.list.remove(this.target); + this.list.remove(target); } } diff --git a/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanList.java b/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanList.java index 94be0e84..46b47d54 100644 --- a/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanList.java +++ b/src/main/java/org/bukkit/craftbukkit/ban/CraftIpBanList.java @@ -8,8 +8,8 @@ import java.time.Instant; import java.util.Date; import java.util.Set; +import net.minecraft.server.players.IpBanEntry; import net.minecraft.server.players.IpBanList; -import net.minecraft.server.players.IpBanListEntry; import org.bukkit.BanEntry; public class CraftIpBanList implements org.bukkit.ban.IpBanList { @@ -23,12 +23,12 @@ public CraftIpBanList(IpBanList list) { public BanEntry getBanEntry(String target) { Preconditions.checkArgument(target != null, "Target cannot be null"); - IpBanListEntry entry = this.list.get(target); + IpBanEntry entry = this.list.get(target); if (entry == null) { return null; } - return new CraftIpBanEntry(target, entry, this.list); + return new CraftIpBanEntry(target, entry, list); } @Override @@ -40,13 +40,13 @@ public BanEntry getBanEntry(InetAddress target) { public BanEntry addBan(String target, String reason, Date expires, String source) { Preconditions.checkArgument(target != null, "Ban target cannot be null"); - IpBanListEntry entry = new IpBanListEntry(target, new Date(), + IpBanEntry entry = new IpBanEntry(target, new Date(), (source == null || source.isBlank()) ? null : source, expires, (reason == null || reason.isBlank()) ? null : reason); this.list.add(entry); - return new CraftIpBanEntry(target, entry, this.list); + return new CraftIpBanEntry(target, entry, list); } @Override @@ -57,22 +57,22 @@ public BanEntry addBan(InetAddress target, String reason, Date expi @Override public BanEntry addBan(InetAddress target, String reason, Instant expires, String source) { Date date = expires != null ? Date.from(expires) : null; - return this.addBan(target, reason, date, source); + return addBan(target, reason, date, source); } @Override public BanEntry addBan(InetAddress target, String reason, Duration duration, String source) { Instant instant = duration != null ? Instant.now().plus(duration) : null; - return this.addBan(target, reason, instant, source); + return addBan(target, reason, instant, source); } @Override public Set getBanEntries() { ImmutableSet.Builder builder = ImmutableSet.builder(); - for (String target : this.list.getUserList()) { - IpBanListEntry ipBanEntry = this.list.get(target); + for (String target : list.getUserList()) { + IpBanEntry ipBanEntry = list.get(target); if (ipBanEntry != null) { - builder.add(new CraftIpBanEntry(target, ipBanEntry, this.list)); + builder.add(new CraftIpBanEntry(target, ipBanEntry, list)); } } return builder.build(); @@ -81,10 +81,10 @@ public Set getBanEntries() { @Override public Set> getEntries() { ImmutableSet.Builder> builder = ImmutableSet.builder(); - for (String target : this.list.getUserList()) { - IpBanListEntry ipBanEntry = this.list.get(target); + for (String target : list.getUserList()) { + IpBanEntry ipBanEntry = list.get(target); if (ipBanEntry != null) { - builder.add(new CraftIpBanEntry(target, ipBanEntry, this.list)); + builder.add(new CraftIpBanEntry(target, ipBanEntry, list)); } } return builder.build(); @@ -98,7 +98,7 @@ public boolean isBanned(String target) { @Override public boolean isBanned(InetAddress target) { - return this.isBanned(this.getIpFromAddress(target)); + return this.isBanned(getIpFromAddress(target)); } @Override @@ -109,7 +109,7 @@ public void pardon(String target) { @Override public void pardon(InetAddress target) { - this.pardon(this.getIpFromAddress(target)); + this.pardon(getIpFromAddress(target)); } private String getIpFromAddress(InetAddress address) { diff --git a/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanEntry.java b/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanEntry.java index 13e5e44b..6cc8990e 100644 --- a/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanEntry.java +++ b/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanEntry.java @@ -3,22 +3,22 @@ import com.mojang.authlib.GameProfile; import java.time.Instant; import java.util.Date; -import net.minecraft.server.players.UserBanList; -import net.minecraft.server.players.UserBanListEntry; +import net.minecraft.server.players.GameProfileBanEntry; +import net.minecraft.server.players.GameProfileBanList; import org.bukkit.BanEntry; import org.bukkit.craftbukkit.profile.CraftPlayerProfile; import org.bukkit.profile.PlayerProfile; public final class CraftProfileBanEntry implements BanEntry { private static final Date minorDate = Date.from(Instant.parse("1899-12-31T04:00:00Z")); - private final UserBanList list; + private final GameProfileBanList list; private final GameProfile profile; private Date created; private String source; private Date expiration; private String reason; - public CraftProfileBanEntry(GameProfile profile, UserBanListEntry entry, UserBanList list) { + public CraftProfileBanEntry(GameProfile profile, GameProfileBanEntry entry, GameProfileBanList list) { this.list = list; this.profile = profile; this.created = entry.getCreated() != null ? new Date(entry.getCreated().getTime()) : null; @@ -64,7 +64,7 @@ public Date getExpiration() { @Override public void setExpiration(Date expiration) { - if (expiration != null && expiration.getTime() == CraftProfileBanEntry.minorDate.getTime()) { + if (expiration != null && expiration.getTime() == minorDate.getTime()) { expiration = null; // Forces "forever" } @@ -83,7 +83,7 @@ public void setReason(String reason) { @Override public void save() { - UserBanListEntry entry = new UserBanListEntry(this.profile, this.created, this.source, this.expiration, this.reason); + GameProfileBanEntry entry = new GameProfileBanEntry(this.profile, this.created, this.source, this.expiration, this.reason); this.list.add(entry); } diff --git a/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanList.java b/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanList.java index 172202ac..c7bf2cb8 100644 --- a/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanList.java +++ b/src/main/java/org/bukkit/craftbukkit/ban/CraftProfileBanList.java @@ -9,17 +9,17 @@ import java.util.Set; import java.util.UUID; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.players.UserBanList; -import net.minecraft.server.players.UserBanListEntry; +import net.minecraft.server.players.GameProfileBanEntry; +import net.minecraft.server.players.GameProfileBanList; import org.bukkit.BanEntry; import org.bukkit.ban.ProfileBanList; import org.bukkit.craftbukkit.profile.CraftPlayerProfile; import org.bukkit.profile.PlayerProfile; public class CraftProfileBanList implements ProfileBanList { - private final UserBanList list; + private final GameProfileBanList list; - public CraftProfileBanList(UserBanList list) { + public CraftProfileBanList(GameProfileBanList list) { this.list = list; } @@ -27,7 +27,7 @@ public CraftProfileBanList(UserBanList list) { public BanEntry getBanEntry(String target) { Preconditions.checkArgument(target != null, "Target cannot be null"); - return this.getBanEntry(CraftProfileBanList.getProfile(target)); + return this.getBanEntry(getProfile(target)); } @Override @@ -41,7 +41,7 @@ public BanEntry getBanEntry(PlayerProfile target) { public BanEntry addBan(String target, String reason, Date expires, String source) { Preconditions.checkArgument(target != null, "Ban target cannot be null"); - return this.addBan(CraftProfileBanList.getProfileByName(target), reason, expires, source); + return this.addBan(getProfileByName(target), reason, expires, source); } @Override @@ -55,21 +55,21 @@ public BanEntry addBan(PlayerProfile target, String reason, Date @Override public BanEntry addBan(PlayerProfile target, String reason, Instant expires, String source) { Date date = expires != null ? Date.from(expires) : null; - return this.addBan(target, reason, date, source); + return addBan(target, reason, date, source); } @Override public BanEntry addBan(PlayerProfile target, String reason, Duration duration, String source) { Instant instant = duration != null ? Instant.now().plus(duration) : null; - return this.addBan(target, reason, instant, source); + return addBan(target, reason, instant, source); } @Override public Set getBanEntries() { ImmutableSet.Builder builder = ImmutableSet.builder(); - for (UserBanListEntry entry : this.list.getEntries()) { + for (GameProfileBanEntry entry : list.getEntries()) { GameProfile profile = entry.getUser(); - builder.add(new CraftProfileBanEntry(profile, entry, this.list)); + builder.add(new CraftProfileBanEntry(profile, entry, list)); } return builder.build(); @@ -78,9 +78,9 @@ public Set getBanEntries() { @Override public Set> getEntries() { ImmutableSet.Builder> builder = ImmutableSet.builder(); - for (UserBanListEntry entry : this.list.getEntries()) { + for (GameProfileBanEntry entry : list.getEntries()) { GameProfile profile = entry.getUser(); - builder.add(new CraftProfileBanEntry(profile, entry, this.list)); + builder.add(new CraftProfileBanEntry(profile, entry, list)); } return builder.build(); @@ -97,7 +97,7 @@ public boolean isBanned(PlayerProfile target) { public boolean isBanned(String target) { Preconditions.checkArgument(target != null, "Target cannot be null"); - return this.isBanned(CraftProfileBanList.getProfile(target)); + return this.isBanned(getProfile(target)); } @Override @@ -111,7 +111,7 @@ public void pardon(PlayerProfile target) { public void pardon(String target) { Preconditions.checkArgument(target != null, "Target cannot be null"); - this.pardon(CraftProfileBanList.getProfile(target)); + this.pardon(getProfile(target)); } public BanEntry getBanEntry(GameProfile profile) { @@ -119,12 +119,12 @@ public BanEntry getBanEntry(GameProfile profile) { return null; } - UserBanListEntry entry = this.list.get(profile); + GameProfileBanEntry entry = list.get(profile); if (entry == null) { return null; } - return new CraftProfileBanEntry(profile, entry, this.list); + return new CraftProfileBanEntry(profile, entry, list); } public BanEntry addBan(GameProfile profile, String reason, Date expires, String source) { @@ -132,21 +132,21 @@ public BanEntry addBan(GameProfile profile, String reason, Date e return null; } - UserBanListEntry entry = new UserBanListEntry(profile, new Date(), + GameProfileBanEntry entry = new GameProfileBanEntry(profile, new Date(), (source == null || source.isBlank()) ? null : source, expires, (reason == null || reason.isBlank()) ? null : reason); - this.list.add(entry); + list.add(entry); - return new CraftProfileBanEntry(profile, entry, this.list); + return new CraftProfileBanEntry(profile, entry, list); } private void pardon(GameProfile profile) { - this.list.remove(profile); + list.remove(profile); } private boolean isBanned(GameProfile profile) { - return profile != null && this.list.isBanned(profile); + return profile != null && list.isBanned(profile); } static GameProfile getProfile(String target) { @@ -157,7 +157,7 @@ static GameProfile getProfile(String target) { } catch (IllegalArgumentException ignored) { } - return (uuid != null) ? CraftProfileBanList.getProfileByUUID(uuid) : CraftProfileBanList.getProfileByName(target); + return (uuid != null) ? getProfileByUUID(uuid) : getProfileByName(target); } static GameProfile getProfileByUUID(UUID uuid) { diff --git a/src/main/java/org/bukkit/craftbukkit/block/CapturedBlockState.java b/src/main/java/org/bukkit/craftbukkit/block/CapturedBlockState.java index b709d453..00d67b4b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CapturedBlockState.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CapturedBlockState.java @@ -2,10 +2,10 @@ import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.entity.BeehiveBlockEntity; -import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.GeneratorAccessSeed; +import net.minecraft.world.level.World; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.entity.TileEntityBeehive; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -33,7 +33,7 @@ public boolean update(boolean force, boolean applyPhysics) { // Probably no longer needed with the extra #updatedTree method, // but leave if here for now in case a plugin for whatever reason relies on this. - this.addBees(); + addBees(); return result; } @@ -41,27 +41,27 @@ public boolean update(boolean force, boolean applyPhysics) { private void updatedTree() { // SPIGOT-7248 - Manual update to avoid physics where appropriate // SPIGOT-7572 - Move SPIGOT-7248 fix from nms ItemStack to here, to allow bee generation in nests - this.world.getHandle().setBlock(CraftLocation.toBlockPosition(this.getLocation()), this.getHandle(), this.getFlag()); + world.getHandle().setBlock(CraftLocation.toBlockPos(getLocation()), getHandle(), getFlag()); - this.addBees(); + addBees(); } private void addBees() { // SPIGOT-5537: Horrible hack to manually add bees given World.captureTreeGeneration does not support tiles - if (this.treeBlock && this.getType() == Material.BEE_NEST) { - WorldGenLevel generatoraccessseed = this.world.getHandle(); + if (this.treeBlock && getType() == Material.BEE_NEST) { + GeneratorAccessSeed generatoraccessseed = this.world.getHandle(); BlockPos blockposition1 = this.getPosition(); RandomSource random = generatoraccessseed.getRandom(); // Begin copied block from WorldGenFeatureTreeBeehive - BlockEntity tileentity = generatoraccessseed.getBlockEntity(blockposition1); + TileEntity tileentity = generatoraccessseed.getBlockEntity(blockposition1); - if (tileentity instanceof BeehiveBlockEntity) { - BeehiveBlockEntity tileentitybeehive = (BeehiveBlockEntity) tileentity; + if (tileentity instanceof TileEntityBeehive) { + TileEntityBeehive tileentitybeehive = (TileEntityBeehive) tileentity; int j = 2 + random.nextInt(2); for (int k = 0; k < j; ++k) { - tileentitybeehive.storeBee(BeehiveBlockEntity.Occupant.create(random.nextInt(599))); + tileentitybeehive.storeBee(TileEntityBeehive.c.create(random.nextInt(599))); } } // End copied block @@ -78,11 +78,11 @@ public CapturedBlockState copy(Location location) { return new CapturedBlockState(this, location); } - public static CapturedBlockState getBlockState(Level world, BlockPos pos, int flag) { + public static CapturedBlockState getBlockState(World world, BlockPos pos, int flag) { return new CapturedBlockState(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), flag, false); } - public static CapturedBlockState getTreeBlockState(Level world, BlockPos pos, int flag) { + public static CapturedBlockState getTreeBlockState(World world, BlockPos pos, int flag) { return new CapturedBlockState(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), flag, true); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java index 5635230f..27916fc4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java @@ -3,9 +3,10 @@ import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; -import net.minecraft.world.level.block.AbstractBannerBlock; -import net.minecraft.world.level.block.entity.BannerBlockEntity; +import net.minecraft.world.item.EnumColor; +import net.minecraft.world.level.block.BlockBannerAbstract; import net.minecraft.world.level.block.entity.BannerPatternLayers; +import net.minecraft.world.level.block.entity.TileEntityBanner; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.World; @@ -13,12 +14,12 @@ import org.bukkit.block.banner.Pattern; import org.bukkit.craftbukkit.block.banner.CraftPatternType; -public class CraftBanner extends CraftBlockEntityState implements Banner { +public class CraftBanner extends CraftBlockEntityState implements Banner { private DyeColor base; private List patterns; - public CraftBanner(World world, BannerBlockEntity tileEntity) { + public CraftBanner(World world, TileEntityBanner tileEntity) { super(world, tileEntity); } @@ -29,16 +30,16 @@ protected CraftBanner(CraftBanner state, Location location) { } @Override - public void load(BannerBlockEntity banner) { + public void load(TileEntityBanner banner) { super.load(banner); - this.base = DyeColor.getByWoolData((byte) ((AbstractBannerBlock) this.data.getBlock()).getColor().getId()); - this.patterns = new ArrayList(); + base = DyeColor.getByWoolData((byte) ((BlockBannerAbstract) this.data.getBlock()).getColor().getId()); + patterns = new ArrayList(); if (banner.getPatterns() != null) { for (int i = 0; i < banner.getPatterns().layers().size(); i++) { - BannerPatternLayers.Layer p = banner.getPatterns().layers().get(i); - this.patterns.add(new Pattern(DyeColor.getByWoolData((byte) p.color().getId()), CraftPatternType.minecraftHolderToBukkit(p.pattern()))); + BannerPatternLayers.b p = banner.getPatterns().layers().get(i); + patterns.add(new Pattern(DyeColor.getByWoolData((byte) p.color().getId()), CraftPatternType.minecraftHolderToBukkit(p.pattern()))); } } } @@ -56,7 +57,7 @@ public void setBaseColor(DyeColor color) { @Override public List getPatterns() { - return new ArrayList(this.patterns); + return new ArrayList(patterns); } @Override @@ -86,19 +87,19 @@ public void setPattern(int i, Pattern pattern) { @Override public int numberOfPatterns() { - return this.patterns.size(); + return patterns.size(); } @Override - public void applyTo(BannerBlockEntity banner) { + public void applyTo(TileEntityBanner banner) { super.applyTo(banner); - banner.baseColor = net.minecraft.world.item.DyeColor.byId(this.base.getWoolData()); + banner.baseColor = EnumColor.byId(base.getWoolData()); - List newPatterns = new ArrayList<>(); + List newPatterns = new ArrayList<>(); - for (Pattern p : this.patterns) { - newPatterns.add(new net.minecraft.world.level.block.entity.BannerPatternLayers.Layer(CraftPatternType.bukkitToMinecraftHolder(p.getPattern()), net.minecraft.world.item.DyeColor.byId(p.getColor().getWoolData()))); + for (Pattern p : patterns) { + newPatterns.add(new net.minecraft.world.level.block.entity.BannerPatternLayers.b(CraftPatternType.bukkitToMinecraftHolder(p.getPattern()), EnumColor.byId(p.getColor().getWoolData()))); } banner.setPatterns(new BannerPatternLayers(newPatterns)); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java index f4b480e3..cf0b4bae 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java @@ -1,18 +1,18 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.level.block.BarrelBlock; -import net.minecraft.world.level.block.entity.BarrelBlockEntity; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.sounds.SoundEffects; +import net.minecraft.world.level.block.BlockBarrel; +import net.minecraft.world.level.block.entity.TileEntityBarrel; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Barrel; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.inventory.Inventory; -public class CraftBarrel extends CraftLootable implements Barrel { +public class CraftBarrel extends CraftLootable implements Barrel { - public CraftBarrel(World world, BarrelBlockEntity tileEntity) { + public CraftBarrel(World world, TileEntityBarrel tileEntity) { super(world, tileEntity); } @@ -36,32 +36,32 @@ public Inventory getInventory() { @Override public void open() { - this.requirePlaced(); - if (!this.getTileEntity().openersCounter.opened) { - BlockState blockData = this.getTileEntity().getBlockState(); - boolean open = blockData.getValue(BarrelBlock.OPEN); + requirePlaced(); + if (!getTileEntity().openersCounter.opened) { + IBlockData blockData = getTileEntity().getBlockState(); + boolean open = blockData.getValue(BlockBarrel.OPEN); if (!open) { - this.getTileEntity().updateBlockState(blockData, true); - if (this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - this.getTileEntity().playSound(blockData, SoundEvents.BARREL_OPEN); + getTileEntity().updateBlockState(blockData, true); + if (getWorldHandle() instanceof net.minecraft.world.level.World) { + getTileEntity().playSound(blockData, SoundEffects.BARREL_OPEN); } } } - this.getTileEntity().openersCounter.opened = true; + getTileEntity().openersCounter.opened = true; } @Override public void close() { - this.requirePlaced(); - if (this.getTileEntity().openersCounter.opened) { - BlockState blockData = this.getTileEntity().getBlockState(); - this.getTileEntity().updateBlockState(blockData, false); - if (this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - this.getTileEntity().playSound(blockData, SoundEvents.BARREL_CLOSE); + requirePlaced(); + if (getTileEntity().openersCounter.opened) { + IBlockData blockData = getTileEntity().getBlockState(); + getTileEntity().updateBlockState(blockData, false); + if (getWorldHandle() instanceof net.minecraft.world.level.World) { + getTileEntity().playSound(blockData, SoundEffects.BARREL_CLOSE); } } - this.getTileEntity().openersCounter.opened = false; + getTileEntity().openersCounter.opened = false; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java index 9ef8b032..e6bc7d5d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java @@ -2,22 +2,31 @@ import java.util.ArrayList; import java.util.Collection; -import net.minecraft.world.LockCode; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.block.entity.BeaconBlockEntity; -import net.minecraft.world.level.block.entity.BlockEntity; +import java.util.Collections; +import java.util.Optional; +import net.minecraft.advancements.critereon.CriterionConditionItem; +import net.minecraft.advancements.critereon.CriterionConditionValue; +import net.minecraft.core.component.DataComponentPredicate; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.world.ChestLock; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.entity.TileEntityBeacon; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Beacon; +import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -public class CraftBeacon extends CraftBlockEntityState implements Beacon { +public class CraftBeacon extends CraftBlockEntityState implements Beacon { - public CraftBeacon(World world, BeaconBlockEntity tileEntity) { + public CraftBeacon(World world, TileEntityBeacon tileEntity) { super(world, tileEntity); } @@ -27,16 +36,16 @@ protected CraftBeacon(CraftBeacon state, Location location) { @Override public Collection getEntitiesInRange() { - this.ensureNoWorldGeneration(); + ensureNoWorldGeneration(); - BlockEntity tileEntity = this.getTileEntityFromWorld(); - if (tileEntity instanceof BeaconBlockEntity) { - BeaconBlockEntity beacon = (BeaconBlockEntity) tileEntity; + TileEntity tileEntity = this.getTileEntityFromWorld(); + if (tileEntity instanceof TileEntityBeacon) { + TileEntityBeacon beacon = (TileEntityBeacon) tileEntity; - Collection nms = BeaconBlockEntity.getHumansInRange(beacon.getLevel(), beacon.getBlockPos(), beacon.levels); + Collection nms = TileEntityBeacon.getHumansInRange(beacon.getLevel(), beacon.getBlockPos(), beacon.levels); Collection bukkit = new ArrayList(nms.size()); - for (Player human : nms) { + for (EntityHuman human : nms) { bukkit.add(human.getBukkitEntity()); } @@ -74,7 +83,7 @@ public void setSecondaryEffect(PotionEffectType effect) { @Override public String getCustomName() { - BeaconBlockEntity beacon = this.getSnapshot(); + TileEntityBeacon beacon = this.getSnapshot(); return beacon.name != null ? CraftChatMessage.fromComponent(beacon.name) : null; } @@ -85,17 +94,33 @@ public void setCustomName(String name) { @Override public boolean isLocked() { - return !this.getSnapshot().lockKey.key().isEmpty(); + return this.getSnapshot().lockKey != ChestLock.NO_LOCK; } @Override public String getLock() { - return this.getSnapshot().lockKey.key(); + Optional customName = this.getSnapshot().lockKey.predicate().components().asPatch().get(DataComponents.CUSTOM_NAME); + + return (customName != null) ? customName.map(CraftChatMessage::fromComponent).orElse("") : ""; } @Override public void setLock(String key) { - this.getSnapshot().lockKey = (key == null) ? LockCode.NO_LOCK : new LockCode(key); + if (key == null) { + this.getSnapshot().lockKey = ChestLock.NO_LOCK; + } else { + DataComponentPredicate predicate = DataComponentPredicate.builder().expect(DataComponents.CUSTOM_NAME, CraftChatMessage.fromStringOrNull(key)).build(); + this.getSnapshot().lockKey = new ChestLock(new CriterionConditionItem(Optional.empty(), CriterionConditionValue.IntegerRange.ANY, predicate, Collections.emptyMap())); + } + } + + @Override + public void setLockItem(ItemStack key) { + if (key == null) { + this.getSnapshot().lockKey = ChestLock.NO_LOCK; + } else { + this.getSnapshot().lockKey = new ChestLock(CraftItemStack.asCriterionConditionItem(key)); + } } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java index b5bc9b22..d77cea20 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.BedBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityBed; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Bed; -public class CraftBed extends CraftBlockEntityState implements Bed { +public class CraftBed extends CraftBlockEntityState implements Bed { - public CraftBed(World world, BedBlockEntity tileEntity) { + public CraftBed(World world, TileEntityBed tileEntity) { super(world, tileEntity); } @@ -18,7 +18,7 @@ protected CraftBed(CraftBed state, Location location) { @Override public DyeColor getColor() { - switch (this.getType()) { + switch (getType()) { case BLACK_BED: return DyeColor.BLACK; case BLUE_BED: @@ -52,7 +52,7 @@ public DyeColor getColor() { case YELLOW_BED: return DyeColor.YELLOW; default: - throw new IllegalArgumentException("Unknown DyeColor for " + this.getType()); + throw new IllegalArgumentException("Unknown DyeColor for " + getType()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBeehive.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBeehive.java index fbacbef0..a423534e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBeehive.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBeehive.java @@ -5,8 +5,8 @@ import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.block.entity.BeehiveBlockEntity; -import net.minecraft.world.level.block.entity.BeehiveBlockEntity.BeeReleaseStatus; +import net.minecraft.world.level.block.entity.TileEntityBeehive; +import net.minecraft.world.level.block.entity.TileEntityBeehive.ReleaseStatus; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Beehive; @@ -14,9 +14,9 @@ import org.bukkit.craftbukkit.util.CraftLocation; import org.bukkit.entity.Bee; -public class CraftBeehive extends CraftBlockEntityState implements Beehive { +public class CraftBeehive extends CraftBlockEntityState implements Beehive { - public CraftBeehive(World world, BeehiveBlockEntity tileEntity) { + public CraftBeehive(World world, TileEntityBeehive tileEntity) { super(world, tileEntity); } @@ -26,52 +26,52 @@ protected CraftBeehive(CraftBeehive state, Location location) { @Override public Location getFlower() { - BlockPos flower = this.getSnapshot().savedFlowerPos; - return (flower == null) ? null : CraftLocation.toBukkit(flower, this.getWorld()); + BlockPos flower = getSnapshot().savedFlowerPos; + return (flower == null) ? null : CraftLocation.toBukkit(flower, getWorld()); } @Override public void setFlower(Location location) { Preconditions.checkArgument(location == null || this.getWorld().equals(location.getWorld()), "Flower must be in same world"); - this.getSnapshot().savedFlowerPos = (location == null) ? null : CraftLocation.toBlockPosition(location); + getSnapshot().savedFlowerPos = (location == null) ? null : CraftLocation.toBlockPos(location); } @Override public boolean isFull() { - return this.getSnapshot().isFull(); + return getSnapshot().isFull(); } @Override public boolean isSedated() { - return this.isPlaced() && this.getTileEntity().isSedated(); + return isPlaced() && getTileEntity().isSedated(); } @Override public int getEntityCount() { - return this.getSnapshot().getOccupantCount(); + return getSnapshot().getOccupantCount(); } @Override public int getMaxEntities() { - return this.getSnapshot().maxBees; + return getSnapshot().maxBees; } @Override public void setMaxEntities(int max) { Preconditions.checkArgument(max > 0, "Max bees must be more than 0"); - this.getSnapshot().maxBees = max; + getSnapshot().maxBees = max; } @Override public List releaseEntities() { - this.ensureNoWorldGeneration(); + ensureNoWorldGeneration(); List bees = new ArrayList<>(); - if (this.isPlaced()) { - BeehiveBlockEntity beehive = ((BeehiveBlockEntity) this.getTileEntityFromWorld()); - for (Entity bee : beehive.releaseBees(this.getHandle(), BeeReleaseStatus.BEE_RELEASED, true)) { + if (isPlaced()) { + TileEntityBeehive beehive = ((TileEntityBeehive) this.getTileEntityFromWorld()); + for (Entity bee : beehive.releaseBees(this.getHandle(), ReleaseStatus.BEE_RELEASED, true)) { bees.add((Bee) bee.getBukkitEntity()); } } @@ -83,7 +83,7 @@ public List releaseEntities() { public void addEntity(Bee entity) { Preconditions.checkArgument(entity != null, "Entity must not be null"); - this.getSnapshot().addOccupant(((CraftBee) entity).getHandle()); + getSnapshot().addOccupant(((CraftBee) entity).getHandle()); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java index a816667b..824283a8 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.block; import com.google.common.base.Preconditions; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.BellBlock; +import net.minecraft.core.EnumDirection; +import net.minecraft.world.level.block.BlockBell; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.BellBlockEntity; -import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.entity.TileEntityBell; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Bell; @@ -13,9 +13,9 @@ import org.bukkit.craftbukkit.entity.CraftEntity; import org.bukkit.entity.Entity; -public class CraftBell extends CraftBlockEntityState implements Bell { +public class CraftBell extends CraftBlockEntityState implements Bell { - public CraftBell(World world, BellBlockEntity tileEntity) { + public CraftBell(World world, TileEntityBell tileEntity) { super(world, tileEntity); } @@ -27,50 +27,50 @@ protected CraftBell(CraftBell state, Location location) { public boolean ring(Entity entity, BlockFace direction) { Preconditions.checkArgument(direction == null || direction.isCartesian(), "direction must be cartesian, given %s", direction); - BlockEntity tileEntity = this.getTileEntityFromWorld(); + TileEntity tileEntity = getTileEntityFromWorld(); if (tileEntity == null) { return false; } net.minecraft.world.entity.Entity nmsEntity = (entity != null) ? ((CraftEntity) entity).getHandle() : null; - Direction enumDirection = CraftBlock.blockFaceToNotch(direction); + EnumDirection enumDirection = CraftBlock.blockFaceToNotch(direction); - return ((BellBlock) Blocks.BELL).attemptToRing(nmsEntity, this.world.getHandle(), this.getPosition(), enumDirection); + return ((BlockBell) Blocks.BELL).attemptToRing(nmsEntity, world.getHandle(), getPosition(), enumDirection); } @Override public boolean ring(Entity entity) { - return this.ring(entity, null); + return ring(entity, null); } @Override public boolean ring(BlockFace direction) { - return this.ring(null, direction); + return ring(null, direction); } @Override public boolean ring() { - return this.ring(null, null); + return ring(null, null); } @Override public boolean isShaking() { - return this.getSnapshot().shaking; + return getSnapshot().shaking; } @Override public int getShakingTicks() { - return this.getSnapshot().ticks; + return getSnapshot().ticks; } @Override public boolean isResonating() { - return this.getSnapshot().resonating; + return getSnapshot().resonating; } @Override public int getResonatingTicks() { - return this.isResonating() ? this.getSnapshot().ticks : 0; + return isResonating() ? getSnapshot().ticks : 0; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBiome.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBiome.java index 95b95680..7a668c6b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBiome.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBiome.java @@ -2,7 +2,9 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; +import net.minecraft.world.level.biome.BiomeBase; import org.bukkit.Registry; import org.bukkit.block.Biome; import org.bukkit.craftbukkit.CraftRegistry; @@ -10,10 +12,10 @@ public class CraftBiome { - public static Biome minecraftToBukkit(net.minecraft.world.level.biome.Biome minecraft) { + public static Biome minecraftToBukkit(BiomeBase minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.BIOME); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.BIOME); Biome bukkit = Registry.BIOME.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); if (bukkit == null) { @@ -23,11 +25,11 @@ public static Biome minecraftToBukkit(net.minecraft.world.level.biome.Biome mine return bukkit; } - public static Biome minecraftHolderToBukkit(Holder minecraft) { - return CraftBiome.minecraftToBukkit(minecraft.value()); + public static Biome minecraftHolderToBukkit(Holder minecraft) { + return minecraftToBukkit(minecraft.value()); } - public static net.minecraft.world.level.biome.Biome bukkitToMinecraft(Biome bukkit) { + public static BiomeBase bukkitToMinecraft(Biome bukkit) { if (bukkit == null || bukkit == Biome.CUSTOM) { return null; } @@ -36,14 +38,14 @@ public static net.minecraft.world.level.biome.Biome bukkitToMinecraft(Biome bukk .getOptional(CraftNamespacedKey.toMinecraft(bukkit.getKey())).orElseThrow(); } - public static Holder bukkitToMinecraftHolder(Biome bukkit) { + public static Holder bukkitToMinecraftHolder(Biome bukkit) { if (bukkit == null || bukkit == Biome.CUSTOM) { return null; } - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.BIOME); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.BIOME); - if (registry.wrapAsHolder(CraftBiome.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java index f9cfdaf6..bb0dca41 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityBlastFurnace; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.BlastFurnace; -public class CraftBlastFurnace extends CraftFurnace implements BlastFurnace { +public class CraftBlastFurnace extends CraftFurnace implements BlastFurnace { - public CraftBlastFurnace(World world, BlastFurnaceBlockEntity tileEntity) { + public CraftBlastFurnace(World world, TileEntityBlastFurnace tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java index a1c1a101..8cabeaca 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java @@ -75,38 +75,38 @@ public static CraftBlock at(LevelAccessor world, BlockPos position) { } public net.minecraft.world.level.block.state.BlockState getNMS() { - return this.world.getBlockState(this.position); + return world.getBlockState(position); } public BlockPos getPosition() { - return this.position; + return position; } public LevelAccessor getHandle() { - return this.world; + return world; } @Override public World getWorld() { - return this.world.getMinecraftWorld().getWorld(); + return world.getMinecraftWorld().getWorld(); } public CraftWorld getCraftWorld() { - return (CraftWorld) this.getWorld(); + return (CraftWorld) getWorld(); } @Override public Location getLocation() { - return CraftLocation.toBukkit(this.position, this.getWorld()); + return CraftLocation.toBukkit(position, getWorld()); } @Override public Location getLocation(Location loc) { if (loc != null) { - loc.setWorld(this.getWorld()); - loc.setX(this.position.getX()); - loc.setY(this.position.getY()); - loc.setZ(this.position.getZ()); + loc.setWorld(getWorld()); + loc.setX(position.getX()); + loc.setY(position.getY()); + loc.setZ(position.getZ()); loc.setYaw(0); loc.setPitch(0); } @@ -115,80 +115,80 @@ public Location getLocation(Location loc) { } public BlockVector getVector() { - return new BlockVector(this.getX(), this.getY(), this.getZ()); + return new BlockVector(getX(), getY(), getZ()); } @Override public int getX() { - return this.position.getX(); + return position.getX(); } @Override public int getY() { - return this.position.getY(); + return position.getY(); } @Override public int getZ() { - return this.position.getZ(); + return position.getZ(); } @Override public Chunk getChunk() { - return this.getWorld().getChunkAt(this); + return getWorld().getChunkAt(this); } public void setData(final byte data) { - this.setData(data, 3); + setData(data, 3); } public void setData(final byte data, boolean applyPhysics) { if (applyPhysics) { - this.setData(data, 3); + setData(data, 3); } else { - this.setData(data, 2); + setData(data, 2); } } private void setData(final byte data, int flag) { - this.world.setBlock(this.position, CraftMagicNumbers.getBlock(this.getType(), data), flag); + world.setBlock(position, CraftMagicNumbers.getBlock(getType(), data), flag); } @Override public byte getData() { - net.minecraft.world.level.block.state.BlockState blockData = this.world.getBlockState(this.position); + net.minecraft.world.level.block.state.BlockState blockData = world.getBlockState(position); return CraftMagicNumbers.toLegacyData(blockData); } @Override public BlockData getBlockData() { - return CraftBlockData.fromData(this.getNMS()); + return CraftBlockData.fromData(getNMS()); } @Override public void setType(final Material type) { - this.setType(type, true); + setType(type, true); } @Override public void setType(Material type, boolean applyPhysics) { Preconditions.checkArgument(type != null, "Material cannot be null"); - this.setBlockData(type.createBlockData(), applyPhysics); + setBlockData(type.createBlockData(), applyPhysics); } @Override public void setBlockData(BlockData data) { - this.setBlockData(data, true); + setBlockData(data, true); } @Override public void setBlockData(BlockData data, boolean applyPhysics) { Preconditions.checkArgument(data != null, "BlockData cannot be null"); - this.setTypeAndData(((CraftBlockData) data).getState(), applyPhysics); + setTypeAndData(((CraftBlockData) data).getState(), applyPhysics); } boolean setTypeAndData(final net.minecraft.world.level.block.state.BlockState blockData, final boolean applyPhysics) { - return CraftBlock.setTypeAndData(this.world, this.position, this.getNMS(), blockData, applyPhysics); + return setTypeAndData(world, position, getNMS(), blockData, applyPhysics); } public static boolean setTypeAndData(LevelAccessor world, BlockPos position, net.minecraft.world.level.block.state.BlockState old, net.minecraft.world.level.block.state.BlockState blockData, boolean applyPhysics) { @@ -220,45 +220,45 @@ public static boolean setTypeAndData(LevelAccessor world, BlockPos position, net @Override public Material getType() { - return CraftBlockType.minecraftToBukkit(this.world.getBlockState(this.position).getBlock()); + return CraftBlockType.minecraftToBukkit(world.getBlockState(position).getBlock()); } @Override public byte getLightLevel() { - return (byte) this.world.getMinecraftWorld().getMaxLocalRawBrightness(this.position); + return (byte) world.getMinecraftWorld().getMaxLocalRawBrightness(position); } @Override public byte getLightFromSky() { - return (byte) this.world.getBrightness(LightLayer.SKY, this.position); + return (byte) world.getBrightness(LightLayer.SKY, position); } @Override public byte getLightFromBlocks() { - return (byte) this.world.getBrightness(LightLayer.BLOCK, this.position); + return (byte) world.getBrightness(LightLayer.BLOCK, position); } public Block getFace(final BlockFace face) { - return this.getRelative(face, 1); + return getRelative(face, 1); } public Block getFace(final BlockFace face, final int distance) { - return this.getRelative(face, distance); + return getRelative(face, distance); } @Override public Block getRelative(final int modX, final int modY, final int modZ) { - return this.getWorld().getBlockAt(this.getX() + modX, this.getY() + modY, this.getZ() + modZ); + return getWorld().getBlockAt(getX() + modX, getY() + modY, getZ() + modZ); } @Override public Block getRelative(BlockFace face) { - return this.getRelative(face, 1); + return getRelative(face, 1); } @Override public Block getRelative(BlockFace face, int distance) { - return this.getRelative(face.getModX() * distance, face.getModY() * distance, face.getModZ() * distance); + return getRelative(face.getModX() * distance, face.getModY() * distance, face.getModZ() * distance); } @Override @@ -276,7 +276,7 @@ public BlockFace getFace(final Block block) { @Override public String toString() { - return "CraftBlock{pos=" + this.position + ",type=" + this.getType() + ",data=" + this.getNMS() + ",fluid=" + this.world.getFluidState(this.position) + '}'; + return "CraftBlock{pos=" + position + ",type=" + getType() + ",data=" + getNMS() + ",fluid=" + world.getFluidState(position) + '}'; } public static BlockFace notchToBlockFace(Direction notch) { @@ -330,32 +330,32 @@ public BlockState getState() { @Override public Biome getBiome() { - return this.getWorld().getBiome(this.getX(), this.getY(), this.getZ()); + return getWorld().getBiome(getX(), getY(), getZ()); } @Override public void setBiome(Biome bio) { - this.getWorld().setBiome(this.getX(), this.getY(), this.getZ(), bio); + getWorld().setBiome(getX(), getY(), getZ(), bio); } @Override public double getTemperature() { - return this.world.getBiome(this.position).value().getTemperature(this.position); + return world.getBiome(position).value().getTemperature(position, world.getSeaLevel()); } @Override public double getHumidity() { - return this.getWorld().getHumidity(this.getX(), this.getY(), this.getZ()); + return getWorld().getHumidity(getX(), getY(), getZ()); } @Override public boolean isBlockPowered() { - return this.world.getMinecraftWorld().getDirectSignalTo(this.position) > 0; + return world.getMinecraftWorld().getDirectSignalTo(position) > 0; } @Override public boolean isBlockIndirectlyPowered() { - return this.world.getMinecraftWorld().hasNeighborSignal(this.position); + return world.getMinecraftWorld().hasNeighborSignal(position); } @Override @@ -377,14 +377,14 @@ public int hashCode() { @Override public boolean isBlockFacePowered(BlockFace face) { - return this.world.getMinecraftWorld().hasSignal(this.position, CraftBlock.blockFaceToNotch(face)); + return world.getMinecraftWorld().hasSignal(position, blockFaceToNotch(face)); } @Override public boolean isBlockFaceIndirectlyPowered(BlockFace face) { - int power = this.world.getMinecraftWorld().getSignal(this.position, CraftBlock.blockFaceToNotch(face)); + int power = world.getMinecraftWorld().getSignal(position, blockFaceToNotch(face)); - Block relative = this.getRelative(face); + Block relative = getRelative(face); if (relative.getType() == Material.REDSTONE_WIRE) { return Math.max(power, relative.getData()) > 0; } @@ -396,16 +396,16 @@ public boolean isBlockFaceIndirectlyPowered(BlockFace face) { public int getBlockPower(BlockFace face) { int power = 0; net.minecraft.world.level.Level world = this.world.getMinecraftWorld(); - int x = this.getX(); - int y = this.getY(); - int z = this.getZ(); - if ((face == BlockFace.DOWN || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y - 1, z), Direction.DOWN)) power = CraftBlock.getPower(power, world.getBlockState(new BlockPos(x, y - 1, z))); - if ((face == BlockFace.UP || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y + 1, z), Direction.UP)) power = CraftBlock.getPower(power, world.getBlockState(new BlockPos(x, y + 1, z))); - if ((face == BlockFace.EAST || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x + 1, y, z), Direction.EAST)) power = CraftBlock.getPower(power, world.getBlockState(new BlockPos(x + 1, y, z))); - if ((face == BlockFace.WEST || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x - 1, y, z), Direction.WEST)) power = CraftBlock.getPower(power, world.getBlockState(new BlockPos(x - 1, y, z))); - if ((face == BlockFace.NORTH || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y, z - 1), Direction.NORTH)) power = CraftBlock.getPower(power, world.getBlockState(new BlockPos(x, y, z - 1))); - if ((face == BlockFace.SOUTH || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y, z + 1), Direction.SOUTH)) power = CraftBlock.getPower(power, world.getBlockState(new BlockPos(x, y, z + 1))); - return power > 0 ? power : (face == BlockFace.SELF ? this.isBlockIndirectlyPowered() : this.isBlockFaceIndirectlyPowered(face)) ? 15 : 0; + int x = getX(); + int y = getY(); + int z = getZ(); + if ((face == BlockFace.DOWN || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y - 1, z), Direction.DOWN)) power = getPower(power, world.getBlockState(new BlockPos(x, y - 1, z))); + if ((face == BlockFace.UP || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y + 1, z), Direction.UP)) power = getPower(power, world.getBlockState(new BlockPos(x, y + 1, z))); + if ((face == BlockFace.EAST || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x + 1, y, z), Direction.EAST)) power = getPower(power, world.getBlockState(new BlockPos(x + 1, y, z))); + if ((face == BlockFace.WEST || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x - 1, y, z), Direction.WEST)) power = getPower(power, world.getBlockState(new BlockPos(x - 1, y, z))); + if ((face == BlockFace.NORTH || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y, z - 1), Direction.NORTH)) power = getPower(power, world.getBlockState(new BlockPos(x, y, z - 1))); + if ((face == BlockFace.SOUTH || face == BlockFace.SELF) && world.hasSignal(new BlockPos(x, y, z + 1), Direction.SOUTH)) power = getPower(power, world.getBlockState(new BlockPos(x, y, z + 1))); + return power > 0 ? power : (face == BlockFace.SELF ? isBlockIndirectlyPowered() : isBlockFaceIndirectlyPowered(face)) ? 15 : 0; } private static int getPower(int i, net.minecraft.world.level.block.state.BlockState iblockdata) { @@ -420,27 +420,27 @@ private static int getPower(int i, net.minecraft.world.level.block.state.BlockSt @Override public int getBlockPower() { - return this.getBlockPower(BlockFace.SELF); + return getBlockPower(BlockFace.SELF); } @Override public boolean isEmpty() { - return this.getNMS().isAir(); + return getNMS().isAir(); } @Override public boolean isLiquid() { - return this.getNMS().liquid(); + return getNMS().liquid(); } @Override public PistonMoveReaction getPistonMoveReaction() { - return PistonMoveReaction.getById(this.getNMS().getPistonPushReaction().ordinal()); + return PistonMoveReaction.getById(getNMS().getPistonPushReaction().ordinal()); } @Override public boolean breakNaturally() { - return this.breakNaturally(null); + return breakNaturally(null); } @Override @@ -453,20 +453,20 @@ public boolean breakNaturally(ItemStack item) { // Modelled off EntityHuman#hasBlock if (block != Blocks.AIR && (item == null || !iblockdata.requiresCorrectToolForDrops() || nmsItem.isCorrectToolForDrops(iblockdata))) { - net.minecraft.world.level.block.Block.dropResources(iblockdata, this.world.getMinecraftWorld(), this.position, this.world.getBlockEntity(this.position), null, nmsItem); + net.minecraft.world.level.block.Block.dropResources(iblockdata, world.getMinecraftWorld(), position, world.getBlockEntity(position), null, nmsItem); result = true; } // SPIGOT-6778: Directly call setBlock instead of setTypeAndData, so that the tile entiy is not removed and custom remove logic is run. - return this.world.setBlock(this.position, Blocks.AIR.defaultBlockState(), 3) && result; + return world.setBlock(position, Blocks.AIR.defaultBlockState(), 3) && result; } @Override public boolean applyBoneMeal(BlockFace face) { - Direction direction = CraftBlock.blockFaceToNotch(face); + Direction direction = blockFaceToNotch(face); BlockFertilizeEvent event = null; - ServerLevel world = this.getCraftWorld().getHandle(); - UseOnContext context = new UseOnContext(world, null, InteractionHand.MAIN_HAND, Items.BONE_MEAL.getDefaultInstance(), new BlockHitResult(Vec3.ZERO, direction, this.getPosition(), false)); + ServerLevel world = getCraftWorld().getHandle(); + UseOnContext context = new UseOnContext(world, null, InteractionHand.MAIN_HAND, Items.BONE_MEAL.getDefaultInstance(), new BlockHitResult(Vec3.ZERO, direction, getPosition(), false)); // SPIGOT-6895: Call StructureGrowEvent and BlockFertilizeEvent world.captureTreeGeneration = true; @@ -481,11 +481,11 @@ public boolean applyBoneMeal(BlockFace face) { StructureGrowEvent structureEvent = null; if (treeType != null) { - structureEvent = new StructureGrowEvent(this.getLocation(), treeType, true, null, blocks); + structureEvent = new StructureGrowEvent(getLocation(), treeType, true, null, blocks); Bukkit.getPluginManager().callEvent(structureEvent); } - event = new BlockFertilizeEvent(CraftBlock.at(world, this.getPosition()), null, blocks); + event = new BlockFertilizeEvent(CraftBlock.at(world, getPosition()), null, blocks); event.setCancelled(structureEvent != null && structureEvent.isCancelled()); Bukkit.getPluginManager().callEvent(event); @@ -501,22 +501,22 @@ public boolean applyBoneMeal(BlockFace face) { @Override public Collection getDrops() { - return this.getDrops(null); + return getDrops(null); } @Override public Collection getDrops(ItemStack item) { - return this.getDrops(item, null); + return getDrops(item, null); } @Override public Collection getDrops(ItemStack item, Entity entity) { - net.minecraft.world.level.block.state.BlockState iblockdata = this.getNMS(); + net.minecraft.world.level.block.state.BlockState iblockdata = getNMS(); net.minecraft.world.item.ItemStack nms = CraftItemStack.asNMSCopy(item); // Modelled off EntityHuman#hasBlock if (item == null || CraftBlockData.isPreferredTool(iblockdata, nms)) { - return net.minecraft.world.level.block.Block.getDrops(iblockdata, (ServerLevel) this.world.getMinecraftWorld(), this.position, this.world.getBlockEntity(this.position), entity == null ? null : ((CraftEntity) entity).getHandle(), nms) + return net.minecraft.world.level.block.Block.getDrops(iblockdata, (ServerLevel) world.getMinecraftWorld(), position, world.getBlockEntity(position), entity == null ? null : ((CraftEntity) entity).getHandle(), nms) .stream().map(CraftItemStack::asBukkitCopy).collect(Collectors.toList()); } else { return Collections.emptyList(); @@ -525,7 +525,7 @@ public Collection getDrops(ItemStack item, Entity entity) { @Override public boolean isPreferredTool(ItemStack item) { - net.minecraft.world.level.block.state.BlockState iblockdata = this.getNMS(); + net.minecraft.world.level.block.state.BlockState iblockdata = getNMS(); net.minecraft.world.item.ItemStack nms = CraftItemStack.asNMSCopy(item); return CraftBlockData.isPreferredTool(iblockdata, nms); } @@ -533,32 +533,32 @@ public boolean isPreferredTool(ItemStack item) { @Override public float getBreakSpeed(Player player) { Preconditions.checkArgument(player != null, "player cannot be null"); - return this.getNMS().getDestroyProgress(((CraftPlayer) player).getHandle(), this.world, this.position); + return getNMS().getDestroyProgress(((CraftPlayer) player).getHandle(), world, position); } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - this.getCraftWorld().getBlockMetadata().setMetadata(this, metadataKey, newMetadataValue); + getCraftWorld().getBlockMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List getMetadata(String metadataKey) { - return this.getCraftWorld().getBlockMetadata().getMetadata(this, metadataKey); + return getCraftWorld().getBlockMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { - return this.getCraftWorld().getBlockMetadata().hasMetadata(this, metadataKey); + return getCraftWorld().getBlockMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { - this.getCraftWorld().getBlockMetadata().removeMetadata(this, metadataKey, owningPlugin); + getCraftWorld().getBlockMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override public boolean isPassable() { - return this.getNMS().getCollisionShape(this.world, this.position).isEmpty(); + return this.getNMS().getCollisionShape(world, position).isEmpty(); } @Override @@ -577,42 +577,42 @@ public RayTraceResult rayTrace(Location start, Vector direction, double maxDista } Vector dir = direction.clone().normalize().multiply(maxDistance); - Vec3 startPos = CraftLocation.toVec3D(start); - Vec3 endPos = startPos.add(dir.getX(), dir.getY(), dir.getZ()); + Vec3D startPos = CraftLocation.toVec3D(start); + Vec3D endPos = startPos.add(dir.getX(), dir.getY(), dir.getZ()); - HitResult nmsHitResult = this.world.clip(new ClipContext(startPos, endPos, ClipContext.Block.OUTLINE, CraftFluidCollisionMode.toNMS(fluidCollisionMode), CollisionContext.empty()), this.position); + MovingObjectPosition nmsHitResult = world.clip(new RayTrace(startPos, endPos, RayTrace.BlockCollisionOption.OUTLINE, CraftFluidCollisionMode.toNMS(fluidCollisionMode), VoxelShapeCollision.empty()), position); return CraftRayTraceResult.fromNMS(this.getWorld(), nmsHitResult); } @Override public BoundingBox getBoundingBox() { - VoxelShape shape = this.getNMS().getShape(this.world, this.position); + VoxelShape shape = getNMS().getShape(world, position); if (shape.isEmpty()) { return new BoundingBox(); // Return an empty bounding box if the block has no dimension } - AABB aabb = shape.bounds(); - return new BoundingBox(this.getX() + aabb.minX, this.getY() + aabb.minY, this.getZ() + aabb.minZ, this.getX() + aabb.maxX, this.getY() + aabb.maxY, this.getZ() + aabb.maxZ); + AxisAlignedBB aabb = shape.bounds(); + return new BoundingBox(getX() + aabb.minX, getY() + aabb.minY, getZ() + aabb.minZ, getX() + aabb.maxX, getY() + aabb.maxY, getZ() + aabb.maxZ); } @Override public org.bukkit.util.VoxelShape getCollisionShape() { - VoxelShape shape = this.getNMS().getCollisionShape(this.world, this.position); + VoxelShape shape = getNMS().getCollisionShape(world, position); return new CraftVoxelShape(shape); } @Override public boolean canPlace(BlockData data) { Preconditions.checkArgument(data != null, "BlockData cannot be null"); - net.minecraft.world.level.block.state.BlockState iblockdata = ((CraftBlockData) data).getState(); - net.minecraft.world.level.Level world = this.world.getMinecraftWorld(); + net.minecraft.world.level.block.state.BlockState iblockdata = ((CraftBlockData) data).getState(); + net.minecraft.world.level.World world = this.world.getMinecraftWorld(); return iblockdata.canSurvive(world, this.position); } @Override public String getTranslationKey() { - return this.getNMS().getBlock().getDescriptionId(); + return getNMS().getBlock().getDescriptionId(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java index 87d2e77f..3a1e4818 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.block; import java.util.Set; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.IRegistryCustom; import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponentType; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; -import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.network.protocol.game.PacketListenerPlayOut; +import net.minecraft.network.protocol.game.PacketPlayOutTileEntityData; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.GeneratorAccess; +import net.minecraft.world.level.block.entity.TileEntity; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.TileState; @@ -20,7 +20,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class CraftBlockEntityState extends CraftBlockState implements TileState { +public class CraftBlockEntityState extends CraftBlockState implements TileState { private final T tileEntity; private final T snapshot; @@ -32,22 +32,22 @@ public CraftBlockEntityState(World world, T tileEntity) { // copy tile entity data: this.snapshot = this.createSnapshot(tileEntity); - this.load(this.snapshot); + this.load(snapshot); } protected CraftBlockEntityState(CraftBlockEntityState state, Location location) { super(state, location); - this.tileEntity = this.createSnapshot(state.snapshot); - this.snapshot = this.tileEntity; - this.loadData(state.getSnapshotNBT()); + this.tileEntity = createSnapshot(state.snapshot); + this.snapshot = tileEntity; + loadData(state.getSnapshotNBT()); } public void refreshSnapshot() { - this.load(this.tileEntity); + this.load(tileEntity); } - private RegistryAccess getRegistryAccess() { - LevelAccessor worldHandle = this.getWorldHandle(); + private IRegistryCustom getRegistryAccess() { + GeneratorAccess worldHandle = getWorldHandle(); return (worldHandle != null) ? worldHandle.registryAccess() : MinecraftServer.getDefaultRegistryAccess(); } @@ -56,67 +56,75 @@ private T createSnapshot(T tileEntity) { return null; } - CompoundTag nbtTagCompound = tileEntity.saveWithFullMetadata(this.getRegistryAccess()); - T snapshot = (T) BlockEntity.loadStatic(this.getPosition(), this.getHandle(), nbtTagCompound, this.getRegistryAccess()); + NBTTagCompound nbtTagCompound = tileEntity.saveWithFullMetadata(getRegistryAccess()); + T snapshot = (T) TileEntity.loadStatic(getPosition(), getHandle(), nbtTagCompound, getRegistryAccess()); return snapshot; } public Set> applyComponents(DataComponentMap datacomponentmap, DataComponentPatch datacomponentpatch) { Set> result = snapshot.applyComponentsSet(datacomponentmap, datacomponentpatch); - this.load(this.snapshot); + load(snapshot); return result; } public DataComponentMap collectComponents() { - return this.snapshot.collectComponents(); + return snapshot.collectComponents(); } // Loads the specified data into the snapshot TileEntity. - public void loadData(CompoundTag nbtTagCompound) { - this.snapshot.loadWithComponents(nbtTagCompound, this.getRegistryAccess()); - this.load(this.snapshot); + public void loadData(NBTTagCompound nbtTagCompound) { + snapshot.loadWithComponents(nbtTagCompound, getRegistryAccess()); + load(snapshot); } // copies the TileEntity-specific data, retains the position private void copyData(T from, T to) { - CompoundTag nbtTagCompound = from.saveWithFullMetadata(this.getRegistryAccess()); - to.loadWithComponents(nbtTagCompound, this.getRegistryAccess()); + NBTTagCompound nbtTagCompound = from.saveWithFullMetadata(getRegistryAccess()); + to.loadWithComponents(nbtTagCompound, getRegistryAccess()); } // gets the wrapped TileEntity - public T getTileEntity() { - return this.tileEntity; + protected T getTileEntity() { + return tileEntity; } // gets the cloned TileEntity which is used to store the captured data protected T getSnapshot() { - return this.snapshot; + return snapshot; } // gets the current TileEntity from the world at this position - protected BlockEntity getTileEntityFromWorld() { - this.requirePlaced(); + protected TileEntity getTileEntityFromWorld() { + requirePlaced(); - return this.getWorldHandle().getBlockEntity(this.getPosition()); + return getWorldHandle().getBlockEntity(this.getPosition()); } // gets the NBT data of the TileEntity represented by this block state - public CompoundTag getSnapshotNBT() { + public NBTTagCompound getSnapshotNBT() { // update snapshot - this.applyTo(this.snapshot); + applyTo(snapshot); - return this.snapshot.saveWithFullMetadata(this.getRegistryAccess()); + return snapshot.saveWithFullMetadata(getRegistryAccess()); } - public CompoundTag getSnapshotNBTWithoutComponents() { - CompoundTag nbt = this.getSnapshotNBT(); - this.snapshot.removeComponentsFromTag(nbt); + public NBTTagCompound getItemNBT() { + // update snapshot + applyTo(snapshot); + + // See TileEntity#saveToItem + NBTTagCompound nbt = snapshot.saveCustomOnly(getRegistryAccess()); + snapshot.removeComponentsFromTag(nbt); return nbt; } + public void addEntityType(NBTTagCompound nbt) { + TileEntity.addEntityType(nbt, snapshot.getType()); + } + // gets the packet data of the TileEntity represented by this block state - public CompoundTag getUpdateNBT() { + public NBTTagCompound getUpdateNBT() { // update snapshot applyTo(snapshot); @@ -125,19 +133,19 @@ public CompoundTag getUpdateNBT() { // copies the data of the given tile entity to this block state protected void load(T tileEntity) { - if (tileEntity != null && tileEntity != this.snapshot) { - this.copyData(tileEntity, this.snapshot); + if (tileEntity != null && tileEntity != snapshot) { + copyData(tileEntity, snapshot); } } // applies the TileEntity data of this block state to the given TileEntity protected void applyTo(T tileEntity) { - if (tileEntity != null && tileEntity != this.snapshot) { - this.copyData(this.snapshot, tileEntity); + if (tileEntity != null && tileEntity != snapshot) { + copyData(snapshot, tileEntity); } } - protected boolean isApplicable(BlockEntity tileEntity) { + protected boolean isApplicable(TileEntity tileEntity) { return tileEntity != null && this.tileEntity.getClass() == tileEntity.getClass(); } @@ -146,10 +154,10 @@ public boolean update(boolean force, boolean applyPhysics) { boolean result = super.update(force, applyPhysics); if (result && this.isPlaced()) { - BlockEntity tile = this.getTileEntityFromWorld(); + TileEntity tile = getTileEntityFromWorld(); - if (this.isApplicable(tile)) { - this.applyTo((T) tile); + if (isApplicable(tile)) { + applyTo((T) tile); tile.setChanged(); } } @@ -163,8 +171,8 @@ public PersistentDataContainer getPersistentDataContainer() { } @Nullable - public Packet getUpdatePacket(@NotNull Location location) { - return new ClientboundBlockEntityDataPacket(CraftLocation.toBlockPosition(location), snapshot.getType(), getUpdateNBT()); + public Packet getUpdatePacket(@NotNull Location location) { + return new PacketPlayOutTileEntityData(CraftLocation.toBlockPos(location), snapshot.getType(), getUpdateNBT()); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java index fabdec2d..36294584 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java @@ -5,7 +5,8 @@ import java.util.List; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.GeneratorAccess; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; @@ -26,15 +27,15 @@ public class CraftBlockState implements BlockState { protected final CraftWorld world; private final BlockPos position; - protected net.minecraft.world.level.block.state.BlockState data; + protected IBlockData data; protected int flag; - private WeakReference weakWorld; + private WeakReference weakWorld; protected CraftBlockState(final Block block) { this(block.getWorld(), ((CraftBlock) block).getPosition(), ((CraftBlock) block).getNMS()); this.flag = 3; - this.setWorldHandle(((CraftBlock) block).getHandle()); + setWorldHandle(((CraftBlock) block).getHandle()); } protected CraftBlockState(final Block block, int flag) { @@ -43,10 +44,10 @@ protected CraftBlockState(final Block block, int flag) { } // world can be null for non-placed BlockStates. - protected CraftBlockState(@Nullable World world, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData) { + protected CraftBlockState(@Nullable World world, BlockPos blockPosition, IBlockData blockData) { this.world = (CraftWorld) world; - this.position = blockPosition; - this.data = blockData; + position = blockPosition; + data = blockData; } // Creates an unplaced copy of the given CraftBlockState at the given location @@ -56,15 +57,15 @@ protected CraftBlockState(CraftBlockState state, @Nullable Location location) { this.position = state.getPosition().immutable(); } else { this.world = (CraftWorld) location.getWorld(); - this.position = CraftLocation.toBlockPosition(location); + this.position = CraftLocation.toBlockPos(location); } this.data = state.data; this.flag = state.flag; - this.setWorldHandle(state.getWorldHandle()); + setWorldHandle(state.getWorldHandle()); } - public void setWorldHandle(LevelAccessor generatorAccess) { - if (generatorAccess instanceof net.minecraft.world.level.Level) { + public void setWorldHandle(GeneratorAccess generatorAccess) { + if (generatorAccess instanceof net.minecraft.world.level.World) { this.weakWorld = null; } else { this.weakWorld = new WeakReference<>(generatorAccess); @@ -73,57 +74,57 @@ public void setWorldHandle(LevelAccessor generatorAccess) { // Returns null if weakWorld is not available and the BlockState is not placed. // If this returns a World instead of only a GeneratorAccess, this implies that this BlockState is placed. - public LevelAccessor getWorldHandle() { - if (this.weakWorld == null) { - return this.isPlaced() ? this.world.getHandle() : null; + public GeneratorAccess getWorldHandle() { + if (weakWorld == null) { + return this.isPlaced() ? world.getHandle() : null; } - LevelAccessor access = this.weakWorld.get(); + GeneratorAccess access = weakWorld.get(); if (access == null) { - this.weakWorld = null; - return this.isPlaced() ? this.world.getHandle() : null; + weakWorld = null; + return this.isPlaced() ? world.getHandle() : null; } return access; } protected final boolean isWorldGeneration() { - LevelAccessor generatorAccess = this.getWorldHandle(); - return generatorAccess != null && !(generatorAccess instanceof net.minecraft.world.level.Level); + GeneratorAccess generatorAccess = this.getWorldHandle(); + return generatorAccess != null && !(generatorAccess instanceof net.minecraft.world.level.World); } protected final void ensureNoWorldGeneration() { - Preconditions.checkState(!this.isWorldGeneration(), "This operation is not supported during world generation!"); + Preconditions.checkState(!isWorldGeneration(), "This operation is not supported during world generation!"); } @Override public World getWorld() { - this.requirePlaced(); - return this.world; + requirePlaced(); + return world; } @Override public int getX() { - return this.position.getX(); + return position.getX(); } @Override public int getY() { - return this.position.getY(); + return position.getY(); } @Override public int getZ() { - return this.position.getZ(); + return position.getZ(); } @Override public Chunk getChunk() { - this.requirePlaced(); - return this.world.getChunkAt(this.getX() >> 4, this.getZ() >> 4); + requirePlaced(); + return world.getChunkAt(getX() >> 4, getZ() >> 4); } - public void setData(net.minecraft.world.level.block.state.BlockState data) { + public void setData(IBlockData data) { this.data = data; } @@ -131,13 +132,13 @@ public BlockPos getPosition() { return this.position; } - public net.minecraft.world.level.block.state.BlockState getHandle() { + public IBlockData getHandle() { return this.data; } @Override public BlockData getBlockData() { - return CraftBlockData.fromData(this.data); + return CraftBlockData.fromData(data); } @Override @@ -160,7 +161,7 @@ public void setData(final MaterialData data) { @Override public MaterialData getData() { - return CraftMagicNumbers.getMaterial(this.data); + return CraftMagicNumbers.getMaterial(data); } @Override @@ -175,7 +176,7 @@ public void setType(final Material type) { @Override public Material getType() { - return CraftBlockType.minecraftToBukkit(this.data.getBlock()); + return CraftBlockType.minecraftToBukkit(data.getBlock()); } public void setFlag(int flag) { @@ -183,49 +184,49 @@ public void setFlag(int flag) { } public int getFlag() { - return this.flag; + return flag; } @Override public byte getLightLevel() { - return this.getBlock().getLightLevel(); + return getBlock().getLightLevel(); } @Override public CraftBlock getBlock() { - this.requirePlaced(); - return CraftBlock.at(this.getWorldHandle(), this.position); + requirePlaced(); + return CraftBlock.at(getWorldHandle(), position); } @Override public boolean update() { - return this.update(false); + return update(false); } @Override public boolean update(boolean force) { - return this.update(force, true); + return update(force, true); } @Override public boolean update(boolean force, boolean applyPhysics) { - if (!this.isPlaced()) { + if (!isPlaced()) { return true; } - LevelAccessor access = this.getWorldHandle(); - CraftBlock block = this.getBlock(); + GeneratorAccess access = getWorldHandle(); + CraftBlock block = getBlock(); - if (block.getType() != this.getType()) { + if (block.getType() != getType()) { if (!force) { return false; } } - net.minecraft.world.level.block.state.BlockState newBlock = this.data; + IBlockData newBlock = this.data; block.setTypeAndData(newBlock, applyPhysics); - if (access instanceof net.minecraft.world.level.Level) { - this.world.getHandle().sendBlockUpdated( - this.position, + if (access instanceof net.minecraft.world.level.World) { + world.getHandle().sendBlockUpdated( + position, block.getNMS(), newBlock, 3 @@ -233,8 +234,8 @@ public boolean update(boolean force, boolean applyPhysics) { } // Update levers etc - if (false && applyPhysics && this.getData() instanceof Attachable) { // Call does not map to new API - this.world.getHandle().updateNeighborsAt(this.position.relative(CraftBlock.blockFaceToNotch(((Attachable) this.getData()).getAttachedFace())), newBlock.getBlock()); + if (false && applyPhysics && getData() instanceof Attachable) { // Call does not map to new API + world.getHandle().updateNeighborsAt(position.relative(CraftBlock.blockFaceToNotch(((Attachable) getData()).getAttachedFace())), newBlock.getBlock()); } return true; @@ -242,7 +243,7 @@ public boolean update(boolean force, boolean applyPhysics) { @Override public byte getRawData() { - return CraftMagicNumbers.toLegacyData(this.data); + return CraftMagicNumbers.toLegacyData(data); } @Override @@ -253,10 +254,10 @@ public Location getLocation() { @Override public Location getLocation(Location loc) { if (loc != null) { - loc.setWorld(this.world); - loc.setX(this.getX()); - loc.setY(this.getY()); - loc.setZ(this.getZ()); + loc.setWorld(world); + loc.setX(getX()); + loc.setY(getY()); + loc.setZ(getZ()); loc.setYaw(0); loc.setPitch(0); } @@ -266,7 +267,7 @@ public Location getLocation(Location loc) { @Override public void setRawData(byte data) { - this.data = CraftMagicNumbers.getBlock(this.getType(), data); + this.data = CraftMagicNumbers.getBlock(getType(), data); } @Override @@ -274,7 +275,7 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (this.getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final CraftBlockState other = (CraftBlockState) obj; @@ -301,35 +302,35 @@ public int hashCode() { @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - this.requirePlaced(); - this.world.getBlockMetadata().setMetadata(this.getBlock(), metadataKey, newMetadataValue); + requirePlaced(); + world.getBlockMetadata().setMetadata(getBlock(), metadataKey, newMetadataValue); } @Override public List getMetadata(String metadataKey) { - this.requirePlaced(); - return this.world.getBlockMetadata().getMetadata(this.getBlock(), metadataKey); + requirePlaced(); + return world.getBlockMetadata().getMetadata(getBlock(), metadataKey); } @Override public boolean hasMetadata(String metadataKey) { - this.requirePlaced(); - return this.world.getBlockMetadata().hasMetadata(this.getBlock(), metadataKey); + requirePlaced(); + return world.getBlockMetadata().hasMetadata(getBlock(), metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { - this.requirePlaced(); - this.world.getBlockMetadata().removeMetadata(this.getBlock(), metadataKey, owningPlugin); + requirePlaced(); + world.getBlockMetadata().removeMetadata(getBlock(), metadataKey, owningPlugin); } @Override public boolean isPlaced() { - return this.world != null; + return world != null; } protected void requirePlaced() { - Preconditions.checkState(this.isPlaced(), "The blockState must be placed to call this method"); + Preconditions.checkState(isPlaced(), "The blockState must be placed to call this method"); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockStates.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockStates.java index 97a7dacb..0e2b6604 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockStates.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockStates.java @@ -9,56 +9,58 @@ import java.util.function.BiFunction; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; -import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.entity.BannerBlockEntity; -import net.minecraft.world.level.block.entity.BarrelBlockEntity; -import net.minecraft.world.level.block.entity.BeaconBlockEntity; -import net.minecraft.world.level.block.entity.BedBlockEntity; -import net.minecraft.world.level.block.entity.BeehiveBlockEntity; -import net.minecraft.world.level.block.entity.BellBlockEntity; -import net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; +import net.minecraft.world.level.GeneratorAccess; +import net.minecraft.world.level.IWorldReader; import net.minecraft.world.level.block.entity.BrushableBlockEntity; import net.minecraft.world.level.block.entity.CalibratedSculkSensorBlockEntity; -import net.minecraft.world.level.block.entity.CampfireBlockEntity; -import net.minecraft.world.level.block.entity.ChestBlockEntity; import net.minecraft.world.level.block.entity.ChiseledBookShelfBlockEntity; -import net.minecraft.world.level.block.entity.CommandBlockEntity; -import net.minecraft.world.level.block.entity.ComparatorBlockEntity; -import net.minecraft.world.level.block.entity.ConduitBlockEntity; import net.minecraft.world.level.block.entity.CrafterBlockEntity; -import net.minecraft.world.level.block.entity.DaylightDetectorBlockEntity; +import net.minecraft.world.level.block.entity.CreakingHeartBlockEntity; import net.minecraft.world.level.block.entity.DecoratedPotBlockEntity; -import net.minecraft.world.level.block.entity.DispenserBlockEntity; -import net.minecraft.world.level.block.entity.DropperBlockEntity; -import net.minecraft.world.level.block.entity.EnchantingTableBlockEntity; -import net.minecraft.world.level.block.entity.EnderChestBlockEntity; -import net.minecraft.world.level.block.entity.FurnaceBlockEntity; import net.minecraft.world.level.block.entity.HangingSignBlockEntity; -import net.minecraft.world.level.block.entity.HopperBlockEntity; -import net.minecraft.world.level.block.entity.JigsawBlockEntity; -import net.minecraft.world.level.block.entity.JukeboxBlockEntity; -import net.minecraft.world.level.block.entity.LecternBlockEntity; import net.minecraft.world.level.block.entity.SculkCatalystBlockEntity; import net.minecraft.world.level.block.entity.SculkSensorBlockEntity; import net.minecraft.world.level.block.entity.SculkShriekerBlockEntity; -import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; -import net.minecraft.world.level.block.entity.SignBlockEntity; -import net.minecraft.world.level.block.entity.SkullBlockEntity; -import net.minecraft.world.level.block.entity.SmokerBlockEntity; -import net.minecraft.world.level.block.entity.SpawnerBlockEntity; -import net.minecraft.world.level.block.entity.StructureBlockEntity; -import net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity; -import net.minecraft.world.level.block.entity.TheEndPortalBlockEntity; -import net.minecraft.world.level.block.entity.TrappedChestBlockEntity; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.entity.TileEntityBanner; +import net.minecraft.world.level.block.entity.TileEntityBarrel; +import net.minecraft.world.level.block.entity.TileEntityBeacon; +import net.minecraft.world.level.block.entity.TileEntityBed; +import net.minecraft.world.level.block.entity.TileEntityBeehive; +import net.minecraft.world.level.block.entity.TileEntityBell; +import net.minecraft.world.level.block.entity.TileEntityBlastFurnace; +import net.minecraft.world.level.block.entity.TileEntityBrewingStand; +import net.minecraft.world.level.block.entity.TileEntityCampfire; +import net.minecraft.world.level.block.entity.TileEntityChest; +import net.minecraft.world.level.block.entity.TileEntityChestTrapped; +import net.minecraft.world.level.block.entity.TileEntityCommand; +import net.minecraft.world.level.block.entity.TileEntityComparator; +import net.minecraft.world.level.block.entity.TileEntityConduit; +import net.minecraft.world.level.block.entity.TileEntityDispenser; +import net.minecraft.world.level.block.entity.TileEntityDropper; +import net.minecraft.world.level.block.entity.TileEntityEnchantTable; +import net.minecraft.world.level.block.entity.TileEntityEndGateway; +import net.minecraft.world.level.block.entity.TileEntityEnderChest; +import net.minecraft.world.level.block.entity.TileEntityEnderPortal; +import net.minecraft.world.level.block.entity.TileEntityFurnaceFurnace; +import net.minecraft.world.level.block.entity.TileEntityHopper; +import net.minecraft.world.level.block.entity.TileEntityJigsaw; +import net.minecraft.world.level.block.entity.TileEntityJukeBox; +import net.minecraft.world.level.block.entity.TileEntityLectern; +import net.minecraft.world.level.block.entity.TileEntityLightDetector; +import net.minecraft.world.level.block.entity.TileEntityMobSpawner; +import net.minecraft.world.level.block.entity.TileEntityShulkerBox; +import net.minecraft.world.level.block.entity.TileEntitySign; +import net.minecraft.world.level.block.entity.TileEntitySkull; +import net.minecraft.world.level.block.entity.TileEntitySmoker; +import net.minecraft.world.level.block.entity.TileEntityStructure; import net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity; import net.minecraft.world.level.block.entity.vault.VaultBlockEntity; -import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; +import net.minecraft.world.level.block.piston.TileEntityPiston; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; @@ -81,22 +83,22 @@ public BlockStateFactory(Class blockStateType) { // If the given tile entity is not null, its position and block data are expected to match the given block position and block data. // In some situations, such as during chunk generation, the tile entity's world may be null, even if the given world is not null. // If the tile entity's world is not null, it is expected to match the given world. - public abstract B createBlockState(World world, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData, BlockEntity tileEntity); + public abstract B createBlockState(World world, BlockPos blockPosition, IBlockData blockData, TileEntity tileEntity); } - private static class BlockEntityStateFactory> extends BlockStateFactory { + private static class BlockEntityStateFactory> extends BlockStateFactory { private final BiFunction blockStateConstructor; - private final BiFunction tileEntityConstructor; + private final BiFunction tileEntityConstructor; - protected BlockEntityStateFactory(Class blockStateType, BiFunction blockStateConstructor, BiFunction tileEntityConstructor) { + protected BlockEntityStateFactory(Class blockStateType, BiFunction blockStateConstructor, BiFunction tileEntityConstructor) { super(blockStateType); this.blockStateConstructor = blockStateConstructor; this.tileEntityConstructor = tileEntityConstructor; } @Override - public final B createBlockState(World world, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData, BlockEntity tileEntity) { + public final B createBlockState(World world, BlockPos blockPosition, IBlockData blockData, TileEntity tileEntity) { if (world != null) { Preconditions.checkState(tileEntity != null, "Tile is null, asynchronous access? %s", CraftBlock.at(((CraftWorld) world).getHandle(), blockPosition)); } else if (tileEntity == null) { @@ -105,19 +107,19 @@ public final B createBlockState(World world, BlockPos blockPosition, net.minecra return this.createBlockState(world, (T) tileEntity); } - private T createTileEntity(BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData) { - return this.tileEntityConstructor.apply(blockPosition, blockData); + private T createTileEntity(BlockPos blockPosition, IBlockData blockData) { + return tileEntityConstructor.apply(blockPosition, blockData); } private B createBlockState(World world, T tileEntity) { - return this.blockStateConstructor.apply(world, tileEntity); + return blockStateConstructor.apply(world, tileEntity); } } private static final Map> FACTORIES = new HashMap<>(); private static final BlockStateFactory DEFAULT_FACTORY = new BlockStateFactory(CraftBlockState.class) { @Override - public CraftBlockState createBlockState(World world, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData, BlockEntity tileEntity) { + public CraftBlockState createBlockState(World world, BlockPos blockPosition, IBlockData blockData, TileEntity tileEntity) { // SPIGOT-6754, SPIGOT-6817: Restore previous behaviour for tile entities with removed blocks (loot generation post-destroy) if (tileEntity != null) { // block with unhandled TileEntity: @@ -149,11 +151,13 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.MANGROVE_WALL_SIGN, Material.OAK_SIGN, Material.OAK_WALL_SIGN, + Material.PALE_OAK_SIGN, + Material.PALE_OAK_WALL_SIGN, Material.SPRUCE_SIGN, Material.SPRUCE_WALL_SIGN, Material.WARPED_SIGN, Material.WARPED_WALL_SIGN - ), CraftSign.class, CraftSign::new, SignBlockEntity::new + ), CraftSign.class, CraftSign::new, TileEntitySign::new ); register( @@ -176,6 +180,8 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.MANGROVE_WALL_HANGING_SIGN, Material.OAK_HANGING_SIGN, Material.OAK_WALL_HANGING_SIGN, + Material.PALE_OAK_HANGING_SIGN, + Material.PALE_OAK_WALL_HANGING_SIGN, Material.SPRUCE_HANGING_SIGN, Material.SPRUCE_WALL_HANGING_SIGN, Material.WARPED_HANGING_SIGN, @@ -199,7 +205,7 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.WITHER_SKELETON_WALL_SKULL, Material.ZOMBIE_HEAD, Material.ZOMBIE_WALL_HEAD - ), CraftSkull.class, CraftSkull::new, SkullBlockEntity::new + ), CraftSkull.class, CraftSkull::new, TileEntitySkull::new ); register( @@ -207,7 +213,7 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.COMMAND_BLOCK, Material.REPEATING_COMMAND_BLOCK, Material.CHAIN_COMMAND_BLOCK - ), CraftCommandBlock.class, CraftCommandBlock::new, CommandBlockEntity::new + ), CraftCommandBlock.class, CraftCommandBlock::new, TileEntityCommand::new ); register( @@ -244,7 +250,7 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.WHITE_WALL_BANNER, Material.YELLOW_BANNER, Material.YELLOW_WALL_BANNER - ), CraftBanner.class, CraftBanner::new, BannerBlockEntity::new + ), CraftBanner.class, CraftBanner::new, TileEntityBanner::new ); register( @@ -266,7 +272,7 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.GREEN_SHULKER_BOX, Material.RED_SHULKER_BOX, Material.BLACK_SHULKER_BOX - ), CraftShulkerBox.class, CraftShulkerBox::new, ShulkerBoxBlockEntity::new + ), CraftShulkerBox.class, CraftShulkerBox::new, TileEntityShulkerBox::new ); register( @@ -287,97 +293,98 @@ public CraftBlockState createBlockState(World world, BlockPos blockPosition, net Material.RED_BED, Material.WHITE_BED, Material.YELLOW_BED - ), CraftBed.class, CraftBed::new, BedBlockEntity::new + ), CraftBed.class, CraftBed::new, TileEntityBed::new ); register( Arrays.asList( Material.BEEHIVE, Material.BEE_NEST - ), CraftBeehive.class, CraftBeehive::new, BeehiveBlockEntity::new + ), CraftBeehive.class, CraftBeehive::new, TileEntityBeehive::new ); register( Arrays.asList( Material.CAMPFIRE, Material.SOUL_CAMPFIRE - ), CraftCampfire.class, CraftCampfire::new, CampfireBlockEntity::new + ), CraftCampfire.class, CraftCampfire::new, TileEntityCampfire::new ); - register(Material.BARREL, CraftBarrel.class, CraftBarrel::new, BarrelBlockEntity::new); - register(Material.BEACON, CraftBeacon.class, CraftBeacon::new, BeaconBlockEntity::new); - register(Material.BELL, CraftBell.class, CraftBell::new, BellBlockEntity::new); - register(Material.BLAST_FURNACE, CraftBlastFurnace.class, CraftBlastFurnace::new, BlastFurnaceBlockEntity::new); - register(Material.BREWING_STAND, CraftBrewingStand.class, CraftBrewingStand::new, BrewingStandBlockEntity::new); - register(Material.CHEST, CraftChest.class, CraftChest::new, ChestBlockEntity::new); + register(Material.BARREL, CraftBarrel.class, CraftBarrel::new, TileEntityBarrel::new); + register(Material.BEACON, CraftBeacon.class, CraftBeacon::new, TileEntityBeacon::new); + register(Material.BELL, CraftBell.class, CraftBell::new, TileEntityBell::new); + register(Material.BLAST_FURNACE, CraftBlastFurnace.class, CraftBlastFurnace::new, TileEntityBlastFurnace::new); + register(Material.BREWING_STAND, CraftBrewingStand.class, CraftBrewingStand::new, TileEntityBrewingStand::new); + register(Material.CHEST, CraftChest.class, CraftChest::new, TileEntityChest::new); register(Material.CHISELED_BOOKSHELF, CraftChiseledBookshelf.class, CraftChiseledBookshelf::new, ChiseledBookShelfBlockEntity::new); - register(Material.COMPARATOR, CraftComparator.class, CraftComparator::new, ComparatorBlockEntity::new); - register(Material.CONDUIT, CraftConduit.class, CraftConduit::new, ConduitBlockEntity::new); - register(Material.DAYLIGHT_DETECTOR, CraftDaylightDetector.class, CraftDaylightDetector::new, DaylightDetectorBlockEntity::new); + register(Material.COMPARATOR, CraftComparator.class, CraftComparator::new, TileEntityComparator::new); + register(Material.CONDUIT, CraftConduit.class, CraftConduit::new, TileEntityConduit::new); + register(Material.CREAKING_HEART, CraftCreakingHeart.class, CraftCreakingHeart::new, CreakingHeartBlockEntity::new); + register(Material.DAYLIGHT_DETECTOR, CraftDaylightDetector.class, CraftDaylightDetector::new, TileEntityLightDetector::new); register(Material.DECORATED_POT, CraftDecoratedPot.class, CraftDecoratedPot::new, DecoratedPotBlockEntity::new); - register(Material.DISPENSER, CraftDispenser.class, CraftDispenser::new, DispenserBlockEntity::new); - register(Material.DROPPER, CraftDropper.class, CraftDropper::new, DropperBlockEntity::new); - register(Material.ENCHANTING_TABLE, CraftEnchantingTable.class, CraftEnchantingTable::new, EnchantingTableBlockEntity::new); - register(Material.ENDER_CHEST, CraftEnderChest.class, CraftEnderChest::new, EnderChestBlockEntity::new); - register(Material.END_GATEWAY, CraftEndGateway.class, CraftEndGateway::new, TheEndGatewayBlockEntity::new); - register(Material.END_PORTAL, CraftEndPortal.class, CraftEndPortal::new, TheEndPortalBlockEntity::new); - register(Material.FURNACE, CraftFurnaceFurnace.class, CraftFurnaceFurnace::new, FurnaceBlockEntity::new); - register(Material.HOPPER, CraftHopper.class, CraftHopper::new, HopperBlockEntity::new); - register(Material.JIGSAW, CraftJigsaw.class, CraftJigsaw::new, JigsawBlockEntity::new); - register(Material.JUKEBOX, CraftJukebox.class, CraftJukebox::new, JukeboxBlockEntity::new); - register(Material.LECTERN, CraftLectern.class, CraftLectern::new, LecternBlockEntity::new); - register(Material.MOVING_PISTON, CraftMovingPiston.class, CraftMovingPiston::new, PistonMovingBlockEntity::new); + register(Material.DISPENSER, CraftDispenser.class, CraftDispenser::new, TileEntityDispenser::new); + register(Material.DROPPER, CraftDropper.class, CraftDropper::new, TileEntityDropper::new); + register(Material.ENCHANTING_TABLE, CraftEnchantingTable.class, CraftEnchantingTable::new, TileEntityEnchantTable::new); + register(Material.ENDER_CHEST, CraftEnderChest.class, CraftEnderChest::new, TileEntityEnderChest::new); + register(Material.END_GATEWAY, CraftEndGateway.class, CraftEndGateway::new, TileEntityEndGateway::new); + register(Material.END_PORTAL, CraftEndPortal.class, CraftEndPortal::new, TileEntityEnderPortal::new); + register(Material.FURNACE, CraftFurnaceFurnace.class, CraftFurnaceFurnace::new, TileEntityFurnaceFurnace::new); + register(Material.HOPPER, CraftHopper.class, CraftHopper::new, TileEntityHopper::new); + register(Material.JIGSAW, CraftJigsaw.class, CraftJigsaw::new, TileEntityJigsaw::new); + register(Material.JUKEBOX, CraftJukebox.class, CraftJukebox::new, TileEntityJukeBox::new); + register(Material.LECTERN, CraftLectern.class, CraftLectern::new, TileEntityLectern::new); + register(Material.MOVING_PISTON, CraftMovingPiston.class, CraftMovingPiston::new, TileEntityPiston::new); register(Material.SCULK_CATALYST, CraftSculkCatalyst.class, CraftSculkCatalyst::new, SculkCatalystBlockEntity::new); register(Material.CALIBRATED_SCULK_SENSOR, CraftCalibratedSculkSensor.class, CraftCalibratedSculkSensor::new, CalibratedSculkSensorBlockEntity::new); register(Material.SCULK_SENSOR, CraftSculkSensor.class, CraftSculkSensor::new, SculkSensorBlockEntity::new); register(Material.SCULK_SHRIEKER, CraftSculkShrieker.class, CraftSculkShrieker::new, SculkShriekerBlockEntity::new); - register(Material.SMOKER, CraftSmoker.class, CraftSmoker::new, SmokerBlockEntity::new); - register(Material.SPAWNER, CraftCreatureSpawner.class, CraftCreatureSpawner::new, SpawnerBlockEntity::new); - register(Material.STRUCTURE_BLOCK, CraftStructureBlock.class, CraftStructureBlock::new, StructureBlockEntity::new); + register(Material.SMOKER, CraftSmoker.class, CraftSmoker::new, TileEntitySmoker::new); + register(Material.SPAWNER, CraftCreatureSpawner.class, CraftCreatureSpawner::new, TileEntityMobSpawner::new); + register(Material.STRUCTURE_BLOCK, CraftStructureBlock.class, CraftStructureBlock::new, TileEntityStructure::new); register(Material.SUSPICIOUS_SAND, CraftSuspiciousSand.class, CraftSuspiciousSand::new, BrushableBlockEntity::new); register(Material.SUSPICIOUS_GRAVEL, CraftBrushableBlock.class, CraftBrushableBlock::new, BrushableBlockEntity::new); - register(Material.TRAPPED_CHEST, CraftChest.class, CraftChest::new, TrappedChestBlockEntity::new); + register(Material.TRAPPED_CHEST, CraftChest.class, CraftChest::new, TileEntityChestTrapped::new); register(Material.CRAFTER, CraftCrafter.class, CraftCrafter::new, CrafterBlockEntity::new); register(Material.TRIAL_SPAWNER, CraftTrialSpawner.class, CraftTrialSpawner::new, TrialSpawnerBlockEntity::new); register(Material.VAULT, CraftVault.class, CraftVault::new, VaultBlockEntity::new); } private static void register(Material blockType, BlockStateFactory factory) { - CraftBlockStates.FACTORIES.put(blockType, factory); + FACTORIES.put(blockType, factory); } - public static > void register( + private static > void register( Material blockType, Class blockStateType, BiFunction blockStateConstructor, - BiFunction tileEntityConstructor + BiFunction tileEntityConstructor ) { - CraftBlockStates.register(Collections.singletonList(blockType), blockStateType, blockStateConstructor, tileEntityConstructor); + register(Collections.singletonList(blockType), blockStateType, blockStateConstructor, tileEntityConstructor); } - private static > void register( + private static > void register( List blockTypes, Class blockStateType, BiFunction blockStateConstructor, - BiFunction tileEntityConstructor + BiFunction tileEntityConstructor ) { BlockStateFactory factory = new BlockEntityStateFactory<>(blockStateType, blockStateConstructor, tileEntityConstructor); for (Material blockType : blockTypes) { - CraftBlockStates.register(blockType, factory); + register(blockType, factory); } } private static BlockStateFactory getFactory(Material material) { - return CraftBlockStates.FACTORIES.getOrDefault(material, CraftBlockStates.DEFAULT_FACTORY); + return FACTORIES.getOrDefault(material, DEFAULT_FACTORY); } public static Class getBlockStateType(Material material) { Preconditions.checkNotNull(material, "material is null"); - return CraftBlockStates.getFactory(material).blockStateType; + return getFactory(material).blockStateType; } - public static BlockEntity createNewTileEntity(Material material) { - BlockStateFactory factory = CraftBlockStates.getFactory(material); + public static TileEntity createNewTileEntity(Material material) { + BlockStateFactory factory = getFactory(material); if (factory instanceof BlockEntityStateFactory) { return ((BlockEntityStateFactory) factory).createTileEntity(BlockPos.ZERO, CraftBlockType.bukkitToMinecraft(material).defaultBlockState()); @@ -391,54 +398,54 @@ public static BlockState getBlockState(Block block) { CraftBlock craftBlock = (CraftBlock) block; CraftWorld world = (CraftWorld) block.getWorld(); BlockPos blockPosition = craftBlock.getPosition(); - net.minecraft.world.level.block.state.BlockState blockData = craftBlock.getNMS(); - BlockEntity tileEntity = craftBlock.getHandle().getBlockEntity(blockPosition); - CraftBlockState blockState = CraftBlockStates.getBlockState(world, blockPosition, blockData, tileEntity); + IBlockData blockData = craftBlock.getNMS(); + TileEntity tileEntity = craftBlock.getHandle().getBlockEntity(blockPosition); + CraftBlockState blockState = getBlockState(world, blockPosition, blockData, tileEntity); blockState.setWorldHandle(craftBlock.getHandle()); // Inject the block's generator access return blockState; } @Deprecated - public static BlockState getBlockState(BlockPos blockPosition, Material material, @Nullable CompoundTag blockEntityTag) { - return CraftBlockStates.getBlockState(MinecraftServer.getDefaultRegistryAccess(), blockPosition, material, blockEntityTag); + public static BlockState getBlockState(BlockPos blockPosition, Material material, @Nullable NBTTagCompound blockEntityTag) { + return getBlockState(MinecraftServer.getDefaultRegistryAccess(), blockPosition, material, blockEntityTag); } - public static BlockState getBlockState(LevelReader world, BlockPos blockPosition, Material material, @Nullable CompoundTag blockEntityTag) { - return CraftBlockStates.getBlockState(world.registryAccess(), blockPosition, material, blockEntityTag); + public static BlockState getBlockState(IWorldReader world, BlockPos blockPosition, Material material, @Nullable NBTTagCompound blockEntityTag) { + return getBlockState(world.registryAccess(), blockPosition, material, blockEntityTag); } - public static BlockState getBlockState(RegistryAccess registry, BlockPos blockPosition, Material material, @Nullable CompoundTag blockEntityTag) { + public static BlockState getBlockState(IRegistryCustom registry, BlockPos blockPosition, Material material, @Nullable NBTTagCompound blockEntityTag) { Preconditions.checkNotNull(material, "material is null"); - net.minecraft.world.level.block.state.BlockState blockData = CraftBlockType.bukkitToMinecraft(material).defaultBlockState(); - return CraftBlockStates.getBlockState(registry, blockPosition, blockData, blockEntityTag); + IBlockData blockData = CraftBlockType.bukkitToMinecraft(material).defaultBlockState(); + return getBlockState(registry, blockPosition, blockData, blockEntityTag); } @Deprecated - public static BlockState getBlockState(net.minecraft.world.level.block.state.BlockState blockData, @Nullable CompoundTag blockEntityTag) { - return CraftBlockStates.getBlockState(MinecraftServer.getDefaultRegistryAccess(), BlockPos.ZERO, blockData, blockEntityTag); + public static BlockState getBlockState(IBlockData blockData, @Nullable NBTTagCompound blockEntityTag) { + return getBlockState(MinecraftServer.getDefaultRegistryAccess(), BlockPos.ZERO, blockData, blockEntityTag); } - public static BlockState getBlockState(LevelReader world, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData, @Nullable CompoundTag blockEntityTag) { - return CraftBlockStates.getBlockState(world.registryAccess(), blockPosition, blockData, blockEntityTag); + public static BlockState getBlockState(IWorldReader world, BlockPos blockPosition, IBlockData blockData, @Nullable NBTTagCompound blockEntityTag) { + return getBlockState(world.registryAccess(), blockPosition, blockData, blockEntityTag); } - public static BlockState getBlockState(RegistryAccess registry, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData, @Nullable CompoundTag blockEntityTag) { + public static BlockState getBlockState(IRegistryCustom registry, BlockPos blockPosition, IBlockData blockData, @Nullable NBTTagCompound blockEntityTag) { Preconditions.checkNotNull(blockPosition, "blockPosition is null"); Preconditions.checkNotNull(blockData, "blockData is null"); - BlockEntity tileEntity = (blockEntityTag == null) ? null : BlockEntity.loadStatic(blockPosition, blockData, blockEntityTag, registry); - return CraftBlockStates.getBlockState(null, blockPosition, blockData, tileEntity); + TileEntity tileEntity = (blockEntityTag == null) ? null : TileEntity.loadStatic(blockPosition, blockData, blockEntityTag, registry); + return getBlockState(null, blockPosition, blockData, tileEntity); } - // See BlockStateFactory#createBlockState(World, BlockPosition, IBlockData, TileEntity) - private static CraftBlockState getBlockState(World world, BlockPos blockPosition, net.minecraft.world.level.block.state.BlockState blockData, BlockEntity tileEntity) { + // See BlockStateFactory#createBlockState(World, BlockPos, IBlockData, TileEntity) + private static CraftBlockState getBlockState(World world, BlockPos blockPosition, IBlockData blockData, TileEntity tileEntity) { Material material = CraftBlockType.minecraftToBukkit(blockData.getBlock()); BlockStateFactory factory; // For some types of TileEntity blocks (eg. moving pistons), Minecraft may in some situations (eg. when using Block#setType or the // setBlock command) not create a corresponding TileEntity in the world. We return a normal BlockState in this case. - if (world != null && tileEntity == null && CraftBlockStates.isTileEntityOptional(material)) { - factory = CraftBlockStates.DEFAULT_FACTORY; + if (world != null && tileEntity == null && isTileEntityOptional(material)) { + factory = DEFAULT_FACTORY; } else { - factory = CraftBlockStates.getFactory(material); + factory = getFactory(material); } return factory.createBlockState(world, blockPosition, blockData, tileEntity); } @@ -448,12 +455,12 @@ public static boolean isTileEntityOptional(Material material) { } // This ignores tile entity data. - public static CraftBlockState getBlockState(LevelAccessor world, BlockPos pos) { + public static CraftBlockState getBlockState(GeneratorAccess world, BlockPos pos) { return new CraftBlockState(CraftBlock.at(world, pos)); } // This ignores tile entity data. - public static CraftBlockState getBlockState(LevelAccessor world, BlockPos pos, int flag) { + public static CraftBlockState getBlockState(GeneratorAccess world, BlockPos pos, int flag) { return new CraftBlockState(CraftBlock.at(world, pos), flag); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockSupport.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockSupport.java index 5d902c1d..dc4b113f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockSupport.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockSupport.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.SupportType; +import net.minecraft.world.level.block.EnumBlockSupport; import org.bukkit.block.BlockSupport; public final class CraftBlockSupport { @@ -8,7 +8,7 @@ public final class CraftBlockSupport { private CraftBlockSupport() { } - public static BlockSupport toBukkit(SupportType support) { + public static BlockSupport toBukkit(EnumBlockSupport support) { return switch (support) { case FULL -> BlockSupport.FULL; case CENTER -> BlockSupport.CENTER; @@ -17,11 +17,11 @@ public static BlockSupport toBukkit(SupportType support) { }; } - public static SupportType toNMS(BlockSupport support) { + public static EnumBlockSupport toNMS(BlockSupport support) { return switch (support) { - case FULL -> SupportType.FULL; - case CENTER -> SupportType.CENTER; - case RIGID -> SupportType.RIGID; + case FULL -> EnumBlockSupport.FULL; + case CENTER -> EnumBlockSupport.CENTER; + case RIGID -> EnumBlockSupport.RIGID; default -> throw new IllegalArgumentException("Unsupported BlockSupport type: " + support + ". This is a bug."); }; } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockType.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockType.java index ec1266a1..967cf71d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockType.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockType.java @@ -1,21 +1,23 @@ package org.bukkit.craftbukkit.block; import com.google.common.base.Preconditions; +import java.lang.reflect.Method; +import java.util.Arrays; import java.util.function.Consumer; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.EnumHand; +import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; -import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.BlockAccessAir; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.BlockFire; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.FallingBlock; -import net.minecraft.world.level.block.FireBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.level.block.Fallable; +import net.minecraft.world.level.block.state.BlockBase; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.phys.MovingObjectPositionBlock; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -54,28 +56,35 @@ public static Block bukkitToMinecraftNew(BlockType bukkit) { return CraftRegistry.bukkitToMinecraft(bukkit); } - private static boolean hasMethod(Class clazz, String methodName, Class... params) { - boolean hasMethod; - try { - hasMethod = clazz.getDeclaredMethod(methodName, params) != null; - } catch (NoSuchMethodException ex) { - hasMethod = false; + private static boolean hasMethod(Class clazz, Class... params) { + boolean hasMethod = false; + for (Method method : clazz.getDeclaredMethods()) { + if (Arrays.equals(method.getParameterTypes(), params)) { + Preconditions.checkArgument(!hasMethod, "More than one matching method for %s, args %s", clazz, Arrays.toString(params)); + + hasMethod = true; + } } return hasMethod; } + private static final Class[] USE_WITHOUT_ITEM_ARGS = new Class[]{ + IBlockData.class, net.minecraft.world.level.World.class, BlockPos.class, EntityHuman.class, MovingObjectPositionBlock.class + }; + private static final Class[] USE_ITEM_ON_ARGS = new Class[]{ + net.minecraft.world.item.ItemStack.class, IBlockData.class, net.minecraft.world.level.World.class, BlockPos.class, EntityHuman.class, EnumHand.class, MovingObjectPositionBlock.class + }; + private static boolean isInteractable(Block block) { Class clazz = block.getClass(); - boolean hasMethod = hasMethod(clazz, "useWithoutItem", BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, BlockHitResult.class) - || hasMethod(clazz, "useItemOn", net.minecraft.world.item.ItemStack.class, BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, BlockHitResult.class); + boolean hasMethod = hasMethod(clazz, USE_WITHOUT_ITEM_ARGS) || hasMethod(clazz, USE_ITEM_ON_ARGS); - if (!hasMethod && clazz.getSuperclass() != BlockBehaviour.class) { + if (!hasMethod && clazz.getSuperclass() != BlockBase.class) { clazz = clazz.getSuperclass(); - hasMethod = hasMethod(clazz, "useWithoutItem", BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, BlockHitResult.class) - || hasMethod(clazz, "useItemOn", net.minecraft.world.item.ItemStack.class, BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, BlockHitResult.class); + hasMethod = hasMethod(clazz, USE_WITHOUT_ITEM_ARGS) || hasMethod(clazz, USE_ITEM_ON_ARGS); } return hasMethod; @@ -177,17 +186,17 @@ public boolean isFlammable() { @Override public boolean isBurnable() { - return ((FireBlock) Blocks.FIRE).igniteOdds.getOrDefault(block, 0) > 0; + return ((BlockFire) Blocks.FIRE).igniteOdds.getOrDefault(block, 0) > 0; } @Override public boolean isOccluding() { - return block.defaultBlockState().isRedstoneConductor(EmptyBlockGetter.INSTANCE, BlockPos.ZERO); + return block.defaultBlockState().isRedstoneConductor(BlockAccessAir.INSTANCE, BlockPos.ZERO); } @Override public boolean hasGravity() { - return block instanceof FallingBlock; + return block instanceof Fallable; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java index e9f55c89..8b00bd16 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java @@ -1,15 +1,15 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityBrewingStand; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.BrewingStand; import org.bukkit.craftbukkit.inventory.CraftInventoryBrewer; import org.bukkit.inventory.BrewerInventory; -public class CraftBrewingStand extends CraftContainer implements BrewingStand { +public class CraftBrewingStand extends CraftContainer implements BrewingStand { - public CraftBrewingStand(World world, BrewingStandBlockEntity tileEntity) { + public CraftBrewingStand(World world, TileEntityBrewingStand tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBrushableBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBrushableBlock.java index 949e074a..6484fa6f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBrushableBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBrushableBlock.java @@ -21,12 +21,12 @@ protected CraftBrushableBlock(CraftBrushableBlock state, Location location) { @Override public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getSnapshot().getItem()); + return CraftItemStack.asBukkitCopy(getSnapshot().getItem()); } @Override public void setItem(ItemStack item) { - this.getSnapshot().item = CraftItemStack.asNMSCopy(item); + getSnapshot().item = CraftItemStack.asNMSCopy(item); } @Override @@ -40,26 +40,26 @@ public void applyTo(BrushableBlockEntity lootable) { @Override public LootTable getLootTable() { - return CraftLootTable.minecraftToBukkit(this.getSnapshot().lootTable); + return CraftLootTable.minecraftToBukkit(getSnapshot().lootTable); } @Override public void setLootTable(LootTable table) { - this.setLootTable(table, this.getSeed()); + setLootTable(table, getSeed()); } @Override public long getSeed() { - return this.getSnapshot().lootTableSeed; + return getSnapshot().lootTableSeed; } @Override public void setSeed(long seed) { - this.setLootTable(this.getLootTable(), seed); + setLootTable(getLootTable(), seed); } private void setLootTable(LootTable table, long seed) { - this.getSnapshot().setLootTable(CraftLootTable.bukkitToMinecraft(table), seed); + getSnapshot().setLootTable(CraftLootTable.bukkitToMinecraft(table), seed); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java index 4850cbf2..aba52da7 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java @@ -1,15 +1,15 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.CampfireBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityCampfire; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Campfire; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; -public class CraftCampfire extends CraftBlockEntityState implements Campfire { +public class CraftCampfire extends CraftBlockEntityState implements Campfire { - public CraftCampfire(World world, CampfireBlockEntity tileEntity) { + public CraftCampfire(World world, TileEntityCampfire tileEntity) { super(world, tileEntity); } @@ -19,38 +19,38 @@ protected CraftCampfire(CraftCampfire state, Location location) { @Override public int getSize() { - return this.getSnapshot().getItems().size(); + return getSnapshot().getItems().size(); } @Override public ItemStack getItem(int index) { - net.minecraft.world.item.ItemStack item = this.getSnapshot().getItems().get(index); + net.minecraft.world.item.ItemStack item = getSnapshot().getItems().get(index); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } @Override public void setItem(int index, ItemStack item) { - this.getSnapshot().getItems().set(index, CraftItemStack.asNMSCopy(item)); + getSnapshot().getItems().set(index, CraftItemStack.asNMSCopy(item)); } @Override public int getCookTime(int index) { - return this.getSnapshot().cookingProgress[index]; + return getSnapshot().cookingProgress[index]; } @Override public void setCookTime(int index, int cookTime) { - this.getSnapshot().cookingProgress[index] = cookTime; + getSnapshot().cookingProgress[index] = cookTime; } @Override public int getCookTimeTotal(int index) { - return this.getSnapshot().cookingTime[index]; + return getSnapshot().cookingTime[index]; } @Override public void setCookTimeTotal(int index, int cookTimeTotal) { - this.getSnapshot().cookingTime[index] = cookTimeTotal; + getSnapshot().cookingTime[index] = cookTimeTotal; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java b/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java index 2b6a93a9..04d86c68 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java @@ -1,10 +1,10 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.MenuProvider; +import net.minecraft.world.ITileInventory; +import net.minecraft.world.level.block.BlockChest; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.ChestBlock; -import net.minecraft.world.level.block.entity.ChestBlockEntity; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.entity.TileEntityChest; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -14,9 +14,9 @@ import org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest; import org.bukkit.inventory.Inventory; -public class CraftChest extends CraftLootable implements Chest { +public class CraftChest extends CraftLootable implements Chest { - public CraftChest(World world, ChestBlockEntity tileEntity) { + public CraftChest(World world, TileEntityChest tileEntity) { super(world, tileEntity); } @@ -41,46 +41,46 @@ public Inventory getBlockInventory() { @Override public Inventory getInventory() { CraftInventory inventory = (CraftInventory) this.getBlockInventory(); - if (!this.isPlaced() || this.isWorldGeneration()) { + if (!isPlaced() || isWorldGeneration()) { return inventory; } // The logic here is basically identical to the logic in BlockChest.interact CraftWorld world = (CraftWorld) this.getWorld(); - ChestBlock blockChest = (ChestBlock) (this.getType() == Material.CHEST ? Blocks.CHEST : Blocks.TRAPPED_CHEST); - MenuProvider nms = blockChest.getMenuProvider(this.data, world.getHandle(), this.getPosition(), true); + BlockChest blockChest = (BlockChest) (this.getType() == Material.CHEST ? Blocks.CHEST : Blocks.TRAPPED_CHEST); + ITileInventory nms = blockChest.getMenuProvider(data, world.getHandle(), this.getPosition(), true); - if (nms instanceof ChestBlock.DoubleInventory) { - inventory = new CraftInventoryDoubleChest((ChestBlock.DoubleInventory) nms); + if (nms instanceof BlockChest.DoubleInventory) { + inventory = new CraftInventoryDoubleChest((BlockChest.DoubleInventory) nms); } return inventory; } @Override public void open() { - this.requirePlaced(); - if (!this.getTileEntity().openersCounter.opened && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - BlockState block = this.getTileEntity().getBlockState(); - int openCount = this.getTileEntity().openersCounter.getOpenerCount(); + requirePlaced(); + if (!getTileEntity().openersCounter.opened && getWorldHandle() instanceof net.minecraft.world.level.World) { + IBlockData block = getTileEntity().getBlockState(); + int openCount = getTileEntity().openersCounter.getOpenerCount(); - this.getTileEntity().openersCounter.onAPIOpen((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block); - this.getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block, openCount, openCount + 1); + getTileEntity().openersCounter.onAPIOpen((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block); + getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block, openCount, openCount + 1); } - this.getTileEntity().openersCounter.opened = true; + getTileEntity().openersCounter.opened = true; } @Override public void close() { - this.requirePlaced(); - if (this.getTileEntity().openersCounter.opened && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - BlockState block = this.getTileEntity().getBlockState(); - int openCount = this.getTileEntity().openersCounter.getOpenerCount(); + requirePlaced(); + if (getTileEntity().openersCounter.opened && getWorldHandle() instanceof net.minecraft.world.level.World) { + IBlockData block = getTileEntity().getBlockState(); + int openCount = getTileEntity().openersCounter.getOpenerCount(); - this.getTileEntity().openersCounter.onAPIClose((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block); - this.getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block, openCount, 0); + getTileEntity().openersCounter.onAPIClose((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block); + getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block, openCount, 0); } - this.getTileEntity().openersCounter.opened = false; + getTileEntity().openersCounter.opened = false; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftChiseledBookshelf.java b/src/main/java/org/bukkit/craftbukkit/block/CraftChiseledBookshelf.java index 9a11ff21..1fd52565 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftChiseledBookshelf.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftChiseledBookshelf.java @@ -2,7 +2,7 @@ import net.minecraft.world.level.block.ChiseledBookShelfBlock; import net.minecraft.world.level.block.entity.ChiseledBookShelfBlockEntity; -import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec2F; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.BlockFace; @@ -24,12 +24,12 @@ protected CraftChiseledBookshelf(CraftChiseledBookshelf state, Location location @Override public int getLastInteractedSlot() { - return this.getSnapshot().getLastInteractedSlot(); + return getSnapshot().getLastInteractedSlot(); } @Override public void setLastInteractedSlot(int lastInteractedSlot) { - this.getSnapshot().lastInteractedSlot = lastInteractedSlot; + getSnapshot().lastInteractedSlot = lastInteractedSlot; } @Override @@ -50,19 +50,19 @@ public ChiseledBookshelfInventory getInventory() { public int getSlot(Vector clickVector) { BlockFace facing = ((Directional) this.getBlockData()).getFacing(); - Vec2 faceVector; + Vec2F faceVector; switch (facing) { case NORTH: - faceVector = new Vec2((float) (1.0f - clickVector.getX()), (float) clickVector.getY()); + faceVector = new Vec2F((float) (1.0f - clickVector.getX()), (float) clickVector.getY()); break; case SOUTH: - faceVector = new Vec2((float) clickVector.getX(), (float) clickVector.getY()); + faceVector = new Vec2F((float) clickVector.getX(), (float) clickVector.getY()); break; case WEST: - faceVector = new Vec2((float) clickVector.getZ(), (float) clickVector.getY()); + faceVector = new Vec2F((float) clickVector.getZ(), (float) clickVector.getY()); break; case EAST: - faceVector = new Vec2((float) (1f - clickVector.getZ()), (float) clickVector.getY()); + faceVector = new Vec2F((float) (1f - clickVector.getZ()), (float) clickVector.getY()); break; case DOWN: case UP: @@ -70,10 +70,10 @@ public int getSlot(Vector clickVector) { return -1; } - return CraftChiseledBookshelf.getHitSlot(faceVector); + return getHitSlot(faceVector); } - private static int getHitSlot(Vec2 vec2f) { + private static int getHitSlot(Vec2F vec2f) { int i = vec2f.y >= 0.5F ? 0 : 1; int j = ChiseledBookShelfBlock.getSection(vec2f.x); diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java index f9b89a7c..164d1148 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.CommandBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityCommand; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.CommandBlock; import org.bukkit.craftbukkit.util.CraftChatMessage; -public class CraftCommandBlock extends CraftBlockEntityState implements CommandBlock { +public class CraftCommandBlock extends CraftBlockEntityState implements CommandBlock { - public CraftCommandBlock(World world, CommandBlockEntity tileEntity) { + public CraftCommandBlock(World world, TileEntityCommand tileEntity) { super(world, tileEntity); } @@ -18,22 +18,22 @@ protected CraftCommandBlock(CraftCommandBlock state, Location location) { @Override public String getCommand() { - return this.getSnapshot().getCommandBlock().getCommand(); + return getSnapshot().getCommandBlock().getCommand(); } @Override public void setCommand(String command) { - this.getSnapshot().getCommandBlock().setCommand(command != null ? command : ""); + getSnapshot().getCommandBlock().setCommand(command != null ? command : ""); } @Override public String getName() { - return CraftChatMessage.fromComponent(this.getSnapshot().getCommandBlock().getName()); + return CraftChatMessage.fromComponent(getSnapshot().getCommandBlock().getName()); } @Override public void setName(String name) { - this.getSnapshot().getCommandBlock().setCustomName(CraftChatMessage.fromStringOrNull(name != null ? name : "@")); + getSnapshot().getCommandBlock().setCustomName(CraftChatMessage.fromStringOrNull(name != null ? name : "@")); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java b/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java index 2d45ae44..cdb27f81 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.ComparatorBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityComparator; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Comparator; -public class CraftComparator extends CraftBlockEntityState implements Comparator { +public class CraftComparator extends CraftBlockEntityState implements Comparator { - public CraftComparator(World world, ComparatorBlockEntity tileEntity) { + public CraftComparator(World world, TileEntityComparator tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java b/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java index c1759aeb..5dfaf87d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java @@ -3,8 +3,9 @@ import java.util.ArrayList; import java.util.Collection; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.entity.ConduitBlockEntity; -import net.minecraft.world.phys.AABB; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.level.block.entity.TileEntityConduit; +import net.minecraft.world.phys.AxisAlignedBB; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; @@ -13,9 +14,9 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.util.BoundingBox; -public class CraftConduit extends CraftBlockEntityState implements Conduit { +public class CraftConduit extends CraftBlockEntityState implements Conduit { - public CraftConduit(World world, ConduitBlockEntity tileEntity) { + public CraftConduit(World world, TileEntityConduit tileEntity) { super(world, tileEntity); } @@ -35,27 +36,27 @@ public CraftConduit copy(Location location) { @Override public boolean isActive() { - this.ensureNoWorldGeneration(); - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + ensureNoWorldGeneration(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); return conduit != null && conduit.isActive(); } @Override public boolean isHunting() { - this.ensureNoWorldGeneration(); - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + ensureNoWorldGeneration(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); return conduit != null && conduit.isHunting(); } @Override public Collection getFrameBlocks() { - this.ensureNoWorldGeneration(); + ensureNoWorldGeneration(); Collection blocks = new ArrayList<>(); - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); if (conduit != null) { for (BlockPos position : conduit.effectBlocks) { - blocks.add(CraftBlock.at(this.getWorldHandle(), position)); + blocks.add(CraftBlock.at(getWorldHandle(), position)); } } @@ -64,26 +65,26 @@ public Collection getFrameBlocks() { @Override public int getFrameBlockCount() { - this.ensureNoWorldGeneration(); - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + ensureNoWorldGeneration(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); return (conduit != null) ? conduit.effectBlocks.size() : 0; } @Override public int getRange() { - this.ensureNoWorldGeneration(); - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); - return (conduit != null) ? ConduitBlockEntity.getRange(conduit.effectBlocks) : 0; + ensureNoWorldGeneration(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); + return (conduit != null) ? TileEntityConduit.getRange(conduit.effectBlocks) : 0; } @Override public boolean setTarget(LivingEntity target) { - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); if (conduit == null) { return false; } - net.minecraft.world.entity.LivingEntity currentTarget = conduit.destroyTarget; + EntityLiving currentTarget = conduit.destroyTarget; if (target == null) { if (currentTarget == null) { @@ -101,30 +102,30 @@ public boolean setTarget(LivingEntity target) { conduit.destroyTargetUUID = target.getUniqueId(); } - ConduitBlockEntity.updateDestroyTarget(conduit.getLevel(), this.getPosition(), this.data, conduit.effectBlocks, conduit, false); + TileEntityConduit.updateDestroyTarget(conduit.getLevel(), getPosition(), data, conduit.effectBlocks, conduit, false); return true; } @Override public LivingEntity getTarget() { - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); if (conduit == null) { return null; } - net.minecraft.world.entity.LivingEntity nmsEntity = conduit.destroyTarget; + EntityLiving nmsEntity = conduit.destroyTarget; return (nmsEntity != null) ? (LivingEntity) nmsEntity.getBukkitEntity() : null; } @Override public boolean hasTarget() { - ConduitBlockEntity conduit = (ConduitBlockEntity) this.getTileEntityFromWorld(); + TileEntityConduit conduit = (TileEntityConduit) getTileEntityFromWorld(); return conduit != null && conduit.destroyTarget != null && conduit.destroyTarget.isAlive(); } @Override public BoundingBox getHuntingArea() { - AABB bounds = ConduitBlockEntity.getDestroyRangeAABB(this.getPosition()); + AxisAlignedBB bounds = TileEntityConduit.getDestroyRangeAABB(getPosition()); return new BoundingBox(bounds.minX, bounds.minY, bounds.minZ, bounds.maxX, bounds.maxY, bounds.maxZ); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java index 007b6d66..75212d99 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java @@ -1,13 +1,22 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.LockCode; -import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; +import java.util.Collections; +import java.util.Optional; +import net.minecraft.advancements.critereon.CriterionConditionItem; +import net.minecraft.advancements.critereon.CriterionConditionValue; +import net.minecraft.core.component.DataComponentPredicate; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.world.ChestLock; +import net.minecraft.world.level.block.entity.TileEntityContainer; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Container; +import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.inventory.ItemStack; -public abstract class CraftContainer extends CraftBlockEntityState implements Container { +public abstract class CraftContainer extends CraftBlockEntityState implements Container { public CraftContainer(World world, T tileEntity) { super(world, tileEntity); @@ -19,17 +28,33 @@ protected CraftContainer(CraftContainer state, Location location) { @Override public boolean isLocked() { - return !this.getSnapshot().lockKey.key().isEmpty(); + return this.getSnapshot().lockKey != ChestLock.NO_LOCK; } @Override public String getLock() { - return this.getSnapshot().lockKey.key(); + Optional customName = this.getSnapshot().lockKey.predicate().components().asPatch().get(DataComponents.CUSTOM_NAME); + + return (customName != null) ? customName.map(CraftChatMessage::fromComponent).orElse("") : ""; } @Override public void setLock(String key) { - this.getSnapshot().lockKey = (key == null) ? LockCode.NO_LOCK : new LockCode(key); + if (key == null) { + this.getSnapshot().lockKey = ChestLock.NO_LOCK; + } else { + DataComponentPredicate predicate = DataComponentPredicate.builder().expect(DataComponents.CUSTOM_NAME, CraftChatMessage.fromStringOrNull(key)).build(); + this.getSnapshot().lockKey = new ChestLock(new CriterionConditionItem(Optional.empty(), CriterionConditionValue.IntegerRange.ANY, predicate, Collections.emptyMap())); + } + } + + @Override + public void setLockItem(ItemStack key) { + if (key == null) { + this.getSnapshot().lockKey = ChestLock.NO_LOCK; + } else { + this.getSnapshot().lockKey = new ChestLock(CraftItemStack.asCriterionConditionItem(key)); + } } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCrafter.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCrafter.java index d9cbd835..d5894a96 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCrafter.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftCrafter.java @@ -44,35 +44,35 @@ public CraftCrafter copy(Location location) { @Override public int getCraftingTicks() { - return this.getSnapshot().craftingTicksRemaining; + return getSnapshot().craftingTicksRemaining; } @Override public void setCraftingTicks(int ticks) { - this.getSnapshot().setCraftingTicksRemaining(ticks); + getSnapshot().setCraftingTicksRemaining(ticks); } @Override public boolean isSlotDisabled(int slot) { Preconditions.checkArgument(slot >= 0 && slot < 9, "Invalid slot index %s for Crafter", slot); - return this.getSnapshot().isSlotDisabled(slot); + return getSnapshot().isSlotDisabled(slot); } @Override public void setSlotDisabled(int slot, boolean disabled) { Preconditions.checkArgument(slot >= 0 && slot < 9, "Invalid slot index %s for Crafter", slot); - this.getSnapshot().setSlotState(slot, disabled); + getSnapshot().setSlotState(slot, disabled); } @Override public boolean isTriggered() { - return this.getSnapshot().isTriggered(); + return getSnapshot().isTriggered(); } @Override public void setTriggered(boolean triggered) { - this.getSnapshot().setTriggered(triggered); + getSnapshot().setTriggered(triggered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCreakingHeart.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCreakingHeart.java new file mode 100644 index 00000000..e7108cd3 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftCreakingHeart.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.world.level.block.entity.CreakingHeartBlockEntity; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.CreakingHeart; + +public class CraftCreakingHeart extends CraftBlockEntityState implements CreakingHeart { + + public CraftCreakingHeart(World world, CreakingHeartBlockEntity tileEntity) { + super(world, tileEntity); + } + + protected CraftCreakingHeart(CraftCreakingHeart state, Location location) { + super(state, location); + } + + @Override + public CraftCreakingHeart copy() { + return new CraftCreakingHeart(this, null); + } + + @Override + public CraftCreakingHeart copy(Location location) { + return new CraftCreakingHeart(this, location); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java index 42a0a0f7..334f27ca 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java @@ -8,16 +8,16 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.InclusiveRange; import net.minecraft.util.RandomSource; import net.minecraft.util.random.SimpleWeightedRandomList; -import net.minecraft.util.random.WeightedEntry.Wrapper; +import net.minecraft.util.random.WeightedEntry.b; +import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.entity.EquipmentTable; -import net.minecraft.world.level.BaseSpawner; -import net.minecraft.world.level.SpawnData; -import net.minecraft.world.level.block.entity.SpawnerBlockEntity; -import net.minecraft.world.level.block.entity.trialspawner.TrialSpawner; +import net.minecraft.world.level.MobSpawnerAbstract; +import net.minecraft.world.level.MobSpawnerData; +import net.minecraft.world.level.block.entity.TileEntityMobSpawner; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.CreatureSpawner; @@ -30,9 +30,9 @@ import org.bukkit.entity.EntitySnapshot; import org.bukkit.entity.EntityType; -public class CraftCreatureSpawner extends CraftBlockEntityState implements CreatureSpawner { +public class CraftCreatureSpawner extends CraftBlockEntityState implements CreatureSpawner { - public CraftCreatureSpawner(World world, SpawnerBlockEntity tileEntity) { + public CraftCreatureSpawner(World world, TileEntityMobSpawner tileEntity) { super(world, tileEntity); } @@ -42,12 +42,12 @@ protected CraftCreatureSpawner(CraftCreatureSpawner state, Location location) { @Override public EntityType getSpawnedType() { - SpawnData spawnData = this.getSnapshot().getSpawner().nextSpawnData; + MobSpawnerData spawnData = this.getSnapshot().getSpawner().nextSpawnData; if (spawnData == null) { return null; } - Optional> type = net.minecraft.world.entity.EntityType.by(spawnData.getEntityToSpawn()); + Optional> type = EntityTypes.by(spawnData.getEntityToSpawn()); return type.map(CraftEntityType::minecraftToBukkit).orElse(null); } @@ -55,7 +55,7 @@ public EntityType getSpawnedType() { public void setSpawnedType(EntityType entityType) { if (entityType == null) { this.getSnapshot().getSpawner().spawnPotentials = SimpleWeightedRandomList.empty(); // need clear the spawnPotentials to avoid nextSpawnData being replaced later - this.getSnapshot().getSpawner().nextSpawnData = new SpawnData(); + this.getSnapshot().getSpawner().nextSpawnData = new MobSpawnerData(); return; } Preconditions.checkArgument(entityType != EntityType.UNKNOWN, "Can't spawn EntityType %s from mob spawners!", entityType); @@ -66,7 +66,7 @@ public void setSpawnedType(EntityType entityType) { @Override public EntitySnapshot getSpawnedEntity() { - SpawnData spawnData = this.getSnapshot().getSpawner().nextSpawnData; + MobSpawnerData spawnData = this.getSnapshot().getSpawner().nextSpawnData; if (spawnData == null) { return null; } @@ -86,16 +86,16 @@ public void setSpawnedEntity(SpawnerEntry spawnerEntry) { setSpawnedEntity(this.getSnapshot().getSpawner(), spawnerEntry.getSnapshot(), spawnerEntry.getSpawnRule(), spawnerEntry.getEquipment()); } - public static void setSpawnedEntity(BaseSpawner spawner, EntitySnapshot snapshot, SpawnRule spawnRule, SpawnerEntry.Equipment equipment) { + public static void setSpawnedEntity(MobSpawnerAbstract spawner, EntitySnapshot snapshot, SpawnRule spawnRule, SpawnerEntry.Equipment equipment) { spawner.spawnPotentials = SimpleWeightedRandomList.empty(); // need clear the spawnPotentials to avoid nextSpawnData being replaced later if (snapshot == null) { - spawner.nextSpawnData = new SpawnData(); + spawner.nextSpawnData = new MobSpawnerData(); return; } - CompoundTag compoundTag = ((CraftEntitySnapshot) snapshot).getData(); + NBTTagCompound compoundTag = ((CraftEntitySnapshot) snapshot).getData(); - spawner.nextSpawnData = new SpawnData(compoundTag, Optional.ofNullable(toMinecraftRule(spawnRule)), getEquipment(equipment)); + spawner.nextSpawnData = new MobSpawnerData(compoundTag, Optional.ofNullable(toMinecraftRule(spawnRule)), getEquipment(equipment)); } @Override @@ -103,13 +103,14 @@ public void addPotentialSpawn(EntitySnapshot snapshot, int weight, SpawnRule spa addPotentialSpawn(this.getSnapshot().getSpawner(), snapshot, weight, spawnRule, null); } - public static void addPotentialSpawn(BaseSpawner spawner, EntitySnapshot snapshot, int weight, SpawnRule spawnRule, SpawnerEntry.Equipment equipment) { + public static void addPotentialSpawn(MobSpawnerAbstract spawner, EntitySnapshot snapshot, int weight, SpawnRule spawnRule, SpawnerEntry.Equipment equipment) { Preconditions.checkArgument(snapshot != null, "Snapshot cannot be null"); - CompoundTag compoundTag = ((CraftEntitySnapshot) snapshot).getData(); - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); // PAIL rename Builder + NBTTagCompound compoundTag = ((CraftEntitySnapshot) snapshot).getData(); + + SimpleWeightedRandomList.a builder = SimpleWeightedRandomList.builder(); // PAIL rename Builder spawner.spawnPotentials.unwrap().forEach(entry -> builder.add(entry.data(), entry.getWeight().asInt())); - builder.add(new SpawnData(compoundTag, Optional.ofNullable(toMinecraftRule(spawnRule)), getEquipment(equipment)), weight); + builder.add(new MobSpawnerData(compoundTag, Optional.ofNullable(toMinecraftRule(spawnRule)), getEquipment(equipment)), weight); spawner.spawnPotentials = builder.build(); } @@ -117,7 +118,7 @@ public static void addPotentialSpawn(BaseSpawner spawner, EntitySnapshot snapsho public void addPotentialSpawn(SpawnerEntry spawnerEntry) { Preconditions.checkArgument(spawnerEntry != null, "Entry cannot be null"); - this.addPotentialSpawn(spawnerEntry.getSnapshot(), spawnerEntry.getSpawnWeight(), spawnerEntry.getSpawnRule()); + addPotentialSpawn(spawnerEntry.getSnapshot(), spawnerEntry.getSpawnWeight(), spawnerEntry.getSpawnRule()); } @Override @@ -125,13 +126,13 @@ public void setPotentialSpawns(Collection entries) { setPotentialSpawns(this.getSnapshot().getSpawner(), entries); } - public static void setPotentialSpawns(BaseSpawner spawner, Collection entries) { + public static void setPotentialSpawns(MobSpawnerAbstract spawner, Collection entries) { Preconditions.checkArgument(entries != null, "Entries cannot be null"); - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); + SimpleWeightedRandomList.a builder = SimpleWeightedRandomList.builder(); for (SpawnerEntry spawnerEntry : entries) { - CompoundTag compoundTag = ((CraftEntitySnapshot) spawnerEntry.getSnapshot()).getData(); - builder.add(new SpawnData(compoundTag, Optional.ofNullable(toMinecraftRule(spawnerEntry.getSpawnRule())), CraftCreatureSpawner.getEquipment(spawnerEntry.getEquipment())), spawnerEntry.getSpawnWeight()); + NBTTagCompound compoundTag = ((CraftEntitySnapshot) spawnerEntry.getSnapshot()).getData(); + builder.add(new MobSpawnerData(compoundTag, Optional.ofNullable(toMinecraftRule(spawnerEntry.getSpawnRule())), getEquipment(spawnerEntry.getEquipment())), spawnerEntry.getSpawnWeight()); } spawner.spawnPotentials = builder.build(); } @@ -141,28 +142,28 @@ public List getPotentialSpawns() { return getPotentialSpawns(this.getSnapshot().getSpawner()); } - public static List getPotentialSpawns(BaseSpawner spawner) { + public static List getPotentialSpawns(MobSpawnerAbstract spawner) { List entries = new ArrayList<>(); - for (Wrapper entry : spawner.spawnPotentials.unwrap()) { // PAIL rename Wrapper + for (b entry : spawner.spawnPotentials.unwrap()) { // PAIL rename Wrapper CraftEntitySnapshot snapshot = CraftEntitySnapshot.create(entry.data().getEntityToSpawn()); if (snapshot != null) { SpawnRule rule = entry.data().customSpawnRules().map(CraftCreatureSpawner::fromMinecraftRule).orElse(null); - entries.add(new SpawnerEntry(snapshot, entry.getWeight().asInt(), rule, CraftCreatureSpawner.getEquipment(entry.data().equipment()))); + entries.add(new SpawnerEntry(snapshot, entry.getWeight().asInt(), rule, getEquipment(entry.data().equipment()))); } } return entries; } - public static SpawnData.CustomSpawnRules toMinecraftRule(SpawnRule rule) { // PAIL rename CustomSpawnRules + public static MobSpawnerData.a toMinecraftRule(SpawnRule rule) { // PAIL rename CustomSpawnRules if (rule == null) { return null; } - return new SpawnData.CustomSpawnRules(new InclusiveRange<>(rule.getMinBlockLight(), rule.getMaxBlockLight()), new InclusiveRange<>(rule.getMinSkyLight(), rule.getMaxSkyLight())); + return new MobSpawnerData.a(new InclusiveRange<>(rule.getMinBlockLight(), rule.getMaxBlockLight()), new InclusiveRange<>(rule.getMinSkyLight(), rule.getMaxSkyLight())); } - public static SpawnRule fromMinecraftRule(SpawnData.CustomSpawnRules rule) { + public static SpawnRule fromMinecraftRule(MobSpawnerData.a rule) { InclusiveRange blockLight = rule.blockLightLimit(); InclusiveRange skyLight = rule.skyLightLimit(); @@ -171,12 +172,12 @@ public static SpawnRule fromMinecraftRule(SpawnData.CustomSpawnRules rule) { @Override public String getCreatureTypeName() { - SpawnData spawnData = this.getSnapshot().getSpawner().nextSpawnData; + MobSpawnerData spawnData = this.getSnapshot().getSpawner().nextSpawnData; if (spawnData == null) { return null; } - Optional> type = net.minecraft.world.entity.EntityType.by(spawnData.getEntityToSpawn()); + Optional> type = EntityTypes.by(spawnData.getEntityToSpawn()); return type.map(CraftEntityType::minecraftToBukkit).map(CraftEntityType::bukkitToString).orElse(null); } @@ -185,10 +186,10 @@ public void setCreatureTypeByName(String creatureType) { // Verify input EntityType type = CraftEntityType.stringToBukkit(creatureType); if (type == null) { - this.setSpawnedType(null); + setSpawnedType(null); return; } - this.setSpawnedType(type); + setSpawnedType(type); } @Override @@ -208,7 +209,7 @@ public int getMinSpawnDelay() { @Override public void setMinSpawnDelay(int spawnDelay) { - Preconditions.checkArgument(spawnDelay <= this.getMaxSpawnDelay(), "Minimum Spawn Delay must be less than or equal to Maximum Spawn Delay"); + Preconditions.checkArgument(spawnDelay <= getMaxSpawnDelay(), "Minimum Spawn Delay must be less than or equal to Maximum Spawn Delay"); this.getSnapshot().getSpawner().minSpawnDelay = spawnDelay; } @@ -220,7 +221,7 @@ public int getMaxSpawnDelay() { @Override public void setMaxSpawnDelay(int spawnDelay) { Preconditions.checkArgument(spawnDelay > 0, "Maximum Spawn Delay must be greater than 0."); - Preconditions.checkArgument(spawnDelay >= this.getMinSpawnDelay(), "Maximum Spawn Delay must be greater than or equal to Minimum Spawn Delay"); + Preconditions.checkArgument(spawnDelay >= getMinSpawnDelay(), "Maximum Spawn Delay must be greater than or equal to Minimum Spawn Delay"); this.getSnapshot().getSpawner().maxSpawnDelay = spawnDelay; } @@ -274,7 +275,7 @@ public CraftCreatureSpawner copy(Location location) { return new CraftCreatureSpawner(this, location); } - public static Optional getEquipment(SpawnerEntry.Equipment bukkit) { + public static Optional getEquipment(SpawnerEntry.Equipment bukkit) { if (bukkit == null) { return Optional.empty(); } @@ -285,7 +286,7 @@ public static Optional getEquipment(SpawnerEntry.Equipment bukk ); } - public static SpawnerEntry.Equipment getEquipment(Optional optional) { + public static SpawnerEntry.Equipment getEquipment(Optional optional) { return optional.map((nms) -> new SpawnerEntry.Equipment( CraftLootTable.minecraftToBukkit(nms.lootTable()), new HashMap<>(nms.slotDropChances().entrySet().stream().collect(Collectors.toMap((entry) -> CraftEquipmentSlot.getSlot(entry.getKey()), Map.Entry::getValue))) diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java index 09f3a59f..a9b4d54b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.DaylightDetectorBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityLightDetector; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.DaylightDetector; -public class CraftDaylightDetector extends CraftBlockEntityState implements DaylightDetector { +public class CraftDaylightDetector extends CraftBlockEntityState implements DaylightDetector { - public CraftDaylightDetector(World world, DaylightDetectorBlockEntity tileEntity) { + public CraftDaylightDetector(World world, TileEntityLightDetector tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDecoratedPot.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDecoratedPot.java index 6e0258d4..703d4705 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDecoratedPot.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftDecoratedPot.java @@ -49,13 +49,13 @@ public void setSherd(Side face, Material sherd) { Preconditions.checkArgument(sherd == null || sherd == Material.BRICK || Tag.ITEMS_DECORATED_POT_SHERDS.isTagged(sherd), "sherd is not a valid sherd material: %s", sherd); Optional sherdItem = (sherd != null) ? Optional.of(CraftItemType.bukkitToMinecraft(sherd)) : Optional.of(Items.BRICK); - PotDecorations decorations = this.getSnapshot().getDecorations(); + PotDecorations decorations = getSnapshot().getDecorations(); switch (face) { - case BACK -> this.getSnapshot().decorations = new PotDecorations(sherdItem, decorations.left(), decorations.right(), decorations.front()); - case LEFT -> this.getSnapshot().decorations = new PotDecorations(decorations.back(), sherdItem, decorations.right(), decorations.front()); - case RIGHT -> this.getSnapshot().decorations = new PotDecorations(decorations.back(), decorations.left(), sherdItem, decorations.front()); - case FRONT -> this.getSnapshot().decorations = new PotDecorations(decorations.back(), decorations.left(), decorations.right(), sherdItem); + case BACK -> getSnapshot().decorations = new PotDecorations(sherdItem, decorations.left(), decorations.right(), decorations.front()); + case LEFT -> getSnapshot().decorations = new PotDecorations(decorations.back(), sherdItem, decorations.right(), decorations.front()); + case RIGHT -> getSnapshot().decorations = new PotDecorations(decorations.back(), decorations.left(), sherdItem, decorations.front()); + case FRONT -> getSnapshot().decorations = new PotDecorations(decorations.back(), decorations.left(), decorations.right(), sherdItem); default -> throw new IllegalArgumentException("Unexpected value: " + face); } } @@ -64,7 +64,7 @@ public void setSherd(Side face, Material sherd) { public Material getSherd(Side face) { Preconditions.checkArgument(face != null, "face must not be null"); - PotDecorations decorations = this.getSnapshot().getDecorations(); + PotDecorations decorations = getSnapshot().getDecorations(); Optional sherdItem = switch (face) { case BACK -> decorations.back(); case LEFT -> decorations.left(); @@ -78,7 +78,7 @@ public Material getSherd(Side face) { @Override public Map getSherds() { - PotDecorations decorations = this.getSnapshot().getDecorations(); + PotDecorations decorations = getSnapshot().getDecorations(); Map sherds = new EnumMap<>(Side.class); sherds.put(Side.BACK, CraftItemType.minecraftToBukkit(decorations.back().orElse(Items.BRICK))); @@ -90,7 +90,7 @@ public Map getSherds() { @Override public List getShards() { - return this.getSnapshot().getDecorations().ordered().stream().map(CraftItemType::minecraftToBukkit).collect(Collectors.toUnmodifiableList()); + return getSnapshot().getDecorations().ordered().stream().map(CraftItemType::minecraftToBukkit).collect(Collectors.toUnmodifiableList()); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java index ab9f0ee3..5215a49e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.block; +import net.minecraft.world.level.block.BlockDispenser; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.DispenserBlock; -import net.minecraft.world.level.block.entity.DispenserBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityDispenser; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -14,9 +14,9 @@ import org.bukkit.inventory.Inventory; import org.bukkit.projectiles.BlockProjectileSource; -public class CraftDispenser extends CraftLootable implements Dispenser { +public class CraftDispenser extends CraftLootable implements Dispenser { - public CraftDispenser(World world, DispenserBlockEntity tileEntity) { + public CraftDispenser(World world, TileEntityDispenser tileEntity) { super(world, tileEntity); } @@ -40,22 +40,22 @@ public Inventory getInventory() { @Override public BlockProjectileSource getBlockProjectileSource() { - Block block = this.getBlock(); + Block block = getBlock(); if (block.getType() != Material.DISPENSER) { return null; } - return new CraftBlockProjectileSource((DispenserBlockEntity) this.getTileEntityFromWorld()); + return new CraftBlockProjectileSource((TileEntityDispenser) this.getTileEntityFromWorld()); } @Override public boolean dispense() { - this.ensureNoWorldGeneration(); - Block block = this.getBlock(); + ensureNoWorldGeneration(); + Block block = getBlock(); if (block.getType() == Material.DISPENSER) { CraftWorld world = (CraftWorld) this.getWorld(); - DispenserBlock dispense = (DispenserBlock) Blocks.DISPENSER; + BlockDispenser dispense = (BlockDispenser) Blocks.DISPENSER; dispense.dispenseFrom(world.getHandle(), this.getHandle(), this.getPosition()); return true; diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java index 5eed6c24..98f59355 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.block; +import net.minecraft.world.level.block.BlockDropper; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.DropperBlock; -import net.minecraft.world.level.block.entity.DropperBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityDropper; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -12,9 +12,9 @@ import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.inventory.Inventory; -public class CraftDropper extends CraftLootable implements Dropper { +public class CraftDropper extends CraftLootable implements Dropper { - public CraftDropper(World world, DropperBlockEntity tileEntity) { + public CraftDropper(World world, TileEntityDropper tileEntity) { super(world, tileEntity); } @@ -38,11 +38,11 @@ public Inventory getInventory() { @Override public void drop() { - this.ensureNoWorldGeneration(); - Block block = this.getBlock(); + ensureNoWorldGeneration(); + Block block = getBlock(); if (block.getType() == Material.DROPPER) { CraftWorld world = (CraftWorld) this.getWorld(); - DropperBlock drop = (DropperBlock) Blocks.DROPPER; + BlockDropper drop = (BlockDropper) Blocks.DROPPER; drop.dispenseFrom(world.getHandle(), this.getHandle(), this.getPosition()); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java index 690dd79b..87613252 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.EnchantingTableBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityEnchantTable; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.EnchantingTable; import org.bukkit.craftbukkit.util.CraftChatMessage; -public class CraftEnchantingTable extends CraftBlockEntityState implements EnchantingTable { +public class CraftEnchantingTable extends CraftBlockEntityState implements EnchantingTable { - public CraftEnchantingTable(World world, EnchantingTableBlockEntity tileEntity) { + public CraftEnchantingTable(World world, TileEntityEnchantTable tileEntity) { super(world, tileEntity); } @@ -18,7 +18,7 @@ protected CraftEnchantingTable(CraftEnchantingTable state, Location location) { @Override public String getCustomName() { - EnchantingTableBlockEntity enchant = this.getSnapshot(); + TileEntityEnchantTable enchant = this.getSnapshot(); return enchant.hasCustomName() ? CraftChatMessage.fromComponent(enchant.getCustomName()) : null; } @@ -28,7 +28,7 @@ public void setCustomName(String name) { } @Override - public void applyTo(EnchantingTableBlockEntity enchantingTable) { + public void applyTo(TileEntityEnchantTable enchantingTable) { super.applyTo(enchantingTable); if (!this.getSnapshot().hasCustomName()) { diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java index c21d2813..b0c4b027 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java @@ -2,15 +2,15 @@ import java.util.Objects; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.entity.TheEndGatewayBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityEndGateway; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.EndGateway; import org.bukkit.craftbukkit.util.CraftLocation; -public class CraftEndGateway extends CraftBlockEntityState implements EndGateway { +public class CraftEndGateway extends CraftBlockEntityState implements EndGateway { - public CraftEndGateway(World world, TheEndGatewayBlockEntity tileEntity) { + public CraftEndGateway(World world, TileEntityEndGateway tileEntity) { super(world, tileEntity); } @@ -31,7 +31,7 @@ public void setExitLocation(Location location) { } else if (!Objects.equals(location.getWorld(), this.isPlaced() ? this.getWorld() : null)) { throw new IllegalArgumentException("Cannot set exit location to different world"); } else { - this.getSnapshot().exitPortal = CraftLocation.toBlockPosition(location); + this.getSnapshot().exitPortal = CraftLocation.toBlockPos(location); } } @@ -56,7 +56,7 @@ public void setAge(long age) { } @Override - public void applyTo(TheEndGatewayBlockEntity endGateway) { + public void applyTo(TileEntityEndGateway endGateway) { super.applyTo(endGateway); if (this.getSnapshot().exitPortal == null) { diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEndPortal.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEndPortal.java index 4968db34..38787ce4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEndPortal.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftEndPortal.java @@ -1,12 +1,12 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.TheEndPortalBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityEnderPortal; import org.bukkit.Location; import org.bukkit.World; -public class CraftEndPortal extends CraftBlockEntityState { +public class CraftEndPortal extends CraftBlockEntityState { - public CraftEndPortal(World world, TheEndPortalBlockEntity tileEntity) { + public CraftEndPortal(World world, TileEntityEnderPortal tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java index 07b63ce5..746d23c0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.EnderChestBlockEntity; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.entity.TileEntityEnderChest; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.EnderChest; -public class CraftEnderChest extends CraftBlockEntityState implements EnderChest { +public class CraftEnderChest extends CraftBlockEntityState implements EnderChest { - public CraftEnderChest(World world, EnderChestBlockEntity tileEntity) { + public CraftEnderChest(World world, TileEntityEnderChest tileEntity) { super(world, tileEntity); } @@ -18,28 +18,28 @@ protected CraftEnderChest(CraftEnderChest state, Location location) { @Override public void open() { - this.requirePlaced(); - if (!this.getTileEntity().openersCounter.opened && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - BlockState block = this.getTileEntity().getBlockState(); - int openCount = this.getTileEntity().openersCounter.getOpenerCount(); + requirePlaced(); + if (!getTileEntity().openersCounter.opened && getWorldHandle() instanceof net.minecraft.world.level.World) { + IBlockData block = getTileEntity().getBlockState(); + int openCount = getTileEntity().openersCounter.getOpenerCount(); - this.getTileEntity().openersCounter.onAPIOpen((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block); - this.getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block, openCount, openCount + 1); + getTileEntity().openersCounter.onAPIOpen((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block); + getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block, openCount, openCount + 1); } - this.getTileEntity().openersCounter.opened = true; + getTileEntity().openersCounter.opened = true; } @Override public void close() { - this.requirePlaced(); - if (this.getTileEntity().openersCounter.opened && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - BlockState block = this.getTileEntity().getBlockState(); - int openCount = this.getTileEntity().openersCounter.getOpenerCount(); + requirePlaced(); + if (getTileEntity().openersCounter.opened && getWorldHandle() instanceof net.minecraft.world.level.World) { + IBlockData block = getTileEntity().getBlockState(); + int openCount = getTileEntity().openersCounter.getOpenerCount(); - this.getTileEntity().openersCounter.onAPIClose((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block); - this.getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.Level) this.getWorldHandle(), this.getPosition(), block, openCount, 0); + getTileEntity().openersCounter.onAPIClose((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block); + getTileEntity().openersCounter.openerAPICountChanged((net.minecraft.world.level.World) getWorldHandle(), getPosition(), block, openCount, 0); } - this.getTileEntity().openersCounter.opened = false; + getTileEntity().openersCounter.opened = false; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java index 46a1c96e..9b0c39bd 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java @@ -2,9 +2,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.AbstractFurnaceBlock; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.level.block.BlockFurnace; +import net.minecraft.world.level.block.entity.TileEntityFurnace; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; @@ -15,7 +14,7 @@ import org.bukkit.inventory.FurnaceInventory; import org.bukkit.inventory.Recipe; -public abstract class CraftFurnace extends CraftContainer implements Furnace { +public abstract class CraftFurnace extends CraftContainer implements Furnace { public CraftFurnace(World world, T tileEntity) { super(world, tileEntity); @@ -48,7 +47,7 @@ public short getBurnTime() { public void setBurnTime(short burnTime) { this.getSnapshot().litTime = burnTime; // SPIGOT-844: Allow lighting and relighting using this API - this.data = this.data.setValue(AbstractFurnaceBlock.LIT, burnTime > 0); + this.data = this.data.setValue(BlockFurnace.LIT, burnTime > 0); } @Override @@ -74,12 +73,12 @@ public void setCookTimeTotal(int cookTimeTotal) { @Override public Map, Integer> getRecipesUsed() { ImmutableMap.Builder, Integer> recipesUsed = ImmutableMap.builder(); - for (Map.Entry entrySet : this.getSnapshot().getRecipesUsed().object2IntEntrySet()) { - Recipe recipe = Bukkit.getRecipe(CraftNamespacedKey.fromMinecraft(entrySet.getKey())); + this.getSnapshot().recipesUsed.reference2IntEntrySet().fastForEach(entrySet -> { + Recipe recipe = Bukkit.getRecipe(CraftNamespacedKey.fromMinecraft(entrySet.getKey().location())); if (recipe instanceof CookingRecipe cookingRecipe) { recipesUsed.put(cookingRecipe, entrySet.getValue()); } - } + }); return recipesUsed.build(); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java index 8d3eade1..8776d394 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java @@ -1,12 +1,12 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.FurnaceBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityFurnaceFurnace; import org.bukkit.Location; import org.bukkit.World; -public class CraftFurnaceFurnace extends CraftFurnace { +public class CraftFurnaceFurnace extends CraftFurnace { - public CraftFurnaceFurnace(World world, FurnaceBlockEntity tileEntity) { + public CraftFurnaceFurnace(World world, TileEntityFurnaceFurnace tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java b/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java index 2995b407..70bc3338 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java @@ -1,15 +1,15 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.HopperBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityHopper; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Hopper; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.inventory.Inventory; -public class CraftHopper extends CraftLootable implements Hopper { +public class CraftHopper extends CraftLootable implements Hopper { - public CraftHopper(World world, HopperBlockEntity tileEntity) { + public CraftHopper(World world, TileEntityHopper tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java b/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java index 69cc43eb..3a98aac0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.JigsawBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityJigsaw; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Jigsaw; -public class CraftJigsaw extends CraftBlockEntityState implements Jigsaw { +public class CraftJigsaw extends CraftBlockEntityState implements Jigsaw { - public CraftJigsaw(World world, JigsawBlockEntity tileEntity) { + public CraftJigsaw(World world, TileEntityJigsaw tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java b/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java index 5248450d..880e32a8 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java @@ -1,23 +1,21 @@ package org.bukkit.craftbukkit.block; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.JukeboxBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.JukeboxBlockEntity; -import org.bukkit.Effect; +import net.minecraft.world.level.block.BlockJukeBox; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.entity.TileEntityJukeBox; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Jukebox; -import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.inventory.CraftInventoryJukebox; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.inventory.CraftItemType; import org.bukkit.inventory.JukeboxInventory; -public class CraftJukebox extends CraftBlockEntityState implements Jukebox { +public class CraftJukebox extends CraftBlockEntityState implements Jukebox { - public CraftJukebox(World world, JukeboxBlockEntity tileEntity) { + public CraftJukebox(World world, TileEntityJukeBox tileEntity) { super(world, tileEntity); } @@ -44,10 +42,10 @@ public boolean update(boolean force, boolean applyPhysics) { boolean result = super.update(force, applyPhysics); if (result && this.isPlaced() && this.getType() == Material.JUKEBOX) { - this.getWorldHandle().setBlock(this.getPosition(), this.data, 3); + getWorldHandle().setBlock(this.getPosition(), data, 3); - BlockEntity tileEntity = this.getTileEntityFromWorld(); - if (tileEntity instanceof JukeboxBlockEntity jukebox) { + TileEntity tileEntity = this.getTileEntityFromWorld(); + if (tileEntity instanceof TileEntityJukeBox jukebox) { jukebox.setTheItem(jukebox.getTheItem()); } } @@ -57,7 +55,7 @@ public boolean update(boolean force, boolean applyPhysics) { @Override public Material getPlaying() { - return this.getRecord().getType(); + return getRecord().getType(); } @Override @@ -66,12 +64,12 @@ public void setPlaying(Material record) { record = Material.AIR; } - this.setRecord(new org.bukkit.inventory.ItemStack(record)); + setRecord(new org.bukkit.inventory.ItemStack(record)); } @Override public boolean hasRecord() { - return this.getHandle().getValue(JukeboxBlock.HAS_RECORD) && !this.getPlaying().isAir(); + return getHandle().getValue(BlockJukeBox.HAS_RECORD) && !getPlaying().isAir(); } @Override @@ -84,31 +82,31 @@ public org.bukkit.inventory.ItemStack getRecord() { public void setRecord(org.bukkit.inventory.ItemStack record) { ItemStack nms = CraftItemStack.asNMSCopy(record); - JukeboxBlockEntity snapshot = this.getSnapshot(); + TileEntityJukeBox snapshot = this.getSnapshot(); snapshot.setSongItemWithoutPlaying(nms, snapshot.getSongPlayer().getTicksSinceSongStarted()); - this.data = this.data.setValue(JukeboxBlock.HAS_RECORD, !nms.isEmpty()); + this.data = this.data.setValue(BlockJukeBox.HAS_RECORD, !nms.isEmpty()); } @Override public boolean isPlaying() { - this.requirePlaced(); + requirePlaced(); - BlockEntity tileEntity = this.getTileEntityFromWorld(); - return tileEntity instanceof JukeboxBlockEntity jukebox && jukebox.getSongPlayer().isPlaying(); + TileEntity tileEntity = this.getTileEntityFromWorld(); + return tileEntity instanceof TileEntityJukeBox jukebox && jukebox.getSongPlayer().isPlaying(); } @Override public boolean startPlaying() { - this.requirePlaced(); + requirePlaced(); - BlockEntity tileEntity = this.getTileEntityFromWorld(); - if (!(tileEntity instanceof JukeboxBlockEntity jukebox)) { + TileEntity tileEntity = this.getTileEntityFromWorld(); + if (!(tileEntity instanceof TileEntityJukeBox jukebox)) { return false; } ItemStack record = jukebox.getTheItem(); - if (record.isEmpty() || this.isPlaying()) { + if (record.isEmpty() || isPlaying()) { return false; } @@ -118,10 +116,10 @@ public boolean startPlaying() { @Override public void stopPlaying() { - this.requirePlaced(); + requirePlaced(); - BlockEntity tileEntity = this.getTileEntityFromWorld(); - if (!(tileEntity instanceof JukeboxBlockEntity jukebox)) { + TileEntity tileEntity = this.getTileEntityFromWorld(); + if (!(tileEntity instanceof TileEntityJukeBox jukebox)) { return; } @@ -130,12 +128,12 @@ public void stopPlaying() { @Override public boolean eject() { - this.ensureNoWorldGeneration(); + ensureNoWorldGeneration(); - BlockEntity tileEntity = this.getTileEntityFromWorld(); - if (!(tileEntity instanceof JukeboxBlockEntity)) return false; + TileEntity tileEntity = this.getTileEntityFromWorld(); + if (!(tileEntity instanceof TileEntityJukeBox)) return false; - JukeboxBlockEntity jukebox = (JukeboxBlockEntity) tileEntity; + TileEntityJukeBox jukebox = (TileEntityJukeBox) tileEntity; boolean result = !jukebox.getTheItem().isEmpty(); jukebox.popOutTheItem(); return result; diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java b/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java index b881a69c..76c11ad3 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.LecternBlock; -import net.minecraft.world.level.block.entity.LecternBlockEntity; +import net.minecraft.world.level.block.BlockLectern; +import net.minecraft.world.level.block.entity.TileEntityLectern; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -9,9 +9,9 @@ import org.bukkit.craftbukkit.inventory.CraftInventoryLectern; import org.bukkit.inventory.Inventory; -public class CraftLectern extends CraftBlockEntityState implements Lectern { +public class CraftLectern extends CraftBlockEntityState implements Lectern { - public CraftLectern(World world, LecternBlockEntity tileEntity) { + public CraftLectern(World world, TileEntityLectern tileEntity) { super(world, tileEntity); } @@ -21,12 +21,12 @@ protected CraftLectern(CraftLectern state, Location location) { @Override public int getPage() { - return this.getSnapshot().getPage(); + return getSnapshot().getPage(); } @Override public void setPage(int page) { - this.getSnapshot().setPage(page); + getSnapshot().setPage(page); } @Override @@ -47,8 +47,8 @@ public Inventory getInventory() { public boolean update(boolean force, boolean applyPhysics) { boolean result = super.update(force, applyPhysics); - if (result && this.getType() == Material.LECTERN && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - LecternBlock.signalPageChange(this.world.getHandle(), this.getPosition(), this.getHandle()); + if (result && this.getType() == Material.LECTERN && getWorldHandle() instanceof net.minecraft.world.level.World) { + BlockLectern.signalPageChange(this.world.getHandle(), this.getPosition(), this.getHandle()); } return result; diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java b/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java index 5baa4ab6..716cd98e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityLootable; import org.bukkit.Location; import org.bukkit.Nameable; import org.bukkit.World; @@ -8,7 +8,7 @@ import org.bukkit.loot.LootTable; import org.bukkit.loot.Lootable; -public abstract class CraftLootable extends CraftContainer implements Nameable, Lootable { +public abstract class CraftLootable extends CraftContainer implements Nameable, Lootable { public CraftLootable(World world, T tileEntity) { super(world, tileEntity); @@ -29,26 +29,26 @@ public void applyTo(T lootable) { @Override public LootTable getLootTable() { - return CraftLootTable.minecraftToBukkit(this.getSnapshot().lootTable); + return CraftLootTable.minecraftToBukkit(getSnapshot().lootTable); } @Override public void setLootTable(LootTable table) { - this.setLootTable(table, this.getSeed()); + setLootTable(table, getSeed()); } @Override public long getSeed() { - return this.getSnapshot().lootTableSeed; + return getSnapshot().lootTableSeed; } @Override public void setSeed(long seed) { - this.setLootTable(this.getLootTable(), seed); + setLootTable(getLootTable(), seed); } private void setLootTable(LootTable table, long seed) { - this.getSnapshot().setLootTable(CraftLootTable.bukkitToMinecraft(table), seed); + getSnapshot().setLootTable(CraftLootTable.bukkitToMinecraft(table), seed); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftMovingPiston.java b/src/main/java/org/bukkit/craftbukkit/block/CraftMovingPiston.java index 25b759de..cd4e2ef9 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftMovingPiston.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftMovingPiston.java @@ -1,12 +1,12 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.piston.PistonMovingBlockEntity; +import net.minecraft.world.level.block.piston.TileEntityPiston; import org.bukkit.Location; import org.bukkit.World; -public class CraftMovingPiston extends CraftBlockEntityState { +public class CraftMovingPiston extends CraftBlockEntityState { - public CraftMovingPiston(World world, PistonMovingBlockEntity tileEntity) { + public CraftMovingPiston(World world, TileEntityPiston tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSculkCatalyst.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSculkCatalyst.java index 5211dc80..d6567d6c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSculkCatalyst.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSculkCatalyst.java @@ -22,11 +22,11 @@ protected CraftSculkCatalyst(CraftSculkCatalyst state, Location location) { public void bloom(Block block, int charge) { Preconditions.checkArgument(block != null, "block cannot be null"); Preconditions.checkArgument(charge > 0, "charge must be positive"); - this.requirePlaced(); + requirePlaced(); // bloom() is for visual blooming effect, cursors are what changes the blocks. - this.getTileEntity().getListener().bloom(this.world.getHandle(), this.getPosition(), this.getHandle(), this.world.getHandle().getRandom()); - this.getTileEntity().getListener().getSculkSpreader().addCursors(new BlockPos(block.getX(), block.getY(), block.getZ()), charge); + getTileEntity().getListener().bloom(world.getHandle(), getPosition(), getHandle(), world.getHandle().getRandom()); + getTileEntity().getListener().getSculkSpreader().addCursors(new BlockPos(block.getX(), block.getY(), block.getZ()), charge); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSculkSensor.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSculkSensor.java index 70d85dbf..2dc4a491 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSculkSensor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSculkSensor.java @@ -18,13 +18,13 @@ protected CraftSculkSensor(CraftSculkSensor state, Location location) { @Override public int getLastVibrationFrequency() { - return this.getSnapshot().getLastVibrationFrequency(); + return getSnapshot().getLastVibrationFrequency(); } @Override public void setLastVibrationFrequency(int lastVibrationFrequency) { Preconditions.checkArgument(0 <= lastVibrationFrequency && lastVibrationFrequency <= 15, "Vibration frequency must be between 0-15"); - this.getSnapshot().lastVibrationFrequency = lastVibrationFrequency; + getSnapshot().lastVibrationFrequency = lastVibrationFrequency; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSculkShrieker.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSculkShrieker.java index 9cdcbaf3..af97c980 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSculkShrieker.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSculkShrieker.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.EntityPlayer; import net.minecraft.world.level.block.entity.SculkShriekerBlockEntity; import org.bukkit.Location; import org.bukkit.World; @@ -20,20 +20,20 @@ protected CraftSculkShrieker(CraftSculkShrieker state, Location location) { @Override public int getWarningLevel() { - return this.getSnapshot().warningLevel; + return getSnapshot().warningLevel; } @Override public void setWarningLevel(int level) { - this.getSnapshot().warningLevel = level; + getSnapshot().warningLevel = level; } @Override public void tryShriek(Player player) { - this.requirePlaced(); + requirePlaced(); - ServerPlayer entityPlayer = (player == null) ? null : ((CraftPlayer) player).getHandle(); - this.getTileEntity().tryShriek(this.world.getHandle(), entityPlayer); + EntityPlayer entityPlayer = (player == null) ? null : ((CraftPlayer) player).getHandle(); + getTileEntity().tryShriek(world.getHandle(), entityPlayer); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java b/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java index 76763134..d3b985ae 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java @@ -1,9 +1,10 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.level.block.ShulkerBoxBlock; -import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.sounds.SoundCategory; +import net.minecraft.sounds.SoundEffects; +import net.minecraft.world.item.EnumColor; +import net.minecraft.world.level.block.BlockShulkerBox; +import net.minecraft.world.level.block.entity.TileEntityShulkerBox; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.World; @@ -11,9 +12,9 @@ import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.inventory.Inventory; -public class CraftShulkerBox extends CraftLootable implements ShulkerBox { +public class CraftShulkerBox extends CraftLootable implements ShulkerBox { - public CraftShulkerBox(World world, ShulkerBoxBlockEntity tileEntity) { + public CraftShulkerBox(World world, TileEntityShulkerBox tileEntity) { super(world, tileEntity); } @@ -37,31 +38,31 @@ public Inventory getInventory() { @Override public DyeColor getColor() { - net.minecraft.world.item.DyeColor color = ((ShulkerBoxBlock) CraftBlockType.bukkitToMinecraft(this.getType())).color; + EnumColor color = ((BlockShulkerBox) CraftBlockType.bukkitToMinecraft(this.getType())).color; return (color == null) ? null : DyeColor.getByWoolData((byte) color.getId()); } @Override public void open() { - this.requirePlaced(); - if (!this.getTileEntity().opened && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - net.minecraft.world.level.Level world = this.getTileEntity().getLevel(); - world.blockEvent(this.getPosition(), this.getTileEntity().getBlockState().getBlock(), 1, 1); - world.playSound(null, this.getPosition(), SoundEvents.SHULKER_BOX_OPEN, SoundSource.BLOCKS, 0.5F, world.random.nextFloat() * 0.1F + 0.9F); + requirePlaced(); + if (!getTileEntity().opened && getWorldHandle() instanceof net.minecraft.world.level.World) { + net.minecraft.world.level.World world = getTileEntity().getLevel(); + world.blockEvent(getPosition(), getTileEntity().getBlockState().getBlock(), 1, 1); + world.playSound(null, getPosition(), SoundEffects.SHULKER_BOX_OPEN, SoundCategory.BLOCKS, 0.5F, world.random.nextFloat() * 0.1F + 0.9F); } - this.getTileEntity().opened = true; + getTileEntity().opened = true; } @Override public void close() { - this.requirePlaced(); - if (this.getTileEntity().opened && this.getWorldHandle() instanceof net.minecraft.world.level.Level) { - net.minecraft.world.level.Level world = this.getTileEntity().getLevel(); - world.blockEvent(this.getPosition(), this.getTileEntity().getBlockState().getBlock(), 1, 0); - world.playSound(null, this.getPosition(), SoundEvents.SHULKER_BOX_OPEN, SoundSource.BLOCKS, 0.5F, world.random.nextFloat() * 0.1F + 0.9F); + requirePlaced(); + if (getTileEntity().opened && getWorldHandle() instanceof net.minecraft.world.level.World) { + net.minecraft.world.level.World world = getTileEntity().getLevel(); + world.blockEvent(getPosition(), getTileEntity().getBlockState().getBlock(), 1, 0); + world.playSound(null, getPosition(), SoundEffects.SHULKER_BOX_OPEN, SoundCategory.BLOCKS, 0.5F, world.random.nextFloat() * 0.1F + 0.9F); } - this.getTileEntity().opened = false; + getTileEntity().opened = false; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java index 0641d17d..ae670045 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java @@ -2,8 +2,8 @@ import com.google.common.base.Preconditions; import java.util.UUID; -import net.minecraft.network.chat.Component; -import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.world.level.block.entity.TileEntitySign; import org.bukkit.Bukkit; import org.bukkit.DyeColor; import org.bukkit.Location; @@ -19,7 +19,7 @@ import org.bukkit.event.player.PlayerSignOpenEvent; import org.jetbrains.annotations.NotNull; -public class CraftSign extends CraftBlockEntityState implements Sign { +public class CraftSign extends CraftBlockEntityState implements Sign { private final CraftSignSide front; private final CraftSignSide back; @@ -38,22 +38,22 @@ protected CraftSign(CraftSign state, Location location) { @Override public String[] getLines() { - return this.front.getLines(); + return front.getLines(); } @Override public String getLine(int index) throws IndexOutOfBoundsException { - return this.front.getLine(index); + return front.getLine(index); } @Override public void setLine(int index, String line) throws IndexOutOfBoundsException { - this.front.setLine(index, line); + front.setLine(index, line); } @Override public boolean isEditable() { - return !this.isWaxed(); + return !isWaxed(); } @Override @@ -63,22 +63,22 @@ public void setEditable(boolean editable) { @Override public boolean isWaxed() { - return this.getSnapshot().isWaxed(); + return getSnapshot().isWaxed(); } @Override public void setWaxed(boolean waxed) { - this.getSnapshot().setWaxed(waxed); + getSnapshot().setWaxed(waxed); } @Override public boolean isGlowingText() { - return this.front.isGlowingText(); + return front.isGlowingText(); } @Override public void setGlowingText(boolean glowing) { - this.front.setGlowingText(glowing); + front.setGlowingText(glowing); } @NotNull @@ -88,9 +88,9 @@ public SignSide getSide(Side side) { switch (side) { case FRONT: - return this.front; + return front; case BACK: - return this.back; + return back; default: throw new IllegalArgumentException(); } @@ -98,39 +98,39 @@ public SignSide getSide(Side side) { @Override public SignSide getTargetSide(Player player) { - this.ensureNoWorldGeneration(); + ensureNoWorldGeneration(); Preconditions.checkArgument(player != null, "player cannot be null"); - if (this.getSnapshot().isFacingFrontText(((CraftPlayer) player).getHandle())) { - return this.front; + if (getSnapshot().isFacingFrontText(((CraftPlayer) player).getHandle())) { + return front; } - return this.back; + return back; } @Override public Player getAllowedEditor() { - this.ensureNoWorldGeneration(); + ensureNoWorldGeneration(); // getPlayerWhoMayEdit is always null for the snapshot, so we use the wrapped TileEntity - UUID id = this.getTileEntity().getPlayerWhoMayEdit(); + UUID id = getTileEntity().getPlayerWhoMayEdit(); return (id == null) ? null : Bukkit.getPlayer(id); } @Override public DyeColor getColor() { - return this.front.getColor(); + return front.getColor(); } @Override public void setColor(DyeColor color) { - this.front.setColor(color); + front.setColor(color); } @Override public void applyTo(T sign) { - this.getSnapshot().setText(this.front.applyLegacyStringToSignSide(), true); - this.getSnapshot().setText(this.back.applyLegacyStringToSignSide(), false); + getSnapshot().setText(front.applyLegacyStringToSignSide(), true); + getSnapshot().setText(back.applyLegacyStringToSignSide(), false); super.applyTo(sign); } @@ -155,35 +155,35 @@ public static void openSign(Sign sign, Player player, Side side) { return; } - SignBlockEntity handle = ((CraftSign) sign).getTileEntity(); + TileEntitySign handle = ((CraftSign) sign).getTileEntity(); handle.setAllowedPlayerEditor(player.getUniqueId()); ((CraftPlayer) player).getHandle().openTextEdit(handle, Side.FRONT == side); } - public static Component[] sanitizeLines(String[] lines) { - Component[] components = new Component[4]; + public static IChatBaseComponent[] sanitizeLines(String[] lines) { + IChatBaseComponent[] components = new IChatBaseComponent[4]; for (int i = 0; i < 4; i++) { if (i < lines.length && lines[i] != null) { components[i] = CraftChatMessage.fromString(lines[i])[0]; } else { - components[i] = Component.empty(); + components[i] = IChatBaseComponent.empty(); } } return components; } - public static String[] revertComponents(Component[] components) { + public static String[] revertComponents(IChatBaseComponent[] components) { String[] lines = new String[components.length]; for (int i = 0; i < lines.length; i++) { - lines[i] = CraftSign.revertComponent(components[i]); + lines[i] = revertComponent(components[i]); } return lines; } - private static String revertComponent(Component component) { + private static String revertComponent(IChatBaseComponent component) { return CraftChatMessage.fromComponent(component); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java index 15117120..650e25c1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java @@ -2,11 +2,11 @@ import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; -import net.minecraft.Util; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.SystemUtils; +import net.minecraft.resources.MinecraftKey; import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.component.ResolvableProfile; -import net.minecraft.world.level.block.entity.SkullBlockEntity; +import net.minecraft.world.level.block.entity.TileEntitySkull; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; @@ -24,12 +24,12 @@ import org.bukkit.profile.PlayerProfile; import org.jetbrains.annotations.Nullable; -public class CraftSkull extends CraftBlockEntityState implements Skull { +public class CraftSkull extends CraftBlockEntityState implements Skull { private static final int MAX_OWNER_LENGTH = 16; private ResolvableProfile profile; - public CraftSkull(World world, SkullBlockEntity tileEntity) { + public CraftSkull(World world, TileEntitySkull tileEntity) { super(world, tileEntity); } @@ -38,28 +38,28 @@ protected CraftSkull(CraftSkull state, Location location) { } @Override - public void load(SkullBlockEntity skull) { + public void load(TileEntitySkull skull) { super.load(skull); ResolvableProfile owner = skull.getOwnerProfile(); if (owner != null) { - this.profile = owner; + profile = owner; } } @Override public boolean hasOwner() { - return this.profile != null; + return profile != null; } @Override public String getOwner() { - return this.hasOwner() ? this.profile.name().orElse(null) : null; + return hasOwner() ? profile.name().orElse(null) : null; } @Override public boolean setOwner(String name) { - if (name == null || name.length() > CraftSkull.MAX_OWNER_LENGTH) { + if (name == null || name.length() > MAX_OWNER_LENGTH) { return false; } @@ -75,7 +75,7 @@ public boolean setOwner(String name) { @Override public OfflinePlayer getOwningPlayer() { if (hasOwner()) { - if (profile.id().filter(u -> !u.equals(Util.NIL_UUID)).isPresent()) { + if (profile.id().filter(u -> !u.equals(SystemUtils.NIL_UUID)).isPresent()) { return Bukkit.getOfflinePlayer(profile.id().get()); } @@ -100,11 +100,11 @@ public void setOwningPlayer(OfflinePlayer player) { @Override public PlayerProfile getOwnerProfile() { - if (!this.hasOwner()) { + if (!hasOwner()) { return null; } - return new CraftPlayerProfile(this.profile); + return new CraftPlayerProfile(profile); } @Override @@ -118,7 +118,7 @@ public void setOwnerProfile(PlayerProfile profile) { @Override public NamespacedKey getNoteBlockSound() { - ResourceLocation key = this.getSnapshot().getNoteBlockSound(); + MinecraftKey key = getSnapshot().getNoteBlockSound(); return (key != null) ? CraftNamespacedKey.fromMinecraft(key) : null; } @@ -133,24 +133,24 @@ public void setNoteBlockSound(@Nullable NamespacedKey namespacedKey) { @Override public BlockFace getRotation() { - BlockData blockData = this.getBlockData(); + BlockData blockData = getBlockData(); return (blockData instanceof Rotatable rotatable) ? rotatable.getRotation() : ((Directional) blockData).getFacing(); } @Override public void setRotation(BlockFace rotation) { - BlockData blockData = this.getBlockData(); + BlockData blockData = getBlockData(); if (blockData instanceof Rotatable) { ((Rotatable) blockData).setRotation(rotation); } else { ((Directional) blockData).setFacing(rotation); } - this.setBlockData(blockData); + setBlockData(blockData); } @Override public SkullType getSkullType() { - switch (this.getType()) { + switch (getType()) { case SKELETON_SKULL: case SKELETON_WALL_SKULL: return SkullType.SKELETON; @@ -173,7 +173,7 @@ public SkullType getSkullType() { case DRAGON_WALL_HEAD: return SkullType.DRAGON; default: - throw new IllegalArgumentException("Unknown SkullType for " + this.getType()); + throw new IllegalArgumentException("Unknown SkullType for " + getType()); } } @@ -183,10 +183,10 @@ public void setSkullType(SkullType skullType) { } @Override - public void applyTo(SkullBlockEntity skull) { + public void applyTo(TileEntitySkull skull) { super.applyTo(skull); - if (this.getSkullType() == SkullType.PLAYER) { + if (getSkullType() == SkullType.PLAYER) { skull.setOwner(hasOwner() ? profile : null); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java index 756cc05c..aa5d9393 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.block; -import net.minecraft.world.level.block.entity.SmokerBlockEntity; +import net.minecraft.world.level.block.entity.TileEntitySmoker; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Smoker; -public class CraftSmoker extends CraftFurnace implements Smoker { +public class CraftSmoker extends CraftFurnace implements Smoker { - public CraftSmoker(World world, SmokerBlockEntity tileEntity) { + public CraftSmoker(World world, TileEntitySmoker tileEntity) { super(world, tileEntity); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java index 30546017..f867c7d3 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java @@ -1,9 +1,10 @@ package org.bukkit.craftbukkit.block; import com.google.common.base.Preconditions; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.block.entity.StructureBlockEntity; -import net.minecraft.world.level.block.state.properties.StructureMode; +import net.minecraft.world.level.block.EnumBlockMirror; +import net.minecraft.world.level.block.EnumBlockRotation; +import net.minecraft.world.level.block.entity.TileEntityStructure; +import net.minecraft.world.level.block.state.properties.BlockPropertyStructureMode; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Structure; @@ -15,11 +16,11 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.util.BlockVector; -public class CraftStructureBlock extends CraftBlockEntityState implements Structure { +public class CraftStructureBlock extends CraftBlockEntityState implements Structure { private static final int MAX_SIZE = 48; - public CraftStructureBlock(World world, StructureBlockEntity tileEntity) { + public CraftStructureBlock(World world, TileEntityStructure tileEntity) { super(world, tileEntity); } @@ -29,170 +30,170 @@ protected CraftStructureBlock(CraftStructureBlock state, Location location) { @Override public String getStructureName() { - return this.getSnapshot().getStructureName(); + return getSnapshot().getStructureName(); } @Override public void setStructureName(String name) { Preconditions.checkArgument(name != null, "Structure name cannot be null"); - this.getSnapshot().setStructureName(name); + getSnapshot().setStructureName(name); } @Override public String getAuthor() { - return this.getSnapshot().author; + return getSnapshot().author; } @Override public void setAuthor(String author) { Preconditions.checkArgument(author != null, "Author name cannot be null"); Preconditions.checkArgument(!author.isEmpty(), "Author name cannot be empty"); - this.getSnapshot().author = author; + getSnapshot().author = author; } @Override public void setAuthor(LivingEntity entity) { Preconditions.checkArgument(entity != null, "Structure Block author entity cannot be null"); - this.getSnapshot().createdBy(((CraftLivingEntity) entity).getHandle()); + getSnapshot().createdBy(((CraftLivingEntity) entity).getHandle()); } @Override public BlockVector getRelativePosition() { - return CraftBlockVector.toBukkit(this.getSnapshot().structurePos); + return CraftBlockVector.toBukkit(getSnapshot().structurePos); } @Override public void setRelativePosition(BlockVector vector) { - Preconditions.checkArgument(CraftStructureBlock.isBetween(vector.getBlockX(), -CraftStructureBlock.MAX_SIZE, CraftStructureBlock.MAX_SIZE), "Structure Size (X) must be between -%s and %s but got %s", CraftStructureBlock.MAX_SIZE, CraftStructureBlock.MAX_SIZE, vector.getBlockX()); - Preconditions.checkArgument(CraftStructureBlock.isBetween(vector.getBlockY(), -CraftStructureBlock.MAX_SIZE, CraftStructureBlock.MAX_SIZE), "Structure Size (Y) must be between -%s and %s but got %s", CraftStructureBlock.MAX_SIZE, CraftStructureBlock.MAX_SIZE, vector.getBlockY()); - Preconditions.checkArgument(CraftStructureBlock.isBetween(vector.getBlockZ(), -CraftStructureBlock.MAX_SIZE, CraftStructureBlock.MAX_SIZE), "Structure Size (Z) must be between -%s and %s but got %s", CraftStructureBlock.MAX_SIZE, CraftStructureBlock.MAX_SIZE, vector.getBlockZ()); - this.getSnapshot().structurePos = CraftBlockVector.toBlockPosition(vector); + Preconditions.checkArgument(isBetween(vector.getBlockX(), -MAX_SIZE, MAX_SIZE), "Structure Size (X) must be between -%s and %s but got %s", MAX_SIZE, MAX_SIZE, vector.getBlockX()); + Preconditions.checkArgument(isBetween(vector.getBlockY(), -MAX_SIZE, MAX_SIZE), "Structure Size (Y) must be between -%s and %s but got %s", MAX_SIZE, MAX_SIZE, vector.getBlockY()); + Preconditions.checkArgument(isBetween(vector.getBlockZ(), -MAX_SIZE, MAX_SIZE), "Structure Size (Z) must be between -%s and %s but got %s", MAX_SIZE, MAX_SIZE, vector.getBlockZ()); + getSnapshot().structurePos = CraftBlockVector.toBlockPos(vector); } @Override public BlockVector getStructureSize() { - return CraftBlockVector.toBukkit(this.getSnapshot().structureSize); + return CraftBlockVector.toBukkit(getSnapshot().structureSize); } @Override public void setStructureSize(BlockVector vector) { - Preconditions.checkArgument(CraftStructureBlock.isBetween(vector.getBlockX(), 0, CraftStructureBlock.MAX_SIZE), "Structure Size (X) must be between %s and %s but got %s", 0, CraftStructureBlock.MAX_SIZE, vector.getBlockX()); - Preconditions.checkArgument(CraftStructureBlock.isBetween(vector.getBlockY(), 0, CraftStructureBlock.MAX_SIZE), "Structure Size (Y) must be between %s and %s but got %s", 0, CraftStructureBlock.MAX_SIZE, vector.getBlockY()); - Preconditions.checkArgument(CraftStructureBlock.isBetween(vector.getBlockZ(), 0, CraftStructureBlock.MAX_SIZE), "Structure Size (Z) must be between %s and %s but got %s", 0, CraftStructureBlock.MAX_SIZE, vector.getBlockZ()); - this.getSnapshot().structureSize = CraftBlockVector.toBlockPosition(vector); + Preconditions.checkArgument(isBetween(vector.getBlockX(), 0, MAX_SIZE), "Structure Size (X) must be between %s and %s but got %s", 0, MAX_SIZE, vector.getBlockX()); + Preconditions.checkArgument(isBetween(vector.getBlockY(), 0, MAX_SIZE), "Structure Size (Y) must be between %s and %s but got %s", 0, MAX_SIZE, vector.getBlockY()); + Preconditions.checkArgument(isBetween(vector.getBlockZ(), 0, MAX_SIZE), "Structure Size (Z) must be between %s and %s but got %s", 0, MAX_SIZE, vector.getBlockZ()); + getSnapshot().structureSize = CraftBlockVector.toBlockPos(vector); } @Override public void setMirror(Mirror mirror) { Preconditions.checkArgument(mirror != null, "Mirror cannot be null"); - this.getSnapshot().mirror = net.minecraft.world.level.block.Mirror.valueOf(mirror.name()); + getSnapshot().mirror = EnumBlockMirror.valueOf(mirror.name()); } @Override public Mirror getMirror() { - return Mirror.valueOf(this.getSnapshot().mirror.name()); + return Mirror.valueOf(getSnapshot().mirror.name()); } @Override public void setRotation(StructureRotation rotation) { Preconditions.checkArgument(rotation != null, "StructureRotation cannot be null"); - this.getSnapshot().rotation = Rotation.valueOf(rotation.name()); + getSnapshot().rotation = EnumBlockRotation.valueOf(rotation.name()); } @Override public StructureRotation getRotation() { - return StructureRotation.valueOf(this.getSnapshot().rotation.name()); + return StructureRotation.valueOf(getSnapshot().rotation.name()); } @Override public void setUsageMode(UsageMode mode) { Preconditions.checkArgument(mode != null, "UsageMode cannot be null"); - this.getSnapshot().mode = StructureMode.valueOf(mode.name()); + getSnapshot().mode = BlockPropertyStructureMode.valueOf(mode.name()); } @Override public UsageMode getUsageMode() { - return UsageMode.valueOf(this.getSnapshot().getMode().name()); + return UsageMode.valueOf(getSnapshot().getMode().name()); } @Override public void setIgnoreEntities(boolean flag) { - this.getSnapshot().ignoreEntities = flag; + getSnapshot().ignoreEntities = flag; } @Override public boolean isIgnoreEntities() { - return this.getSnapshot().ignoreEntities; + return getSnapshot().ignoreEntities; } @Override public void setShowAir(boolean showAir) { - this.getSnapshot().showAir = showAir; + getSnapshot().showAir = showAir; } @Override public boolean isShowAir() { - return this.getSnapshot().showAir; + return getSnapshot().showAir; } @Override public void setBoundingBoxVisible(boolean showBoundingBox) { - this.getSnapshot().showBoundingBox = showBoundingBox; + getSnapshot().showBoundingBox = showBoundingBox; } @Override public boolean isBoundingBoxVisible() { - return this.getSnapshot().showBoundingBox; + return getSnapshot().showBoundingBox; } @Override public void setIntegrity(float integrity) { - Preconditions.checkArgument(CraftStructureBlock.isBetween(integrity, 0.0f, 1.0f), "Integrity must be between 0.0f and 1.0f but got %s", integrity); - this.getSnapshot().integrity = integrity; + Preconditions.checkArgument(isBetween(integrity, 0.0f, 1.0f), "Integrity must be between 0.0f and 1.0f but got %s", integrity); + getSnapshot().integrity = integrity; } @Override public float getIntegrity() { - return this.getSnapshot().integrity; + return getSnapshot().integrity; } @Override public void setSeed(long seed) { - this.getSnapshot().seed = seed; + getSnapshot().seed = seed; } @Override public long getSeed() { - return this.getSnapshot().seed; + return getSnapshot().seed; } @Override public void setMetadata(String metadata) { Preconditions.checkArgument(metadata != null, "Structure metadata cannot be null"); - if (this.getUsageMode() == UsageMode.DATA) { - this.getSnapshot().metaData = metadata; + if (getUsageMode() == UsageMode.DATA) { + getSnapshot().metaData = metadata; } } @Override public String getMetadata() { - return this.getSnapshot().metaData; + return getSnapshot().metaData; } @Override - protected void applyTo(StructureBlockEntity tileEntity) { + protected void applyTo(TileEntityStructure tileEntity) { super.applyTo(tileEntity); - net.minecraft.world.level.LevelAccessor access = this.getWorldHandle(); + net.minecraft.world.level.GeneratorAccess access = getWorldHandle(); // Ensure block type is correct - if (access instanceof net.minecraft.world.level.Level) { + if (access instanceof net.minecraft.world.level.World) { tileEntity.setMode(tileEntity.getMode()); } else if (access != null) { // Custom handle during world generation // From TileEntityStructure#setUsageMode(BlockPropertyStructureMode) - net.minecraft.world.level.block.state.BlockState data = access.getBlockState(this.getPosition()); + net.minecraft.world.level.block.state.IBlockData data = access.getBlockState(this.getPosition()); if (data.is(net.minecraft.world.level.block.Blocks.STRUCTURE_BLOCK)) { - access.setBlock(this.getPosition(), data.setValue(net.minecraft.world.level.block.StructureBlock.MODE, tileEntity.getMode()), 2); + access.setBlock(this.getPosition(), data.setValue(net.minecraft.world.level.block.BlockStructure.MODE, tileEntity.getMode()), 2); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawner.java b/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawner.java index 669842e6..5ece537e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawner.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawner.java @@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.UUID; +import net.minecraft.core.Holder; import net.minecraft.world.level.block.TrialSpawnerBlock; import net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerData; @@ -44,7 +45,7 @@ public void setCooldownLength(int ticks) { @Override public int getRequiredPlayerRange() { - return getSnapshot().trialSpawner.getRequiredPlayerRange(); + return getSnapshot().trialSpawner.getRequiredPlayerRange(); } @Override @@ -139,20 +140,20 @@ public void setOminous(boolean ominous) { @Override public TrialSpawnerConfiguration getNormalConfiguration() { - return normalConfig; + return normalConfig; } @Override public TrialSpawnerConfiguration getOminousConfiguration() { - return ominousConfig; + return ominousConfig; } @Override protected void applyTo(TrialSpawnerBlockEntity tileEntity) { super.applyTo(tileEntity); - tileEntity.trialSpawner.normalConfig = normalConfig.toMinecraft(); - tileEntity.trialSpawner.ominousConfig = ominousConfig.toMinecraft(); + tileEntity.trialSpawner.normalConfig = Holder.direct(normalConfig.toMinecraft()); + tileEntity.trialSpawner.ominousConfig = Holder.direct(ominousConfig.toMinecraft()); } private TrialSpawnerData getTrialData() { diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawnerConfiguration.java b/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawnerConfiguration.java index 7b188232..0062664c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawnerConfiguration.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftTrialSpawnerConfiguration.java @@ -8,11 +8,12 @@ import java.util.Map; import java.util.Optional; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.resources.ResourceKey; import net.minecraft.util.random.SimpleWeightedRandomList; -import net.minecraft.util.random.WeightedEntry.Wrapper; -import net.minecraft.world.level.SpawnData; +import net.minecraft.util.random.WeightedEntry.b; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.level.MobSpawnerData; import net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerConfig; import net.minecraft.world.level.block.entity.trialspawner.TrialSpawnerData; @@ -35,7 +36,7 @@ public class CraftTrialSpawnerConfiguration implements TrialSpawnerConfiguration private float totalMobsAddedPerPlayer; private float simultaneousMobsAddedPerPlayer; private int ticksBetweenSpawn; - private SimpleWeightedRandomList spawnPotentialsDefinition; + private SimpleWeightedRandomList spawnPotentialsDefinition; private SimpleWeightedRandomList> lootTablesToEject; private ResourceKey itemsToDropWhenOminous; @@ -55,12 +56,12 @@ public CraftTrialSpawnerConfiguration(TrialSpawnerConfig minecraft, TrialSpawner @Override public EntityType getSpawnedType() { - if (spawnPotentialsDefinition.isEmpty()) { - return null; - } + if (spawnPotentialsDefinition.isEmpty()) { + return null; + } - Optional> type = net.minecraft.world.entity.EntityType.by(spawnPotentialsDefinition.unwrap().get(0).data().getEntityToSpawn()); - return type.map(CraftEntityType::minecraftToBukkit).orElse(null); + Optional> type = EntityTypes.by(spawnPotentialsDefinition.unwrap().get(0).data().getEntityToSpawn()); + return type.map(CraftEntityType::minecraftToBukkit).orElse(null); } @Override @@ -72,7 +73,7 @@ public void setSpawnedType(EntityType entityType) { } Preconditions.checkArgument(entityType != EntityType.UNKNOWN, "Can't spawn EntityType %s from mob spawners!", entityType); - SpawnData data = new SpawnData(); + MobSpawnerData data = new MobSpawnerData(); data.getEntityToSpawn().putString("id", BuiltInRegistries.ENTITY_TYPE.getKey(CraftEntityType.bukkitToMinecraft(entityType)).toString()); getTrialData().nextSpawnData = Optional.of(data); spawnPotentialsDefinition = SimpleWeightedRandomList.single(data); @@ -120,7 +121,7 @@ public void setAdditionalSimultaneousEntities(float amount) { @Override public int getDelay() { - return ticksBetweenSpawn; + return ticksBetweenSpawn; } @Override @@ -142,7 +143,7 @@ public void setSpawnRange(int spawnRange) { @Override public EntitySnapshot getSpawnedEntity() { - SimpleWeightedRandomList potentials = spawnPotentialsDefinition; + SimpleWeightedRandomList potentials = spawnPotentialsDefinition; if (potentials.isEmpty()) { return null; } @@ -169,8 +170,8 @@ private void setSpawnedEntity(EntitySnapshot snapshot, SpawnRule spawnRule, Spaw return; } - CompoundTag compoundTag = ((CraftEntitySnapshot) snapshot).getData(); - SpawnData data = new SpawnData(compoundTag, Optional.ofNullable(CraftCreatureSpawner.toMinecraftRule(spawnRule)), CraftCreatureSpawner.getEquipment(equipment)); + NBTTagCompound compoundTag = ((CraftEntitySnapshot) snapshot).getData(); + MobSpawnerData data = new MobSpawnerData(compoundTag, Optional.ofNullable(CraftCreatureSpawner.toMinecraftRule(spawnRule)), CraftCreatureSpawner.getEquipment(equipment)); getTrialData().nextSpawnData = Optional.of(data); spawnPotentialsDefinition = SimpleWeightedRandomList.single(data); @@ -184,11 +185,11 @@ public void addPotentialSpawn(EntitySnapshot snapshot, int weight, SpawnRule spa private void addPotentialSpawn(EntitySnapshot snapshot, int weight, SpawnRule spawnRule, SpawnerEntry.Equipment equipment) { Preconditions.checkArgument(snapshot != null, "Snapshot cannot be null"); - CompoundTag compoundTag = ((CraftEntitySnapshot) snapshot).getData(); + NBTTagCompound compoundTag = ((CraftEntitySnapshot) snapshot).getData(); - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); // PAIL rename Builder + SimpleWeightedRandomList.a builder = SimpleWeightedRandomList.builder(); // PAIL rename Builder spawnPotentialsDefinition.unwrap().forEach(entry -> builder.add(entry.data(), entry.getWeight().asInt())); - builder.add(new SpawnData(compoundTag, Optional.ofNullable(CraftCreatureSpawner.toMinecraftRule(spawnRule)), CraftCreatureSpawner.getEquipment(equipment)), weight); + builder.add(new MobSpawnerData(compoundTag, Optional.ofNullable(CraftCreatureSpawner.toMinecraftRule(spawnRule)), CraftCreatureSpawner.getEquipment(equipment)), weight); spawnPotentialsDefinition = builder.build(); } @@ -203,10 +204,10 @@ public void addPotentialSpawn(SpawnerEntry spawnerEntry) { public void setPotentialSpawns(Collection entries) { Preconditions.checkArgument(entries != null, "Entries cannot be null"); - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); + SimpleWeightedRandomList.a builder = SimpleWeightedRandomList.builder(); for (SpawnerEntry spawnerEntry : entries) { - CompoundTag compoundTag = ((CraftEntitySnapshot) spawnerEntry.getSnapshot()).getData(); - builder.add(new SpawnData(compoundTag, Optional.ofNullable(CraftCreatureSpawner.toMinecraftRule(spawnerEntry.getSpawnRule())), CraftCreatureSpawner.getEquipment(spawnerEntry.getEquipment())), spawnerEntry.getSpawnWeight()); + NBTTagCompound compoundTag = ((CraftEntitySnapshot) spawnerEntry.getSnapshot()).getData(); + builder.add(new MobSpawnerData(compoundTag, Optional.ofNullable(CraftCreatureSpawner.toMinecraftRule(spawnerEntry.getSpawnRule())), CraftCreatureSpawner.getEquipment(spawnerEntry.getEquipment())), spawnerEntry.getSpawnWeight()); } spawnPotentialsDefinition = builder.build(); } @@ -215,7 +216,7 @@ public void setPotentialSpawns(Collection entries) { public List getPotentialSpawns() { List entries = new ArrayList<>(); - for (Wrapper entry : spawnPotentialsDefinition.unwrap()) { // PAIL rename Wrapper + for (b entry : spawnPotentialsDefinition.unwrap()) { // PAIL rename Wrapper CraftEntitySnapshot snapshot = CraftEntitySnapshot.create(entry.data().getEntityToSpawn()); if (snapshot != null) { @@ -230,7 +231,7 @@ public List getPotentialSpawns() { public Map getPossibleRewards() { Map tables = new HashMap<>(); - for (Wrapper> entry : lootTablesToEject.unwrap()) { + for (b> entry : lootTablesToEject.unwrap()) { LootTable table = CraftLootTable.minecraftToBukkit(entry.data()); if (table != null) { tables.put(table, entry.getWeight().asInt()); @@ -245,7 +246,7 @@ public void addPossibleReward(LootTable table, int weight) { Preconditions.checkArgument(table != null, "Table cannot be null"); Preconditions.checkArgument(weight >= 1, "Weight must be at least 1"); - SimpleWeightedRandomList.Builder> builder = SimpleWeightedRandomList.builder(); + SimpleWeightedRandomList.a> builder = SimpleWeightedRandomList.builder(); lootTablesToEject.unwrap().forEach(entry -> builder.add(entry.data(), entry.getWeight().asInt())); builder.add(CraftLootTable.bukkitToMinecraft(table), weight); lootTablesToEject = builder.build(); @@ -256,9 +257,9 @@ public void removePossibleReward(LootTable table) { Preconditions.checkArgument(table != null, "Key cannot be null"); ResourceKey minecraftKey = CraftLootTable.bukkitToMinecraft(table); - SimpleWeightedRandomList.Builder> builder = SimpleWeightedRandomList.builder(); + SimpleWeightedRandomList.a> builder = SimpleWeightedRandomList.builder(); - for (Wrapper> entry : lootTablesToEject.unwrap()) { + for (b> entry : lootTablesToEject.unwrap()) { if (!entry.data().equals(minecraftKey)) { builder.add(entry.data(), entry.getWeight().asInt()); } @@ -273,7 +274,7 @@ public void setPossibleRewards(Map rewards) { return; } - SimpleWeightedRandomList.Builder> builder = SimpleWeightedRandomList.builder(); + SimpleWeightedRandomList.a> builder = SimpleWeightedRandomList.builder(); rewards.forEach((table, weight) -> { Preconditions.checkArgument(table != null, "Table cannot be null"); Preconditions.checkArgument(weight >= 1, "Weight must be at least 1"); @@ -286,7 +287,7 @@ public void setPossibleRewards(Map rewards) { @Override public int getRequiredPlayerRange() { - return snapshot.trialSpawner.getRequiredPlayerRange(); + return snapshot.trialSpawner.getRequiredPlayerRange(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/block/banner/CraftPatternType.java b/src/main/java/org/bukkit/craftbukkit/block/banner/CraftPatternType.java index 03968477..8a534735 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/banner/CraftPatternType.java +++ b/src/main/java/org/bukkit/craftbukkit/block/banner/CraftPatternType.java @@ -3,36 +3,37 @@ import com.google.common.base.Preconditions; import java.util.Locale; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; -import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.level.block.entity.EnumBannerPatternType; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.block.banner.PatternType; import org.bukkit.craftbukkit.CraftRegistry; import org.bukkit.craftbukkit.util.Handleable; -public class CraftPatternType implements PatternType, Handleable { +public class CraftPatternType implements PatternType, Handleable { private static int count = 0; - public static PatternType minecraftToBukkit(BannerPattern minecraft) { + public static PatternType minecraftToBukkit(EnumBannerPatternType minecraft) { return CraftRegistry.minecraftToBukkit(minecraft, Registries.BANNER_PATTERN, Registry.BANNER_PATTERN); } - public static PatternType minecraftHolderToBukkit(Holder minecraft) { - return CraftPatternType.minecraftToBukkit(minecraft.value()); + public static PatternType minecraftHolderToBukkit(Holder minecraft) { + return minecraftToBukkit(minecraft.value()); } - public static BannerPattern bukkitToMinecraft(PatternType bukkit) { + public static EnumBannerPatternType bukkitToMinecraft(PatternType bukkit) { return CraftRegistry.bukkitToMinecraft(bukkit); } - public static Holder bukkitToMinecraftHolder(PatternType bukkit) { + public static Holder bukkitToMinecraftHolder(PatternType bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.BANNER_PATTERN); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.BANNER_PATTERN); - if (registry.wrapAsHolder(CraftPatternType.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -41,11 +42,11 @@ public static Holder bukkitToMinecraftHolder(PatternType bukkit) } private final NamespacedKey key; - private final BannerPattern bannerPatternType; + private final EnumBannerPatternType bannerPatternType; private final String name; private final int ordinal; - public CraftPatternType(NamespacedKey key, BannerPattern bannerPatternType) { + public CraftPatternType(NamespacedKey key, EnumBannerPatternType bannerPatternType) { this.key = key; this.bannerPatternType = bannerPatternType; // For backwards compatibility, minecraft values will stile return the uppercase name without the namespace, @@ -57,38 +58,38 @@ public CraftPatternType(NamespacedKey key, BannerPattern bannerPatternType) { } else { this.name = key.toString(); } - this.ordinal = CraftPatternType.count++; + this.ordinal = count++; } @Override - public BannerPattern getHandle() { - return this.bannerPatternType; + public EnumBannerPatternType getHandle() { + return bannerPatternType; } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public int compareTo(PatternType patternType) { - return this.ordinal - patternType.ordinal(); + return ordinal - patternType.ordinal(); } @Override public String name() { - return this.name; + return name; } @Override public int ordinal() { - return this.ordinal; + return ordinal; } @Override public String toString() { // For backwards compatibility - return this.name(); + return name(); } @Override @@ -101,12 +102,12 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((PatternType) other).getKey()); + return getKey().equals(((PatternType) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } @Override @@ -158,4 +159,4 @@ public String getIdentifier() { default -> this.getKey().toString(); }; } -} \ No newline at end of file +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java index 09616eb1..124a7962 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java @@ -4,20 +4,20 @@ public abstract class CraftAgeable extends CraftBlockData implements Ageable { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger("age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger("age"); @Override public int getAge() { - return this.get(CraftAgeable.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftAgeable.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftAgeable.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java index 2b9b115a..a295c404 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java @@ -4,20 +4,20 @@ public abstract class CraftAnaloguePowerable extends CraftBlockData implements AnaloguePowerable { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger("power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger("power"); @Override public int getPower() { - return this.get(CraftAnaloguePowerable.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftAnaloguePowerable.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftAnaloguePowerable.POWER); + return getMax(POWER); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java index 005ff155..dd2099a5 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java @@ -4,15 +4,15 @@ public abstract class CraftAttachable extends CraftBlockData implements Attachable { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty ATTACHED = getBoolean("attached"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean ATTACHED = getBoolean("attached"); @Override public boolean isAttached() { - return this.get(CraftAttachable.ATTACHED); + return get(ATTACHED); } @Override public void setAttached(boolean attached) { - this.set(CraftAttachable.ATTACHED, attached); + set(ATTACHED, attached); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java index c8dd400c..79837ff2 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java @@ -4,15 +4,15 @@ public class CraftBisected extends CraftBlockData implements Bisected { - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum("half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum("half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftBisected.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftBisected.HALF, half); + set(HALF, half); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java index eadc24ce..c83fc01b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java @@ -9,19 +9,22 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.commands.arguments.blocks.ArgumentBlock; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.EnumDirection; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.StringRepresentable; -import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.core.registries.Registries; +import net.minecraft.util.INamable; +import net.minecraft.world.level.BlockAccessAir; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.block.state.StateHolder; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.level.block.state.properties.EnumProperty; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.block.EnumBlockMirror; +import net.minecraft.world.level.block.EnumBlockRotation; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.block.state.IBlockDataHolder; +import net.minecraft.world.level.block.state.properties.BlockStateBoolean; +import net.minecraft.world.level.block.state.properties.BlockStateEnum; +import net.minecraft.world.level.block.state.properties.BlockStateInteger; +import net.minecraft.world.level.block.state.properties.IBlockState; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; @@ -34,6 +37,7 @@ import org.bukkit.block.data.BlockData; import org.bukkit.block.structure.Mirror; import org.bukkit.block.structure.StructureRotation; +import org.bukkit.craftbukkit.CraftRegistry; import org.bukkit.craftbukkit.CraftSoundGroup; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.block.CraftBlock; @@ -48,24 +52,24 @@ public class CraftBlockData implements BlockData { - private net.minecraft.world.level.block.state.BlockState state; - private Map, Comparable> parsedStates; + private IBlockData state; + private Map, Comparable> parsedStates; protected CraftBlockData() { throw new AssertionError("Template Constructor"); } - protected CraftBlockData(net.minecraft.world.level.block.state.BlockState state) { + protected CraftBlockData(IBlockData state) { this.state = state; } @Override public Material getMaterial() { - return CraftBlockType.minecraftToBukkit(this.state.getBlock()); + return CraftBlockType.minecraftToBukkit(state.getBlock()); } - public net.minecraft.world.level.block.state.BlockState getState() { - return this.state; + public IBlockData getState() { + return state; } /** @@ -76,8 +80,8 @@ public net.minecraft.world.level.block.state.BlockState getState() { * @param the type * @return the matching Bukkit type */ - protected > B get(EnumProperty nms, Class bukkit) { - return CraftBlockData.toBukkit(this.state.getValue(nms), bukkit); + protected > B get(BlockStateEnum nms, Class bukkit) { + return toBukkit(state.getValue(nms), bukkit); } /** @@ -90,27 +94,27 @@ protected > B get(EnumProperty nms, Class bukkit) { * @return an immutable Set of values in their appropriate Bukkit type */ @SuppressWarnings("unchecked") - protected > Set getValues(EnumProperty nms, Class bukkit) { + protected > Set getValues(BlockStateEnum nms, Class bukkit) { ImmutableSet.Builder values = ImmutableSet.builder(); for (Enum e : nms.getPossibleValues()) { - values.add(CraftBlockData.toBukkit(e, bukkit)); + values.add(toBukkit(e, bukkit)); } return values.build(); } /** - * Set a given {@link EnumProperty} with the matching enum from Bukkit. + * Set a given {@link BlockStateEnum} with the matching enum from Bukkit. * * @param nms the NMS BlockStateEnum to set * @param bukkit the matching Bukkit Enum * @param the Bukkit type * @param the NMS type */ - protected , N extends Enum & StringRepresentable> void set(EnumProperty nms, Enum bukkit) { + protected , N extends Enum & INamable> void set(BlockStateEnum nms, Enum bukkit) { this.parsedStates = null; - this.state = this.state.setValue(nms, CraftBlockData.toNMS(bukkit, nms.getValueClass())); + this.state = this.state.setValue(nms, toNMS(bukkit, nms.getValueClass())); } @Override @@ -122,7 +126,7 @@ public BlockData merge(BlockData data) { CraftBlockData clone = (CraftBlockData) this.clone(); clone.parsedStates = null; - for (Property parsed : craft.parsedStates.keySet()) { + for (IBlockState parsed : craft.parsedStates.keySet()) { clone.state = clone.state.setValue(parsed, craft.state.getValue(parsed)); } @@ -164,10 +168,10 @@ public boolean matches(BlockData data) { */ @SuppressWarnings("unchecked") private static > B toBukkit(Enum nms, Class bukkit) { - if (nms instanceof Direction) { - return (B) CraftBlock.notchToBlockFace((Direction) nms); + if (nms instanceof EnumDirection) { + return (B) CraftBlock.notchToBlockFace((EnumDirection) nms); } - return (B) CraftBlockData.ENUM_VALUES.computeIfAbsent(bukkit, Class::getEnumConstants)[nms.ordinal()]; + return (B) ENUM_VALUES.computeIfAbsent(bukkit, Class::getEnumConstants)[nms.ordinal()]; } /** @@ -179,11 +183,11 @@ private static > B toBukkit(Enum nms, Class bukkit) { * @throws IllegalStateException if the Enum could not be converted */ @SuppressWarnings("unchecked") - private static & StringRepresentable> N toNMS(Enum bukkit, Class nms) { + private static & INamable> N toNMS(Enum bukkit, Class nms) { if (bukkit instanceof BlockFace) { return (N) CraftBlock.blockFaceToNotch((BlockFace) bukkit); } - return (N) CraftBlockData.ENUM_VALUES.computeIfAbsent(nms, Class::getEnumConstants)[bukkit.ordinal()]; + return (N) ENUM_VALUES.computeIfAbsent(nms, Class::getEnumConstants)[bukkit.ordinal()]; } /** @@ -193,7 +197,7 @@ private static & StringRepresentable> N toNMS(Enum bukkit, * @param the type * @return the current value of the given state */ - protected > T get(Property ibs) { + protected > T get(IBlockState ibs) { // Straight integer or boolean getter return this.state.getValue(ibs); } @@ -206,7 +210,7 @@ protected > T get(Property ibs) { * @param the state's type * @param the value's type. Must match the state's type. */ - public , V extends T> void set(Property ibs, V v) { + public , V extends T> void set(IBlockState ibs, V v) { // Straight integer or boolean setter this.parsedStates = null; this.state = this.state.setValue(ibs, v); @@ -214,12 +218,12 @@ public , V extends T> void set(Property ibs, V v) { @Override public String getAsString() { - return this.toString(this.state.getValues()); + return toString(state.getValues()); } @Override public String getAsString(boolean hideUnspecified) { - return (hideUnspecified && this.parsedStates != null) ? this.toString(this.parsedStates) : this.getAsString(); + return (hideUnspecified && parsedStates != null) ? toString(parsedStates) : getAsString(); } @Override @@ -233,16 +237,16 @@ public BlockData clone() { @Override public String toString() { - return "CraftBlockData{" + this.getAsString() + "}"; + return "CraftBlockData{" + getAsString() + "}"; } // Mimicked from BlockDataAbstract#toString() - public String toString(Map, Comparable> states) { - StringBuilder stateString = new StringBuilder(BuiltInRegistries.BLOCK.getKey(this.state.getBlock()).toString()); + public String toString(Map, Comparable> states) { + StringBuilder stateString = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()); if (!states.isEmpty()) { stateString.append('['); - stateString.append(states.entrySet().stream().map(StateHolder.PROPERTY_ENTRY_TO_STRING_FUNCTION).collect(Collectors.joining(","))); + stateString.append(states.entrySet().stream().map(IBlockDataHolder.PROPERTY_ENTRY_TO_STRING_FUNCTION).collect(Collectors.joining(","))); stateString.append(']'); } @@ -252,8 +256,8 @@ public String toString(Map, Comparable> states) { public Map toStates() { Map compound = new HashMap<>(); - for (Map.Entry, Comparable> entry : this.state.getValues().entrySet()) { - Property iblockstate = (Property) entry.getKey(); + for (Map.Entry, Comparable> entry : state.getValues().entrySet()) { + IBlockState iblockstate = (IBlockState) entry.getKey(); compound.put(iblockstate.getName(), iblockstate.getName(entry.getValue())); } @@ -263,48 +267,48 @@ public Map toStates() { @Override public boolean equals(Object obj) { - return obj instanceof CraftBlockData && this.state.equals(((CraftBlockData) obj).state); + return obj instanceof CraftBlockData && state.equals(((CraftBlockData) obj).state); } @Override public int hashCode() { - return this.state.hashCode(); + return state.hashCode(); } - protected static BooleanProperty getBoolean(String name) { + protected static BlockStateBoolean getBoolean(String name) { throw new AssertionError("Template Method"); } - protected static BooleanProperty getBoolean(String name, boolean optional) { + protected static BlockStateBoolean getBoolean(String name, boolean optional) { throw new AssertionError("Template Method"); } - protected static EnumProperty getEnum(String name) { + protected static BlockStateEnum getEnum(String name) { throw new AssertionError("Template Method"); } - protected static IntegerProperty getInteger(String name) { + protected static BlockStateInteger getInteger(String name) { throw new AssertionError("Template Method"); } - protected static BooleanProperty getBoolean(Class block, String name) { - return (BooleanProperty) CraftBlockData.getState(block, name, false); + protected static BlockStateBoolean getBoolean(Class block, String name) { + return (BlockStateBoolean) getState(block, name, false); } - protected static BooleanProperty getBoolean(Class block, String name, boolean optional) { - return (BooleanProperty) CraftBlockData.getState(block, name, optional); + protected static BlockStateBoolean getBoolean(Class block, String name, boolean optional) { + return (BlockStateBoolean) getState(block, name, optional); } - protected static EnumProperty getEnum(Class block, String name) { - return (EnumProperty) CraftBlockData.getState(block, name, false); + protected static BlockStateEnum getEnum(Class block, String name) { + return (BlockStateEnum) getState(block, name, false); } - protected static IntegerProperty getInteger(Class block, String name) { - return (IntegerProperty) CraftBlockData.getState(block, name, false); + protected static BlockStateInteger getInteger(Class block, String name) { + return (BlockStateInteger) getState(block, name, false); } /** - * Get a specified {@link Property} from a given block's class with a + * Get a specified {@link IBlockState} from a given block's class with a * given name * * @param block the class to retrieve the state from @@ -314,15 +318,15 @@ protected static IntegerProperty getInteger(Class block, String * @throws IllegalStateException if the state is null and {@code optional} * is false. */ - private static Property getState(Class block, String name, boolean optional) { - Property state = null; + private static IBlockState getState(Class block, String name, boolean optional) { + IBlockState state = null; for (Block instance : BuiltInRegistries.BLOCK) { if (instance.getClass() == block) { if (state == null) { state = instance.getStateDefinition().getProperty(name); } else { - Property newState = instance.getStateDefinition().getProperty(name); + IBlockState newState = instance.getStateDefinition().getProperty(name); Preconditions.checkState(state == newState, "State mistmatch %s,%s", state, newState); } @@ -340,7 +344,7 @@ private static Property getState(Class block, String name, b * @param state the state to check * @return the minimum value allowed */ - protected static int getMin(IntegerProperty state) { + protected static int getMin(BlockStateInteger state) { return state.min; } @@ -350,140 +354,140 @@ protected static int getMin(IntegerProperty state) { * @param state the state to check * @return the maximum value allowed */ - protected static int getMax(IntegerProperty state) { + protected static int getMax(BlockStateInteger state) { return state.max; } // - private static final Map, Function> MAP = new HashMap<>(); + private static final Map, Function> MAP = new HashMap<>(); static { // register(net.minecraft.world.level.block.AmethystClusterBlock.class, org.bukkit.craftbukkit.block.impl.CraftAmethystCluster::new); register(net.minecraft.world.level.block.BigDripleafBlock.class, org.bukkit.craftbukkit.block.impl.CraftBigDripleaf::new); register(net.minecraft.world.level.block.BigDripleafStemBlock.class, org.bukkit.craftbukkit.block.impl.CraftBigDripleafStem::new); - register(net.minecraft.world.level.block.AnvilBlock.class, org.bukkit.craftbukkit.block.impl.CraftAnvil::new); - register(net.minecraft.world.level.block.BambooStalkBlock.class, org.bukkit.craftbukkit.block.impl.CraftBamboo::new); - register(net.minecraft.world.level.block.BannerBlock.class, org.bukkit.craftbukkit.block.impl.CraftBanner::new); - register(net.minecraft.world.level.block.WallBannerBlock.class, org.bukkit.craftbukkit.block.impl.CraftBannerWall::new); - register(net.minecraft.world.level.block.BarrelBlock.class, org.bukkit.craftbukkit.block.impl.CraftBarrel::new); - register(net.minecraft.world.level.block.BarrierBlock.class, org.bukkit.craftbukkit.block.impl.CraftBarrier::new); - register(net.minecraft.world.level.block.BedBlock.class, org.bukkit.craftbukkit.block.impl.CraftBed::new); - register(net.minecraft.world.level.block.BeehiveBlock.class, org.bukkit.craftbukkit.block.impl.CraftBeehive::new); - register(net.minecraft.world.level.block.BeetrootBlock.class, org.bukkit.craftbukkit.block.impl.CraftBeetroot::new); - register(net.minecraft.world.level.block.BellBlock.class, org.bukkit.craftbukkit.block.impl.CraftBell::new); - register(net.minecraft.world.level.block.BlastFurnaceBlock.class, org.bukkit.craftbukkit.block.impl.CraftBlastFurnace::new); - register(net.minecraft.world.level.block.BrewingStandBlock.class, org.bukkit.craftbukkit.block.impl.CraftBrewingStand::new); - register(net.minecraft.world.level.block.BubbleColumnBlock.class, org.bukkit.craftbukkit.block.impl.CraftBubbleColumn::new); - register(net.minecraft.world.level.block.ButtonBlock.class, org.bukkit.craftbukkit.block.impl.CraftButtonAbstract::new); - register(net.minecraft.world.level.block.CactusBlock.class, org.bukkit.craftbukkit.block.impl.CraftCactus::new); - register(net.minecraft.world.level.block.CakeBlock.class, org.bukkit.craftbukkit.block.impl.CraftCake::new); - register(net.minecraft.world.level.block.CampfireBlock.class, org.bukkit.craftbukkit.block.impl.CraftCampfire::new); - register(net.minecraft.world.level.block.CarrotBlock.class, org.bukkit.craftbukkit.block.impl.CraftCarrots::new); - register(net.minecraft.world.level.block.ChainBlock.class, org.bukkit.craftbukkit.block.impl.CraftChain::new); - register(net.minecraft.world.level.block.ChestBlock.class, org.bukkit.craftbukkit.block.impl.CraftChest::new); - register(net.minecraft.world.level.block.TrappedChestBlock.class, org.bukkit.craftbukkit.block.impl.CraftChestTrapped::new); - register(net.minecraft.world.level.block.ChorusFlowerBlock.class, org.bukkit.craftbukkit.block.impl.CraftChorusFlower::new); - register(net.minecraft.world.level.block.ChorusPlantBlock.class, org.bukkit.craftbukkit.block.impl.CraftChorusFruit::new); - register(net.minecraft.world.level.block.WallBlock.class, org.bukkit.craftbukkit.block.impl.CraftCobbleWall::new); - register(net.minecraft.world.level.block.CocoaBlock.class, org.bukkit.craftbukkit.block.impl.CraftCocoa::new); - register(net.minecraft.world.level.block.CommandBlock.class, org.bukkit.craftbukkit.block.impl.CraftCommand::new); - register(net.minecraft.world.level.block.ComposterBlock.class, org.bukkit.craftbukkit.block.impl.CraftComposter::new); - register(net.minecraft.world.level.block.ConduitBlock.class, org.bukkit.craftbukkit.block.impl.CraftConduit::new); - register(net.minecraft.world.level.block.BaseCoralPlantBlock.class, org.bukkit.craftbukkit.block.impl.CraftCoralDead::new); - register(net.minecraft.world.level.block.CoralFanBlock.class, org.bukkit.craftbukkit.block.impl.CraftCoralFan::new); - register(net.minecraft.world.level.block.BaseCoralFanBlock.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanAbstract::new); - register(net.minecraft.world.level.block.CoralWallFanBlock.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanWall::new); - register(net.minecraft.world.level.block.BaseCoralWallFanBlock.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanWallAbstract::new); - register(net.minecraft.world.level.block.CoralPlantBlock.class, org.bukkit.craftbukkit.block.impl.CraftCoralPlant::new); - register(net.minecraft.world.level.block.CropBlock.class, org.bukkit.craftbukkit.block.impl.CraftCrops::new); - register(net.minecraft.world.level.block.DaylightDetectorBlock.class, org.bukkit.craftbukkit.block.impl.CraftDaylightDetector::new); - register(net.minecraft.world.level.block.SnowyDirtBlock.class, org.bukkit.craftbukkit.block.impl.CraftDirtSnow::new); - register(net.minecraft.world.level.block.DispenserBlock.class, org.bukkit.craftbukkit.block.impl.CraftDispenser::new); - register(net.minecraft.world.level.block.DoorBlock.class, org.bukkit.craftbukkit.block.impl.CraftDoor::new); - register(net.minecraft.world.level.block.DropperBlock.class, org.bukkit.craftbukkit.block.impl.CraftDropper::new); - register(net.minecraft.world.level.block.EndRodBlock.class, org.bukkit.craftbukkit.block.impl.CraftEndRod::new); - register(net.minecraft.world.level.block.EnderChestBlock.class, org.bukkit.craftbukkit.block.impl.CraftEnderChest::new); - register(net.minecraft.world.level.block.EndPortalFrameBlock.class, org.bukkit.craftbukkit.block.impl.CraftEnderPortalFrame::new); - register(net.minecraft.world.level.block.FenceBlock.class, org.bukkit.craftbukkit.block.impl.CraftFence::new); - register(net.minecraft.world.level.block.FenceGateBlock.class, org.bukkit.craftbukkit.block.impl.CraftFenceGate::new); - register(net.minecraft.world.level.block.FireBlock.class, org.bukkit.craftbukkit.block.impl.CraftFire::new); - register(net.minecraft.world.level.block.StandingSignBlock.class, org.bukkit.craftbukkit.block.impl.CraftFloorSign::new); - register(net.minecraft.world.level.block.LiquidBlock.class, org.bukkit.craftbukkit.block.impl.CraftFluids::new); - register(net.minecraft.world.level.block.FurnaceBlock.class, org.bukkit.craftbukkit.block.impl.CraftFurnaceFurace::new); - register(net.minecraft.world.level.block.GlazedTerracottaBlock.class, org.bukkit.craftbukkit.block.impl.CraftGlazedTerracotta::new); - register(net.minecraft.world.level.block.GrassBlock.class, org.bukkit.craftbukkit.block.impl.CraftGrass::new); - register(net.minecraft.world.level.block.GrindstoneBlock.class, org.bukkit.craftbukkit.block.impl.CraftGrindstone::new); - register(net.minecraft.world.level.block.HayBlock.class, org.bukkit.craftbukkit.block.impl.CraftHay::new); - register(net.minecraft.world.level.block.HopperBlock.class, org.bukkit.craftbukkit.block.impl.CraftHopper::new); - register(net.minecraft.world.level.block.HugeMushroomBlock.class, org.bukkit.craftbukkit.block.impl.CraftHugeMushroom::new); - register(net.minecraft.world.level.block.FrostedIceBlock.class, org.bukkit.craftbukkit.block.impl.CraftIceFrost::new); - register(net.minecraft.world.level.block.IronBarsBlock.class, org.bukkit.craftbukkit.block.impl.CraftIronBars::new); - register(net.minecraft.world.level.block.JigsawBlock.class, org.bukkit.craftbukkit.block.impl.CraftJigsaw::new); - register(net.minecraft.world.level.block.JukeboxBlock.class, org.bukkit.craftbukkit.block.impl.CraftJukeBox::new); - register(net.minecraft.world.level.block.KelpBlock.class, org.bukkit.craftbukkit.block.impl.CraftKelp::new); - register(net.minecraft.world.level.block.LadderBlock.class, org.bukkit.craftbukkit.block.impl.CraftLadder::new); - register(net.minecraft.world.level.block.LanternBlock.class, org.bukkit.craftbukkit.block.impl.CraftLantern::new); - register(net.minecraft.world.level.block.LeavesBlock.class, org.bukkit.craftbukkit.block.impl.CraftLeaves::new); - register(net.minecraft.world.level.block.LecternBlock.class, org.bukkit.craftbukkit.block.impl.CraftLectern::new); - register(net.minecraft.world.level.block.LeverBlock.class, org.bukkit.craftbukkit.block.impl.CraftLever::new); - register(net.minecraft.world.level.block.LoomBlock.class, org.bukkit.craftbukkit.block.impl.CraftLoom::new); - register(net.minecraft.world.level.block.DetectorRailBlock.class, org.bukkit.craftbukkit.block.impl.CraftMinecartDetector::new); - register(net.minecraft.world.level.block.RailBlock.class, org.bukkit.craftbukkit.block.impl.CraftMinecartTrack::new); - register(net.minecraft.world.level.block.MyceliumBlock.class, org.bukkit.craftbukkit.block.impl.CraftMycel::new); - register(net.minecraft.world.level.block.NetherWartBlock.class, org.bukkit.craftbukkit.block.impl.CraftNetherWart::new); - register(net.minecraft.world.level.block.NoteBlock.class, org.bukkit.craftbukkit.block.impl.CraftNote::new); - register(net.minecraft.world.level.block.ObserverBlock.class, org.bukkit.craftbukkit.block.impl.CraftObserver::new); - register(net.minecraft.world.level.block.NetherPortalBlock.class, org.bukkit.craftbukkit.block.impl.CraftPortal::new); - register(net.minecraft.world.level.block.PotatoBlock.class, org.bukkit.craftbukkit.block.impl.CraftPotatoes::new); - register(net.minecraft.world.level.block.PoweredRailBlock.class, org.bukkit.craftbukkit.block.impl.CraftPoweredRail::new); - register(net.minecraft.world.level.block.PressurePlateBlock.class, org.bukkit.craftbukkit.block.impl.CraftPressurePlateBinary::new); - register(net.minecraft.world.level.block.WeightedPressurePlateBlock.class, org.bukkit.craftbukkit.block.impl.CraftPressurePlateWeighted::new); - register(net.minecraft.world.level.block.CarvedPumpkinBlock.class, org.bukkit.craftbukkit.block.impl.CraftPumpkinCarved::new); - register(net.minecraft.world.level.block.ComparatorBlock.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneComparator::new); - register(net.minecraft.world.level.block.RedstoneLampBlock.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneLamp::new); - register(net.minecraft.world.level.block.RedStoneOreBlock.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneOre::new); - register(net.minecraft.world.level.block.RedstoneTorchBlock.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneTorch::new); - register(net.minecraft.world.level.block.RedstoneWallTorchBlock.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneTorchWall::new); - register(net.minecraft.world.level.block.RedStoneWireBlock.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneWire::new); - register(net.minecraft.world.level.block.SugarCaneBlock.class, org.bukkit.craftbukkit.block.impl.CraftReed::new); - register(net.minecraft.world.level.block.RepeaterBlock.class, org.bukkit.craftbukkit.block.impl.CraftRepeater::new); - register(net.minecraft.world.level.block.RespawnAnchorBlock.class, org.bukkit.craftbukkit.block.impl.CraftRespawnAnchor::new); - register(net.minecraft.world.level.block.RotatedPillarBlock.class, org.bukkit.craftbukkit.block.impl.CraftRotatable::new); - register(net.minecraft.world.level.block.SaplingBlock.class, org.bukkit.craftbukkit.block.impl.CraftSapling::new); - register(net.minecraft.world.level.block.ScaffoldingBlock.class, org.bukkit.craftbukkit.block.impl.CraftScaffolding::new); - register(net.minecraft.world.level.block.SeaPickleBlock.class, org.bukkit.craftbukkit.block.impl.CraftSeaPickle::new); - register(net.minecraft.world.level.block.ShulkerBoxBlock.class, org.bukkit.craftbukkit.block.impl.CraftShulkerBox::new); - register(net.minecraft.world.level.block.SkullBlock.class, org.bukkit.craftbukkit.block.impl.CraftSkull::new); - register(net.minecraft.world.level.block.PlayerHeadBlock.class, org.bukkit.craftbukkit.block.impl.CraftSkullPlayer::new); - register(net.minecraft.world.level.block.PlayerWallHeadBlock.class, org.bukkit.craftbukkit.block.impl.CraftSkullPlayerWall::new); - register(net.minecraft.world.level.block.WallSkullBlock.class, org.bukkit.craftbukkit.block.impl.CraftSkullWall::new); - register(net.minecraft.world.level.block.SmokerBlock.class, org.bukkit.craftbukkit.block.impl.CraftSmoker::new); - register(net.minecraft.world.level.block.SnowLayerBlock.class, org.bukkit.craftbukkit.block.impl.CraftSnow::new); - register(net.minecraft.world.level.block.FarmBlock.class, org.bukkit.craftbukkit.block.impl.CraftSoil::new); - register(net.minecraft.world.level.block.StainedGlassPaneBlock.class, org.bukkit.craftbukkit.block.impl.CraftStainedGlassPane::new); - register(net.minecraft.world.level.block.StairBlock.class, org.bukkit.craftbukkit.block.impl.CraftStairs::new); - register(net.minecraft.world.level.block.StemBlock.class, org.bukkit.craftbukkit.block.impl.CraftStem::new); - register(net.minecraft.world.level.block.AttachedStemBlock.class, org.bukkit.craftbukkit.block.impl.CraftStemAttached::new); - register(net.minecraft.world.level.block.SlabBlock.class, org.bukkit.craftbukkit.block.impl.CraftStepAbstract::new); - register(net.minecraft.world.level.block.StonecutterBlock.class, org.bukkit.craftbukkit.block.impl.CraftStonecutter::new); - register(net.minecraft.world.level.block.StructureBlock.class, org.bukkit.craftbukkit.block.impl.CraftStructure::new); - register(net.minecraft.world.level.block.SweetBerryBushBlock.class, org.bukkit.craftbukkit.block.impl.CraftSweetBerryBush::new); - register(net.minecraft.world.level.block.TntBlock.class, org.bukkit.craftbukkit.block.impl.CraftTNT::new); - register(net.minecraft.world.level.block.DoublePlantBlock.class, org.bukkit.craftbukkit.block.impl.CraftTallPlant::new); - register(net.minecraft.world.level.block.TallFlowerBlock.class, org.bukkit.craftbukkit.block.impl.CraftTallPlantFlower::new); - register(net.minecraft.world.level.block.TargetBlock.class, org.bukkit.craftbukkit.block.impl.CraftTarget::new); - register(net.minecraft.world.level.block.WallTorchBlock.class, org.bukkit.craftbukkit.block.impl.CraftTorchWall::new); - register(net.minecraft.world.level.block.TrapDoorBlock.class, org.bukkit.craftbukkit.block.impl.CraftTrapdoor::new); - register(net.minecraft.world.level.block.TripWireBlock.class, org.bukkit.craftbukkit.block.impl.CraftTripwire::new); - register(net.minecraft.world.level.block.TripWireHookBlock.class, org.bukkit.craftbukkit.block.impl.CraftTripwireHook::new); - register(net.minecraft.world.level.block.TurtleEggBlock.class, org.bukkit.craftbukkit.block.impl.CraftTurtleEgg::new); - register(net.minecraft.world.level.block.TwistingVinesBlock.class, org.bukkit.craftbukkit.block.impl.CraftTwistingVines::new); - register(net.minecraft.world.level.block.VineBlock.class, org.bukkit.craftbukkit.block.impl.CraftVine::new); - register(net.minecraft.world.level.block.WallSignBlock.class, org.bukkit.craftbukkit.block.impl.CraftWallSign::new); - register(net.minecraft.world.level.block.WeepingVinesBlock.class, org.bukkit.craftbukkit.block.impl.CraftWeepingVines::new); - register(net.minecraft.world.level.block.WitherSkullBlock.class, org.bukkit.craftbukkit.block.impl.CraftWitherSkull::new); - register(net.minecraft.world.level.block.WitherWallSkullBlock.class, org.bukkit.craftbukkit.block.impl.CraftWitherSkullWall::new); + register(net.minecraft.world.level.block.BlockAnvil.class, org.bukkit.craftbukkit.block.impl.CraftAnvil::new); + register(net.minecraft.world.level.block.BlockBamboo.class, org.bukkit.craftbukkit.block.impl.CraftBamboo::new); + register(net.minecraft.world.level.block.BlockBanner.class, org.bukkit.craftbukkit.block.impl.CraftBanner::new); + register(net.minecraft.world.level.block.BlockBannerWall.class, org.bukkit.craftbukkit.block.impl.CraftBannerWall::new); + register(net.minecraft.world.level.block.BlockBarrel.class, org.bukkit.craftbukkit.block.impl.CraftBarrel::new); + register(net.minecraft.world.level.block.BlockBarrier.class, org.bukkit.craftbukkit.block.impl.CraftBarrier::new); + register(net.minecraft.world.level.block.BlockBed.class, org.bukkit.craftbukkit.block.impl.CraftBed::new); + register(net.minecraft.world.level.block.BlockBeehive.class, org.bukkit.craftbukkit.block.impl.CraftBeehive::new); + register(net.minecraft.world.level.block.BlockBeetroot.class, org.bukkit.craftbukkit.block.impl.CraftBeetroot::new); + register(net.minecraft.world.level.block.BlockBell.class, org.bukkit.craftbukkit.block.impl.CraftBell::new); + register(net.minecraft.world.level.block.BlockBlastFurnace.class, org.bukkit.craftbukkit.block.impl.CraftBlastFurnace::new); + register(net.minecraft.world.level.block.BlockBrewingStand.class, org.bukkit.craftbukkit.block.impl.CraftBrewingStand::new); + register(net.minecraft.world.level.block.BlockBubbleColumn.class, org.bukkit.craftbukkit.block.impl.CraftBubbleColumn::new); + register(net.minecraft.world.level.block.BlockButtonAbstract.class, org.bukkit.craftbukkit.block.impl.CraftButtonAbstract::new); + register(net.minecraft.world.level.block.BlockCactus.class, org.bukkit.craftbukkit.block.impl.CraftCactus::new); + register(net.minecraft.world.level.block.BlockCake.class, org.bukkit.craftbukkit.block.impl.CraftCake::new); + register(net.minecraft.world.level.block.BlockCampfire.class, org.bukkit.craftbukkit.block.impl.CraftCampfire::new); + register(net.minecraft.world.level.block.BlockCarrots.class, org.bukkit.craftbukkit.block.impl.CraftCarrots::new); + register(net.minecraft.world.level.block.BlockChain.class, org.bukkit.craftbukkit.block.impl.CraftChain::new); + register(net.minecraft.world.level.block.BlockChest.class, org.bukkit.craftbukkit.block.impl.CraftChest::new); + register(net.minecraft.world.level.block.BlockChestTrapped.class, org.bukkit.craftbukkit.block.impl.CraftChestTrapped::new); + register(net.minecraft.world.level.block.BlockChorusFlower.class, org.bukkit.craftbukkit.block.impl.CraftChorusFlower::new); + register(net.minecraft.world.level.block.BlockChorusFruit.class, org.bukkit.craftbukkit.block.impl.CraftChorusFruit::new); + register(net.minecraft.world.level.block.BlockCobbleWall.class, org.bukkit.craftbukkit.block.impl.CraftCobbleWall::new); + register(net.minecraft.world.level.block.BlockCocoa.class, org.bukkit.craftbukkit.block.impl.CraftCocoa::new); + register(net.minecraft.world.level.block.BlockCommand.class, org.bukkit.craftbukkit.block.impl.CraftCommand::new); + register(net.minecraft.world.level.block.BlockComposter.class, org.bukkit.craftbukkit.block.impl.CraftComposter::new); + register(net.minecraft.world.level.block.BlockConduit.class, org.bukkit.craftbukkit.block.impl.CraftConduit::new); + register(net.minecraft.world.level.block.BlockCoralDead.class, org.bukkit.craftbukkit.block.impl.CraftCoralDead::new); + register(net.minecraft.world.level.block.BlockCoralFan.class, org.bukkit.craftbukkit.block.impl.CraftCoralFan::new); + register(net.minecraft.world.level.block.BlockCoralFanAbstract.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanAbstract::new); + register(net.minecraft.world.level.block.BlockCoralFanWall.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanWall::new); + register(net.minecraft.world.level.block.BlockCoralFanWallAbstract.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanWallAbstract::new); + register(net.minecraft.world.level.block.BlockCoralPlant.class, org.bukkit.craftbukkit.block.impl.CraftCoralPlant::new); + register(net.minecraft.world.level.block.BlockCrops.class, org.bukkit.craftbukkit.block.impl.CraftCrops::new); + register(net.minecraft.world.level.block.BlockDaylightDetector.class, org.bukkit.craftbukkit.block.impl.CraftDaylightDetector::new); + register(net.minecraft.world.level.block.BlockDirtSnow.class, org.bukkit.craftbukkit.block.impl.CraftDirtSnow::new); + register(net.minecraft.world.level.block.BlockDispenser.class, org.bukkit.craftbukkit.block.impl.CraftDispenser::new); + register(net.minecraft.world.level.block.BlockDoor.class, org.bukkit.craftbukkit.block.impl.CraftDoor::new); + register(net.minecraft.world.level.block.BlockDropper.class, org.bukkit.craftbukkit.block.impl.CraftDropper::new); + register(net.minecraft.world.level.block.BlockEndRod.class, org.bukkit.craftbukkit.block.impl.CraftEndRod::new); + register(net.minecraft.world.level.block.BlockEnderChest.class, org.bukkit.craftbukkit.block.impl.CraftEnderChest::new); + register(net.minecraft.world.level.block.BlockEnderPortalFrame.class, org.bukkit.craftbukkit.block.impl.CraftEnderPortalFrame::new); + register(net.minecraft.world.level.block.BlockFence.class, org.bukkit.craftbukkit.block.impl.CraftFence::new); + register(net.minecraft.world.level.block.BlockFenceGate.class, org.bukkit.craftbukkit.block.impl.CraftFenceGate::new); + register(net.minecraft.world.level.block.BlockFire.class, org.bukkit.craftbukkit.block.impl.CraftFire::new); + register(net.minecraft.world.level.block.BlockFloorSign.class, org.bukkit.craftbukkit.block.impl.CraftFloorSign::new); + register(net.minecraft.world.level.block.BlockFluids.class, org.bukkit.craftbukkit.block.impl.CraftFluids::new); + register(net.minecraft.world.level.block.BlockFurnaceFurace.class, org.bukkit.craftbukkit.block.impl.CraftFurnaceFurace::new); + register(net.minecraft.world.level.block.BlockGlazedTerracotta.class, org.bukkit.craftbukkit.block.impl.CraftGlazedTerracotta::new); + register(net.minecraft.world.level.block.BlockGrass.class, org.bukkit.craftbukkit.block.impl.CraftGrass::new); + register(net.minecraft.world.level.block.BlockGrindstone.class, org.bukkit.craftbukkit.block.impl.CraftGrindstone::new); + register(net.minecraft.world.level.block.BlockHay.class, org.bukkit.craftbukkit.block.impl.CraftHay::new); + register(net.minecraft.world.level.block.BlockHopper.class, org.bukkit.craftbukkit.block.impl.CraftHopper::new); + register(net.minecraft.world.level.block.BlockHugeMushroom.class, org.bukkit.craftbukkit.block.impl.CraftHugeMushroom::new); + register(net.minecraft.world.level.block.BlockIceFrost.class, org.bukkit.craftbukkit.block.impl.CraftIceFrost::new); + register(net.minecraft.world.level.block.BlockIronBars.class, org.bukkit.craftbukkit.block.impl.CraftIronBars::new); + register(net.minecraft.world.level.block.BlockJigsaw.class, org.bukkit.craftbukkit.block.impl.CraftJigsaw::new); + register(net.minecraft.world.level.block.BlockJukeBox.class, org.bukkit.craftbukkit.block.impl.CraftJukeBox::new); + register(net.minecraft.world.level.block.BlockKelp.class, org.bukkit.craftbukkit.block.impl.CraftKelp::new); + register(net.minecraft.world.level.block.BlockLadder.class, org.bukkit.craftbukkit.block.impl.CraftLadder::new); + register(net.minecraft.world.level.block.BlockLantern.class, org.bukkit.craftbukkit.block.impl.CraftLantern::new); + register(net.minecraft.world.level.block.BlockLeaves.class, org.bukkit.craftbukkit.block.impl.CraftLeaves::new); + register(net.minecraft.world.level.block.BlockLectern.class, org.bukkit.craftbukkit.block.impl.CraftLectern::new); + register(net.minecraft.world.level.block.BlockLever.class, org.bukkit.craftbukkit.block.impl.CraftLever::new); + register(net.minecraft.world.level.block.BlockLoom.class, org.bukkit.craftbukkit.block.impl.CraftLoom::new); + register(net.minecraft.world.level.block.BlockMinecartDetector.class, org.bukkit.craftbukkit.block.impl.CraftMinecartDetector::new); + register(net.minecraft.world.level.block.BlockMinecartTrack.class, org.bukkit.craftbukkit.block.impl.CraftMinecartTrack::new); + register(net.minecraft.world.level.block.BlockMycel.class, org.bukkit.craftbukkit.block.impl.CraftMycel::new); + register(net.minecraft.world.level.block.BlockNetherWart.class, org.bukkit.craftbukkit.block.impl.CraftNetherWart::new); + register(net.minecraft.world.level.block.BlockNote.class, org.bukkit.craftbukkit.block.impl.CraftNote::new); + register(net.minecraft.world.level.block.BlockObserver.class, org.bukkit.craftbukkit.block.impl.CraftObserver::new); + register(net.minecraft.world.level.block.BlockPortal.class, org.bukkit.craftbukkit.block.impl.CraftPortal::new); + register(net.minecraft.world.level.block.BlockPotatoes.class, org.bukkit.craftbukkit.block.impl.CraftPotatoes::new); + register(net.minecraft.world.level.block.BlockPoweredRail.class, org.bukkit.craftbukkit.block.impl.CraftPoweredRail::new); + register(net.minecraft.world.level.block.BlockPressurePlateBinary.class, org.bukkit.craftbukkit.block.impl.CraftPressurePlateBinary::new); + register(net.minecraft.world.level.block.BlockPressurePlateWeighted.class, org.bukkit.craftbukkit.block.impl.CraftPressurePlateWeighted::new); + register(net.minecraft.world.level.block.BlockPumpkinCarved.class, org.bukkit.craftbukkit.block.impl.CraftPumpkinCarved::new); + register(net.minecraft.world.level.block.BlockRedstoneComparator.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneComparator::new); + register(net.minecraft.world.level.block.BlockRedstoneLamp.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneLamp::new); + register(net.minecraft.world.level.block.BlockRedstoneOre.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneOre::new); + register(net.minecraft.world.level.block.BlockRedstoneTorch.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneTorch::new); + register(net.minecraft.world.level.block.BlockRedstoneTorchWall.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneTorchWall::new); + register(net.minecraft.world.level.block.BlockRedstoneWire.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneWire::new); + register(net.minecraft.world.level.block.BlockReed.class, org.bukkit.craftbukkit.block.impl.CraftReed::new); + register(net.minecraft.world.level.block.BlockRepeater.class, org.bukkit.craftbukkit.block.impl.CraftRepeater::new); + register(net.minecraft.world.level.block.BlockRespawnAnchor.class, org.bukkit.craftbukkit.block.impl.CraftRespawnAnchor::new); + register(net.minecraft.world.level.block.BlockRotatable.class, org.bukkit.craftbukkit.block.impl.CraftRotatable::new); + register(net.minecraft.world.level.block.BlockSapling.class, org.bukkit.craftbukkit.block.impl.CraftSapling::new); + register(net.minecraft.world.level.block.BlockScaffolding.class, org.bukkit.craftbukkit.block.impl.CraftScaffolding::new); + register(net.minecraft.world.level.block.BlockSeaPickle.class, org.bukkit.craftbukkit.block.impl.CraftSeaPickle::new); + register(net.minecraft.world.level.block.BlockShulkerBox.class, org.bukkit.craftbukkit.block.impl.CraftShulkerBox::new); + register(net.minecraft.world.level.block.BlockSkull.class, org.bukkit.craftbukkit.block.impl.CraftSkull::new); + register(net.minecraft.world.level.block.BlockSkullPlayer.class, org.bukkit.craftbukkit.block.impl.CraftSkullPlayer::new); + register(net.minecraft.world.level.block.BlockSkullPlayerWall.class, org.bukkit.craftbukkit.block.impl.CraftSkullPlayerWall::new); + register(net.minecraft.world.level.block.BlockSkullWall.class, org.bukkit.craftbukkit.block.impl.CraftSkullWall::new); + register(net.minecraft.world.level.block.BlockSmoker.class, org.bukkit.craftbukkit.block.impl.CraftSmoker::new); + register(net.minecraft.world.level.block.BlockSnow.class, org.bukkit.craftbukkit.block.impl.CraftSnow::new); + register(net.minecraft.world.level.block.BlockSoil.class, org.bukkit.craftbukkit.block.impl.CraftSoil::new); + register(net.minecraft.world.level.block.BlockStainedGlassPane.class, org.bukkit.craftbukkit.block.impl.CraftStainedGlassPane::new); + register(net.minecraft.world.level.block.BlockStairs.class, org.bukkit.craftbukkit.block.impl.CraftStairs::new); + register(net.minecraft.world.level.block.BlockStem.class, org.bukkit.craftbukkit.block.impl.CraftStem::new); + register(net.minecraft.world.level.block.BlockStemAttached.class, org.bukkit.craftbukkit.block.impl.CraftStemAttached::new); + register(net.minecraft.world.level.block.BlockStepAbstract.class, org.bukkit.craftbukkit.block.impl.CraftStepAbstract::new); + register(net.minecraft.world.level.block.BlockStonecutter.class, org.bukkit.craftbukkit.block.impl.CraftStonecutter::new); + register(net.minecraft.world.level.block.BlockStructure.class, org.bukkit.craftbukkit.block.impl.CraftStructure::new); + register(net.minecraft.world.level.block.BlockSweetBerryBush.class, org.bukkit.craftbukkit.block.impl.CraftSweetBerryBush::new); + register(net.minecraft.world.level.block.BlockTNT.class, org.bukkit.craftbukkit.block.impl.CraftTNT::new); + register(net.minecraft.world.level.block.BlockTallPlant.class, org.bukkit.craftbukkit.block.impl.CraftTallPlant::new); + register(net.minecraft.world.level.block.BlockTallPlantFlower.class, org.bukkit.craftbukkit.block.impl.CraftTallPlantFlower::new); + register(net.minecraft.world.level.block.BlockTarget.class, org.bukkit.craftbukkit.block.impl.CraftTarget::new); + register(net.minecraft.world.level.block.BlockTorchWall.class, org.bukkit.craftbukkit.block.impl.CraftTorchWall::new); + register(net.minecraft.world.level.block.BlockTrapdoor.class, org.bukkit.craftbukkit.block.impl.CraftTrapdoor::new); + register(net.minecraft.world.level.block.BlockTripwire.class, org.bukkit.craftbukkit.block.impl.CraftTripwire::new); + register(net.minecraft.world.level.block.BlockTripwireHook.class, org.bukkit.craftbukkit.block.impl.CraftTripwireHook::new); + register(net.minecraft.world.level.block.BlockTurtleEgg.class, org.bukkit.craftbukkit.block.impl.CraftTurtleEgg::new); + register(net.minecraft.world.level.block.BlockTwistingVines.class, org.bukkit.craftbukkit.block.impl.CraftTwistingVines::new); + register(net.minecraft.world.level.block.BlockVine.class, org.bukkit.craftbukkit.block.impl.CraftVine::new); + register(net.minecraft.world.level.block.BlockWallSign.class, org.bukkit.craftbukkit.block.impl.CraftWallSign::new); + register(net.minecraft.world.level.block.BlockWeepingVines.class, org.bukkit.craftbukkit.block.impl.CraftWeepingVines::new); + register(net.minecraft.world.level.block.BlockWitherSkull.class, org.bukkit.craftbukkit.block.impl.CraftWitherSkull::new); + register(net.minecraft.world.level.block.BlockWitherSkullWall.class, org.bukkit.craftbukkit.block.impl.CraftWitherSkullWall::new); register(net.minecraft.world.level.block.BrushableBlock.class, org.bukkit.craftbukkit.block.impl.CraftBrushable::new); register(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, org.bukkit.craftbukkit.block.impl.CraftCalibratedSculkSensor::new); register(net.minecraft.world.level.block.CandleBlock.class, org.bukkit.craftbukkit.block.impl.CraftCandle::new); @@ -495,9 +499,10 @@ protected static int getMax(IntegerProperty state) { register(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, org.bukkit.craftbukkit.block.impl.CraftChiseledBookShelf::new); register(net.minecraft.world.level.block.CopperBulbBlock.class, org.bukkit.craftbukkit.block.impl.CraftCopperBulb::new); register(net.minecraft.world.level.block.CrafterBlock.class, org.bukkit.craftbukkit.block.impl.CraftCrafter::new); + register(net.minecraft.world.level.block.CreakingHeartBlock.class, org.bukkit.craftbukkit.block.impl.CraftCreakingHeart::new); register(net.minecraft.world.level.block.DecoratedPotBlock.class, org.bukkit.craftbukkit.block.impl.CraftDecoratedPot::new); - register(net.minecraft.world.level.block.EquipableCarvedPumpkinBlock.class, org.bukkit.craftbukkit.block.impl.CraftEquipableCarvedPumpkin::new); register(net.minecraft.world.level.block.GlowLichenBlock.class, org.bukkit.craftbukkit.block.impl.CraftGlowLichen::new); + register(net.minecraft.world.level.block.HangingMossBlock.class, org.bukkit.craftbukkit.block.impl.CraftHangingMoss::new); register(net.minecraft.world.level.block.HangingRootsBlock.class, org.bukkit.craftbukkit.block.impl.CraftHangingRoots::new); register(net.minecraft.world.level.block.HeavyCoreBlock.class, org.bukkit.craftbukkit.block.impl.CraftHeavyCore::new); register(net.minecraft.world.level.block.InfestedRotatedPillarBlock.class, org.bukkit.craftbukkit.block.impl.CraftInfestedRotatedPillar::new); @@ -507,6 +512,7 @@ protected static int getMax(IntegerProperty state) { register(net.minecraft.world.level.block.MangroveLeavesBlock.class, org.bukkit.craftbukkit.block.impl.CraftMangroveLeaves::new); register(net.minecraft.world.level.block.MangrovePropaguleBlock.class, org.bukkit.craftbukkit.block.impl.CraftMangrovePropagule::new); register(net.minecraft.world.level.block.MangroveRootsBlock.class, org.bukkit.craftbukkit.block.impl.CraftMangroveRoots::new); + register(net.minecraft.world.level.block.MossyCarpetBlock.class, org.bukkit.craftbukkit.block.impl.CraftMossyCarpet::new); register(net.minecraft.world.level.block.PiglinWallSkullBlock.class, org.bukkit.craftbukkit.block.impl.CraftPiglinWallSkull::new); register(net.minecraft.world.level.block.PinkPetalsBlock.class, org.bukkit.craftbukkit.block.impl.CraftPinkPetals::new); register(net.minecraft.world.level.block.PitcherCropBlock.class, org.bukkit.craftbukkit.block.impl.CraftPitcherCrop::new); @@ -529,20 +535,20 @@ protected static int getMax(IntegerProperty state) { register(net.minecraft.world.level.block.WeatheringCopperSlabBlock.class, org.bukkit.craftbukkit.block.impl.CraftWeatheringCopperSlab::new); register(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, org.bukkit.craftbukkit.block.impl.CraftWeatheringCopperStair::new); register(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, org.bukkit.craftbukkit.block.impl.CraftWeatheringCopperTrapDoor::new); - register(net.minecraft.world.level.block.piston.PistonBaseBlock.class, org.bukkit.craftbukkit.block.impl.CraftPiston::new); - register(net.minecraft.world.level.block.piston.PistonHeadBlock.class, org.bukkit.craftbukkit.block.impl.CraftPistonExtension::new); - register(net.minecraft.world.level.block.piston.MovingPistonBlock.class, org.bukkit.craftbukkit.block.impl.CraftPistonMoving::new); + register(net.minecraft.world.level.block.piston.BlockPiston.class, org.bukkit.craftbukkit.block.impl.CraftPiston::new); + register(net.minecraft.world.level.block.piston.BlockPistonExtension.class, org.bukkit.craftbukkit.block.impl.CraftPistonExtension::new); + register(net.minecraft.world.level.block.piston.BlockPistonMoving.class, org.bukkit.craftbukkit.block.impl.CraftPistonMoving::new); // } - private static void register(Class nms, Function bukkit) { - Preconditions.checkState(CraftBlockData.MAP.put(nms, bukkit) == null, "Duplicate mapping %s->%s", nms, bukkit); + private static void register(Class nms, Function bukkit) { + Preconditions.checkState(MAP.put(nms, bukkit) == null, "Duplicate mapping %s->%s", nms, bukkit); } public static CraftBlockData newData(BlockType blockType, String data) { - net.minecraft.world.level.block.state.BlockState blockData; + IBlockData blockData; Block block = blockType == null ? null : ((CraftBlockType) blockType).getHandle(); - Map, Comparable> parsed = null; + Map, Comparable> parsed = null; // Data provided, use it if (data != null) { @@ -553,7 +559,7 @@ public static CraftBlockData newData(BlockType blockType, String data) { } StringReader reader = new StringReader(data); - BlockStateParser.BlockResult arg = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK.asLookup(), reader, false); + ArgumentBlock.a arg = ArgumentBlock.parseForBlock(CraftRegistry.getMinecraftRegistry(Registries.BLOCK), reader, false); Preconditions.checkArgument(!reader.canRead(), "Spurious trailing data: " + data); blockData = arg.blockState(); @@ -565,33 +571,33 @@ public static CraftBlockData newData(BlockType blockType, String data) { blockData = block.defaultBlockState(); } - CraftBlockData craft = CraftBlockData.fromData(blockData); + CraftBlockData craft = fromData(blockData); craft.parsedStates = parsed; return craft; } - public static CraftBlockData fromData(net.minecraft.world.level.block.state.BlockState data) { - return CraftBlockData.MAP.getOrDefault(data.getBlock().getClass(), CraftBlockData::new).apply(data); + public static CraftBlockData fromData(IBlockData data) { + return MAP.getOrDefault(data.getBlock().getClass(), CraftBlockData::new).apply(data); } @Override public SoundGroup getSoundGroup() { - return CraftSoundGroup.getSoundGroup(this.state.getSoundType()); + return CraftSoundGroup.getSoundGroup(state.getSoundType()); } @Override public int getLightEmission() { - return this.state.getLightEmission(); + return state.getLightEmission(); } @Override public boolean isOccluding() { - return this.state.canOcclude(); + return state.canOcclude(); } @Override public boolean requiresCorrectToolForDrops() { - return this.state.requiresCorrectToolForDrops(); + return state.requiresCorrectToolForDrops(); } @Override @@ -599,16 +605,16 @@ public boolean isPreferredTool(ItemStack tool) { Preconditions.checkArgument(tool != null, "tool must not be null"); net.minecraft.world.item.ItemStack nms = CraftItemStack.asNMSCopy(tool); - return CraftBlockData.isPreferredTool(this.state, nms); + return isPreferredTool(state, nms); } - public static boolean isPreferredTool(net.minecraft.world.level.block.state.BlockState iblockdata, net.minecraft.world.item.ItemStack nmsItem) { + public static boolean isPreferredTool(IBlockData iblockdata, net.minecraft.world.item.ItemStack nmsItem) { return !iblockdata.requiresCorrectToolForDrops() || nmsItem.isCorrectToolForDrops(iblockdata); } @Override public PistonMoveReaction getPistonMoveReaction() { - return PistonMoveReaction.getById(this.state.getPistonPushReaction().ordinal()); + return PistonMoveReaction.getById(state.getPistonPushReaction().ordinal()); } @Override @@ -616,7 +622,7 @@ public boolean isSupported(org.bukkit.block.Block block) { Preconditions.checkArgument(block != null, "block must not be null"); CraftBlock craftBlock = (CraftBlock) block; - return this.state.canSurvive(craftBlock.getCraftWorld().getHandle(), craftBlock.getPosition()); + return state.canSurvive(craftBlock.getCraftWorld().getHandle(), craftBlock.getPosition()); } @Override @@ -626,8 +632,8 @@ public boolean isSupported(Location location) { CraftWorld world = (CraftWorld) location.getWorld(); Preconditions.checkArgument(world != null, "location must not have a null world"); - BlockPos position = CraftLocation.toBlockPosition(location); - return this.state.canSurvive(world.getHandle(), position); + BlockPos position = CraftLocation.toBlockPos(location); + return state.canSurvive(world.getHandle(), position); } @Override @@ -635,43 +641,43 @@ public boolean isFaceSturdy(BlockFace face, BlockSupport support) { Preconditions.checkArgument(face != null, "face must not be null"); Preconditions.checkArgument(support != null, "support must not be null"); - return this.state.isFaceSturdy(EmptyBlockGetter.INSTANCE, BlockPos.ZERO, CraftBlock.blockFaceToNotch(face), CraftBlockSupport.toNMS(support)); + return state.isFaceSturdy(BlockAccessAir.INSTANCE, BlockPos.ZERO, CraftBlock.blockFaceToNotch(face), CraftBlockSupport.toNMS(support)); } @Override public Color getMapColor() { - return Color.fromRGB(this.state.getMapColor(null, null).col); + return Color.fromRGB(state.getMapColor(null, null).col); } @Override public Material getPlacementMaterial() { - return CraftItemType.minecraftToBukkit(this.state.getBlock().asItem()); + return CraftItemType.minecraftToBukkit(state.getBlock().asItem()); } @Override public void rotate(StructureRotation rotation) { - this.state = this.state.rotate(Rotation.valueOf(rotation.name())); + this.state = state.rotate(EnumBlockRotation.valueOf(rotation.name())); } @Override public void mirror(Mirror mirror) { - this.state = this.state.mirror(net.minecraft.world.level.block.Mirror.valueOf(mirror.name())); + this.state = state.mirror(EnumBlockMirror.valueOf(mirror.name())); } @Override public void copyTo(BlockData blockData) { CraftBlockData other = (CraftBlockData) blockData; - net.minecraft.world.level.block.state.BlockState nms = other.state; - for (Property property : this.state.getBlock().getStateDefinition().getProperties()) { + IBlockData nms = other.state; + for (IBlockState property : state.getBlock().getStateDefinition().getProperties()) { if (nms.hasProperty(property)) { - nms = this.copyProperty(this.state, nms, property); + nms = copyProperty(state, nms, property); } } other.state = nms; } - private > net.minecraft.world.level.block.state.BlockState copyProperty(net.minecraft.world.level.block.state.BlockState source, net.minecraft.world.level.block.state.BlockState target, Property property) { + private > IBlockData copyProperty(IBlockData source, IBlockData target, IBlockState property) { return target.setValue(property, source.getValue(property)); } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBrushable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBrushable.java index dfc651e5..ee4d20b0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBrushable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBrushable.java @@ -4,20 +4,20 @@ public abstract class CraftBrushable extends CraftBlockData implements Brushable { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DUSTED = getInteger("dusted"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DUSTED = getInteger("dusted"); @Override public int getDusted() { - return this.get(CraftBrushable.DUSTED); + return get(DUSTED); } @Override public void setDusted(int dusted) { - this.set(CraftBrushable.DUSTED, dusted); + set(DUSTED, dusted); } @Override public int getMaximumDusted() { - return getMax(CraftBrushable.DUSTED); + return getMax(DUSTED); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java index 88b765e2..7c7f118d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java @@ -4,20 +4,20 @@ public abstract class CraftDirectional extends CraftBlockData implements Directional { - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum("facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum("facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftDirectional.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftDirectional.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftDirectional.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftFaceAttachable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftFaceAttachable.java index 9cf2eb59..6ab47e6b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftFaceAttachable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftFaceAttachable.java @@ -4,15 +4,15 @@ public abstract class CraftFaceAttachable extends CraftBlockData implements FaceAttachable { - private static final net.minecraft.world.level.block.state.properties.EnumProperty ATTACH_FACE = getEnum("face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ATTACH_FACE = getEnum("face"); @Override public org.bukkit.block.data.FaceAttachable.AttachedFace getAttachedFace() { - return this.get(CraftFaceAttachable.ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); + return get(ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); } @Override public void setAttachedFace(org.bukkit.block.data.FaceAttachable.AttachedFace face) { - this.set(CraftFaceAttachable.ATTACH_FACE, face); + set(ATTACH_FACE, face); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftHangable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftHangable.java index 5b99b722..e65c0442 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftHangable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftHangable.java @@ -4,15 +4,15 @@ public abstract class CraftHangable extends CraftBlockData implements Hangable { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HANGING = getBoolean("hanging"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HANGING = getBoolean("hanging"); @Override public boolean isHanging() { - return this.get(CraftHangable.HANGING); + return get(HANGING); } @Override public void setHanging(boolean hanging) { - this.set(CraftHangable.HANGING, hanging); + set(HANGING, hanging); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftHatchable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftHatchable.java index 0e232236..462bda80 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftHatchable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftHatchable.java @@ -4,20 +4,20 @@ public abstract class CraftHatchable extends CraftBlockData implements Hatchable { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty HATCH = getInteger("hatch"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger HATCH = getInteger("hatch"); @Override public int getHatch() { - return this.get(CraftHatchable.HATCH); + return get(HATCH); } @Override public void setHatch(int hatch) { - this.set(CraftHatchable.HATCH, hatch); + set(HATCH, hatch); } @Override public int getMaximumHatch() { - return getMax(CraftHatchable.HATCH); + return getMax(HATCH); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java index a4624182..fb7b5ae8 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java @@ -4,20 +4,20 @@ public abstract class CraftLevelled extends CraftBlockData implements Levelled { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LEVEL = getInteger("level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LEVEL = getInteger("level"); @Override public int getLevel() { - return this.get(CraftLevelled.LEVEL); + return get(LEVEL); } @Override public void setLevel(int level) { - this.set(CraftLevelled.LEVEL, level); + set(LEVEL, level); } @Override public int getMaximumLevel() { - return getMax(CraftLevelled.LEVEL); + return getMax(LEVEL); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java index ca2b7800..684c868f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java @@ -4,15 +4,15 @@ public abstract class CraftLightable extends CraftBlockData implements Lightable { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean("lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean("lit"); @Override public boolean isLit() { - return this.get(CraftLightable.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftLightable.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java index 2d0af804..7748d40d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java @@ -4,34 +4,34 @@ public abstract class CraftMultipleFacing extends CraftBlockData implements MultipleFacing { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ getBoolean("north", true), getBoolean("east", true), getBoolean("south", true), getBoolean("west", true), getBoolean("up", true), getBoolean("down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftMultipleFacing.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftMultipleFacing.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftMultipleFacing.FACES.length; i++) { - if (CraftMultipleFacing.FACES[i] != null && this.get(CraftMultipleFacing.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -43,8 +43,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftMultipleFacing.FACES.length; i++) { - if (CraftMultipleFacing.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java index 46a0e3e4..738e5c6b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java @@ -4,15 +4,15 @@ public abstract class CraftOpenable extends CraftBlockData implements Openable { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean("open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean("open"); @Override public boolean isOpen() { - return this.get(CraftOpenable.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftOpenable.OPEN, open); + set(OPEN, open); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java index 55d96a0d..b556d081 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java @@ -4,20 +4,20 @@ public class CraftOrientable extends CraftBlockData implements Orientable { - private static final net.minecraft.world.level.block.state.properties.EnumProperty AXIS = getEnum("axis"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum("axis"); @Override public org.bukkit.Axis getAxis() { - return this.get(CraftOrientable.AXIS, org.bukkit.Axis.class); + return get(AXIS, org.bukkit.Axis.class); } @Override public void setAxis(org.bukkit.Axis axis) { - this.set(CraftOrientable.AXIS, axis); + set(AXIS, axis); } @Override public java.util.Set getAxes() { - return this.getValues(CraftOrientable.AXIS, org.bukkit.Axis.class); + return getValues(AXIS, org.bukkit.Axis.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java index 70c58e03..bbe860fd 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java @@ -4,15 +4,15 @@ public abstract class CraftPowerable extends CraftBlockData implements Powerable { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean("powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean("powered"); @Override public boolean isPowered() { - return this.get(CraftPowerable.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftPowerable.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java index 8a4937b3..b44fe1cf 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java @@ -4,20 +4,20 @@ public abstract class CraftRail extends CraftBlockData implements Rail { - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum("shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum("shape"); @Override public org.bukkit.block.data.Rail.Shape getShape() { - return this.get(CraftRail.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return get(SHAPE, org.bukkit.block.data.Rail.Shape.class); } @Override public void setShape(org.bukkit.block.data.Rail.Shape shape) { - this.set(CraftRail.SHAPE, shape); + set(SHAPE, shape); } @Override public java.util.Set getShapes() { - return this.getValues(CraftRail.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return getValues(SHAPE, org.bukkit.block.data.Rail.Shape.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java index 665b52ad..907387ee 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java @@ -4,11 +4,11 @@ public abstract class CraftRotatable extends CraftBlockData implements Rotatable { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger("rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger("rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftRotatable.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -102,6 +102,6 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftRotatable.ROTATION, val); + set(ROTATION, val); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java index 1f5c02fe..81dba385 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java @@ -4,15 +4,15 @@ public abstract class CraftSnowable extends CraftBlockData implements Snowable { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SNOWY = getBoolean("snowy"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SNOWY = getBoolean("snowy"); @Override public boolean isSnowy() { - return this.get(CraftSnowable.SNOWY); + return get(SNOWY); } @Override public void setSnowy(boolean snowy) { - this.set(CraftSnowable.SNOWY, snowy); + set(SNOWY, snowy); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java index 73679510..43f2d7a6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java @@ -4,15 +4,15 @@ public abstract class CraftWaterlogged extends CraftBlockData implements Waterlogged { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean("waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean("waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWaterlogged.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWaterlogged.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java index 2e657e4b..1c5ba682 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java @@ -5,15 +5,15 @@ public abstract class CraftBamboo extends CraftBlockData implements Bamboo { - private static final net.minecraft.world.level.block.state.properties.EnumProperty LEAVES = getEnum("leaves"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum LEAVES = getEnum("leaves"); @Override public org.bukkit.block.data.type.Bamboo.Leaves getLeaves() { - return this.get(CraftBamboo.LEAVES, org.bukkit.block.data.type.Bamboo.Leaves.class); + return get(LEAVES, org.bukkit.block.data.type.Bamboo.Leaves.class); } @Override public void setLeaves(org.bukkit.block.data.type.Bamboo.Leaves leaves) { - this.set(CraftBamboo.LEAVES, leaves); + set(LEAVES, leaves); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java index f636a6b6..3c12a80a 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java @@ -5,21 +5,21 @@ public abstract class CraftBed extends CraftBlockData implements Bed { - private static final net.minecraft.world.level.block.state.properties.EnumProperty PART = getEnum("part"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OCCUPIED = getBoolean("occupied"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum PART = getEnum("part"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OCCUPIED = getBoolean("occupied"); @Override public org.bukkit.block.data.type.Bed.Part getPart() { - return this.get(CraftBed.PART, org.bukkit.block.data.type.Bed.Part.class); + return get(PART, org.bukkit.block.data.type.Bed.Part.class); } @Override public void setPart(org.bukkit.block.data.type.Bed.Part part) { - this.set(CraftBed.PART, part); + set(PART, part); } @Override public boolean isOccupied() { - return this.get(CraftBed.OCCUPIED); + return get(OCCUPIED); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBeehive.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBeehive.java index cf4185a3..8966c06e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBeehive.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBeehive.java @@ -5,20 +5,20 @@ public abstract class CraftBeehive extends CraftBlockData implements Beehive { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty HONEY_LEVEL = getInteger("honey_level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger HONEY_LEVEL = getInteger("honey_level"); @Override public int getHoneyLevel() { - return this.get(CraftBeehive.HONEY_LEVEL); + return get(HONEY_LEVEL); } @Override public void setHoneyLevel(int honeyLevel) { - this.set(CraftBeehive.HONEY_LEVEL, honeyLevel); + set(HONEY_LEVEL, honeyLevel); } @Override public int getMaximumHoneyLevel() { - return getMax(CraftBeehive.HONEY_LEVEL); + return getMax(HONEY_LEVEL); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java index 7ffb256c..a360627c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java @@ -5,15 +5,15 @@ public abstract class CraftBell extends CraftBlockData implements Bell { - private static final net.minecraft.world.level.block.state.properties.EnumProperty ATTACHMENT = getEnum("attachment"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ATTACHMENT = getEnum("attachment"); @Override public org.bukkit.block.data.type.Bell.Attachment getAttachment() { - return this.get(CraftBell.ATTACHMENT, org.bukkit.block.data.type.Bell.Attachment.class); + return get(ATTACHMENT, org.bukkit.block.data.type.Bell.Attachment.class); } @Override public void setAttachment(org.bukkit.block.data.type.Bell.Attachment leaves) { - this.set(CraftBell.ATTACHMENT, leaves); + set(ATTACHMENT, leaves); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBigDripleaf.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBigDripleaf.java index 25bbb744..bd509f2f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBigDripleaf.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBigDripleaf.java @@ -5,15 +5,15 @@ public abstract class CraftBigDripleaf extends CraftBlockData implements BigDripleaf { - private static final net.minecraft.world.level.block.state.properties.EnumProperty TILT = getEnum("tilt"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TILT = getEnum("tilt"); @Override public Tilt getTilt() { - return this.get(CraftBigDripleaf.TILT, org.bukkit.block.data.type.BigDripleaf.Tilt.class); + return get(TILT, org.bukkit.block.data.type.BigDripleaf.Tilt.class); } @Override public void setTilt(org.bukkit.block.data.type.BigDripleaf.Tilt tilt) { - this.set(CraftBigDripleaf.TILT, tilt); + set(TILT, tilt); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java index fceebad3..b446b4d2 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java @@ -5,26 +5,26 @@ public abstract class CraftBrewingStand extends CraftBlockData implements BrewingStand { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] HAS_BOTTLE = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] HAS_BOTTLE = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ getBoolean("has_bottle_0"), getBoolean("has_bottle_1"), getBoolean("has_bottle_2") }; @Override public boolean hasBottle(int bottle) { - return this.get(CraftBrewingStand.HAS_BOTTLE[bottle]); + return get(HAS_BOTTLE[bottle]); } @Override public void setBottle(int bottle, boolean has) { - this.set(CraftBrewingStand.HAS_BOTTLE[bottle], has); + set(HAS_BOTTLE[bottle], has); } @Override public java.util.Set getBottles() { com.google.common.collect.ImmutableSet.Builder bottles = com.google.common.collect.ImmutableSet.builder(); - for (int index = 0; index < this.getMaximumBottles(); index++) { - if (this.hasBottle(index)) { + for (int index = 0; index < getMaximumBottles(); index++) { + if (hasBottle(index)) { bottles.add(index); } } @@ -34,6 +34,6 @@ public java.util.Set getBottles() { @Override public int getMaximumBottles() { - return CraftBrewingStand.HAS_BOTTLE.length; + return HAS_BOTTLE.length; } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrushable.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrushable.java index 52f053b7..444af6dd 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrushable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrushable.java @@ -5,20 +5,20 @@ public abstract class CraftBrushable extends CraftBlockData implements Brushable { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DUSTED = getInteger("dusted"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DUSTED = getInteger("dusted"); @Override public int getDusted() { - return this.get(CraftBrushable.DUSTED); + return get(DUSTED); } @Override public void setDusted(int dusted) { - this.set(CraftBrushable.DUSTED, dusted); + set(DUSTED, dusted); } @Override public int getMaximumDusted() { - return getMax(CraftBrushable.DUSTED); + return getMax(DUSTED); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java index dd9661a5..a5fc982c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java @@ -5,15 +5,15 @@ public abstract class CraftBubbleColumn extends CraftBlockData implements BubbleColumn { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty DRAG = getBoolean("drag"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean DRAG = getBoolean("drag"); @Override public boolean isDrag() { - return this.get(CraftBubbleColumn.DRAG); + return get(DRAG); } @Override public void setDrag(boolean drag) { - this.set(CraftBubbleColumn.DRAG, drag); + set(DRAG, drag); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java index d33ab8bc..24f0c31b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java @@ -5,20 +5,20 @@ public abstract class CraftCake extends CraftBlockData implements Cake { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty BITES = getInteger("bites"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger BITES = getInteger("bites"); @Override public int getBites() { - return this.get(CraftCake.BITES); + return get(BITES); } @Override public void setBites(int bites) { - this.set(CraftCake.BITES, bites); + set(BITES, bites); } @Override public int getMaximumBites() { - return getMax(CraftCake.BITES); + return getMax(BITES); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java index cd69fa35..3f13c29a 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java @@ -5,15 +5,15 @@ public abstract class CraftCampfire extends CraftBlockData implements Campfire { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SIGNAL_FIRE = getBoolean("signal_fire"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SIGNAL_FIRE = getBoolean("signal_fire"); @Override public boolean isSignalFire() { - return this.get(CraftCampfire.SIGNAL_FIRE); + return get(SIGNAL_FIRE); } @Override public void setSignalFire(boolean signalFire) { - this.set(CraftCampfire.SIGNAL_FIRE, signalFire); + set(SIGNAL_FIRE, signalFire); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCandle.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCandle.java index 8a350500..21477978 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCandle.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCandle.java @@ -5,20 +5,20 @@ public abstract class CraftCandle extends CraftBlockData implements Candle { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty CANDLES = getInteger("candles"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger CANDLES = getInteger("candles"); @Override public int getCandles() { - return this.get(CraftCandle.CANDLES); + return get(CANDLES); } @Override public void setCandles(int candles) { - this.set(CraftCandle.CANDLES, candles); + set(CANDLES, candles); } @Override public int getMaximumCandles() { - return getMax(CraftCandle.CANDLES); + return getMax(CANDLES); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCaveVinesPlant.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCaveVinesPlant.java index 52c032e5..5cd6f7ef 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCaveVinesPlant.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCaveVinesPlant.java @@ -5,15 +5,15 @@ public abstract class CraftCaveVinesPlant extends CraftBlockData implements CaveVinesPlant { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BERRIES = getBoolean("berries"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BERRIES = getBoolean("berries"); @Override public boolean isBerries() { - return this.get(CraftCaveVinesPlant.BERRIES); + return get(BERRIES); } @Override public void setBerries(boolean berries) { - this.set(CraftCaveVinesPlant.BERRIES, berries); + set(BERRIES, berries); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java index 02ddf75b..bfb700be 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java @@ -5,15 +5,15 @@ public abstract class CraftChest extends CraftBlockData implements Chest { - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum("type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum("type"); @Override public org.bukkit.block.data.type.Chest.Type getType() { - return this.get(CraftChest.TYPE, org.bukkit.block.data.type.Chest.Type.class); + return get(TYPE, org.bukkit.block.data.type.Chest.Type.class); } @Override public void setType(org.bukkit.block.data.type.Chest.Type type) { - this.set(CraftChest.TYPE, type); + set(TYPE, type); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChiseledBookshelf.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChiseledBookshelf.java index 49a5c5c6..a7009f4e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChiseledBookshelf.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChiseledBookshelf.java @@ -5,27 +5,27 @@ public abstract class CraftChiseledBookshelf extends CraftBlockData implements ChiseledBookshelf { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] SLOT_OCCUPIED = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] SLOT_OCCUPIED = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ getBoolean("slot_0_occupied"), getBoolean("slot_1_occupied"), getBoolean("slot_2_occupied"), getBoolean("slot_3_occupied"), getBoolean("slot_4_occupied"), getBoolean("slot_5_occupied") }; @Override public boolean isSlotOccupied(int slot) { - return this.get(CraftChiseledBookshelf.SLOT_OCCUPIED[slot]); + return get(SLOT_OCCUPIED[slot]); } @Override public void setSlotOccupied(int slot, boolean has) { - this.set(CraftChiseledBookshelf.SLOT_OCCUPIED[slot], has); + set(SLOT_OCCUPIED[slot], has); } @Override public java.util.Set getOccupiedSlots() { com.google.common.collect.ImmutableSet.Builder slots = com.google.common.collect.ImmutableSet.builder(); - for (int index = 0; index < this.getMaximumOccupiedSlots(); index++) { - if (this.isSlotOccupied(index)) { + for (int index = 0; index < getMaximumOccupiedSlots(); index++) { + if (isSlotOccupied(index)) { slots.add(index); } } @@ -35,6 +35,6 @@ public java.util.Set getOccupiedSlots() { @Override public int getMaximumOccupiedSlots() { - return CraftChiseledBookshelf.SLOT_OCCUPIED.length; + return SLOT_OCCUPIED.length; } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java index 45357318..132df871 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java @@ -5,15 +5,15 @@ public abstract class CraftCommandBlock extends CraftBlockData implements CommandBlock { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty CONDITIONAL = getBoolean("conditional"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean CONDITIONAL = getBoolean("conditional"); @Override public boolean isConditional() { - return this.get(CraftCommandBlock.CONDITIONAL); + return get(CONDITIONAL); } @Override public void setConditional(boolean conditional) { - this.set(CraftCommandBlock.CONDITIONAL, conditional); + set(CONDITIONAL, conditional); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java index d9bc3823..09378dde 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java @@ -5,15 +5,15 @@ public abstract class CraftComparator extends CraftBlockData implements Comparator { - private static final net.minecraft.world.level.block.state.properties.EnumProperty MODE = getEnum("mode"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum MODE = getEnum("mode"); @Override public org.bukkit.block.data.type.Comparator.Mode getMode() { - return this.get(CraftComparator.MODE, org.bukkit.block.data.type.Comparator.Mode.class); + return get(MODE, org.bukkit.block.data.type.Comparator.Mode.class); } @Override public void setMode(org.bukkit.block.data.type.Comparator.Mode mode) { - this.set(CraftComparator.MODE, mode); + set(MODE, mode); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCrafter.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCrafter.java index b42a212b..afeb2283 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCrafter.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCrafter.java @@ -5,37 +5,37 @@ public abstract class CraftCrafter extends CraftBlockData implements Crafter { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty CRAFTING = getBoolean("crafting"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty TRIGGERED = getBoolean("triggered"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty ORIENTATION = getEnum("orientation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean CRAFTING = getBoolean("crafting"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TRIGGERED = getBoolean("triggered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ORIENTATION = getEnum("orientation"); @Override public boolean isCrafting() { - return this.get(CraftCrafter.CRAFTING); + return get(CRAFTING); } @Override public void setCrafting(boolean crafting) { - this.set(CraftCrafter.CRAFTING, crafting); + set(CRAFTING, crafting); } @Override public boolean isTriggered() { - return this.get(CraftCrafter.TRIGGERED); + return get(TRIGGERED); } @Override public void setTriggered(boolean triggered) { - this.set(CraftCrafter.TRIGGERED, triggered); + set(TRIGGERED, triggered); } @Override public org.bukkit.block.data.type.Crafter.Orientation getOrientation() { - return this.get(CraftCrafter.ORIENTATION, org.bukkit.block.data.type.Crafter.Orientation.class); + return get(ORIENTATION, org.bukkit.block.data.type.Crafter.Orientation.class); } @Override public void setOrientation(org.bukkit.block.data.type.Crafter.Orientation orientation) { - this.set(CraftCrafter.ORIENTATION, orientation); + set(ORIENTATION, orientation); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCreakingHeart.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCreakingHeart.java new file mode 100644 index 00000000..a4461a7d --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCreakingHeart.java @@ -0,0 +1,19 @@ +package org.bukkit.craftbukkit.block.data.type; + +import org.bukkit.block.data.type.CreakingHeart; +import org.bukkit.craftbukkit.block.data.CraftBlockData; + +public abstract class CraftCreakingHeart extends CraftBlockData implements CreakingHeart { + + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum CREAKING = getEnum("creaking"); + + @Override + public org.bukkit.block.data.type.CreakingHeart.Creaking getCreaking() { + return get(CREAKING, org.bukkit.block.data.type.CreakingHeart.Creaking.class); + } + + @Override + public void setCreaking(org.bukkit.block.data.type.CreakingHeart.Creaking creaking) { + set(CREAKING, creaking); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java index 87d09248..f58d0ce4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java @@ -5,15 +5,15 @@ public abstract class CraftDaylightDetector extends CraftBlockData implements DaylightDetector { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty INVERTED = getBoolean("inverted"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean INVERTED = getBoolean("inverted"); @Override public boolean isInverted() { - return this.get(CraftDaylightDetector.INVERTED); + return get(INVERTED); } @Override public void setInverted(boolean inverted) { - this.set(CraftDaylightDetector.INVERTED, inverted); + set(INVERTED, inverted); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java index 911d02e8..c674d19e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java @@ -5,15 +5,15 @@ public abstract class CraftDispenser extends CraftBlockData implements Dispenser { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty TRIGGERED = getBoolean("triggered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TRIGGERED = getBoolean("triggered"); @Override public boolean isTriggered() { - return this.get(CraftDispenser.TRIGGERED); + return get(TRIGGERED); } @Override public void setTriggered(boolean triggered) { - this.set(CraftDispenser.TRIGGERED, triggered); + set(TRIGGERED, triggered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java index 9563cb79..6681c433 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java @@ -5,15 +5,15 @@ public abstract class CraftDoor extends CraftBlockData implements Door { - private static final net.minecraft.world.level.block.state.properties.EnumProperty HINGE = getEnum("hinge"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HINGE = getEnum("hinge"); @Override public org.bukkit.block.data.type.Door.Hinge getHinge() { - return this.get(CraftDoor.HINGE, org.bukkit.block.data.type.Door.Hinge.class); + return get(HINGE, org.bukkit.block.data.type.Door.Hinge.class); } @Override public void setHinge(org.bukkit.block.data.type.Door.Hinge hinge) { - this.set(CraftDoor.HINGE, hinge); + set(HINGE, hinge); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java index d9741748..af50653a 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java @@ -5,15 +5,15 @@ public abstract class CraftEndPortalFrame extends CraftBlockData implements EndPortalFrame { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty EYE = getBoolean("eye"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean EYE = getBoolean("eye"); @Override public boolean hasEye() { - return this.get(CraftEndPortalFrame.EYE); + return get(EYE); } @Override public void setEye(boolean eye) { - this.set(CraftEndPortalFrame.EYE, eye); + set(EYE, eye); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java index b90c9188..5d8f71f5 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java @@ -5,20 +5,20 @@ public abstract class CraftFarmland extends CraftBlockData implements Farmland { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty MOISTURE = getInteger("moisture"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger MOISTURE = getInteger("moisture"); @Override public int getMoisture() { - return this.get(CraftFarmland.MOISTURE); + return get(MOISTURE); } @Override public void setMoisture(int moisture) { - this.set(CraftFarmland.MOISTURE, moisture); + set(MOISTURE, moisture); } @Override public int getMaximumMoisture() { - return getMax(CraftFarmland.MOISTURE); + return getMax(MOISTURE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java index cd2350f5..63e14889 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java @@ -5,15 +5,15 @@ public abstract class CraftGate extends CraftBlockData implements Gate { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty IN_WALL = getBoolean("in_wall"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean IN_WALL = getBoolean("in_wall"); @Override public boolean isInWall() { - return this.get(CraftGate.IN_WALL); + return get(IN_WALL); } @Override public void setInWall(boolean inWall) { - this.set(CraftGate.IN_WALL, inWall); + set(IN_WALL, inWall); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHangingMoss.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHangingMoss.java new file mode 100644 index 00000000..1c81156c --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHangingMoss.java @@ -0,0 +1,19 @@ +package org.bukkit.craftbukkit.block.data.type; + +import org.bukkit.block.data.type.HangingMoss; +import org.bukkit.craftbukkit.block.data.CraftBlockData; + +public abstract class CraftHangingMoss extends CraftBlockData implements HangingMoss { + + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TIP = getBoolean("tip"); + + @Override + public boolean isTip() { + return get(TIP); + } + + @Override + public void setTip(boolean tip) { + set(TIP, tip); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java index 2da0ea26..5e11dc83 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java @@ -5,15 +5,15 @@ public abstract class CraftHopper extends CraftBlockData implements Hopper { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty ENABLED = getBoolean("enabled"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean ENABLED = getBoolean("enabled"); @Override public boolean isEnabled() { - return this.get(CraftHopper.ENABLED); + return get(ENABLED); } @Override public void setEnabled(boolean enabled) { - this.set(CraftHopper.ENABLED, enabled); + set(ENABLED, enabled); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJigsaw.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJigsaw.java index 0c88bb82..9538eaa8 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJigsaw.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJigsaw.java @@ -5,15 +5,15 @@ public abstract class CraftJigsaw extends CraftBlockData implements Jigsaw { - private static final net.minecraft.world.level.block.state.properties.EnumProperty ORIENTATION = getEnum("orientation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ORIENTATION = getEnum("orientation"); @Override public org.bukkit.block.data.type.Jigsaw.Orientation getOrientation() { - return this.get(CraftJigsaw.ORIENTATION, org.bukkit.block.data.type.Jigsaw.Orientation.class); + return get(ORIENTATION, org.bukkit.block.data.type.Jigsaw.Orientation.class); } @Override public void setOrientation(org.bukkit.block.data.type.Jigsaw.Orientation orientation) { - this.set(CraftJigsaw.ORIENTATION, orientation); + set(ORIENTATION, orientation); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java index 2f22f99b..fc5f588f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java @@ -5,10 +5,10 @@ public abstract class CraftJukebox extends CraftBlockData implements Jukebox { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HAS_RECORD = getBoolean("has_record"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HAS_RECORD = getBoolean("has_record"); @Override public boolean hasRecord() { - return this.get(CraftJukebox.HAS_RECORD); + return get(HAS_RECORD); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java index 832c984b..6edeaf08 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java @@ -5,26 +5,26 @@ public abstract class CraftLeaves extends CraftBlockData implements Leaves { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DISTANCE = getInteger("distance"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty PERSISTENT = getBoolean("persistent"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DISTANCE = getInteger("distance"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean PERSISTENT = getBoolean("persistent"); @Override public boolean isPersistent() { - return this.get(CraftLeaves.PERSISTENT); + return get(PERSISTENT); } @Override public void setPersistent(boolean persistent) { - this.set(CraftLeaves.PERSISTENT, persistent); + set(PERSISTENT, persistent); } @Override public int getDistance() { - return this.get(CraftLeaves.DISTANCE); + return get(DISTANCE); } @Override public void setDistance(int distance) { - this.set(CraftLeaves.DISTANCE, distance); + set(DISTANCE, distance); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java index dcbe832b..b585ed54 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java @@ -5,10 +5,10 @@ public abstract class CraftLectern extends CraftBlockData implements Lectern { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HAS_BOOK = getBoolean("has_book"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HAS_BOOK = getBoolean("has_book"); @Override public boolean hasBook() { - return this.get(CraftLectern.HAS_BOOK); + return get(HAS_BOOK); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftMossyCarpet.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftMossyCarpet.java new file mode 100644 index 00000000..462fc498 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftMossyCarpet.java @@ -0,0 +1,32 @@ +package org.bukkit.craftbukkit.block.data.type; + +import org.bukkit.block.data.type.MossyCarpet; +import org.bukkit.craftbukkit.block.data.CraftBlockData; + +public abstract class CraftMossyCarpet extends CraftBlockData implements MossyCarpet { + + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BOTTOM = getBoolean("bottom"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum[] HEIGHTS = new net.minecraft.world.level.block.state.properties.BlockStateEnum[]{ + getEnum("north"), getEnum("east"), getEnum("south"), getEnum("west") + }; + + @Override + public boolean isBottom() { + return get(BOTTOM); + } + + @Override + public void setBottom(boolean up) { + set(BOTTOM, up); + } + + @Override + public org.bukkit.block.data.type.MossyCarpet.Height getHeight(org.bukkit.block.BlockFace face) { + return get(HEIGHTS[face.ordinal()], org.bukkit.block.data.type.MossyCarpet.Height.class); + } + + @Override + public void setHeight(org.bukkit.block.BlockFace face, org.bukkit.block.data.type.MossyCarpet.Height height) { + set(HEIGHTS[face.ordinal()], height); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java index c44d33fb..70cb460d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java @@ -5,26 +5,26 @@ public abstract class CraftNoteBlock extends CraftBlockData implements NoteBlock { - private static final net.minecraft.world.level.block.state.properties.EnumProperty INSTRUMENT = getEnum("instrument"); - private static final net.minecraft.world.level.block.state.properties.IntegerProperty NOTE = getInteger("note"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum INSTRUMENT = getEnum("instrument"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger NOTE = getInteger("note"); @Override public org.bukkit.Instrument getInstrument() { - return this.get(CraftNoteBlock.INSTRUMENT, org.bukkit.Instrument.class); + return get(INSTRUMENT, org.bukkit.Instrument.class); } @Override public void setInstrument(org.bukkit.Instrument instrument) { - this.set(CraftNoteBlock.INSTRUMENT, instrument); + set(INSTRUMENT, instrument); } @Override public org.bukkit.Note getNote() { - return new org.bukkit.Note(this.get(CraftNoteBlock.NOTE)); + return new org.bukkit.Note(get(NOTE)); } @Override public void setNote(org.bukkit.Note note) { - this.set(CraftNoteBlock.NOTE, (int) note.getId()); + set(NOTE, (int) note.getId()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPinkPetals.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPinkPetals.java index 97fd7e4a..cbf3f5cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPinkPetals.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPinkPetals.java @@ -5,20 +5,20 @@ public abstract class CraftPinkPetals extends CraftBlockData implements PinkPetals { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty FLOWER_AMOUNT = getInteger("flower_amount"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger FLOWER_AMOUNT = getInteger("flower_amount"); @Override public int getFlowerAmount() { - return this.get(CraftPinkPetals.FLOWER_AMOUNT); + return get(FLOWER_AMOUNT); } @Override public void setFlowerAmount(int flower_amount) { - this.set(CraftPinkPetals.FLOWER_AMOUNT, flower_amount); + set(FLOWER_AMOUNT, flower_amount); } @Override public int getMaximumFlowerAmount() { - return getMax(CraftPinkPetals.FLOWER_AMOUNT); + return getMax(FLOWER_AMOUNT); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java index 193cf626..061e5c12 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java @@ -5,15 +5,15 @@ public abstract class CraftPiston extends CraftBlockData implements Piston { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty EXTENDED = getBoolean("extended"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean EXTENDED = getBoolean("extended"); @Override public boolean isExtended() { - return this.get(CraftPiston.EXTENDED); + return get(EXTENDED); } @Override public void setExtended(boolean extended) { - this.set(CraftPiston.EXTENDED, extended); + set(EXTENDED, extended); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java index 07447b95..1dc2cdaa 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java @@ -5,15 +5,15 @@ public abstract class CraftPistonHead extends CraftBlockData implements PistonHead { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SHORT = getBoolean("short"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SHORT = getBoolean("short"); @Override public boolean isShort() { - return this.get(CraftPistonHead.SHORT); + return get(SHORT); } @Override public void setShort(boolean _short) { - this.set(CraftPistonHead.SHORT, _short); + set(SHORT, _short); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPointedDripstone.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPointedDripstone.java index bfff4e16..f677c007 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPointedDripstone.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPointedDripstone.java @@ -5,31 +5,31 @@ public abstract class CraftPointedDripstone extends CraftBlockData implements PointedDripstone { - private static final net.minecraft.world.level.block.state.properties.EnumProperty VERTICAL_DIRECTION = getEnum("vertical_direction"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty THICKNESS = getEnum("thickness"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum VERTICAL_DIRECTION = getEnum("vertical_direction"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum THICKNESS = getEnum("thickness"); @Override public org.bukkit.block.BlockFace getVerticalDirection() { - return this.get(CraftPointedDripstone.VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); + return get(VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); } @Override public void setVerticalDirection(org.bukkit.block.BlockFace direction) { - this.set(CraftPointedDripstone.VERTICAL_DIRECTION, direction); + set(VERTICAL_DIRECTION, direction); } @Override public java.util.Set getVerticalDirections() { - return this.getValues(CraftPointedDripstone.VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); + return getValues(VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); } @Override public org.bukkit.block.data.type.PointedDripstone.Thickness getThickness() { - return this.get(CraftPointedDripstone.THICKNESS, org.bukkit.block.data.type.PointedDripstone.Thickness.class); + return get(THICKNESS, org.bukkit.block.data.type.PointedDripstone.Thickness.class); } @Override public void setThickness(org.bukkit.block.data.type.PointedDripstone.Thickness thickness) { - this.set(CraftPointedDripstone.THICKNESS, thickness); + set(THICKNESS, thickness); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java index 9d1f4d0b..962b9982 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java @@ -5,22 +5,22 @@ public abstract class CraftRedstoneWire extends CraftBlockData implements RedstoneWire { - private static final net.minecraft.world.level.block.state.properties.EnumProperty NORTH = getEnum("north"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty EAST = getEnum("east"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty SOUTH = getEnum("south"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty WEST = getEnum("west"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum NORTH = getEnum("north"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum EAST = getEnum("east"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SOUTH = getEnum("south"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum WEST = getEnum("west"); @Override public org.bukkit.block.data.type.RedstoneWire.Connection getFace(org.bukkit.block.BlockFace face) { switch (face) { case NORTH: - return this.get(CraftRedstoneWire.NORTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(NORTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); case EAST: - return this.get(CraftRedstoneWire.EAST, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(EAST, org.bukkit.block.data.type.RedstoneWire.Connection.class); case SOUTH: - return this.get(CraftRedstoneWire.SOUTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(SOUTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); case WEST: - return this.get(CraftRedstoneWire.WEST, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(WEST, org.bukkit.block.data.type.RedstoneWire.Connection.class); default: throw new IllegalArgumentException("Cannot have face " + face); } @@ -30,16 +30,16 @@ public org.bukkit.block.data.type.RedstoneWire.Connection getFace(org.bukkit.blo public void setFace(org.bukkit.block.BlockFace face, org.bukkit.block.data.type.RedstoneWire.Connection connection) { switch (face) { case NORTH: - this.set(CraftRedstoneWire.NORTH, connection); + set(NORTH, connection); break; case EAST: - this.set(CraftRedstoneWire.EAST, connection); + set(EAST, connection); break; case SOUTH: - this.set(CraftRedstoneWire.SOUTH, connection); + set(SOUTH, connection); break; case WEST: - this.set(CraftRedstoneWire.WEST, connection); + set(WEST, connection); break; default: throw new IllegalArgumentException("Cannot have face " + face); diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java index 8f2f55f9..a43a4dfa 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java @@ -5,36 +5,36 @@ public abstract class CraftRepeater extends CraftBlockData implements Repeater { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DELAY = getInteger("delay"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LOCKED = getBoolean("locked"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DELAY = getInteger("delay"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LOCKED = getBoolean("locked"); @Override public int getDelay() { - return this.get(CraftRepeater.DELAY); + return get(DELAY); } @Override public void setDelay(int delay) { - this.set(CraftRepeater.DELAY, delay); + set(DELAY, delay); } @Override public int getMinimumDelay() { - return getMin(CraftRepeater.DELAY); + return getMin(DELAY); } @Override public int getMaximumDelay() { - return getMax(CraftRepeater.DELAY); + return getMax(DELAY); } @Override public boolean isLocked() { - return this.get(CraftRepeater.LOCKED); + return get(LOCKED); } @Override public void setLocked(boolean locked) { - this.set(CraftRepeater.LOCKED, locked); + set(LOCKED, locked); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRespawnAnchor.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRespawnAnchor.java index eb4f3938..797326ff 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRespawnAnchor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRespawnAnchor.java @@ -5,20 +5,20 @@ public abstract class CraftRespawnAnchor extends CraftBlockData implements RespawnAnchor { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty CHARGES = getInteger("charges"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger CHARGES = getInteger("charges"); @Override public int getCharges() { - return this.get(CraftRespawnAnchor.CHARGES); + return get(CHARGES); } @Override public void setCharges(int charges) { - this.set(CraftRespawnAnchor.CHARGES, charges); + set(CHARGES, charges); } @Override public int getMaximumCharges() { - return getMax(CraftRespawnAnchor.CHARGES); + return getMax(CHARGES); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java index a0a4249e..b8dedea6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java @@ -5,20 +5,20 @@ public abstract class CraftSapling extends CraftBlockData implements Sapling { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty STAGE = getInteger("stage"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger STAGE = getInteger("stage"); @Override public int getStage() { - return this.get(CraftSapling.STAGE); + return get(STAGE); } @Override public void setStage(int stage) { - this.set(CraftSapling.STAGE, stage); + set(STAGE, stage); } @Override public int getMaximumStage() { - return getMax(CraftSapling.STAGE); + return getMax(STAGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java index d8f4ddf8..f80edd89 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java @@ -5,31 +5,31 @@ public abstract class CraftScaffolding extends CraftBlockData implements Scaffolding { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BOTTOM = getBoolean("bottom"); - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DISTANCE = getInteger("distance"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BOTTOM = getBoolean("bottom"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DISTANCE = getInteger("distance"); @Override public boolean isBottom() { - return this.get(CraftScaffolding.BOTTOM); + return get(BOTTOM); } @Override public void setBottom(boolean bottom) { - this.set(CraftScaffolding.BOTTOM, bottom); + set(BOTTOM, bottom); } @Override public int getDistance() { - return this.get(CraftScaffolding.DISTANCE); + return get(DISTANCE); } @Override public void setDistance(int distance) { - this.set(CraftScaffolding.DISTANCE, distance); + set(DISTANCE, distance); } @Override public int getMaximumDistance() { - return getMax(CraftScaffolding.DISTANCE); + return getMax(DISTANCE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkCatalyst.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkCatalyst.java index 8b714e03..d35ed668 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkCatalyst.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkCatalyst.java @@ -5,15 +5,15 @@ public abstract class CraftSculkCatalyst extends CraftBlockData implements SculkCatalyst { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BLOOM = getBoolean("bloom"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BLOOM = getBoolean("bloom"); @Override public boolean isBloom() { - return this.get(CraftSculkCatalyst.BLOOM); + return get(BLOOM); } @Override public void setBloom(boolean bloom) { - this.set(CraftSculkCatalyst.BLOOM, bloom); + set(BLOOM, bloom); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkSensor.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkSensor.java index de48a235..c1a76487 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkSensor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkSensor.java @@ -5,15 +5,15 @@ public abstract class CraftSculkSensor extends CraftBlockData implements SculkSensor { - private static final net.minecraft.world.level.block.state.properties.EnumProperty PHASE = getEnum("sculk_sensor_phase"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum PHASE = getEnum("sculk_sensor_phase"); @Override public org.bukkit.block.data.type.SculkSensor.Phase getPhase() { - return this.get(CraftSculkSensor.PHASE, org.bukkit.block.data.type.SculkSensor.Phase.class); + return get(PHASE, org.bukkit.block.data.type.SculkSensor.Phase.class); } @Override public void setPhase(org.bukkit.block.data.type.SculkSensor.Phase phase) { - this.set(CraftSculkSensor.PHASE, phase); + set(PHASE, phase); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkShrieker.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkShrieker.java index a3fb0f17..714a3625 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkShrieker.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSculkShrieker.java @@ -5,26 +5,26 @@ public abstract class CraftSculkShrieker extends CraftBlockData implements SculkShrieker { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty CAN_SUMMON = getBoolean("can_summon"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SHRIEKING = getBoolean("shrieking"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean CAN_SUMMON = getBoolean("can_summon"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SHRIEKING = getBoolean("shrieking"); @Override public boolean isCanSummon() { - return this.get(CraftSculkShrieker.CAN_SUMMON); + return get(CAN_SUMMON); } @Override public void setCanSummon(boolean can_summon) { - this.set(CraftSculkShrieker.CAN_SUMMON, can_summon); + set(CAN_SUMMON, can_summon); } @Override public boolean isShrieking() { - return this.get(CraftSculkShrieker.SHRIEKING); + return get(SHRIEKING); } @Override public void setShrieking(boolean shrieking) { - this.set(CraftSculkShrieker.SHRIEKING, shrieking); + set(SHRIEKING, shrieking); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java index 71ab0b24..bf92e11e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java @@ -5,25 +5,25 @@ public abstract class CraftSeaPickle extends CraftBlockData implements SeaPickle { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty PICKLES = getInteger("pickles"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger PICKLES = getInteger("pickles"); @Override public int getPickles() { - return this.get(CraftSeaPickle.PICKLES); + return get(PICKLES); } @Override public void setPickles(int pickles) { - this.set(CraftSeaPickle.PICKLES, pickles); + set(PICKLES, pickles); } @Override public int getMinimumPickles() { - return getMin(CraftSeaPickle.PICKLES); + return getMin(PICKLES); } @Override public int getMaximumPickles() { - return getMax(CraftSeaPickle.PICKLES); + return getMax(PICKLES); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java index c64c1baa..31380b3d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java @@ -5,15 +5,15 @@ public abstract class CraftSlab extends CraftBlockData implements Slab { - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum("type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum("type"); @Override public org.bukkit.block.data.type.Slab.Type getType() { - return this.get(CraftSlab.TYPE, org.bukkit.block.data.type.Slab.Type.class); + return get(TYPE, org.bukkit.block.data.type.Slab.Type.class); } @Override public void setType(org.bukkit.block.data.type.Slab.Type type) { - this.set(CraftSlab.TYPE, type); + set(TYPE, type); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java index e3c91828..7002206b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java @@ -5,25 +5,25 @@ public class CraftSnow extends CraftBlockData implements Snow { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LAYERS = getInteger("layers"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LAYERS = getInteger("layers"); @Override public int getLayers() { - return this.get(CraftSnow.LAYERS); + return get(LAYERS); } @Override public void setLayers(int layers) { - this.set(CraftSnow.LAYERS, layers); + set(LAYERS, layers); } @Override public int getMinimumLayers() { - return getMin(CraftSnow.LAYERS); + return getMin(LAYERS); } @Override public int getMaximumLayers() { - return getMax(CraftSnow.LAYERS); + return getMax(LAYERS); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java index 11554923..47d914f1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java @@ -5,15 +5,15 @@ public abstract class CraftStairs extends CraftBlockData implements Stairs { - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum("shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum("shape"); @Override public org.bukkit.block.data.type.Stairs.Shape getShape() { - return this.get(CraftStairs.SHAPE, org.bukkit.block.data.type.Stairs.Shape.class); + return get(SHAPE, org.bukkit.block.data.type.Stairs.Shape.class); } @Override public void setShape(org.bukkit.block.data.type.Stairs.Shape shape) { - this.set(CraftStairs.SHAPE, shape); + set(SHAPE, shape); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java index dc4cb64a..f568d7a4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java @@ -5,15 +5,15 @@ public abstract class CraftStructureBlock extends CraftBlockData implements StructureBlock { - private static final net.minecraft.world.level.block.state.properties.EnumProperty MODE = getEnum("mode"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum MODE = getEnum("mode"); @Override public org.bukkit.block.data.type.StructureBlock.Mode getMode() { - return this.get(CraftStructureBlock.MODE, org.bukkit.block.data.type.StructureBlock.Mode.class); + return get(MODE, org.bukkit.block.data.type.StructureBlock.Mode.class); } @Override public void setMode(org.bukkit.block.data.type.StructureBlock.Mode mode) { - this.set(CraftStructureBlock.MODE, mode); + set(MODE, mode); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java index f756460f..4b12349f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java @@ -5,15 +5,15 @@ public abstract class CraftSwitch extends CraftBlockData implements Switch { - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACE = getEnum("face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACE = getEnum("face"); @Override public org.bukkit.block.data.type.Switch.Face getFace() { - return this.get(CraftSwitch.FACE, org.bukkit.block.data.type.Switch.Face.class); + return get(FACE, org.bukkit.block.data.type.Switch.Face.class); } @Override public void setFace(org.bukkit.block.data.type.Switch.Face face) { - this.set(CraftSwitch.FACE, face); + set(FACE, face); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java index 47fa133d..2f431bd4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java @@ -5,15 +5,15 @@ public abstract class CraftTNT extends CraftBlockData implements TNT { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty UNSTABLE = getBoolean("unstable"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean UNSTABLE = getBoolean("unstable"); @Override public boolean isUnstable() { - return this.get(CraftTNT.UNSTABLE); + return get(UNSTABLE); } @Override public void setUnstable(boolean unstable) { - this.set(CraftTNT.UNSTABLE, unstable); + set(UNSTABLE, unstable); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java index 8a9b4573..0ad988f6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java @@ -5,15 +5,15 @@ public abstract class CraftTechnicalPiston extends CraftBlockData implements TechnicalPiston { - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum("type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum("type"); @Override public org.bukkit.block.data.type.TechnicalPiston.Type getType() { - return this.get(CraftTechnicalPiston.TYPE, org.bukkit.block.data.type.TechnicalPiston.Type.class); + return get(TYPE, org.bukkit.block.data.type.TechnicalPiston.Type.class); } @Override public void setType(org.bukkit.block.data.type.TechnicalPiston.Type type) { - this.set(CraftTechnicalPiston.TYPE, type); + set(TYPE, type); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTrialSpawner.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTrialSpawner.java index 9aba1df5..e212c5be 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTrialSpawner.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTrialSpawner.java @@ -5,26 +5,26 @@ public abstract class CraftTrialSpawner extends CraftBlockData implements TrialSpawner { - private static final net.minecraft.world.level.block.state.properties.EnumProperty TRIAL_SPAWNER_STATE = getEnum("trial_spawner_state"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OMINOUS = getBoolean("ominous"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TRIAL_SPAWNER_STATE = getEnum("trial_spawner_state"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OMINOUS = getBoolean("ominous"); @Override public org.bukkit.block.data.type.TrialSpawner.State getTrialSpawnerState() { - return this.get(CraftTrialSpawner.TRIAL_SPAWNER_STATE, org.bukkit.block.data.type.TrialSpawner.State.class); + return get(TRIAL_SPAWNER_STATE, org.bukkit.block.data.type.TrialSpawner.State.class); } @Override public void setTrialSpawnerState(org.bukkit.block.data.type.TrialSpawner.State state) { - this.set(CraftTrialSpawner.TRIAL_SPAWNER_STATE, state); + set(TRIAL_SPAWNER_STATE, state); } @Override public boolean isOminous() { - return this.get(CraftTrialSpawner.OMINOUS); + return get(OMINOUS); } @Override public void setOminous(boolean ominous) { - this.set(CraftTrialSpawner.OMINOUS, ominous); + set(OMINOUS, ominous); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java index 7e943cdf..7f8dda3e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java @@ -5,15 +5,15 @@ public abstract class CraftTripwire extends CraftBlockData implements Tripwire { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty DISARMED = getBoolean("disarmed"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean DISARMED = getBoolean("disarmed"); @Override public boolean isDisarmed() { - return this.get(CraftTripwire.DISARMED); + return get(DISARMED); } @Override public void setDisarmed(boolean disarmed) { - this.set(CraftTripwire.DISARMED, disarmed); + set(DISARMED, disarmed); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java index 98c0a4e9..2150d67e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java @@ -5,25 +5,25 @@ public abstract class CraftTurtleEgg extends CraftBlockData implements TurtleEgg { - private static final net.minecraft.world.level.block.state.properties.IntegerProperty EGGS = getInteger("eggs"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger EGGS = getInteger("eggs"); @Override public int getEggs() { - return this.get(CraftTurtleEgg.EGGS); + return get(EGGS); } @Override public void setEggs(int eggs) { - this.set(CraftTurtleEgg.EGGS, eggs); + set(EGGS, eggs); } @Override public int getMinimumEggs() { - return getMin(CraftTurtleEgg.EGGS); + return getMin(EGGS); } @Override public int getMaximumEggs() { - return getMax(CraftTurtleEgg.EGGS); + return getMax(EGGS); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftVault.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftVault.java index 5a5f60ba..4210dd38 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftVault.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftVault.java @@ -5,26 +5,26 @@ public abstract class CraftVault extends CraftBlockData implements Vault { - private static final net.minecraft.world.level.block.state.properties.EnumProperty VAULT_STATE = getEnum("vault_state"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OMINOUS = getBoolean("ominous"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum VAULT_STATE = getEnum("vault_state"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OMINOUS = getBoolean("ominous"); @Override public org.bukkit.block.data.type.Vault.State getTrialSpawnerState() { - return this.get(CraftVault.VAULT_STATE, org.bukkit.block.data.type.Vault.State.class); + return get(VAULT_STATE, org.bukkit.block.data.type.Vault.State.class); } @Override public void setTrialSpawnerState(org.bukkit.block.data.type.Vault.State state) { - this.set(CraftVault.VAULT_STATE, state); + set(VAULT_STATE, state); } @Override public boolean isOminous() { - return this.get(CraftVault.OMINOUS); + return get(OMINOUS); } @Override public void setOminous(boolean ominous) { - this.set(CraftVault.OMINOUS, ominous); + set(OMINOUS, ominous); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftWall.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftWall.java index 00f287a8..c02ab57d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftWall.java @@ -5,28 +5,28 @@ public abstract class CraftWall extends CraftBlockData implements Wall { - private static final net.minecraft.world.level.block.state.properties.BooleanProperty UP = getBoolean("up"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty[] HEIGHTS = new net.minecraft.world.level.block.state.properties.EnumProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean UP = getBoolean("up"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum[] HEIGHTS = new net.minecraft.world.level.block.state.properties.BlockStateEnum[]{ getEnum("north"), getEnum("east"), getEnum("south"), getEnum("west") }; @Override public boolean isUp() { - return this.get(CraftWall.UP); + return get(UP); } @Override public void setUp(boolean up) { - this.set(CraftWall.UP, up); + set(UP, up); } @Override public org.bukkit.block.data.type.Wall.Height getHeight(org.bukkit.block.BlockFace face) { - return this.get(CraftWall.HEIGHTS[face.ordinal()], org.bukkit.block.data.type.Wall.Height.class); + return get(HEIGHTS[face.ordinal()], org.bukkit.block.data.type.Wall.Height.class); } @Override public void setHeight(org.bukkit.block.BlockFace face, org.bukkit.block.data.type.Wall.Height height) { - this.set(CraftWall.HEIGHTS[face.ordinal()], height); + set(HEIGHTS[face.ordinal()], height); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAmethystCluster.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAmethystCluster.java index a78c931b..311ce20c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAmethystCluster.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAmethystCluster.java @@ -9,40 +9,40 @@ public CraftAmethystCluster() { super(); } - public CraftAmethystCluster(net.minecraft.world.level.block.state.BlockState state) { + public CraftAmethystCluster(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.AmethystClusterBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.AmethystClusterBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftAmethystCluster.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftAmethystCluster.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftAmethystCluster.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.AmethystClusterBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.AmethystClusterBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftAmethystCluster.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftAmethystCluster.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java index b2ffbebd..e874ad40 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java @@ -9,26 +9,26 @@ public CraftAnvil() { super(); } - public CraftAnvil(net.minecraft.world.level.block.state.BlockState state) { + public CraftAnvil(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.AnvilBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockAnvil.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftAnvil.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftAnvil.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftAnvil.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java index ef370655..3f3a1d10 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java @@ -9,59 +9,59 @@ public CraftBamboo() { super(); } - public CraftBamboo(net.minecraft.world.level.block.state.BlockState state) { + public CraftBamboo(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBamboo - private static final net.minecraft.world.level.block.state.properties.EnumProperty LEAVES = getEnum(net.minecraft.world.level.block.BambooStalkBlock.class, "leaves"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum LEAVES = getEnum(net.minecraft.world.level.block.BlockBamboo.class, "leaves"); @Override public org.bukkit.block.data.type.Bamboo.Leaves getLeaves() { - return this.get(CraftBamboo.LEAVES, org.bukkit.block.data.type.Bamboo.Leaves.class); + return get(LEAVES, org.bukkit.block.data.type.Bamboo.Leaves.class); } @Override public void setLeaves(org.bukkit.block.data.type.Bamboo.Leaves leaves) { - this.set(CraftBamboo.LEAVES, leaves); + set(LEAVES, leaves); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.BambooStalkBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockBamboo.class, "age"); @Override public int getAge() { - return this.get(CraftBamboo.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftBamboo.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftBamboo.AGE); + return getMax(AGE); } // org.bukkit.craftbukkit.block.data.type.CraftSapling - private static final net.minecraft.world.level.block.state.properties.IntegerProperty STAGE = getInteger(net.minecraft.world.level.block.BambooStalkBlock.class, "stage"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger STAGE = getInteger(net.minecraft.world.level.block.BlockBamboo.class, "stage"); @Override public int getStage() { - return this.get(CraftBamboo.STAGE); + return get(STAGE); } @Override public void setStage(int stage) { - this.set(CraftBamboo.STAGE, stage); + set(STAGE, stage); } @Override public int getMaximumStage() { - return getMax(CraftBamboo.STAGE); + return getMax(STAGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java index 79055ee1..79027234 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java @@ -9,17 +9,17 @@ public CraftBanner() { super(); } - public CraftBanner(net.minecraft.world.level.block.state.BlockState state) { + public CraftBanner(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftRotatable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger(net.minecraft.world.level.block.BannerBlock.class, "rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger(net.minecraft.world.level.block.BlockBanner.class, "rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftBanner.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -113,6 +113,6 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftBanner.ROTATION, val); + set(ROTATION, val); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java index 03f2ca67..981c3256 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java @@ -9,26 +9,26 @@ public CraftBannerWall() { super(); } - public CraftBannerWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftBannerWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WallBannerBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockBannerWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBannerWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBannerWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBannerWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java index 511460a8..ff86fc61 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java @@ -9,40 +9,40 @@ public CraftBarrel() { super(); } - public CraftBarrel(net.minecraft.world.level.block.state.BlockState state) { + public CraftBarrel(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BarrelBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockBarrel.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBarrel.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBarrel.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBarrel.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftOpenable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean(net.minecraft.world.level.block.BarrelBlock.class, "open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean(net.minecraft.world.level.block.BlockBarrel.class, "open"); @Override public boolean isOpen() { - return this.get(CraftBarrel.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftBarrel.OPEN, open); + set(OPEN, open); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrier.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrier.java index 1e810e5b..d5713edb 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrier.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrier.java @@ -9,21 +9,21 @@ public CraftBarrier() { super(); } - public CraftBarrier(net.minecraft.world.level.block.state.BlockState state) { + public CraftBarrier(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.BarrierBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockBarrier.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftBarrier.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftBarrier.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java index 2ccf3fbe..50deaba4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java @@ -9,46 +9,46 @@ public CraftBed() { super(); } - public CraftBed(net.minecraft.world.level.block.state.BlockState state) { + public CraftBed(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBed - private static final net.minecraft.world.level.block.state.properties.EnumProperty PART = getEnum(net.minecraft.world.level.block.BedBlock.class, "part"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OCCUPIED = getBoolean(net.minecraft.world.level.block.BedBlock.class, "occupied"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum PART = getEnum(net.minecraft.world.level.block.BlockBed.class, "part"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OCCUPIED = getBoolean(net.minecraft.world.level.block.BlockBed.class, "occupied"); @Override public org.bukkit.block.data.type.Bed.Part getPart() { - return this.get(CraftBed.PART, org.bukkit.block.data.type.Bed.Part.class); + return get(PART, org.bukkit.block.data.type.Bed.Part.class); } @Override public void setPart(org.bukkit.block.data.type.Bed.Part part) { - this.set(CraftBed.PART, part); + set(PART, part); } @Override public boolean isOccupied() { - return this.get(CraftBed.OCCUPIED); + return get(OCCUPIED); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BedBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockBed.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBed.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBed.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBed.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeehive.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeehive.java index a081a19e..e537ded2 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeehive.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeehive.java @@ -9,45 +9,45 @@ public CraftBeehive() { super(); } - public CraftBeehive(net.minecraft.world.level.block.state.BlockState state) { + public CraftBeehive(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBeehive - private static final net.minecraft.world.level.block.state.properties.IntegerProperty HONEY_LEVEL = getInteger(net.minecraft.world.level.block.BeehiveBlock.class, "honey_level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger HONEY_LEVEL = getInteger(net.minecraft.world.level.block.BlockBeehive.class, "honey_level"); @Override public int getHoneyLevel() { - return this.get(CraftBeehive.HONEY_LEVEL); + return get(HONEY_LEVEL); } @Override public void setHoneyLevel(int honeyLevel) { - this.set(CraftBeehive.HONEY_LEVEL, honeyLevel); + set(HONEY_LEVEL, honeyLevel); } @Override public int getMaximumHoneyLevel() { - return getMax(CraftBeehive.HONEY_LEVEL); + return getMax(HONEY_LEVEL); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BeehiveBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockBeehive.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBeehive.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBeehive.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBeehive.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java index 90b4883f..a4f21274 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java @@ -9,26 +9,26 @@ public CraftBeetroot() { super(); } - public CraftBeetroot(net.minecraft.world.level.block.state.BlockState state) { + public CraftBeetroot(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.BeetrootBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockBeetroot.class, "age"); @Override public int getAge() { - return this.get(CraftBeetroot.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftBeetroot.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftBeetroot.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java index b534cb23..5a3e2246 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java @@ -9,54 +9,54 @@ public CraftBell() { super(); } - public CraftBell(net.minecraft.world.level.block.state.BlockState state) { + public CraftBell(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBell - private static final net.minecraft.world.level.block.state.properties.EnumProperty ATTACHMENT = getEnum(net.minecraft.world.level.block.BellBlock.class, "attachment"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ATTACHMENT = getEnum(net.minecraft.world.level.block.BlockBell.class, "attachment"); @Override public org.bukkit.block.data.type.Bell.Attachment getAttachment() { - return this.get(CraftBell.ATTACHMENT, org.bukkit.block.data.type.Bell.Attachment.class); + return get(ATTACHMENT, org.bukkit.block.data.type.Bell.Attachment.class); } @Override public void setAttachment(org.bukkit.block.data.type.Bell.Attachment leaves) { - this.set(CraftBell.ATTACHMENT, leaves); + set(ATTACHMENT, leaves); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BellBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockBell.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBell.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBell.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBell.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.BellBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockBell.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftBell.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftBell.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleaf.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleaf.java index 9fe7d421..435386db 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleaf.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleaf.java @@ -9,54 +9,54 @@ public CraftBigDripleaf() { super(); } - public CraftBigDripleaf(net.minecraft.world.level.block.state.BlockState state) { + public CraftBigDripleaf(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBigDripleaf - private static final net.minecraft.world.level.block.state.properties.EnumProperty TILT = getEnum(net.minecraft.world.level.block.BigDripleafBlock.class, "tilt"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TILT = getEnum(net.minecraft.world.level.block.BigDripleafBlock.class, "tilt"); @Override public Tilt getTilt() { - return this.get(CraftBigDripleaf.TILT, org.bukkit.block.data.type.BigDripleaf.Tilt.class); + return get(TILT, org.bukkit.block.data.type.BigDripleaf.Tilt.class); } @Override public void setTilt(org.bukkit.block.data.type.BigDripleaf.Tilt tilt) { - this.set(CraftBigDripleaf.TILT, tilt); + set(TILT, tilt); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BigDripleafBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BigDripleafBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBigDripleaf.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBigDripleaf.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBigDripleaf.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.BigDripleafBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BigDripleafBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftBigDripleaf.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftBigDripleaf.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleafStem.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleafStem.java index 64b872cb..1c054426 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleafStem.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBigDripleafStem.java @@ -9,40 +9,40 @@ public CraftBigDripleafStem() { super(); } - public CraftBigDripleafStem(net.minecraft.world.level.block.state.BlockState state) { + public CraftBigDripleafStem(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BigDripleafStemBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BigDripleafStemBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBigDripleafStem.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBigDripleafStem.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBigDripleafStem.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.BigDripleafStemBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BigDripleafStemBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftBigDripleafStem.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftBigDripleafStem.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java index 64e18412..6c610779 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java @@ -9,40 +9,40 @@ public CraftBlastFurnace() { super(); } - public CraftBlastFurnace(net.minecraft.world.level.block.state.BlockState state) { + public CraftBlastFurnace(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BlastFurnaceBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockBlastFurnace.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftBlastFurnace.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftBlastFurnace.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftBlastFurnace.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.BlastFurnaceBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockBlastFurnace.class, "lit"); @Override public boolean isLit() { - return this.get(CraftBlastFurnace.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftBlastFurnace.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java index 1815adec..3ea151b0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java @@ -9,32 +9,32 @@ public CraftBrewingStand() { super(); } - public CraftBrewingStand(net.minecraft.world.level.block.state.BlockState state) { + public CraftBrewingStand(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBrewingStand - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] HAS_BOTTLE = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.BrewingStandBlock.class, "has_bottle_0"), getBoolean(net.minecraft.world.level.block.BrewingStandBlock.class, "has_bottle_1"), getBoolean(net.minecraft.world.level.block.BrewingStandBlock.class, "has_bottle_2") + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] HAS_BOTTLE = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockBrewingStand.class, "has_bottle_0"), getBoolean(net.minecraft.world.level.block.BlockBrewingStand.class, "has_bottle_1"), getBoolean(net.minecraft.world.level.block.BlockBrewingStand.class, "has_bottle_2") }; @Override public boolean hasBottle(int bottle) { - return this.get(CraftBrewingStand.HAS_BOTTLE[bottle]); + return get(HAS_BOTTLE[bottle]); } @Override public void setBottle(int bottle, boolean has) { - this.set(CraftBrewingStand.HAS_BOTTLE[bottle], has); + set(HAS_BOTTLE[bottle], has); } @Override public java.util.Set getBottles() { com.google.common.collect.ImmutableSet.Builder bottles = com.google.common.collect.ImmutableSet.builder(); - for (int index = 0; index < this.getMaximumBottles(); index++) { - if (this.hasBottle(index)) { + for (int index = 0; index < getMaximumBottles(); index++) { + if (hasBottle(index)) { bottles.add(index); } } @@ -44,6 +44,6 @@ public java.util.Set getBottles() { @Override public int getMaximumBottles() { - return CraftBrewingStand.HAS_BOTTLE.length; + return HAS_BOTTLE.length; } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrushable.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrushable.java index 303d6242..31de535a 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrushable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrushable.java @@ -9,26 +9,26 @@ public CraftBrushable() { super(); } - public CraftBrushable(net.minecraft.world.level.block.state.BlockState state) { + public CraftBrushable(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBrushable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DUSTED = getInteger(net.minecraft.world.level.block.BrushableBlock.class, "dusted"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DUSTED = getInteger(net.minecraft.world.level.block.BrushableBlock.class, "dusted"); @Override public int getDusted() { - return this.get(CraftBrushable.DUSTED); + return get(DUSTED); } @Override public void setDusted(int dusted) { - this.set(CraftBrushable.DUSTED, dusted); + set(DUSTED, dusted); } @Override public int getMaximumDusted() { - return getMax(CraftBrushable.DUSTED); + return getMax(DUSTED); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java index 9c51ee58..63e31263 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java @@ -9,21 +9,21 @@ public CraftBubbleColumn() { super(); } - public CraftBubbleColumn(net.minecraft.world.level.block.state.BlockState state) { + public CraftBubbleColumn(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftBubbleColumn - private static final net.minecraft.world.level.block.state.properties.BooleanProperty DRAG = getBoolean(net.minecraft.world.level.block.BubbleColumnBlock.class, "drag"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean DRAG = getBoolean(net.minecraft.world.level.block.BlockBubbleColumn.class, "drag"); @Override public boolean isDrag() { - return this.get(CraftBubbleColumn.DRAG); + return get(DRAG); } @Override public void setDrag(boolean drag) { - this.set(CraftBubbleColumn.DRAG, drag); + set(DRAG, drag); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftButtonAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftButtonAbstract.java index e71fd199..c0af065d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftButtonAbstract.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftButtonAbstract.java @@ -9,68 +9,68 @@ public CraftButtonAbstract() { super(); } - public CraftButtonAbstract(net.minecraft.world.level.block.state.BlockState state) { + public CraftButtonAbstract(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSwitch - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACE = getEnum(net.minecraft.world.level.block.ButtonBlock.class, "face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACE = getEnum(net.minecraft.world.level.block.BlockButtonAbstract.class, "face"); @Override public org.bukkit.block.data.type.Switch.Face getFace() { - return this.get(CraftButtonAbstract.FACE, org.bukkit.block.data.type.Switch.Face.class); + return get(FACE, org.bukkit.block.data.type.Switch.Face.class); } @Override public void setFace(org.bukkit.block.data.type.Switch.Face face) { - this.set(CraftButtonAbstract.FACE, face); + set(FACE, face); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.ButtonBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockButtonAbstract.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftButtonAbstract.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftButtonAbstract.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftButtonAbstract.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftFaceAttachable - private static final net.minecraft.world.level.block.state.properties.EnumProperty ATTACH_FACE = getEnum(net.minecraft.world.level.block.ButtonBlock.class, "face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ATTACH_FACE = getEnum(net.minecraft.world.level.block.BlockButtonAbstract.class, "face"); @Override public org.bukkit.block.data.FaceAttachable.AttachedFace getAttachedFace() { - return this.get(CraftButtonAbstract.ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); + return get(ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); } @Override public void setAttachedFace(org.bukkit.block.data.FaceAttachable.AttachedFace face) { - this.set(CraftButtonAbstract.ATTACH_FACE, face); + set(ATTACH_FACE, face); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.ButtonBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockButtonAbstract.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftButtonAbstract.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftButtonAbstract.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java index 46321719..279067bf 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java @@ -9,26 +9,26 @@ public CraftCactus() { super(); } - public CraftCactus(net.minecraft.world.level.block.state.BlockState state) { + public CraftCactus(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.CactusBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockCactus.class, "age"); @Override public int getAge() { - return this.get(CraftCactus.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftCactus.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftCactus.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java index 50347a79..ddaf32ce 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java @@ -9,26 +9,26 @@ public CraftCake() { super(); } - public CraftCake(net.minecraft.world.level.block.state.BlockState state) { + public CraftCake(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftCake - private static final net.minecraft.world.level.block.state.properties.IntegerProperty BITES = getInteger(net.minecraft.world.level.block.CakeBlock.class, "bites"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger BITES = getInteger(net.minecraft.world.level.block.BlockCake.class, "bites"); @Override public int getBites() { - return this.get(CraftCake.BITES); + return get(BITES); } @Override public void setBites(int bites) { - this.set(CraftCake.BITES, bites); + set(BITES, bites); } @Override public int getMaximumBites() { - return getMax(CraftCake.BITES); + return getMax(BITES); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCalibratedSculkSensor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCalibratedSculkSensor.java index decacf61..48d0591a 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCalibratedSculkSensor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCalibratedSculkSensor.java @@ -9,73 +9,73 @@ public CraftCalibratedSculkSensor() { super(); } - public CraftCalibratedSculkSensor(net.minecraft.world.level.block.state.BlockState state) { + public CraftCalibratedSculkSensor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftCalibratedSculkSensor.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftCalibratedSculkSensor.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftCalibratedSculkSensor.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.type.CraftSculkSensor - private static final net.minecraft.world.level.block.state.properties.EnumProperty PHASE = getEnum(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "sculk_sensor_phase"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum PHASE = getEnum(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "sculk_sensor_phase"); @Override public org.bukkit.block.data.type.SculkSensor.Phase getPhase() { - return this.get(CraftCalibratedSculkSensor.PHASE, org.bukkit.block.data.type.SculkSensor.Phase.class); + return get(PHASE, org.bukkit.block.data.type.SculkSensor.Phase.class); } @Override public void setPhase(org.bukkit.block.data.type.SculkSensor.Phase phase) { - this.set(CraftCalibratedSculkSensor.PHASE, phase); + set(PHASE, phase); } // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "power"); @Override public int getPower() { - return this.get(CraftCalibratedSculkSensor.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftCalibratedSculkSensor.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftCalibratedSculkSensor.POWER); + return getMax(POWER); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.CalibratedSculkSensorBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCalibratedSculkSensor.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCalibratedSculkSensor.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java index 52b3b5ab..6c79c954 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java @@ -9,68 +9,68 @@ public CraftCampfire() { super(); } - public CraftCampfire(net.minecraft.world.level.block.state.BlockState state) { + public CraftCampfire(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftCampfire - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SIGNAL_FIRE = getBoolean(net.minecraft.world.level.block.CampfireBlock.class, "signal_fire"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SIGNAL_FIRE = getBoolean(net.minecraft.world.level.block.BlockCampfire.class, "signal_fire"); @Override public boolean isSignalFire() { - return this.get(CraftCampfire.SIGNAL_FIRE); + return get(SIGNAL_FIRE); } @Override public void setSignalFire(boolean signalFire) { - this.set(CraftCampfire.SIGNAL_FIRE, signalFire); + set(SIGNAL_FIRE, signalFire); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.CampfireBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockCampfire.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftCampfire.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftCampfire.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftCampfire.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.CampfireBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockCampfire.class, "lit"); @Override public boolean isLit() { - return this.get(CraftCampfire.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftCampfire.LIT, lit); + set(LIT, lit); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CampfireBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCampfire.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCampfire.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCampfire.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandle.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandle.java index 2230160d..d33acb15 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandle.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandle.java @@ -9,54 +9,54 @@ public CraftCandle() { super(); } - public CraftCandle(net.minecraft.world.level.block.state.BlockState state) { + public CraftCandle(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftCandle - private static final net.minecraft.world.level.block.state.properties.IntegerProperty CANDLES = getInteger(net.minecraft.world.level.block.CandleBlock.class, "candles"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger CANDLES = getInteger(net.minecraft.world.level.block.CandleBlock.class, "candles"); @Override public int getCandles() { - return this.get(CraftCandle.CANDLES); + return get(CANDLES); } @Override public void setCandles(int candles) { - this.set(CraftCandle.CANDLES, candles); + set(CANDLES, candles); } @Override public int getMaximumCandles() { - return getMax(CraftCandle.CANDLES); + return getMax(CANDLES); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.CandleBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.CandleBlock.class, "lit"); @Override public boolean isLit() { - return this.get(CraftCandle.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftCandle.LIT, lit); + set(LIT, lit); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CandleBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.CandleBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCandle.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCandle.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandleCake.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandleCake.java index adc224dd..bbcc9755 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandleCake.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCandleCake.java @@ -9,21 +9,21 @@ public CraftCandleCake() { super(); } - public CraftCandleCake(net.minecraft.world.level.block.state.BlockState state) { + public CraftCandleCake(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.CandleCakeBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.CandleCakeBlock.class, "lit"); @Override public boolean isLit() { - return this.get(CraftCandleCake.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftCandleCake.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java index 270416eb..9e2096eb 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java @@ -9,26 +9,26 @@ public CraftCarrots() { super(); } - public CraftCarrots(net.minecraft.world.level.block.state.BlockState state) { + public CraftCarrots(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.CarrotBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockCarrots.class, "age"); @Override public int getAge() { - return this.get(CraftCarrots.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftCarrots.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftCarrots.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVines.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVines.java index 5b387ce8..92e5a4c7 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVines.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVines.java @@ -9,40 +9,40 @@ public CraftCaveVines() { super(); } - public CraftCaveVines(net.minecraft.world.level.block.state.BlockState state) { + public CraftCaveVines(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.CaveVinesBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.CaveVinesBlock.class, "age"); @Override public int getAge() { - return this.get(CraftCaveVines.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftCaveVines.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftCaveVines.AGE); + return getMax(AGE); } // org.bukkit.craftbukkit.block.data.type.CraftCaveVinesPlant - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BERRIES = getBoolean(net.minecraft.world.level.block.CaveVinesBlock.class, "berries"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BERRIES = getBoolean(net.minecraft.world.level.block.CaveVinesBlock.class, "berries"); @Override public boolean isBerries() { - return this.get(CraftCaveVines.BERRIES); + return get(BERRIES); } @Override public void setBerries(boolean berries) { - this.set(CraftCaveVines.BERRIES, berries); + set(BERRIES, berries); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVinesPlant.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVinesPlant.java index b8c199bf..03721a56 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVinesPlant.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCaveVinesPlant.java @@ -9,21 +9,21 @@ public CraftCaveVinesPlant() { super(); } - public CraftCaveVinesPlant(net.minecraft.world.level.block.state.BlockState state) { + public CraftCaveVinesPlant(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftCaveVinesPlant - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BERRIES = getBoolean(net.minecraft.world.level.block.CaveVinesPlantBlock.class, "berries"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BERRIES = getBoolean(net.minecraft.world.level.block.CaveVinesPlantBlock.class, "berries"); @Override public boolean isBerries() { - return this.get(CraftCaveVinesPlant.BERRIES); + return get(BERRIES); } @Override public void setBerries(boolean berries) { - this.set(CraftCaveVinesPlant.BERRIES, berries); + set(BERRIES, berries); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCeilingHangingSign.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCeilingHangingSign.java index fcda5708..6d00c632 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCeilingHangingSign.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCeilingHangingSign.java @@ -9,31 +9,31 @@ public CraftCeilingHangingSign() { super(); } - public CraftCeilingHangingSign(net.minecraft.world.level.block.state.BlockState state) { + public CraftCeilingHangingSign(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAttachable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty ATTACHED = getBoolean(net.minecraft.world.level.block.CeilingHangingSignBlock.class, "attached"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean ATTACHED = getBoolean(net.minecraft.world.level.block.CeilingHangingSignBlock.class, "attached"); @Override public boolean isAttached() { - return this.get(CraftCeilingHangingSign.ATTACHED); + return get(ATTACHED); } @Override public void setAttached(boolean attached) { - this.set(CraftCeilingHangingSign.ATTACHED, attached); + set(ATTACHED, attached); } // org.bukkit.craftbukkit.block.data.CraftRotatable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger(net.minecraft.world.level.block.CeilingHangingSignBlock.class, "rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger(net.minecraft.world.level.block.CeilingHangingSignBlock.class, "rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftCeilingHangingSign.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -127,20 +127,20 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftCeilingHangingSign.ROTATION, val); + set(ROTATION, val); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CeilingHangingSignBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.CeilingHangingSignBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCeilingHangingSign.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCeilingHangingSign.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChain.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChain.java index 50b317d4..be3b6d4d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChain.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChain.java @@ -9,40 +9,40 @@ public CraftChain() { super(); } - public CraftChain(net.minecraft.world.level.block.state.BlockState state) { + public CraftChain(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftOrientable - private static final net.minecraft.world.level.block.state.properties.EnumProperty AXIS = getEnum(net.minecraft.world.level.block.ChainBlock.class, "axis"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum(net.minecraft.world.level.block.BlockChain.class, "axis"); @Override public org.bukkit.Axis getAxis() { - return this.get(CraftChain.AXIS, org.bukkit.Axis.class); + return get(AXIS, org.bukkit.Axis.class); } @Override public void setAxis(org.bukkit.Axis axis) { - this.set(CraftChain.AXIS, axis); + set(AXIS, axis); } @Override public java.util.Set getAxes() { - return this.getValues(CraftChain.AXIS, org.bukkit.Axis.class); + return getValues(AXIS, org.bukkit.Axis.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.ChainBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockChain.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftChain.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftChain.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCherryLeaves.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCherryLeaves.java index af29ff86..e21a2c2a 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCherryLeaves.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCherryLeaves.java @@ -9,46 +9,46 @@ public CraftCherryLeaves() { super(); } - public CraftCherryLeaves(net.minecraft.world.level.block.state.BlockState state) { + public CraftCherryLeaves(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftLeaves - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DISTANCE = getInteger(net.minecraft.world.level.block.CherryLeavesBlock.class, "distance"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty PERSISTENT = getBoolean(net.minecraft.world.level.block.CherryLeavesBlock.class, "persistent"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DISTANCE = getInteger(net.minecraft.world.level.block.CherryLeavesBlock.class, "distance"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean PERSISTENT = getBoolean(net.minecraft.world.level.block.CherryLeavesBlock.class, "persistent"); @Override public boolean isPersistent() { - return this.get(CraftCherryLeaves.PERSISTENT); + return get(PERSISTENT); } @Override public void setPersistent(boolean persistent) { - this.set(CraftCherryLeaves.PERSISTENT, persistent); + set(PERSISTENT, persistent); } @Override public int getDistance() { - return this.get(CraftCherryLeaves.DISTANCE); + return get(DISTANCE); } @Override public void setDistance(int distance) { - this.set(CraftCherryLeaves.DISTANCE, distance); + set(DISTANCE, distance); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CherryLeavesBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.CherryLeavesBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCherryLeaves.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCherryLeaves.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java index 383b146d..df826da1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java @@ -9,54 +9,54 @@ public CraftChest() { super(); } - public CraftChest(net.minecraft.world.level.block.state.BlockState state) { + public CraftChest(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftChest - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum(net.minecraft.world.level.block.ChestBlock.class, "type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum(net.minecraft.world.level.block.BlockChest.class, "type"); @Override public org.bukkit.block.data.type.Chest.Type getType() { - return this.get(CraftChest.TYPE, org.bukkit.block.data.type.Chest.Type.class); + return get(TYPE, org.bukkit.block.data.type.Chest.Type.class); } @Override public void setType(org.bukkit.block.data.type.Chest.Type type) { - this.set(CraftChest.TYPE, type); + set(TYPE, type); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.ChestBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockChest.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftChest.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftChest.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftChest.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.ChestBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockChest.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftChest.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftChest.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java index b24a40c0..08aba0ee 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java @@ -9,54 +9,54 @@ public CraftChestTrapped() { super(); } - public CraftChestTrapped(net.minecraft.world.level.block.state.BlockState state) { + public CraftChestTrapped(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftChest - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum(net.minecraft.world.level.block.TrappedChestBlock.class, "type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum(net.minecraft.world.level.block.BlockChestTrapped.class, "type"); @Override public org.bukkit.block.data.type.Chest.Type getType() { - return this.get(CraftChestTrapped.TYPE, org.bukkit.block.data.type.Chest.Type.class); + return get(TYPE, org.bukkit.block.data.type.Chest.Type.class); } @Override public void setType(org.bukkit.block.data.type.Chest.Type type) { - this.set(CraftChestTrapped.TYPE, type); + set(TYPE, type); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.TrappedChestBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockChestTrapped.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftChestTrapped.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftChestTrapped.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftChestTrapped.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.TrappedChestBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockChestTrapped.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftChestTrapped.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftChestTrapped.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChiseledBookShelf.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChiseledBookShelf.java index 26cfac0a..ed89dde7 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChiseledBookShelf.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChiseledBookShelf.java @@ -9,33 +9,33 @@ public CraftChiseledBookShelf() { super(); } - public CraftChiseledBookShelf(net.minecraft.world.level.block.state.BlockState state) { + public CraftChiseledBookShelf(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftChiseledBookshelf - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] SLOT_OCCUPIED = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] SLOT_OCCUPIED = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ getBoolean(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "slot_0_occupied"), getBoolean(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "slot_1_occupied"), getBoolean(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "slot_2_occupied"), getBoolean(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "slot_3_occupied"), getBoolean(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "slot_4_occupied"), getBoolean(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "slot_5_occupied") }; @Override public boolean isSlotOccupied(int slot) { - return this.get(CraftChiseledBookShelf.SLOT_OCCUPIED[slot]); + return get(SLOT_OCCUPIED[slot]); } @Override public void setSlotOccupied(int slot, boolean has) { - this.set(CraftChiseledBookShelf.SLOT_OCCUPIED[slot], has); + set(SLOT_OCCUPIED[slot], has); } @Override public java.util.Set getOccupiedSlots() { com.google.common.collect.ImmutableSet.Builder slots = com.google.common.collect.ImmutableSet.builder(); - for (int index = 0; index < this.getMaximumOccupiedSlots(); index++) { - if (this.isSlotOccupied(index)) { + for (int index = 0; index < getMaximumOccupiedSlots(); index++) { + if (isSlotOccupied(index)) { slots.add(index); } } @@ -45,25 +45,25 @@ public java.util.Set getOccupiedSlots() { @Override public int getMaximumOccupiedSlots() { - return CraftChiseledBookShelf.SLOT_OCCUPIED.length; + return SLOT_OCCUPIED.length; } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.ChiseledBookShelfBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftChiseledBookShelf.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftChiseledBookShelf.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftChiseledBookShelf.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java index 1c759be1..203cc451 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java @@ -9,26 +9,26 @@ public CraftChorusFlower() { super(); } - public CraftChorusFlower(net.minecraft.world.level.block.state.BlockState state) { + public CraftChorusFlower(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.ChorusFlowerBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockChorusFlower.class, "age"); @Override public int getAge() { - return this.get(CraftChorusFlower.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftChorusFlower.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftChorusFlower.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java index 60190a7c..b1c7fee0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java @@ -9,40 +9,40 @@ public CraftChorusFruit() { super(); } - public CraftChorusFruit(net.minecraft.world.level.block.state.BlockState state) { + public CraftChorusFruit(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.ChorusPlantBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.ChorusPlantBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.ChorusPlantBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.ChorusPlantBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.ChorusPlantBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.ChorusPlantBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockChorusFruit.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockChorusFruit.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockChorusFruit.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockChorusFruit.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockChorusFruit.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockChorusFruit.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftChorusFruit.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftChorusFruit.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftChorusFruit.FACES.length; i++) { - if (CraftChorusFruit.FACES[i] != null && this.get(CraftChorusFruit.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftChorusFruit.FACES.length; i++) { - if (CraftChorusFruit.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java index f860bb30..e05139f0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java @@ -9,48 +9,48 @@ public CraftCobbleWall() { super(); } - public CraftCobbleWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftCobbleWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftWall - private static final net.minecraft.world.level.block.state.properties.BooleanProperty UP = getBoolean(net.minecraft.world.level.block.WallBlock.class, "up"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty[] HEIGHTS = new net.minecraft.world.level.block.state.properties.EnumProperty[]{ - getEnum(net.minecraft.world.level.block.WallBlock.class, "north"), getEnum(net.minecraft.world.level.block.WallBlock.class, "east"), getEnum(net.minecraft.world.level.block.WallBlock.class, "south"), getEnum(net.minecraft.world.level.block.WallBlock.class, "west") + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean UP = getBoolean(net.minecraft.world.level.block.BlockCobbleWall.class, "up"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum[] HEIGHTS = new net.minecraft.world.level.block.state.properties.BlockStateEnum[]{ + getEnum(net.minecraft.world.level.block.BlockCobbleWall.class, "north"), getEnum(net.minecraft.world.level.block.BlockCobbleWall.class, "east"), getEnum(net.minecraft.world.level.block.BlockCobbleWall.class, "south"), getEnum(net.minecraft.world.level.block.BlockCobbleWall.class, "west") }; @Override public boolean isUp() { - return this.get(CraftCobbleWall.UP); + return get(UP); } @Override public void setUp(boolean up) { - this.set(CraftCobbleWall.UP, up); + set(UP, up); } @Override public org.bukkit.block.data.type.Wall.Height getHeight(org.bukkit.block.BlockFace face) { - return this.get(CraftCobbleWall.HEIGHTS[face.ordinal()], org.bukkit.block.data.type.Wall.Height.class); + return get(HEIGHTS[face.ordinal()], org.bukkit.block.data.type.Wall.Height.class); } @Override public void setHeight(org.bukkit.block.BlockFace face, org.bukkit.block.data.type.Wall.Height height) { - this.set(CraftCobbleWall.HEIGHTS[face.ordinal()], height); + set(HEIGHTS[face.ordinal()], height); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WallBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCobbleWall.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCobbleWall.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCobbleWall.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java index 56167946..2298e9a1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java @@ -9,45 +9,45 @@ public CraftCocoa() { super(); } - public CraftCocoa(net.minecraft.world.level.block.state.BlockState state) { + public CraftCocoa(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.CocoaBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockCocoa.class, "age"); @Override public int getAge() { - return this.get(CraftCocoa.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftCocoa.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftCocoa.AGE); + return getMax(AGE); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.CocoaBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockCocoa.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftCocoa.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftCocoa.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftCocoa.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java index 14a78841..f42cf17c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java @@ -9,40 +9,40 @@ public CraftCommand() { super(); } - public CraftCommand(net.minecraft.world.level.block.state.BlockState state) { + public CraftCommand(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftCommandBlock - private static final net.minecraft.world.level.block.state.properties.BooleanProperty CONDITIONAL = getBoolean(net.minecraft.world.level.block.CommandBlock.class, "conditional"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean CONDITIONAL = getBoolean(net.minecraft.world.level.block.BlockCommand.class, "conditional"); @Override public boolean isConditional() { - return this.get(CraftCommand.CONDITIONAL); + return get(CONDITIONAL); } @Override public void setConditional(boolean conditional) { - this.set(CraftCommand.CONDITIONAL, conditional); + set(CONDITIONAL, conditional); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.CommandBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockCommand.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftCommand.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftCommand.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftCommand.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java index 7ce2e8b7..cf572f5b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java @@ -9,26 +9,26 @@ public CraftComposter() { super(); } - public CraftComposter(net.minecraft.world.level.block.state.BlockState state) { + public CraftComposter(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLevelled - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LEVEL = getInteger(net.minecraft.world.level.block.ComposterBlock.class, "level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LEVEL = getInteger(net.minecraft.world.level.block.BlockComposter.class, "level"); @Override public int getLevel() { - return this.get(CraftComposter.LEVEL); + return get(LEVEL); } @Override public void setLevel(int level) { - this.set(CraftComposter.LEVEL, level); + set(LEVEL, level); } @Override public int getMaximumLevel() { - return getMax(CraftComposter.LEVEL); + return getMax(LEVEL); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java index be87c2d5..b2e424b8 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java @@ -9,21 +9,21 @@ public CraftConduit() { super(); } - public CraftConduit(net.minecraft.world.level.block.state.BlockState state) { + public CraftConduit(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.ConduitBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockConduit.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftConduit.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftConduit.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCopperBulb.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCopperBulb.java index e85ccc6e..c3c4a404 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCopperBulb.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCopperBulb.java @@ -9,35 +9,35 @@ public CraftCopperBulb() { super(); } - public CraftCopperBulb(net.minecraft.world.level.block.state.BlockState state) { + public CraftCopperBulb(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.CopperBulbBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.CopperBulbBlock.class, "lit"); @Override public boolean isLit() { - return this.get(CraftCopperBulb.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftCopperBulb.LIT, lit); + set(LIT, lit); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.CopperBulbBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.CopperBulbBlock.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftCopperBulb.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftCopperBulb.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java index 927ee9b6..88a64ddf 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java @@ -9,21 +9,21 @@ public CraftCoralDead() { super(); } - public CraftCoralDead(net.minecraft.world.level.block.state.BlockState state) { + public CraftCoralDead(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.BaseCoralPlantBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCoralDead.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCoralDead.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCoralDead.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java index 42f8430d..35aedfe2 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java @@ -9,21 +9,21 @@ public CraftCoralFan() { super(); } - public CraftCoralFan(net.minecraft.world.level.block.state.BlockState state) { + public CraftCoralFan(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CoralFanBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCoralFan.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCoralFan.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCoralFan.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java index 88c371ca..35b6f083 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java @@ -9,21 +9,21 @@ public CraftCoralFanAbstract() { super(); } - public CraftCoralFanAbstract(net.minecraft.world.level.block.state.BlockState state) { + public CraftCoralFanAbstract(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.BaseCoralFanBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCoralFanAbstract.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCoralFanAbstract.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCoralFanAbstract.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java index 0928c60c..a69bde4b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java @@ -9,40 +9,40 @@ public CraftCoralFanWall() { super(); } - public CraftCoralFanWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftCoralFanWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.CoralWallFanBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockCoralFanWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftCoralFanWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftCoralFanWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftCoralFanWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CoralWallFanBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCoralFanWall.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCoralFanWall.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCoralFanWall.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java index b1715fca..7134c7b1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java @@ -9,40 +9,40 @@ public CraftCoralFanWallAbstract() { super(); } - public CraftCoralFanWallAbstract(net.minecraft.world.level.block.state.BlockState state) { + public CraftCoralFanWallAbstract(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.BaseCoralWallFanBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockCoralFanWallAbstract.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftCoralFanWallAbstract.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftCoralFanWallAbstract.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftCoralFanWallAbstract.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.BaseCoralWallFanBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCoralFanWallAbstract.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCoralFanWallAbstract.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCoralFanWallAbstract.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java index 447c4e1d..31f7e529 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java @@ -9,21 +9,21 @@ public CraftCoralPlant() { super(); } - public CraftCoralPlant(net.minecraft.world.level.block.state.BlockState state) { + public CraftCoralPlant(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.CoralPlantBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockCoralPlant.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftCoralPlant.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftCoralPlant.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrafter.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrafter.java index 78b8a7cd..3eabfe67 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrafter.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrafter.java @@ -9,43 +9,43 @@ public CraftCrafter() { super(); } - public CraftCrafter(net.minecraft.world.level.block.state.BlockState state) { + public CraftCrafter(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftCrafter - private static final net.minecraft.world.level.block.state.properties.BooleanProperty CRAFTING = getBoolean(net.minecraft.world.level.block.CrafterBlock.class, "crafting"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty TRIGGERED = getBoolean(net.minecraft.world.level.block.CrafterBlock.class, "triggered"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty ORIENTATION = getEnum(net.minecraft.world.level.block.CrafterBlock.class, "orientation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean CRAFTING = getBoolean(net.minecraft.world.level.block.CrafterBlock.class, "crafting"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TRIGGERED = getBoolean(net.minecraft.world.level.block.CrafterBlock.class, "triggered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ORIENTATION = getEnum(net.minecraft.world.level.block.CrafterBlock.class, "orientation"); @Override public boolean isCrafting() { - return this.get(CraftCrafter.CRAFTING); + return get(CRAFTING); } @Override public void setCrafting(boolean crafting) { - this.set(CraftCrafter.CRAFTING, crafting); + set(CRAFTING, crafting); } @Override public boolean isTriggered() { - return this.get(CraftCrafter.TRIGGERED); + return get(TRIGGERED); } @Override public void setTriggered(boolean triggered) { - this.set(CraftCrafter.TRIGGERED, triggered); + set(TRIGGERED, triggered); } @Override public org.bukkit.block.data.type.Crafter.Orientation getOrientation() { - return this.get(CraftCrafter.ORIENTATION, org.bukkit.block.data.type.Crafter.Orientation.class); + return get(ORIENTATION, org.bukkit.block.data.type.Crafter.Orientation.class); } @Override public void setOrientation(org.bukkit.block.data.type.Crafter.Orientation orientation) { - this.set(CraftCrafter.ORIENTATION, orientation); + set(ORIENTATION, orientation); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCreakingHeart.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCreakingHeart.java new file mode 100644 index 00000000..3d01917e --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCreakingHeart.java @@ -0,0 +1,48 @@ +/** + * Automatically generated file, changes will be lost. + */ +package org.bukkit.craftbukkit.block.impl; + +public final class CraftCreakingHeart extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.CreakingHeart, org.bukkit.block.data.Orientable { + + public CraftCreakingHeart() { + super(); + } + + public CraftCreakingHeart(net.minecraft.world.level.block.state.IBlockData state) { + super(state); + } + + // org.bukkit.craftbukkit.block.data.type.CraftCreakingHeart + + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum CREAKING = getEnum(net.minecraft.world.level.block.CreakingHeartBlock.class, "creaking"); + + @Override + public org.bukkit.block.data.type.CreakingHeart.Creaking getCreaking() { + return get(CREAKING, org.bukkit.block.data.type.CreakingHeart.Creaking.class); + } + + @Override + public void setCreaking(org.bukkit.block.data.type.CreakingHeart.Creaking creaking) { + set(CREAKING, creaking); + } + + // org.bukkit.craftbukkit.block.data.CraftOrientable + + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum(net.minecraft.world.level.block.CreakingHeartBlock.class, "axis"); + + @Override + public org.bukkit.Axis getAxis() { + return get(AXIS, org.bukkit.Axis.class); + } + + @Override + public void setAxis(org.bukkit.Axis axis) { + set(AXIS, axis); + } + + @Override + public java.util.Set getAxes() { + return getValues(AXIS, org.bukkit.Axis.class); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java index d186de70..83b8b56f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java @@ -9,26 +9,26 @@ public CraftCrops() { super(); } - public CraftCrops(net.minecraft.world.level.block.state.BlockState state) { + public CraftCrops(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.CropBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockCrops.class, "age"); @Override public int getAge() { - return this.get(CraftCrops.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftCrops.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftCrops.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java index 3fd2f7b8..c5ab5700 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java @@ -9,40 +9,40 @@ public CraftDaylightDetector() { super(); } - public CraftDaylightDetector(net.minecraft.world.level.block.state.BlockState state) { + public CraftDaylightDetector(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftDaylightDetector - private static final net.minecraft.world.level.block.state.properties.BooleanProperty INVERTED = getBoolean(net.minecraft.world.level.block.DaylightDetectorBlock.class, "inverted"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean INVERTED = getBoolean(net.minecraft.world.level.block.BlockDaylightDetector.class, "inverted"); @Override public boolean isInverted() { - return this.get(CraftDaylightDetector.INVERTED); + return get(INVERTED); } @Override public void setInverted(boolean inverted) { - this.set(CraftDaylightDetector.INVERTED, inverted); + set(INVERTED, inverted); } // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger(net.minecraft.world.level.block.DaylightDetectorBlock.class, "power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger(net.minecraft.world.level.block.BlockDaylightDetector.class, "power"); @Override public int getPower() { - return this.get(CraftDaylightDetector.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftDaylightDetector.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftDaylightDetector.POWER); + return getMax(POWER); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDecoratedPot.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDecoratedPot.java index 356230b9..c21c7bc1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDecoratedPot.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDecoratedPot.java @@ -9,40 +9,40 @@ public CraftDecoratedPot() { super(); } - public CraftDecoratedPot(net.minecraft.world.level.block.state.BlockState state) { + public CraftDecoratedPot(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.DecoratedPotBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.DecoratedPotBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftDecoratedPot.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftDecoratedPot.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftDecoratedPot.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.DecoratedPotBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.DecoratedPotBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftDecoratedPot.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftDecoratedPot.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java index a2d3b1f7..5c4a061b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java @@ -9,21 +9,21 @@ public CraftDirtSnow() { super(); } - public CraftDirtSnow(net.minecraft.world.level.block.state.BlockState state) { + public CraftDirtSnow(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftSnowable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SNOWY = getBoolean(net.minecraft.world.level.block.SnowyDirtBlock.class, "snowy"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SNOWY = getBoolean(net.minecraft.world.level.block.BlockDirtSnow.class, "snowy"); @Override public boolean isSnowy() { - return this.get(CraftDirtSnow.SNOWY); + return get(SNOWY); } @Override public void setSnowy(boolean snowy) { - this.set(CraftDirtSnow.SNOWY, snowy); + set(SNOWY, snowy); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java index 444c0ef7..061e9869 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java @@ -9,40 +9,40 @@ public CraftDispenser() { super(); } - public CraftDispenser(net.minecraft.world.level.block.state.BlockState state) { + public CraftDispenser(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftDispenser - private static final net.minecraft.world.level.block.state.properties.BooleanProperty TRIGGERED = getBoolean(net.minecraft.world.level.block.DispenserBlock.class, "triggered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TRIGGERED = getBoolean(net.minecraft.world.level.block.BlockDispenser.class, "triggered"); @Override public boolean isTriggered() { - return this.get(CraftDispenser.TRIGGERED); + return get(TRIGGERED); } @Override public void setTriggered(boolean triggered) { - this.set(CraftDispenser.TRIGGERED, triggered); + set(TRIGGERED, triggered); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.DispenserBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockDispenser.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftDispenser.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftDispenser.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftDispenser.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java index 633e7fd0..1dafa4ea 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java @@ -9,82 +9,82 @@ public CraftDoor() { super(); } - public CraftDoor(net.minecraft.world.level.block.state.BlockState state) { + public CraftDoor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftDoor - private static final net.minecraft.world.level.block.state.properties.EnumProperty HINGE = getEnum(net.minecraft.world.level.block.DoorBlock.class, "hinge"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HINGE = getEnum(net.minecraft.world.level.block.BlockDoor.class, "hinge"); @Override public org.bukkit.block.data.type.Door.Hinge getHinge() { - return this.get(CraftDoor.HINGE, org.bukkit.block.data.type.Door.Hinge.class); + return get(HINGE, org.bukkit.block.data.type.Door.Hinge.class); } @Override public void setHinge(org.bukkit.block.data.type.Door.Hinge hinge) { - this.set(CraftDoor.HINGE, hinge); + set(HINGE, hinge); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.DoorBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.BlockDoor.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftDoor.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftDoor.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.DoorBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockDoor.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftDoor.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftDoor.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftDoor.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftOpenable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean(net.minecraft.world.level.block.DoorBlock.class, "open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean(net.minecraft.world.level.block.BlockDoor.class, "open"); @Override public boolean isOpen() { - return this.get(CraftDoor.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftDoor.OPEN, open); + set(OPEN, open); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.DoorBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockDoor.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftDoor.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftDoor.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java index c460bb67..37fbb0b0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java @@ -9,40 +9,40 @@ public CraftDropper() { super(); } - public CraftDropper(net.minecraft.world.level.block.state.BlockState state) { + public CraftDropper(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftDispenser - private static final net.minecraft.world.level.block.state.properties.BooleanProperty TRIGGERED = getBoolean(net.minecraft.world.level.block.DropperBlock.class, "triggered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TRIGGERED = getBoolean(net.minecraft.world.level.block.BlockDropper.class, "triggered"); @Override public boolean isTriggered() { - return this.get(CraftDropper.TRIGGERED); + return get(TRIGGERED); } @Override public void setTriggered(boolean triggered) { - this.set(CraftDropper.TRIGGERED, triggered); + set(TRIGGERED, triggered); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.DropperBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockDropper.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftDropper.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftDropper.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftDropper.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java index 81ad9196..387f1796 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java @@ -9,26 +9,26 @@ public CraftEndRod() { super(); } - public CraftEndRod(net.minecraft.world.level.block.state.BlockState state) { + public CraftEndRod(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.EndRodBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockEndRod.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftEndRod.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftEndRod.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftEndRod.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java index b259fc7f..6bf22b7e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java @@ -9,40 +9,40 @@ public CraftEnderChest() { super(); } - public CraftEnderChest(net.minecraft.world.level.block.state.BlockState state) { + public CraftEnderChest(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.EnderChestBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockEnderChest.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftEnderChest.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftEnderChest.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftEnderChest.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.EnderChestBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockEnderChest.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftEnderChest.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftEnderChest.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java index d1959292..99dd4b6c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java @@ -9,40 +9,40 @@ public CraftEnderPortalFrame() { super(); } - public CraftEnderPortalFrame(net.minecraft.world.level.block.state.BlockState state) { + public CraftEnderPortalFrame(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftEndPortalFrame - private static final net.minecraft.world.level.block.state.properties.BooleanProperty EYE = getBoolean(net.minecraft.world.level.block.EndPortalFrameBlock.class, "eye"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean EYE = getBoolean(net.minecraft.world.level.block.BlockEnderPortalFrame.class, "eye"); @Override public boolean hasEye() { - return this.get(CraftEnderPortalFrame.EYE); + return get(EYE); } @Override public void setEye(boolean eye) { - this.set(CraftEnderPortalFrame.EYE, eye); + set(EYE, eye); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.EndPortalFrameBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockEnderPortalFrame.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftEnderPortalFrame.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftEnderPortalFrame.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftEnderPortalFrame.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEquipableCarvedPumpkin.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEquipableCarvedPumpkin.java deleted file mode 100644 index 718a65d6..00000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEquipableCarvedPumpkin.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftEquipableCarvedPumpkin extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftEquipableCarvedPumpkin() { - super(); - } - - public CraftEquipableCarvedPumpkin(net.minecraft.world.level.block.state.BlockState state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.EquipableCarvedPumpkinBlock.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftEquipableCarvedPumpkin.FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftEquipableCarvedPumpkin.FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return this.getValues(CraftEquipableCarvedPumpkin.FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java index 11f2f107..28eec800 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java @@ -9,40 +9,40 @@ public CraftFence() { super(); } - public CraftFence(net.minecraft.world.level.block.state.BlockState state) { + public CraftFence(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.FenceBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.FenceBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.FenceBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.FenceBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.FenceBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.FenceBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockFence.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockFence.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockFence.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockFence.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockFence.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockFence.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftFence.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftFence.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftFence.FACES.length; i++) { - if (CraftFence.FACES[i] != null && this.get(CraftFence.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftFence.FACES.length; i++) { - if (CraftFence.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -65,15 +65,15 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.FenceBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockFence.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftFence.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftFence.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java index b31474d3..6ffb6060 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java @@ -9,68 +9,68 @@ public CraftFenceGate() { super(); } - public CraftFenceGate(net.minecraft.world.level.block.state.BlockState state) { + public CraftFenceGate(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftGate - private static final net.minecraft.world.level.block.state.properties.BooleanProperty IN_WALL = getBoolean(net.minecraft.world.level.block.FenceGateBlock.class, "in_wall"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean IN_WALL = getBoolean(net.minecraft.world.level.block.BlockFenceGate.class, "in_wall"); @Override public boolean isInWall() { - return this.get(CraftFenceGate.IN_WALL); + return get(IN_WALL); } @Override public void setInWall(boolean inWall) { - this.set(CraftFenceGate.IN_WALL, inWall); + set(IN_WALL, inWall); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.FenceGateBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockFenceGate.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftFenceGate.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftFenceGate.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftFenceGate.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftOpenable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean(net.minecraft.world.level.block.FenceGateBlock.class, "open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean(net.minecraft.world.level.block.BlockFenceGate.class, "open"); @Override public boolean isOpen() { - return this.get(CraftFenceGate.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftFenceGate.OPEN, open); + set(OPEN, open); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.FenceGateBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockFenceGate.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftFenceGate.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftFenceGate.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java index b4a0566c..cac0e18e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java @@ -9,59 +9,59 @@ public CraftFire() { super(); } - public CraftFire(net.minecraft.world.level.block.state.BlockState state) { + public CraftFire(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.FireBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockFire.class, "age"); @Override public int getAge() { - return this.get(CraftFire.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftFire.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftFire.AGE); + return getMax(AGE); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.FireBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.FireBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.FireBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.FireBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.FireBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.FireBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockFire.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockFire.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockFire.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockFire.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockFire.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockFire.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftFire.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftFire.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftFire.FACES.length; i++) { - if (CraftFire.FACES[i] != null && this.get(CraftFire.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -73,8 +73,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftFire.FACES.length; i++) { - if (CraftFire.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java index 6c5c0123..fbea1e86 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java @@ -9,17 +9,17 @@ public CraftFloorSign() { super(); } - public CraftFloorSign(net.minecraft.world.level.block.state.BlockState state) { + public CraftFloorSign(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftRotatable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger(net.minecraft.world.level.block.StandingSignBlock.class, "rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger(net.minecraft.world.level.block.BlockFloorSign.class, "rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftFloorSign.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -113,20 +113,20 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftFloorSign.ROTATION, val); + set(ROTATION, val); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.StandingSignBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockFloorSign.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftFloorSign.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftFloorSign.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java index 70d734fc..0d9bf070 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java @@ -9,26 +9,26 @@ public CraftFluids() { super(); } - public CraftFluids(net.minecraft.world.level.block.state.BlockState state) { + public CraftFluids(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLevelled - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LEVEL = getInteger(net.minecraft.world.level.block.LiquidBlock.class, "level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LEVEL = getInteger(net.minecraft.world.level.block.BlockFluids.class, "level"); @Override public int getLevel() { - return this.get(CraftFluids.LEVEL); + return get(LEVEL); } @Override public void setLevel(int level) { - this.set(CraftFluids.LEVEL, level); + set(LEVEL, level); } @Override public int getMaximumLevel() { - return getMax(CraftFluids.LEVEL); + return getMax(LEVEL); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java index 5698cb11..30478af3 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java @@ -9,40 +9,40 @@ public CraftFurnaceFurace() { super(); } - public CraftFurnaceFurace(net.minecraft.world.level.block.state.BlockState state) { + public CraftFurnaceFurace(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.FurnaceBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockFurnaceFurace.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftFurnaceFurace.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftFurnaceFurace.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftFurnaceFurace.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.FurnaceBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockFurnaceFurace.class, "lit"); @Override public boolean isLit() { - return this.get(CraftFurnaceFurace.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftFurnaceFurace.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java index bae1e6e7..ec024f0d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java @@ -9,26 +9,26 @@ public CraftGlazedTerracotta() { super(); } - public CraftGlazedTerracotta(net.minecraft.world.level.block.state.BlockState state) { + public CraftGlazedTerracotta(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.GlazedTerracottaBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockGlazedTerracotta.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftGlazedTerracotta.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftGlazedTerracotta.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftGlazedTerracotta.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlowLichen.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlowLichen.java index b921b97f..1c82832e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlowLichen.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlowLichen.java @@ -9,40 +9,40 @@ public CraftGlowLichen() { super(); } - public CraftGlowLichen(net.minecraft.world.level.block.state.BlockState state) { + public CraftGlowLichen(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftGlowLichen.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftGlowLichen.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftGlowLichen.FACES.length; i++) { - if (CraftGlowLichen.FACES[i] != null && this.get(CraftGlowLichen.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftGlowLichen.FACES.length; i++) { - if (CraftGlowLichen.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -65,15 +65,15 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.GlowLichenBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftGlowLichen.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftGlowLichen.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java index 550a80ec..bdcd971c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java @@ -9,21 +9,21 @@ public CraftGrass() { super(); } - public CraftGrass(net.minecraft.world.level.block.state.BlockState state) { + public CraftGrass(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftSnowable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SNOWY = getBoolean(net.minecraft.world.level.block.GrassBlock.class, "snowy"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SNOWY = getBoolean(net.minecraft.world.level.block.BlockGrass.class, "snowy"); @Override public boolean isSnowy() { - return this.get(CraftGrass.SNOWY); + return get(SNOWY); } @Override public void setSnowy(boolean snowy) { - this.set(CraftGrass.SNOWY, snowy); + set(SNOWY, snowy); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java index 6f1f0d1b..32444f73 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java @@ -9,40 +9,40 @@ public CraftGrindstone() { super(); } - public CraftGrindstone(net.minecraft.world.level.block.state.BlockState state) { + public CraftGrindstone(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.GrindstoneBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockGrindstone.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftGrindstone.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftGrindstone.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftGrindstone.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftFaceAttachable - private static final net.minecraft.world.level.block.state.properties.EnumProperty ATTACH_FACE = getEnum(net.minecraft.world.level.block.GrindstoneBlock.class, "face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ATTACH_FACE = getEnum(net.minecraft.world.level.block.BlockGrindstone.class, "face"); @Override public org.bukkit.block.data.FaceAttachable.AttachedFace getAttachedFace() { - return this.get(CraftGrindstone.ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); + return get(ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); } @Override public void setAttachedFace(org.bukkit.block.data.FaceAttachable.AttachedFace face) { - this.set(CraftGrindstone.ATTACH_FACE, face); + set(ATTACH_FACE, face); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingMoss.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingMoss.java new file mode 100644 index 00000000..40a59ddd --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingMoss.java @@ -0,0 +1,29 @@ +/** + * Automatically generated file, changes will be lost. + */ +package org.bukkit.craftbukkit.block.impl; + +public final class CraftHangingMoss extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.HangingMoss { + + public CraftHangingMoss() { + super(); + } + + public CraftHangingMoss(net.minecraft.world.level.block.state.IBlockData state) { + super(state); + } + + // org.bukkit.craftbukkit.block.data.type.CraftHangingMoss + + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean TIP = getBoolean(net.minecraft.world.level.block.HangingMossBlock.class, "tip"); + + @Override + public boolean isTip() { + return get(TIP); + } + + @Override + public void setTip(boolean tip) { + set(TIP, tip); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingRoots.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingRoots.java index c3e66c6d..01418e89 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingRoots.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHangingRoots.java @@ -9,21 +9,21 @@ public CraftHangingRoots() { super(); } - public CraftHangingRoots(net.minecraft.world.level.block.state.BlockState state) { + public CraftHangingRoots(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.HangingRootsBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.HangingRootsBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftHangingRoots.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftHangingRoots.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java index 3801685a..afe65601 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java @@ -9,26 +9,26 @@ public CraftHay() { super(); } - public CraftHay(net.minecraft.world.level.block.state.BlockState state) { + public CraftHay(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftOrientable - private static final net.minecraft.world.level.block.state.properties.EnumProperty AXIS = getEnum(net.minecraft.world.level.block.HayBlock.class, "axis"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum(net.minecraft.world.level.block.BlockHay.class, "axis"); @Override public org.bukkit.Axis getAxis() { - return this.get(CraftHay.AXIS, org.bukkit.Axis.class); + return get(AXIS, org.bukkit.Axis.class); } @Override public void setAxis(org.bukkit.Axis axis) { - this.set(CraftHay.AXIS, axis); + set(AXIS, axis); } @Override public java.util.Set getAxes() { - return this.getValues(CraftHay.AXIS, org.bukkit.Axis.class); + return getValues(AXIS, org.bukkit.Axis.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHeavyCore.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHeavyCore.java index d070fc8c..364f7dbc 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHeavyCore.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHeavyCore.java @@ -9,21 +9,21 @@ public CraftHeavyCore() { super(); } - public CraftHeavyCore(net.minecraft.world.level.block.state.BlockState state) { + public CraftHeavyCore(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.HeavyCoreBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.HeavyCoreBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftHeavyCore.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftHeavyCore.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java index 26091ba1..ff70d732 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java @@ -9,40 +9,40 @@ public CraftHopper() { super(); } - public CraftHopper(net.minecraft.world.level.block.state.BlockState state) { + public CraftHopper(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftHopper - private static final net.minecraft.world.level.block.state.properties.BooleanProperty ENABLED = getBoolean(net.minecraft.world.level.block.HopperBlock.class, "enabled"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean ENABLED = getBoolean(net.minecraft.world.level.block.BlockHopper.class, "enabled"); @Override public boolean isEnabled() { - return this.get(CraftHopper.ENABLED); + return get(ENABLED); } @Override public void setEnabled(boolean enabled) { - this.set(CraftHopper.ENABLED, enabled); + set(ENABLED, enabled); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.HopperBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockHopper.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftHopper.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftHopper.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftHopper.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java index ebd0633f..3b8bcfa1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java @@ -9,40 +9,40 @@ public CraftHugeMushroom() { super(); } - public CraftHugeMushroom(net.minecraft.world.level.block.state.BlockState state) { + public CraftHugeMushroom(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.HugeMushroomBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.HugeMushroomBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.HugeMushroomBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.HugeMushroomBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.HugeMushroomBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.HugeMushroomBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockHugeMushroom.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockHugeMushroom.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockHugeMushroom.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockHugeMushroom.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockHugeMushroom.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockHugeMushroom.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftHugeMushroom.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftHugeMushroom.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftHugeMushroom.FACES.length; i++) { - if (CraftHugeMushroom.FACES[i] != null && this.get(CraftHugeMushroom.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftHugeMushroom.FACES.length; i++) { - if (CraftHugeMushroom.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java index 85367bee..b4ad06fd 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java @@ -9,26 +9,26 @@ public CraftIceFrost() { super(); } - public CraftIceFrost(net.minecraft.world.level.block.state.BlockState state) { + public CraftIceFrost(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.FrostedIceBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockIceFrost.class, "age"); @Override public int getAge() { - return this.get(CraftIceFrost.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftIceFrost.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftIceFrost.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftInfestedRotatedPillar.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftInfestedRotatedPillar.java index e3272b34..e7a67d4d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftInfestedRotatedPillar.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftInfestedRotatedPillar.java @@ -9,26 +9,26 @@ public CraftInfestedRotatedPillar() { super(); } - public CraftInfestedRotatedPillar(net.minecraft.world.level.block.state.BlockState state) { + public CraftInfestedRotatedPillar(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftOrientable - private static final net.minecraft.world.level.block.state.properties.EnumProperty AXIS = getEnum(net.minecraft.world.level.block.InfestedRotatedPillarBlock.class, "axis"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum(net.minecraft.world.level.block.InfestedRotatedPillarBlock.class, "axis"); @Override public org.bukkit.Axis getAxis() { - return this.get(CraftInfestedRotatedPillar.AXIS, org.bukkit.Axis.class); + return get(AXIS, org.bukkit.Axis.class); } @Override public void setAxis(org.bukkit.Axis axis) { - this.set(CraftInfestedRotatedPillar.AXIS, axis); + set(AXIS, axis); } @Override public java.util.Set getAxes() { - return this.getValues(CraftInfestedRotatedPillar.AXIS, org.bukkit.Axis.class); + return getValues(AXIS, org.bukkit.Axis.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java index 485d212c..c755dbd0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java @@ -9,40 +9,40 @@ public CraftIronBars() { super(); } - public CraftIronBars(net.minecraft.world.level.block.state.BlockState state) { + public CraftIronBars(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftIronBars.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftIronBars.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftIronBars.FACES.length; i++) { - if (CraftIronBars.FACES[i] != null && this.get(CraftIronBars.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftIronBars.FACES.length; i++) { - if (CraftIronBars.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -65,15 +65,15 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.IronBarsBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockIronBars.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftIronBars.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftIronBars.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java index 12237538..344bdb5d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java @@ -9,21 +9,21 @@ public CraftJigsaw() { super(); } - public CraftJigsaw(net.minecraft.world.level.block.state.BlockState state) { + public CraftJigsaw(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftJigsaw - private static final net.minecraft.world.level.block.state.properties.EnumProperty ORIENTATION = getEnum(net.minecraft.world.level.block.JigsawBlock.class, "orientation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ORIENTATION = getEnum(net.minecraft.world.level.block.BlockJigsaw.class, "orientation"); @Override public org.bukkit.block.data.type.Jigsaw.Orientation getOrientation() { - return this.get(CraftJigsaw.ORIENTATION, org.bukkit.block.data.type.Jigsaw.Orientation.class); + return get(ORIENTATION, org.bukkit.block.data.type.Jigsaw.Orientation.class); } @Override public void setOrientation(org.bukkit.block.data.type.Jigsaw.Orientation orientation) { - this.set(CraftJigsaw.ORIENTATION, orientation); + set(ORIENTATION, orientation); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java index 3e37557b..998a04a1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java @@ -9,16 +9,16 @@ public CraftJukeBox() { super(); } - public CraftJukeBox(net.minecraft.world.level.block.state.BlockState state) { + public CraftJukeBox(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftJukebox - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HAS_RECORD = getBoolean(net.minecraft.world.level.block.JukeboxBlock.class, "has_record"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HAS_RECORD = getBoolean(net.minecraft.world.level.block.BlockJukeBox.class, "has_record"); @Override public boolean hasRecord() { - return this.get(CraftJukeBox.HAS_RECORD); + return get(HAS_RECORD); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java index 299b9112..cf291bbe 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java @@ -9,26 +9,26 @@ public CraftKelp() { super(); } - public CraftKelp(net.minecraft.world.level.block.state.BlockState state) { + public CraftKelp(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.KelpBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockKelp.class, "age"); @Override public int getAge() { - return this.get(CraftKelp.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftKelp.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftKelp.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java index 26e59056..16c1bc18 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java @@ -9,40 +9,40 @@ public CraftLadder() { super(); } - public CraftLadder(net.minecraft.world.level.block.state.BlockState state) { + public CraftLadder(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.LadderBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockLadder.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftLadder.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftLadder.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftLadder.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.LadderBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockLadder.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftLadder.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftLadder.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java index 37ab63bb..a77d99db 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java @@ -9,35 +9,35 @@ public CraftLantern() { super(); } - public CraftLantern(net.minecraft.world.level.block.state.BlockState state) { + public CraftLantern(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftHangable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HANGING = getBoolean(net.minecraft.world.level.block.LanternBlock.class, "hanging"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HANGING = getBoolean(net.minecraft.world.level.block.BlockLantern.class, "hanging"); @Override public boolean isHanging() { - return this.get(CraftLantern.HANGING); + return get(HANGING); } @Override public void setHanging(boolean hanging) { - this.set(CraftLantern.HANGING, hanging); + set(HANGING, hanging); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.LanternBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockLantern.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftLantern.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftLantern.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLayeredCauldron.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLayeredCauldron.java index bf0d53f6..d041159f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLayeredCauldron.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLayeredCauldron.java @@ -9,26 +9,26 @@ public CraftLayeredCauldron() { super(); } - public CraftLayeredCauldron(net.minecraft.world.level.block.state.BlockState state) { + public CraftLayeredCauldron(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLevelled - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LEVEL = getInteger(net.minecraft.world.level.block.LayeredCauldronBlock.class, "level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LEVEL = getInteger(net.minecraft.world.level.block.LayeredCauldronBlock.class, "level"); @Override public int getLevel() { - return this.get(CraftLayeredCauldron.LEVEL); + return get(LEVEL); } @Override public void setLevel(int level) { - this.set(CraftLayeredCauldron.LEVEL, level); + set(LEVEL, level); } @Override public int getMaximumLevel() { - return getMax(CraftLayeredCauldron.LEVEL); + return getMax(LEVEL); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java index 33d9a950..c445da6c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java @@ -9,46 +9,46 @@ public CraftLeaves() { super(); } - public CraftLeaves(net.minecraft.world.level.block.state.BlockState state) { + public CraftLeaves(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftLeaves - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DISTANCE = getInteger(net.minecraft.world.level.block.LeavesBlock.class, "distance"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty PERSISTENT = getBoolean(net.minecraft.world.level.block.LeavesBlock.class, "persistent"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DISTANCE = getInteger(net.minecraft.world.level.block.BlockLeaves.class, "distance"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean PERSISTENT = getBoolean(net.minecraft.world.level.block.BlockLeaves.class, "persistent"); @Override public boolean isPersistent() { - return this.get(CraftLeaves.PERSISTENT); + return get(PERSISTENT); } @Override public void setPersistent(boolean persistent) { - this.set(CraftLeaves.PERSISTENT, persistent); + set(PERSISTENT, persistent); } @Override public int getDistance() { - return this.get(CraftLeaves.DISTANCE); + return get(DISTANCE); } @Override public void setDistance(int distance) { - this.set(CraftLeaves.DISTANCE, distance); + set(DISTANCE, distance); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.LeavesBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockLeaves.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftLeaves.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftLeaves.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java index ee53b152..a25443af 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java @@ -9,49 +9,49 @@ public CraftLectern() { super(); } - public CraftLectern(net.minecraft.world.level.block.state.BlockState state) { + public CraftLectern(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftLectern - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HAS_BOOK = getBoolean(net.minecraft.world.level.block.LecternBlock.class, "has_book"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HAS_BOOK = getBoolean(net.minecraft.world.level.block.BlockLectern.class, "has_book"); @Override public boolean hasBook() { - return this.get(CraftLectern.HAS_BOOK); + return get(HAS_BOOK); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.LecternBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockLectern.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftLectern.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftLectern.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftLectern.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.LecternBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockLectern.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftLectern.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftLectern.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java index 761ab0fb..21761488 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java @@ -9,68 +9,68 @@ public CraftLever() { super(); } - public CraftLever(net.minecraft.world.level.block.state.BlockState state) { + public CraftLever(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSwitch - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACE = getEnum(net.minecraft.world.level.block.LeverBlock.class, "face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACE = getEnum(net.minecraft.world.level.block.BlockLever.class, "face"); @Override public org.bukkit.block.data.type.Switch.Face getFace() { - return this.get(CraftLever.FACE, org.bukkit.block.data.type.Switch.Face.class); + return get(FACE, org.bukkit.block.data.type.Switch.Face.class); } @Override public void setFace(org.bukkit.block.data.type.Switch.Face face) { - this.set(CraftLever.FACE, face); + set(FACE, face); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.LeverBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockLever.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftLever.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftLever.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftLever.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftFaceAttachable - private static final net.minecraft.world.level.block.state.properties.EnumProperty ATTACH_FACE = getEnum(net.minecraft.world.level.block.LeverBlock.class, "face"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum ATTACH_FACE = getEnum(net.minecraft.world.level.block.BlockLever.class, "face"); @Override public org.bukkit.block.data.FaceAttachable.AttachedFace getAttachedFace() { - return this.get(CraftLever.ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); + return get(ATTACH_FACE, org.bukkit.block.data.FaceAttachable.AttachedFace.class); } @Override public void setAttachedFace(org.bukkit.block.data.FaceAttachable.AttachedFace face) { - this.set(CraftLever.ATTACH_FACE, face); + set(ATTACH_FACE, face); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.LeverBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockLever.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftLever.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftLever.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLight.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLight.java index 49f314b1..b09f55f6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLight.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLight.java @@ -9,40 +9,40 @@ public CraftLight() { super(); } - public CraftLight(net.minecraft.world.level.block.state.BlockState state) { + public CraftLight(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLevelled - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LEVEL = getInteger(net.minecraft.world.level.block.LightBlock.class, "level"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LEVEL = getInteger(net.minecraft.world.level.block.LightBlock.class, "level"); @Override public int getLevel() { - return this.get(CraftLight.LEVEL); + return get(LEVEL); } @Override public void setLevel(int level) { - this.set(CraftLight.LEVEL, level); + set(LEVEL, level); } @Override public int getMaximumLevel() { - return getMax(CraftLight.LEVEL); + return getMax(LEVEL); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.LightBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.LightBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftLight.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftLight.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLightningRod.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLightningRod.java index b3bc8b41..5d3446ea 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLightningRod.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLightningRod.java @@ -9,54 +9,54 @@ public CraftLightningRod() { super(); } - public CraftLightningRod(net.minecraft.world.level.block.state.BlockState state) { + public CraftLightningRod(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.LightningRodBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.LightningRodBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftLightningRod.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftLightningRod.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftLightningRod.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.LightningRodBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.LightningRodBlock.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftLightningRod.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftLightningRod.POWERED, powered); + set(POWERED, powered); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.LightningRodBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.LightningRodBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftLightningRod.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftLightningRod.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java index e39737c6..dad3dd22 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java @@ -9,26 +9,26 @@ public CraftLoom() { super(); } - public CraftLoom(net.minecraft.world.level.block.state.BlockState state) { + public CraftLoom(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.LoomBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockLoom.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftLoom.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftLoom.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftLoom.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveLeaves.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveLeaves.java index 7a1f2fd2..1ff34c90 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveLeaves.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveLeaves.java @@ -9,46 +9,46 @@ public CraftMangroveLeaves() { super(); } - public CraftMangroveLeaves(net.minecraft.world.level.block.state.BlockState state) { + public CraftMangroveLeaves(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftLeaves - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DISTANCE = getInteger(net.minecraft.world.level.block.MangroveLeavesBlock.class, "distance"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty PERSISTENT = getBoolean(net.minecraft.world.level.block.MangroveLeavesBlock.class, "persistent"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DISTANCE = getInteger(net.minecraft.world.level.block.MangroveLeavesBlock.class, "distance"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean PERSISTENT = getBoolean(net.minecraft.world.level.block.MangroveLeavesBlock.class, "persistent"); @Override public boolean isPersistent() { - return this.get(CraftMangroveLeaves.PERSISTENT); + return get(PERSISTENT); } @Override public void setPersistent(boolean persistent) { - this.set(CraftMangroveLeaves.PERSISTENT, persistent); + set(PERSISTENT, persistent); } @Override public int getDistance() { - return this.get(CraftMangroveLeaves.DISTANCE); + return get(DISTANCE); } @Override public void setDistance(int distance) { - this.set(CraftMangroveLeaves.DISTANCE, distance); + set(DISTANCE, distance); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.MangroveLeavesBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.MangroveLeavesBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftMangroveLeaves.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftMangroveLeaves.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangrovePropagule.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangrovePropagule.java index 5a48fdd9..1d7671ec 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangrovePropagule.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangrovePropagule.java @@ -9,73 +9,73 @@ public CraftMangrovePropagule() { super(); } - public CraftMangrovePropagule(net.minecraft.world.level.block.state.BlockState state) { + public CraftMangrovePropagule(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "age"); @Override public int getAge() { - return this.get(CraftMangrovePropagule.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftMangrovePropagule.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftMangrovePropagule.AGE); + return getMax(AGE); } // org.bukkit.craftbukkit.block.data.CraftHangable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty HANGING = getBoolean(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "hanging"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean HANGING = getBoolean(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "hanging"); @Override public boolean isHanging() { - return this.get(CraftMangrovePropagule.HANGING); + return get(HANGING); } @Override public void setHanging(boolean hanging) { - this.set(CraftMangrovePropagule.HANGING, hanging); + set(HANGING, hanging); } // org.bukkit.craftbukkit.block.data.type.CraftSapling - private static final net.minecraft.world.level.block.state.properties.IntegerProperty STAGE = getInteger(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "stage"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger STAGE = getInteger(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "stage"); @Override public int getStage() { - return this.get(CraftMangrovePropagule.STAGE); + return get(STAGE); } @Override public void setStage(int stage) { - this.set(CraftMangrovePropagule.STAGE, stage); + set(STAGE, stage); } @Override public int getMaximumStage() { - return getMax(CraftMangrovePropagule.STAGE); + return getMax(STAGE); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.MangrovePropaguleBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftMangrovePropagule.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftMangrovePropagule.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveRoots.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveRoots.java index 1442ed8c..0a16b7d5 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveRoots.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMangroveRoots.java @@ -9,21 +9,21 @@ public CraftMangroveRoots() { super(); } - public CraftMangroveRoots(net.minecraft.world.level.block.state.BlockState state) { + public CraftMangroveRoots(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.MangroveRootsBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.MangroveRootsBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftMangroveRoots.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftMangroveRoots.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java index a462ef71..bd02bb1b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java @@ -9,54 +9,54 @@ public CraftMinecartDetector() { super(); } - public CraftMinecartDetector(net.minecraft.world.level.block.state.BlockState state) { + public CraftMinecartDetector(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.DetectorRailBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockMinecartDetector.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftMinecartDetector.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftMinecartDetector.POWERED, powered); + set(POWERED, powered); } // org.bukkit.craftbukkit.block.data.CraftRail - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum(net.minecraft.world.level.block.DetectorRailBlock.class, "shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum(net.minecraft.world.level.block.BlockMinecartDetector.class, "shape"); @Override public org.bukkit.block.data.Rail.Shape getShape() { - return this.get(CraftMinecartDetector.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return get(SHAPE, org.bukkit.block.data.Rail.Shape.class); } @Override public void setShape(org.bukkit.block.data.Rail.Shape shape) { - this.set(CraftMinecartDetector.SHAPE, shape); + set(SHAPE, shape); } @Override public java.util.Set getShapes() { - return this.getValues(CraftMinecartDetector.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return getValues(SHAPE, org.bukkit.block.data.Rail.Shape.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.DetectorRailBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockMinecartDetector.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftMinecartDetector.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftMinecartDetector.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java index f58d2af8..9ab6b883 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java @@ -9,40 +9,40 @@ public CraftMinecartTrack() { super(); } - public CraftMinecartTrack(net.minecraft.world.level.block.state.BlockState state) { + public CraftMinecartTrack(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftRail - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum(net.minecraft.world.level.block.RailBlock.class, "shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum(net.minecraft.world.level.block.BlockMinecartTrack.class, "shape"); @Override public org.bukkit.block.data.Rail.Shape getShape() { - return this.get(CraftMinecartTrack.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return get(SHAPE, org.bukkit.block.data.Rail.Shape.class); } @Override public void setShape(org.bukkit.block.data.Rail.Shape shape) { - this.set(CraftMinecartTrack.SHAPE, shape); + set(SHAPE, shape); } @Override public java.util.Set getShapes() { - return this.getValues(CraftMinecartTrack.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return getValues(SHAPE, org.bukkit.block.data.Rail.Shape.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.RailBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockMinecartTrack.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftMinecartTrack.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftMinecartTrack.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMossyCarpet.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMossyCarpet.java new file mode 100644 index 00000000..ea190657 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMossyCarpet.java @@ -0,0 +1,42 @@ +/** + * Automatically generated file, changes will be lost. + */ +package org.bukkit.craftbukkit.block.impl; + +public final class CraftMossyCarpet extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.MossyCarpet { + + public CraftMossyCarpet() { + super(); + } + + public CraftMossyCarpet(net.minecraft.world.level.block.state.IBlockData state) { + super(state); + } + + // org.bukkit.craftbukkit.block.data.type.CraftMossyCarpet + + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BOTTOM = getBoolean(net.minecraft.world.level.block.MossyCarpetBlock.class, "bottom"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum[] HEIGHTS = new net.minecraft.world.level.block.state.properties.BlockStateEnum[]{ + getEnum(net.minecraft.world.level.block.MossyCarpetBlock.class, "north"), getEnum(net.minecraft.world.level.block.MossyCarpetBlock.class, "east"), getEnum(net.minecraft.world.level.block.MossyCarpetBlock.class, "south"), getEnum(net.minecraft.world.level.block.MossyCarpetBlock.class, "west") + }; + + @Override + public boolean isBottom() { + return get(BOTTOM); + } + + @Override + public void setBottom(boolean up) { + set(BOTTOM, up); + } + + @Override + public org.bukkit.block.data.type.MossyCarpet.Height getHeight(org.bukkit.block.BlockFace face) { + return get(HEIGHTS[face.ordinal()], org.bukkit.block.data.type.MossyCarpet.Height.class); + } + + @Override + public void setHeight(org.bukkit.block.BlockFace face, org.bukkit.block.data.type.MossyCarpet.Height height) { + set(HEIGHTS[face.ordinal()], height); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java index ec10c721..f39400b7 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java @@ -9,21 +9,21 @@ public CraftMycel() { super(); } - public CraftMycel(net.minecraft.world.level.block.state.BlockState state) { + public CraftMycel(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftSnowable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SNOWY = getBoolean(net.minecraft.world.level.block.MyceliumBlock.class, "snowy"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SNOWY = getBoolean(net.minecraft.world.level.block.BlockMycel.class, "snowy"); @Override public boolean isSnowy() { - return this.get(CraftMycel.SNOWY); + return get(SNOWY); } @Override public void setSnowy(boolean snowy) { - this.set(CraftMycel.SNOWY, snowy); + set(SNOWY, snowy); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java index b98d7f85..036e0d88 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java @@ -9,26 +9,26 @@ public CraftNetherWart() { super(); } - public CraftNetherWart(net.minecraft.world.level.block.state.BlockState state) { + public CraftNetherWart(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.NetherWartBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockNetherWart.class, "age"); @Override public int getAge() { - return this.get(CraftNetherWart.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftNetherWart.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftNetherWart.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java index 60675e55..9cd547ee 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java @@ -9,46 +9,46 @@ public CraftNote() { super(); } - public CraftNote(net.minecraft.world.level.block.state.BlockState state) { + public CraftNote(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftNoteBlock - private static final net.minecraft.world.level.block.state.properties.EnumProperty INSTRUMENT = getEnum(net.minecraft.world.level.block.NoteBlock.class, "instrument"); - private static final net.minecraft.world.level.block.state.properties.IntegerProperty NOTE = getInteger(net.minecraft.world.level.block.NoteBlock.class, "note"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum INSTRUMENT = getEnum(net.minecraft.world.level.block.BlockNote.class, "instrument"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger NOTE = getInteger(net.minecraft.world.level.block.BlockNote.class, "note"); @Override public org.bukkit.Instrument getInstrument() { - return this.get(CraftNote.INSTRUMENT, org.bukkit.Instrument.class); + return get(INSTRUMENT, org.bukkit.Instrument.class); } @Override public void setInstrument(org.bukkit.Instrument instrument) { - this.set(CraftNote.INSTRUMENT, instrument); + set(INSTRUMENT, instrument); } @Override public org.bukkit.Note getNote() { - return new org.bukkit.Note(this.get(CraftNote.NOTE)); + return new org.bukkit.Note(get(NOTE)); } @Override public void setNote(org.bukkit.Note note) { - this.set(CraftNote.NOTE, (int) note.getId()); + set(NOTE, (int) note.getId()); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.NoteBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockNote.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftNote.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftNote.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java index e6364d5b..b06ac028 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java @@ -9,40 +9,40 @@ public CraftObserver() { super(); } - public CraftObserver(net.minecraft.world.level.block.state.BlockState state) { + public CraftObserver(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.ObserverBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockObserver.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftObserver.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftObserver.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftObserver.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.ObserverBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockObserver.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftObserver.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftObserver.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiglinWallSkull.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiglinWallSkull.java index f960c3e3..9eec1f4f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiglinWallSkull.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiglinWallSkull.java @@ -9,32 +9,32 @@ public CraftPiglinWallSkull() { super(); } - public CraftPiglinWallSkull(net.minecraft.world.level.block.state.BlockState state) { + public CraftPiglinWallSkull(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.PiglinWallSkullBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.PiglinWallSkullBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftPiglinWallSkull.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftPiglinWallSkull.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftPiglinWallSkull.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.PiglinWallSkullBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.PiglinWallSkullBlock.class, "powered"); @Override public boolean isPowered() { diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPinkPetals.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPinkPetals.java index 78b220a6..7d3bc82e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPinkPetals.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPinkPetals.java @@ -9,45 +9,45 @@ public CraftPinkPetals() { super(); } - public CraftPinkPetals(net.minecraft.world.level.block.state.BlockState state) { + public CraftPinkPetals(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftPinkPetals - private static final net.minecraft.world.level.block.state.properties.IntegerProperty FLOWER_AMOUNT = getInteger(net.minecraft.world.level.block.PinkPetalsBlock.class, "flower_amount"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger FLOWER_AMOUNT = getInteger(net.minecraft.world.level.block.PinkPetalsBlock.class, "flower_amount"); @Override public int getFlowerAmount() { - return this.get(CraftPinkPetals.FLOWER_AMOUNT); + return get(FLOWER_AMOUNT); } @Override public void setFlowerAmount(int flower_amount) { - this.set(CraftPinkPetals.FLOWER_AMOUNT, flower_amount); + set(FLOWER_AMOUNT, flower_amount); } @Override public int getMaximumFlowerAmount() { - return getMax(CraftPinkPetals.FLOWER_AMOUNT); + return getMax(FLOWER_AMOUNT); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.PinkPetalsBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.PinkPetalsBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftPinkPetals.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftPinkPetals.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftPinkPetals.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java index f31db7da..754dc78c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java @@ -9,40 +9,40 @@ public CraftPiston() { super(); } - public CraftPiston(net.minecraft.world.level.block.state.BlockState state) { + public CraftPiston(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftPiston - private static final net.minecraft.world.level.block.state.properties.BooleanProperty EXTENDED = getBoolean(net.minecraft.world.level.block.piston.PistonBaseBlock.class, "extended"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean EXTENDED = getBoolean(net.minecraft.world.level.block.piston.BlockPiston.class, "extended"); @Override public boolean isExtended() { - return this.get(CraftPiston.EXTENDED); + return get(EXTENDED); } @Override public void setExtended(boolean extended) { - this.set(CraftPiston.EXTENDED, extended); + set(EXTENDED, extended); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.piston.PistonBaseBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.piston.BlockPiston.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftPiston.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftPiston.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftPiston.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java index 21b6d3c1..ad4079ee 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java @@ -9,54 +9,54 @@ public CraftPistonExtension() { super(); } - public CraftPistonExtension(net.minecraft.world.level.block.state.BlockState state) { + public CraftPistonExtension(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftPistonHead - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SHORT = getBoolean(net.minecraft.world.level.block.piston.PistonHeadBlock.class, "short"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SHORT = getBoolean(net.minecraft.world.level.block.piston.BlockPistonExtension.class, "short"); @Override public boolean isShort() { - return this.get(CraftPistonExtension.SHORT); + return get(SHORT); } @Override public void setShort(boolean _short) { - this.set(CraftPistonExtension.SHORT, _short); + set(SHORT, _short); } // org.bukkit.craftbukkit.block.data.type.CraftTechnicalPiston - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum(net.minecraft.world.level.block.piston.PistonHeadBlock.class, "type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum(net.minecraft.world.level.block.piston.BlockPistonExtension.class, "type"); @Override public org.bukkit.block.data.type.TechnicalPiston.Type getType() { - return this.get(CraftPistonExtension.TYPE, org.bukkit.block.data.type.TechnicalPiston.Type.class); + return get(TYPE, org.bukkit.block.data.type.TechnicalPiston.Type.class); } @Override public void setType(org.bukkit.block.data.type.TechnicalPiston.Type type) { - this.set(CraftPistonExtension.TYPE, type); + set(TYPE, type); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.piston.PistonHeadBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.piston.BlockPistonExtension.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftPistonExtension.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftPistonExtension.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftPistonExtension.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java index 497843a5..0d20624e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java @@ -9,40 +9,40 @@ public CraftPistonMoving() { super(); } - public CraftPistonMoving(net.minecraft.world.level.block.state.BlockState state) { + public CraftPistonMoving(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftTechnicalPiston - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum(net.minecraft.world.level.block.piston.MovingPistonBlock.class, "type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum(net.minecraft.world.level.block.piston.BlockPistonMoving.class, "type"); @Override public org.bukkit.block.data.type.TechnicalPiston.Type getType() { - return this.get(CraftPistonMoving.TYPE, org.bukkit.block.data.type.TechnicalPiston.Type.class); + return get(TYPE, org.bukkit.block.data.type.TechnicalPiston.Type.class); } @Override public void setType(org.bukkit.block.data.type.TechnicalPiston.Type type) { - this.set(CraftPistonMoving.TYPE, type); + set(TYPE, type); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.piston.MovingPistonBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.piston.BlockPistonMoving.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftPistonMoving.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftPistonMoving.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftPistonMoving.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPitcherCrop.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPitcherCrop.java index e21d374a..d529867f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPitcherCrop.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPitcherCrop.java @@ -9,40 +9,40 @@ public CraftPitcherCrop() { super(); } - public CraftPitcherCrop(net.minecraft.world.level.block.state.BlockState state) { + public CraftPitcherCrop(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.PitcherCropBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.PitcherCropBlock.class, "age"); @Override public int getAge() { - return this.get(CraftPitcherCrop.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftPitcherCrop.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftPitcherCrop.AGE); + return getMax(AGE); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.PitcherCropBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.PitcherCropBlock.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftPitcherCrop.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftPitcherCrop.HALF, half); + set(HALF, half); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPointedDripstone.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPointedDripstone.java index bdf6d3fc..a1b320d7 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPointedDripstone.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPointedDripstone.java @@ -9,51 +9,51 @@ public CraftPointedDripstone() { super(); } - public CraftPointedDripstone(net.minecraft.world.level.block.state.BlockState state) { + public CraftPointedDripstone(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftPointedDripstone - private static final net.minecraft.world.level.block.state.properties.EnumProperty VERTICAL_DIRECTION = getEnum(net.minecraft.world.level.block.PointedDripstoneBlock.class, "vertical_direction"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty THICKNESS = getEnum(net.minecraft.world.level.block.PointedDripstoneBlock.class, "thickness"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum VERTICAL_DIRECTION = getEnum(net.minecraft.world.level.block.PointedDripstoneBlock.class, "vertical_direction"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum THICKNESS = getEnum(net.minecraft.world.level.block.PointedDripstoneBlock.class, "thickness"); @Override public org.bukkit.block.BlockFace getVerticalDirection() { - return this.get(CraftPointedDripstone.VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); + return get(VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); } @Override public void setVerticalDirection(org.bukkit.block.BlockFace direction) { - this.set(CraftPointedDripstone.VERTICAL_DIRECTION, direction); + set(VERTICAL_DIRECTION, direction); } @Override public java.util.Set getVerticalDirections() { - return this.getValues(CraftPointedDripstone.VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); + return getValues(VERTICAL_DIRECTION, org.bukkit.block.BlockFace.class); } @Override public org.bukkit.block.data.type.PointedDripstone.Thickness getThickness() { - return this.get(CraftPointedDripstone.THICKNESS, org.bukkit.block.data.type.PointedDripstone.Thickness.class); + return get(THICKNESS, org.bukkit.block.data.type.PointedDripstone.Thickness.class); } @Override public void setThickness(org.bukkit.block.data.type.PointedDripstone.Thickness thickness) { - this.set(CraftPointedDripstone.THICKNESS, thickness); + set(THICKNESS, thickness); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.PointedDripstoneBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.PointedDripstoneBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftPointedDripstone.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftPointedDripstone.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java index 0f182381..b74a7783 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java @@ -9,26 +9,26 @@ public CraftPortal() { super(); } - public CraftPortal(net.minecraft.world.level.block.state.BlockState state) { + public CraftPortal(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftOrientable - private static final net.minecraft.world.level.block.state.properties.EnumProperty AXIS = getEnum(net.minecraft.world.level.block.NetherPortalBlock.class, "axis"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum(net.minecraft.world.level.block.BlockPortal.class, "axis"); @Override public org.bukkit.Axis getAxis() { - return this.get(CraftPortal.AXIS, org.bukkit.Axis.class); + return get(AXIS, org.bukkit.Axis.class); } @Override public void setAxis(org.bukkit.Axis axis) { - this.set(CraftPortal.AXIS, axis); + set(AXIS, axis); } @Override public java.util.Set getAxes() { - return this.getValues(CraftPortal.AXIS, org.bukkit.Axis.class); + return getValues(AXIS, org.bukkit.Axis.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java index ee3faab6..7b43c937 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java @@ -9,26 +9,26 @@ public CraftPotatoes() { super(); } - public CraftPotatoes(net.minecraft.world.level.block.state.BlockState state) { + public CraftPotatoes(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.PotatoBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockPotatoes.class, "age"); @Override public int getAge() { - return this.get(CraftPotatoes.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftPotatoes.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftPotatoes.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java index a52e3dce..dd730323 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java @@ -9,54 +9,54 @@ public CraftPoweredRail() { super(); } - public CraftPoweredRail(net.minecraft.world.level.block.state.BlockState state) { + public CraftPoweredRail(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.PoweredRailBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockPoweredRail.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftPoweredRail.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftPoweredRail.POWERED, powered); + set(POWERED, powered); } // org.bukkit.craftbukkit.block.data.CraftRail - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum(net.minecraft.world.level.block.PoweredRailBlock.class, "shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum(net.minecraft.world.level.block.BlockPoweredRail.class, "shape"); @Override public org.bukkit.block.data.Rail.Shape getShape() { - return this.get(CraftPoweredRail.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return get(SHAPE, org.bukkit.block.data.Rail.Shape.class); } @Override public void setShape(org.bukkit.block.data.Rail.Shape shape) { - this.set(CraftPoweredRail.SHAPE, shape); + set(SHAPE, shape); } @Override public java.util.Set getShapes() { - return this.getValues(CraftPoweredRail.SHAPE, org.bukkit.block.data.Rail.Shape.class); + return getValues(SHAPE, org.bukkit.block.data.Rail.Shape.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.PoweredRailBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockPoweredRail.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftPoweredRail.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftPoweredRail.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java index 05c7662f..4239183d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java @@ -9,21 +9,21 @@ public CraftPressurePlateBinary() { super(); } - public CraftPressurePlateBinary(net.minecraft.world.level.block.state.BlockState state) { + public CraftPressurePlateBinary(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.PressurePlateBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockPressurePlateBinary.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftPressurePlateBinary.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftPressurePlateBinary.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java index 0eb4b7bd..4477c73f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java @@ -9,26 +9,26 @@ public CraftPressurePlateWeighted() { super(); } - public CraftPressurePlateWeighted(net.minecraft.world.level.block.state.BlockState state) { + public CraftPressurePlateWeighted(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger(net.minecraft.world.level.block.WeightedPressurePlateBlock.class, "power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger(net.minecraft.world.level.block.BlockPressurePlateWeighted.class, "power"); @Override public int getPower() { - return this.get(CraftPressurePlateWeighted.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftPressurePlateWeighted.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftPressurePlateWeighted.POWER); + return getMax(POWER); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java index ddd573ae..cf2822bd 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java @@ -9,26 +9,26 @@ public CraftPumpkinCarved() { super(); } - public CraftPumpkinCarved(net.minecraft.world.level.block.state.BlockState state) { + public CraftPumpkinCarved(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.CarvedPumpkinBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockPumpkinCarved.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftPumpkinCarved.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftPumpkinCarved.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftPumpkinCarved.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java index d3d68ae0..5d33c10b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java @@ -9,54 +9,54 @@ public CraftRedstoneComparator() { super(); } - public CraftRedstoneComparator(net.minecraft.world.level.block.state.BlockState state) { + public CraftRedstoneComparator(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftComparator - private static final net.minecraft.world.level.block.state.properties.EnumProperty MODE = getEnum(net.minecraft.world.level.block.ComparatorBlock.class, "mode"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum MODE = getEnum(net.minecraft.world.level.block.BlockRedstoneComparator.class, "mode"); @Override public org.bukkit.block.data.type.Comparator.Mode getMode() { - return this.get(CraftRedstoneComparator.MODE, org.bukkit.block.data.type.Comparator.Mode.class); + return get(MODE, org.bukkit.block.data.type.Comparator.Mode.class); } @Override public void setMode(org.bukkit.block.data.type.Comparator.Mode mode) { - this.set(CraftRedstoneComparator.MODE, mode); + set(MODE, mode); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.ComparatorBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockRedstoneComparator.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftRedstoneComparator.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftRedstoneComparator.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftRedstoneComparator.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.ComparatorBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockRedstoneComparator.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftRedstoneComparator.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftRedstoneComparator.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java index 99ea9327..ceb0ab3e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java @@ -9,21 +9,21 @@ public CraftRedstoneLamp() { super(); } - public CraftRedstoneLamp(net.minecraft.world.level.block.state.BlockState state) { + public CraftRedstoneLamp(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.RedstoneLampBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockRedstoneLamp.class, "lit"); @Override public boolean isLit() { - return this.get(CraftRedstoneLamp.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftRedstoneLamp.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java index 5069c1ba..11633149 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java @@ -9,21 +9,21 @@ public CraftRedstoneOre() { super(); } - public CraftRedstoneOre(net.minecraft.world.level.block.state.BlockState state) { + public CraftRedstoneOre(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.RedStoneOreBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockRedstoneOre.class, "lit"); @Override public boolean isLit() { - return this.get(CraftRedstoneOre.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftRedstoneOre.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java index 9ffd14f8..cc346ac0 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java @@ -9,21 +9,21 @@ public CraftRedstoneTorch() { super(); } - public CraftRedstoneTorch(net.minecraft.world.level.block.state.BlockState state) { + public CraftRedstoneTorch(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.RedstoneTorchBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockRedstoneTorch.class, "lit"); @Override public boolean isLit() { - return this.get(CraftRedstoneTorch.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftRedstoneTorch.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java index 4df24528..db64e31e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java @@ -9,40 +9,40 @@ public CraftRedstoneTorchWall() { super(); } - public CraftRedstoneTorchWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftRedstoneTorchWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.RedstoneWallTorchBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockRedstoneTorchWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftRedstoneTorchWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftRedstoneTorchWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftRedstoneTorchWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.RedstoneWallTorchBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockRedstoneTorchWall.class, "lit"); @Override public boolean isLit() { - return this.get(CraftRedstoneTorchWall.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftRedstoneTorchWall.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java index 009be1c9..e05ae0ef 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java @@ -9,28 +9,28 @@ public CraftRedstoneWire() { super(); } - public CraftRedstoneWire(net.minecraft.world.level.block.state.BlockState state) { + public CraftRedstoneWire(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftRedstoneWire - private static final net.minecraft.world.level.block.state.properties.EnumProperty NORTH = getEnum(net.minecraft.world.level.block.RedStoneWireBlock.class, "north"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty EAST = getEnum(net.minecraft.world.level.block.RedStoneWireBlock.class, "east"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty SOUTH = getEnum(net.minecraft.world.level.block.RedStoneWireBlock.class, "south"); - private static final net.minecraft.world.level.block.state.properties.EnumProperty WEST = getEnum(net.minecraft.world.level.block.RedStoneWireBlock.class, "west"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum NORTH = getEnum(net.minecraft.world.level.block.BlockRedstoneWire.class, "north"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum EAST = getEnum(net.minecraft.world.level.block.BlockRedstoneWire.class, "east"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SOUTH = getEnum(net.minecraft.world.level.block.BlockRedstoneWire.class, "south"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum WEST = getEnum(net.minecraft.world.level.block.BlockRedstoneWire.class, "west"); @Override public org.bukkit.block.data.type.RedstoneWire.Connection getFace(org.bukkit.block.BlockFace face) { switch (face) { case NORTH: - return this.get(CraftRedstoneWire.NORTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(NORTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); case EAST: - return this.get(CraftRedstoneWire.EAST, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(EAST, org.bukkit.block.data.type.RedstoneWire.Connection.class); case SOUTH: - return this.get(CraftRedstoneWire.SOUTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(SOUTH, org.bukkit.block.data.type.RedstoneWire.Connection.class); case WEST: - return this.get(CraftRedstoneWire.WEST, org.bukkit.block.data.type.RedstoneWire.Connection.class); + return get(WEST, org.bukkit.block.data.type.RedstoneWire.Connection.class); default: throw new IllegalArgumentException("Cannot have face " + face); } @@ -40,16 +40,16 @@ public org.bukkit.block.data.type.RedstoneWire.Connection getFace(org.bukkit.blo public void setFace(org.bukkit.block.BlockFace face, org.bukkit.block.data.type.RedstoneWire.Connection connection) { switch (face) { case NORTH: - this.set(CraftRedstoneWire.NORTH, connection); + set(NORTH, connection); break; case EAST: - this.set(CraftRedstoneWire.EAST, connection); + set(EAST, connection); break; case SOUTH: - this.set(CraftRedstoneWire.SOUTH, connection); + set(SOUTH, connection); break; case WEST: - this.set(CraftRedstoneWire.WEST, connection); + set(WEST, connection); break; default: throw new IllegalArgumentException("Cannot have face " + face); @@ -63,20 +63,20 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger(net.minecraft.world.level.block.RedStoneWireBlock.class, "power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger(net.minecraft.world.level.block.BlockRedstoneWire.class, "power"); @Override public int getPower() { - return this.get(CraftRedstoneWire.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftRedstoneWire.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftRedstoneWire.POWER); + return getMax(POWER); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java index 4d613c67..f3a8aca1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java @@ -9,26 +9,26 @@ public CraftReed() { super(); } - public CraftReed(net.minecraft.world.level.block.state.BlockState state) { + public CraftReed(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.SugarCaneBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockReed.class, "age"); @Override public int getAge() { - return this.get(CraftReed.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftReed.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftReed.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java index 5894cea1..85772e36 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java @@ -9,75 +9,75 @@ public CraftRepeater() { super(); } - public CraftRepeater(net.minecraft.world.level.block.state.BlockState state) { + public CraftRepeater(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftRepeater - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DELAY = getInteger(net.minecraft.world.level.block.RepeaterBlock.class, "delay"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LOCKED = getBoolean(net.minecraft.world.level.block.RepeaterBlock.class, "locked"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DELAY = getInteger(net.minecraft.world.level.block.BlockRepeater.class, "delay"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LOCKED = getBoolean(net.minecraft.world.level.block.BlockRepeater.class, "locked"); @Override public int getDelay() { - return this.get(CraftRepeater.DELAY); + return get(DELAY); } @Override public void setDelay(int delay) { - this.set(CraftRepeater.DELAY, delay); + set(DELAY, delay); } @Override public int getMinimumDelay() { - return getMin(CraftRepeater.DELAY); + return getMin(DELAY); } @Override public int getMaximumDelay() { - return getMax(CraftRepeater.DELAY); + return getMax(DELAY); } @Override public boolean isLocked() { - return this.get(CraftRepeater.LOCKED); + return get(LOCKED); } @Override public void setLocked(boolean locked) { - this.set(CraftRepeater.LOCKED, locked); + set(LOCKED, locked); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.RepeaterBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockRepeater.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftRepeater.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftRepeater.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftRepeater.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.RepeaterBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockRepeater.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftRepeater.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftRepeater.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRespawnAnchor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRespawnAnchor.java index 4ee32a25..316ea520 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRespawnAnchor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRespawnAnchor.java @@ -9,26 +9,26 @@ public CraftRespawnAnchor() { super(); } - public CraftRespawnAnchor(net.minecraft.world.level.block.state.BlockState state) { + public CraftRespawnAnchor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftRespawnAnchor - private static final net.minecraft.world.level.block.state.properties.IntegerProperty CHARGES = getInteger(net.minecraft.world.level.block.RespawnAnchorBlock.class, "charges"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger CHARGES = getInteger(net.minecraft.world.level.block.BlockRespawnAnchor.class, "charges"); @Override public int getCharges() { - return this.get(CraftRespawnAnchor.CHARGES); + return get(CHARGES); } @Override public void setCharges(int charges) { - this.set(CraftRespawnAnchor.CHARGES, charges); + set(CHARGES, charges); } @Override public int getMaximumCharges() { - return getMax(CraftRespawnAnchor.CHARGES); + return getMax(CHARGES); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java index 4f28a405..b14166e5 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java @@ -9,26 +9,26 @@ public CraftRotatable() { super(); } - public CraftRotatable(net.minecraft.world.level.block.state.BlockState state) { + public CraftRotatable(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftOrientable - private static final net.minecraft.world.level.block.state.properties.EnumProperty AXIS = getEnum(net.minecraft.world.level.block.RotatedPillarBlock.class, "axis"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum AXIS = getEnum(net.minecraft.world.level.block.BlockRotatable.class, "axis"); @Override public org.bukkit.Axis getAxis() { - return this.get(CraftRotatable.AXIS, org.bukkit.Axis.class); + return get(AXIS, org.bukkit.Axis.class); } @Override public void setAxis(org.bukkit.Axis axis) { - this.set(CraftRotatable.AXIS, axis); + set(AXIS, axis); } @Override public java.util.Set getAxes() { - return this.getValues(CraftRotatable.AXIS, org.bukkit.Axis.class); + return getValues(AXIS, org.bukkit.Axis.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java index 9ba586d5..b9a0b146 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java @@ -9,26 +9,26 @@ public CraftSapling() { super(); } - public CraftSapling(net.minecraft.world.level.block.state.BlockState state) { + public CraftSapling(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSapling - private static final net.minecraft.world.level.block.state.properties.IntegerProperty STAGE = getInteger(net.minecraft.world.level.block.SaplingBlock.class, "stage"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger STAGE = getInteger(net.minecraft.world.level.block.BlockSapling.class, "stage"); @Override public int getStage() { - return this.get(CraftSapling.STAGE); + return get(STAGE); } @Override public void setStage(int stage) { - this.set(CraftSapling.STAGE, stage); + set(STAGE, stage); } @Override public int getMaximumStage() { - return getMax(CraftSapling.STAGE); + return getMax(STAGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java index 4b4f6853..10c24424 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java @@ -9,51 +9,51 @@ public CraftScaffolding() { super(); } - public CraftScaffolding(net.minecraft.world.level.block.state.BlockState state) { + public CraftScaffolding(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftScaffolding - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BOTTOM = getBoolean(net.minecraft.world.level.block.ScaffoldingBlock.class, "bottom"); - private static final net.minecraft.world.level.block.state.properties.IntegerProperty DISTANCE = getInteger(net.minecraft.world.level.block.ScaffoldingBlock.class, "distance"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BOTTOM = getBoolean(net.minecraft.world.level.block.BlockScaffolding.class, "bottom"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger DISTANCE = getInteger(net.minecraft.world.level.block.BlockScaffolding.class, "distance"); @Override public boolean isBottom() { - return this.get(CraftScaffolding.BOTTOM); + return get(BOTTOM); } @Override public void setBottom(boolean bottom) { - this.set(CraftScaffolding.BOTTOM, bottom); + set(BOTTOM, bottom); } @Override public int getDistance() { - return this.get(CraftScaffolding.DISTANCE); + return get(DISTANCE); } @Override public void setDistance(int distance) { - this.set(CraftScaffolding.DISTANCE, distance); + set(DISTANCE, distance); } @Override public int getMaximumDistance() { - return getMax(CraftScaffolding.DISTANCE); + return getMax(DISTANCE); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.ScaffoldingBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockScaffolding.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftScaffolding.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftScaffolding.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkCatalyst.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkCatalyst.java index 653cb193..50465990 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkCatalyst.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkCatalyst.java @@ -9,21 +9,21 @@ public CraftSculkCatalyst() { super(); } - public CraftSculkCatalyst(net.minecraft.world.level.block.state.BlockState state) { + public CraftSculkCatalyst(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSculkCatalyst - private static final net.minecraft.world.level.block.state.properties.BooleanProperty BLOOM = getBoolean(net.minecraft.world.level.block.SculkCatalystBlock.class, "bloom"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean BLOOM = getBoolean(net.minecraft.world.level.block.SculkCatalystBlock.class, "bloom"); @Override public boolean isBloom() { - return this.get(CraftSculkCatalyst.BLOOM); + return get(BLOOM); } @Override public void setBloom(boolean bloom) { - this.set(CraftSculkCatalyst.BLOOM, bloom); + set(BLOOM, bloom); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkSensor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkSensor.java index 10eb0ac0..8ba6b02b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkSensor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkSensor.java @@ -9,54 +9,54 @@ public CraftSculkSensor() { super(); } - public CraftSculkSensor(net.minecraft.world.level.block.state.BlockState state) { + public CraftSculkSensor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSculkSensor - private static final net.minecraft.world.level.block.state.properties.EnumProperty PHASE = getEnum(net.minecraft.world.level.block.SculkSensorBlock.class, "sculk_sensor_phase"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum PHASE = getEnum(net.minecraft.world.level.block.SculkSensorBlock.class, "sculk_sensor_phase"); @Override public org.bukkit.block.data.type.SculkSensor.Phase getPhase() { - return this.get(CraftSculkSensor.PHASE, org.bukkit.block.data.type.SculkSensor.Phase.class); + return get(PHASE, org.bukkit.block.data.type.SculkSensor.Phase.class); } @Override public void setPhase(org.bukkit.block.data.type.SculkSensor.Phase phase) { - this.set(CraftSculkSensor.PHASE, phase); + set(PHASE, phase); } // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger(net.minecraft.world.level.block.SculkSensorBlock.class, "power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger(net.minecraft.world.level.block.SculkSensorBlock.class, "power"); @Override public int getPower() { - return this.get(CraftSculkSensor.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftSculkSensor.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftSculkSensor.POWER); + return getMax(POWER); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.SculkSensorBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.SculkSensorBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftSculkSensor.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftSculkSensor.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkShrieker.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkShrieker.java index 09916958..c53927df 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkShrieker.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkShrieker.java @@ -9,46 +9,46 @@ public CraftSculkShrieker() { super(); } - public CraftSculkShrieker(net.minecraft.world.level.block.state.BlockState state) { + public CraftSculkShrieker(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSculkShrieker - private static final net.minecraft.world.level.block.state.properties.BooleanProperty CAN_SUMMON = getBoolean(net.minecraft.world.level.block.SculkShriekerBlock.class, "can_summon"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty SHRIEKING = getBoolean(net.minecraft.world.level.block.SculkShriekerBlock.class, "shrieking"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean CAN_SUMMON = getBoolean(net.minecraft.world.level.block.SculkShriekerBlock.class, "can_summon"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean SHRIEKING = getBoolean(net.minecraft.world.level.block.SculkShriekerBlock.class, "shrieking"); @Override public boolean isCanSummon() { - return this.get(CraftSculkShrieker.CAN_SUMMON); + return get(CAN_SUMMON); } @Override public void setCanSummon(boolean can_summon) { - this.set(CraftSculkShrieker.CAN_SUMMON, can_summon); + set(CAN_SUMMON, can_summon); } @Override public boolean isShrieking() { - return this.get(CraftSculkShrieker.SHRIEKING); + return get(SHRIEKING); } @Override public void setShrieking(boolean shrieking) { - this.set(CraftSculkShrieker.SHRIEKING, shrieking); + set(SHRIEKING, shrieking); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.SculkShriekerBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.SculkShriekerBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftSculkShrieker.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftSculkShrieker.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkVein.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkVein.java index c753e940..fe3321bf 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkVein.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSculkVein.java @@ -9,40 +9,40 @@ public CraftSculkVein() { super(); } - public CraftSculkVein(net.minecraft.world.level.block.state.BlockState state) { + public CraftSculkVein(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftSculkVein.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftSculkVein.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftSculkVein.FACES.length; i++) { - if (CraftSculkVein.FACES[i] != null && this.get(CraftSculkVein.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftSculkVein.FACES.length; i++) { - if (CraftSculkVein.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -65,15 +65,15 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.SculkVeinBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftSculkVein.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftSculkVein.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java index 37d1b9c8..154e4bdd 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java @@ -9,45 +9,45 @@ public CraftSeaPickle() { super(); } - public CraftSeaPickle(net.minecraft.world.level.block.state.BlockState state) { + public CraftSeaPickle(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSeaPickle - private static final net.minecraft.world.level.block.state.properties.IntegerProperty PICKLES = getInteger(net.minecraft.world.level.block.SeaPickleBlock.class, "pickles"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger PICKLES = getInteger(net.minecraft.world.level.block.BlockSeaPickle.class, "pickles"); @Override public int getPickles() { - return this.get(CraftSeaPickle.PICKLES); + return get(PICKLES); } @Override public void setPickles(int pickles) { - this.set(CraftSeaPickle.PICKLES, pickles); + set(PICKLES, pickles); } @Override public int getMinimumPickles() { - return getMin(CraftSeaPickle.PICKLES); + return getMin(PICKLES); } @Override public int getMaximumPickles() { - return getMax(CraftSeaPickle.PICKLES); + return getMax(PICKLES); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.SeaPickleBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockSeaPickle.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftSeaPickle.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftSeaPickle.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java index 37b02535..2310a257 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java @@ -9,26 +9,26 @@ public CraftShulkerBox() { super(); } - public CraftShulkerBox(net.minecraft.world.level.block.state.BlockState state) { + public CraftShulkerBox(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.ShulkerBoxBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockShulkerBox.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftShulkerBox.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftShulkerBox.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftShulkerBox.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java index 66f7bbb0..c216b26c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java @@ -9,13 +9,13 @@ public CraftSkull() { super(); } - public CraftSkull(net.minecraft.world.level.block.state.BlockState state) { + public CraftSkull(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.SkullBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockSkull.class, "powered"); @Override public boolean isPowered() { @@ -29,11 +29,11 @@ public void setPowered(boolean powered) { // org.bukkit.craftbukkit.block.data.CraftRotatable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger(net.minecraft.world.level.block.SkullBlock.class, "rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger(net.minecraft.world.level.block.BlockSkull.class, "rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftSkull.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -127,6 +127,6 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftSkull.ROTATION, val); + set(ROTATION, val); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java index ceecf92f..42398dd6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java @@ -9,13 +9,13 @@ public CraftSkullPlayer() { super(); } - public CraftSkullPlayer(net.minecraft.world.level.block.state.BlockState state) { + public CraftSkullPlayer(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.PlayerHeadBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockSkullPlayer.class, "powered"); @Override public boolean isPowered() { @@ -29,11 +29,11 @@ public void setPowered(boolean powered) { // org.bukkit.craftbukkit.block.data.CraftRotatable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger(net.minecraft.world.level.block.PlayerHeadBlock.class, "rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger(net.minecraft.world.level.block.BlockSkullPlayer.class, "rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftSkullPlayer.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -127,6 +127,6 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftSkullPlayer.ROTATION, val); + set(ROTATION, val); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java index 9eefe6d6..9e8cc352 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java @@ -9,32 +9,32 @@ public CraftSkullPlayerWall() { super(); } - public CraftSkullPlayerWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftSkullPlayerWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.PlayerWallHeadBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockSkullPlayerWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftSkullPlayerWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftSkullPlayerWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftSkullPlayerWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.PlayerWallHeadBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockSkullPlayerWall.class, "powered"); @Override public boolean isPowered() { diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java index 198a01cb..60f038d6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java @@ -9,32 +9,32 @@ public CraftSkullWall() { super(); } - public CraftSkullWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftSkullWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WallSkullBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockSkullWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftSkullWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftSkullWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftSkullWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.WallSkullBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockSkullWall.class, "powered"); @Override public boolean isPowered() { diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmallDripleaf.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmallDripleaf.java index 34a41353..bcc5980f 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmallDripleaf.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmallDripleaf.java @@ -9,54 +9,54 @@ public CraftSmallDripleaf() { super(); } - public CraftSmallDripleaf(net.minecraft.world.level.block.state.BlockState state) { + public CraftSmallDripleaf(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.SmallDripleafBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.SmallDripleafBlock.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftSmallDripleaf.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftSmallDripleaf.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.SmallDripleafBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.SmallDripleafBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftSmallDripleaf.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftSmallDripleaf.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftSmallDripleaf.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.SmallDripleafBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.SmallDripleafBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftSmallDripleaf.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftSmallDripleaf.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java index 5eb2508d..5dd456a4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java @@ -9,40 +9,40 @@ public CraftSmoker() { super(); } - public CraftSmoker(net.minecraft.world.level.block.state.BlockState state) { + public CraftSmoker(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.SmokerBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockSmoker.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftSmoker.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftSmoker.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftSmoker.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.SmokerBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.BlockSmoker.class, "lit"); @Override public boolean isLit() { - return this.get(CraftSmoker.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftSmoker.LIT, lit); + set(LIT, lit); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnifferEgg.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnifferEgg.java index 35978b24..53957ea2 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnifferEgg.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnifferEgg.java @@ -9,26 +9,26 @@ public CraftSnifferEgg() { super(); } - public CraftSnifferEgg(net.minecraft.world.level.block.state.BlockState state) { + public CraftSnifferEgg(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftHatchable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty HATCH = getInteger(net.minecraft.world.level.block.SnifferEggBlock.class, "hatch"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger HATCH = getInteger(net.minecraft.world.level.block.SnifferEggBlock.class, "hatch"); @Override public int getHatch() { - return this.get(CraftSnifferEgg.HATCH); + return get(HATCH); } @Override public void setHatch(int hatch) { - this.set(CraftSnifferEgg.HATCH, hatch); + set(HATCH, hatch); } @Override public int getMaximumHatch() { - return getMax(CraftSnifferEgg.HATCH); + return getMax(HATCH); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java index ff340637..fd54c47c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java @@ -9,31 +9,31 @@ public CraftSnow() { super(); } - public CraftSnow(net.minecraft.world.level.block.state.BlockState state) { + public CraftSnow(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSnow - private static final net.minecraft.world.level.block.state.properties.IntegerProperty LAYERS = getInteger(net.minecraft.world.level.block.SnowLayerBlock.class, "layers"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger LAYERS = getInteger(net.minecraft.world.level.block.BlockSnow.class, "layers"); @Override public int getLayers() { - return this.get(CraftSnow.LAYERS); + return get(LAYERS); } @Override public void setLayers(int layers) { - this.set(CraftSnow.LAYERS, layers); + set(LAYERS, layers); } @Override public int getMinimumLayers() { - return getMin(CraftSnow.LAYERS); + return getMin(LAYERS); } @Override public int getMaximumLayers() { - return getMax(CraftSnow.LAYERS); + return getMax(LAYERS); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java index 56f701e9..9c0e6a32 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java @@ -9,26 +9,26 @@ public CraftSoil() { super(); } - public CraftSoil(net.minecraft.world.level.block.state.BlockState state) { + public CraftSoil(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftFarmland - private static final net.minecraft.world.level.block.state.properties.IntegerProperty MOISTURE = getInteger(net.minecraft.world.level.block.FarmBlock.class, "moisture"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger MOISTURE = getInteger(net.minecraft.world.level.block.BlockSoil.class, "moisture"); @Override public int getMoisture() { - return this.get(CraftSoil.MOISTURE); + return get(MOISTURE); } @Override public void setMoisture(int moisture) { - this.set(CraftSoil.MOISTURE, moisture); + set(MOISTURE, moisture); } @Override public int getMaximumMoisture() { - return getMax(CraftSoil.MOISTURE); + return getMax(MOISTURE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java index 91467410..983a2fcc 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java @@ -9,40 +9,40 @@ public CraftStainedGlassPane() { super(); } - public CraftStainedGlassPane(net.minecraft.world.level.block.state.BlockState state) { + public CraftStainedGlassPane(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftStainedGlassPane.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftStainedGlassPane.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftStainedGlassPane.FACES.length; i++) { - if (CraftStainedGlassPane.FACES[i] != null && this.get(CraftStainedGlassPane.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftStainedGlassPane.FACES.length; i++) { - if (CraftStainedGlassPane.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -65,15 +65,15 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.StainedGlassPaneBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockStainedGlassPane.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftStainedGlassPane.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftStainedGlassPane.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java index 4cec8254..603447b2 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java @@ -9,68 +9,68 @@ public CraftStairs() { super(); } - public CraftStairs(net.minecraft.world.level.block.state.BlockState state) { + public CraftStairs(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftStairs - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum(net.minecraft.world.level.block.StairBlock.class, "shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum(net.minecraft.world.level.block.BlockStairs.class, "shape"); @Override public org.bukkit.block.data.type.Stairs.Shape getShape() { - return this.get(CraftStairs.SHAPE, org.bukkit.block.data.type.Stairs.Shape.class); + return get(SHAPE, org.bukkit.block.data.type.Stairs.Shape.class); } @Override public void setShape(org.bukkit.block.data.type.Stairs.Shape shape) { - this.set(CraftStairs.SHAPE, shape); + set(SHAPE, shape); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.StairBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.BlockStairs.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftStairs.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftStairs.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.StairBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockStairs.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftStairs.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftStairs.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftStairs.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.StairBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockStairs.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftStairs.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftStairs.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java index e85eaca0..9c0e2a12 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java @@ -9,26 +9,26 @@ public CraftStem() { super(); } - public CraftStem(net.minecraft.world.level.block.state.BlockState state) { + public CraftStem(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.StemBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockStem.class, "age"); @Override public int getAge() { - return this.get(CraftStem.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftStem.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftStem.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java index 6da1ae7a..6297c45c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java @@ -9,26 +9,26 @@ public CraftStemAttached() { super(); } - public CraftStemAttached(net.minecraft.world.level.block.state.BlockState state) { + public CraftStemAttached(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.AttachedStemBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockStemAttached.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftStemAttached.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftStemAttached.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftStemAttached.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java index a0d01902..eeaae4fa 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java @@ -9,35 +9,35 @@ public CraftStepAbstract() { super(); } - public CraftStepAbstract(net.minecraft.world.level.block.state.BlockState state) { + public CraftStepAbstract(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSlab - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum(net.minecraft.world.level.block.SlabBlock.class, "type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum(net.minecraft.world.level.block.BlockStepAbstract.class, "type"); @Override public org.bukkit.block.data.type.Slab.Type getType() { - return this.get(CraftStepAbstract.TYPE, org.bukkit.block.data.type.Slab.Type.class); + return get(TYPE, org.bukkit.block.data.type.Slab.Type.class); } @Override public void setType(org.bukkit.block.data.type.Slab.Type type) { - this.set(CraftStepAbstract.TYPE, type); + set(TYPE, type); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.SlabBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockStepAbstract.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftStepAbstract.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftStepAbstract.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java index 40bc4754..5d3ab776 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java @@ -9,26 +9,26 @@ public CraftStonecutter() { super(); } - public CraftStonecutter(net.minecraft.world.level.block.state.BlockState state) { + public CraftStonecutter(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.StonecutterBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockStonecutter.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftStonecutter.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftStonecutter.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftStonecutter.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java index f505d440..297070b8 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java @@ -9,21 +9,21 @@ public CraftStructure() { super(); } - public CraftStructure(net.minecraft.world.level.block.state.BlockState state) { + public CraftStructure(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftStructureBlock - private static final net.minecraft.world.level.block.state.properties.EnumProperty MODE = getEnum(net.minecraft.world.level.block.StructureBlock.class, "mode"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum MODE = getEnum(net.minecraft.world.level.block.BlockStructure.class, "mode"); @Override public org.bukkit.block.data.type.StructureBlock.Mode getMode() { - return this.get(CraftStructure.MODE, org.bukkit.block.data.type.StructureBlock.Mode.class); + return get(MODE, org.bukkit.block.data.type.StructureBlock.Mode.class); } @Override public void setMode(org.bukkit.block.data.type.StructureBlock.Mode mode) { - this.set(CraftStructure.MODE, mode); + set(MODE, mode); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java index 9f135401..39e9375e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java @@ -9,26 +9,26 @@ public CraftSweetBerryBush() { super(); } - public CraftSweetBerryBush(net.minecraft.world.level.block.state.BlockState state) { + public CraftSweetBerryBush(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.SweetBerryBushBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockSweetBerryBush.class, "age"); @Override public int getAge() { - return this.get(CraftSweetBerryBush.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftSweetBerryBush.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftSweetBerryBush.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java index 75fc4fe9..4b08b54d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java @@ -9,21 +9,21 @@ public CraftTNT() { super(); } - public CraftTNT(net.minecraft.world.level.block.state.BlockState state) { + public CraftTNT(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftTNT - private static final net.minecraft.world.level.block.state.properties.BooleanProperty UNSTABLE = getBoolean(net.minecraft.world.level.block.TntBlock.class, "unstable"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean UNSTABLE = getBoolean(net.minecraft.world.level.block.BlockTNT.class, "unstable"); @Override public boolean isUnstable() { - return this.get(CraftTNT.UNSTABLE); + return get(UNSTABLE); } @Override public void setUnstable(boolean unstable) { - this.set(CraftTNT.UNSTABLE, unstable); + set(UNSTABLE, unstable); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java index 0bbe254b..8e753b21 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java @@ -9,21 +9,21 @@ public CraftTallPlant() { super(); } - public CraftTallPlant(net.minecraft.world.level.block.state.BlockState state) { + public CraftTallPlant(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.DoublePlantBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.BlockTallPlant.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftTallPlant.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftTallPlant.HALF, half); + set(HALF, half); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java index f13cdcd3..50490d27 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java @@ -9,21 +9,21 @@ public CraftTallPlantFlower() { super(); } - public CraftTallPlantFlower(net.minecraft.world.level.block.state.BlockState state) { + public CraftTallPlantFlower(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.TallFlowerBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.BlockTallPlantFlower.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftTallPlantFlower.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftTallPlantFlower.HALF, half); + set(HALF, half); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeagrass.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeagrass.java index a69b28f4..2cd6f552 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeagrass.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeagrass.java @@ -9,21 +9,21 @@ public CraftTallSeagrass() { super(); } - public CraftTallSeagrass(net.minecraft.world.level.block.state.BlockState state) { + public CraftTallSeagrass(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.TallSeagrassBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.TallSeagrassBlock.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftTallSeagrass.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftTallSeagrass.HALF, half); + set(HALF, half); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTarget.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTarget.java index baae9fea..f1c73016 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTarget.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTarget.java @@ -9,26 +9,26 @@ public CraftTarget() { super(); } - public CraftTarget(net.minecraft.world.level.block.state.BlockState state) { + public CraftTarget(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty POWER = getInteger(net.minecraft.world.level.block.TargetBlock.class, "power"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger POWER = getInteger(net.minecraft.world.level.block.BlockTarget.class, "power"); @Override public int getPower() { - return this.get(CraftTarget.POWER); + return get(POWER); } @Override public void setPower(int power) { - this.set(CraftTarget.POWER, power); + set(POWER, power); } @Override public int getMaximumPower() { - return getMax(CraftTarget.POWER); + return getMax(POWER); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java index 2d5eefab..fc307680 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java @@ -9,26 +9,26 @@ public CraftTorchWall() { super(); } - public CraftTorchWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftTorchWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WallTorchBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockTorchWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftTorchWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftTorchWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftTorchWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchflowerCrop.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchflowerCrop.java index 2a4ade35..8d8cd4f1 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchflowerCrop.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchflowerCrop.java @@ -9,26 +9,26 @@ public CraftTorchflowerCrop() { super(); } - public CraftTorchflowerCrop(net.minecraft.world.level.block.state.BlockState state) { + public CraftTorchflowerCrop(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.TorchflowerCropBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.TorchflowerCropBlock.class, "age"); @Override public int getAge() { - return this.get(CraftTorchflowerCrop.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftTorchflowerCrop.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftTorchflowerCrop.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java index 5e88ff74..c8c6ae2c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java @@ -9,82 +9,82 @@ public CraftTrapdoor() { super(); } - public CraftTrapdoor(net.minecraft.world.level.block.state.BlockState state) { + public CraftTrapdoor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.TrapDoorBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.BlockTrapdoor.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftTrapdoor.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftTrapdoor.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.TrapDoorBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockTrapdoor.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftTrapdoor.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftTrapdoor.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftTrapdoor.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftOpenable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean(net.minecraft.world.level.block.TrapDoorBlock.class, "open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean(net.minecraft.world.level.block.BlockTrapdoor.class, "open"); @Override public boolean isOpen() { - return this.get(CraftTrapdoor.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftTrapdoor.OPEN, open); + set(OPEN, open); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.TrapDoorBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockTrapdoor.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftTrapdoor.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftTrapdoor.POWERED, powered); + set(POWERED, powered); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.TrapDoorBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockTrapdoor.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftTrapdoor.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftTrapdoor.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrialSpawner.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrialSpawner.java index f510ff9c..298f7032 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrialSpawner.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrialSpawner.java @@ -9,32 +9,32 @@ public CraftTrialSpawner() { super(); } - public CraftTrialSpawner(net.minecraft.world.level.block.state.BlockState state) { + public CraftTrialSpawner(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftTrialSpawner - private static final net.minecraft.world.level.block.state.properties.EnumProperty TRIAL_SPAWNER_STATE = getEnum(net.minecraft.world.level.block.TrialSpawnerBlock.class, "trial_spawner_state"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OMINOUS = getBoolean(net.minecraft.world.level.block.TrialSpawnerBlock.class, "ominous"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TRIAL_SPAWNER_STATE = getEnum(net.minecraft.world.level.block.TrialSpawnerBlock.class, "trial_spawner_state"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OMINOUS = getBoolean(net.minecraft.world.level.block.TrialSpawnerBlock.class, "ominous"); @Override public org.bukkit.block.data.type.TrialSpawner.State getTrialSpawnerState() { - return this.get(CraftTrialSpawner.TRIAL_SPAWNER_STATE, org.bukkit.block.data.type.TrialSpawner.State.class); + return get(TRIAL_SPAWNER_STATE, org.bukkit.block.data.type.TrialSpawner.State.class); } @Override public void setTrialSpawnerState(org.bukkit.block.data.type.TrialSpawner.State state) { - this.set(CraftTrialSpawner.TRIAL_SPAWNER_STATE, state); + set(TRIAL_SPAWNER_STATE, state); } @Override public boolean isOminous() { - return this.get(CraftTrialSpawner.OMINOUS); + return get(OMINOUS); } @Override public void setOminous(boolean ominous) { - this.set(CraftTrialSpawner.OMINOUS, ominous); + set(OMINOUS, ominous); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java index 83375648..b8e01c7b 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java @@ -9,68 +9,68 @@ public CraftTripwire() { super(); } - public CraftTripwire(net.minecraft.world.level.block.state.BlockState state) { + public CraftTripwire(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftTripwire - private static final net.minecraft.world.level.block.state.properties.BooleanProperty DISARMED = getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "disarmed"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean DISARMED = getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "disarmed"); @Override public boolean isDisarmed() { - return this.get(CraftTripwire.DISARMED); + return get(DISARMED); } @Override public void setDisarmed(boolean disarmed) { - this.set(CraftTripwire.DISARMED, disarmed); + set(DISARMED, disarmed); } // org.bukkit.craftbukkit.block.data.CraftAttachable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty ATTACHED = getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "attached"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean ATTACHED = getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "attached"); @Override public boolean isAttached() { - return this.get(CraftTripwire.ATTACHED); + return get(ATTACHED); } @Override public void setAttached(boolean attached) { - this.set(CraftTripwire.ATTACHED, attached); + set(ATTACHED, attached); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftTripwire.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftTripwire.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftTripwire.FACES.length; i++) { - if (CraftTripwire.FACES[i] != null && this.get(CraftTripwire.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -82,8 +82,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftTripwire.FACES.length; i++) { - if (CraftTripwire.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -93,15 +93,15 @@ public java.util.Set getAllowedFaces() { // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.TripWireBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockTripwire.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftTripwire.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftTripwire.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java index e072799d..ccd34c0e 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java @@ -9,54 +9,54 @@ public CraftTripwireHook() { super(); } - public CraftTripwireHook(net.minecraft.world.level.block.state.BlockState state) { + public CraftTripwireHook(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAttachable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty ATTACHED = getBoolean(net.minecraft.world.level.block.TripWireHookBlock.class, "attached"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean ATTACHED = getBoolean(net.minecraft.world.level.block.BlockTripwireHook.class, "attached"); @Override public boolean isAttached() { - return this.get(CraftTripwireHook.ATTACHED); + return get(ATTACHED); } @Override public void setAttached(boolean attached) { - this.set(CraftTripwireHook.ATTACHED, attached); + set(ATTACHED, attached); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.TripWireHookBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockTripwireHook.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftTripwireHook.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftTripwireHook.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftTripwireHook.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.TripWireHookBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockTripwireHook.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftTripwireHook.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftTripwireHook.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java index e4fac5e1..99937123 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java @@ -9,50 +9,50 @@ public CraftTurtleEgg() { super(); } - public CraftTurtleEgg(net.minecraft.world.level.block.state.BlockState state) { + public CraftTurtleEgg(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftTurtleEgg - private static final net.minecraft.world.level.block.state.properties.IntegerProperty EGGS = getInteger(net.minecraft.world.level.block.TurtleEggBlock.class, "eggs"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger EGGS = getInteger(net.minecraft.world.level.block.BlockTurtleEgg.class, "eggs"); @Override public int getEggs() { - return this.get(CraftTurtleEgg.EGGS); + return get(EGGS); } @Override public void setEggs(int eggs) { - this.set(CraftTurtleEgg.EGGS, eggs); + set(EGGS, eggs); } @Override public int getMinimumEggs() { - return getMin(CraftTurtleEgg.EGGS); + return getMin(EGGS); } @Override public int getMaximumEggs() { - return getMax(CraftTurtleEgg.EGGS); + return getMax(EGGS); } // org.bukkit.craftbukkit.block.data.CraftHatchable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty HATCH = getInteger(net.minecraft.world.level.block.TurtleEggBlock.class, "hatch"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger HATCH = getInteger(net.minecraft.world.level.block.BlockTurtleEgg.class, "hatch"); @Override public int getHatch() { - return this.get(CraftTurtleEgg.HATCH); + return get(HATCH); } @Override public void setHatch(int hatch) { - this.set(CraftTurtleEgg.HATCH, hatch); + set(HATCH, hatch); } @Override public int getMaximumHatch() { - return getMax(CraftTurtleEgg.HATCH); + return getMax(HATCH); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTwistingVines.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTwistingVines.java index 116bb870..b3455ee4 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTwistingVines.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTwistingVines.java @@ -9,26 +9,26 @@ public CraftTwistingVines() { super(); } - public CraftTwistingVines(net.minecraft.world.level.block.state.BlockState state) { + public CraftTwistingVines(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.TwistingVinesBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockTwistingVines.class, "age"); @Override public int getAge() { - return this.get(CraftTwistingVines.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftTwistingVines.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftTwistingVines.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVault.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVault.java index 4c62caba..da8e9eb3 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVault.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVault.java @@ -9,51 +9,51 @@ public CraftVault() { super(); } - public CraftVault(net.minecraft.world.level.block.state.BlockState state) { + public CraftVault(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftVault - private static final net.minecraft.world.level.block.state.properties.EnumProperty VAULT_STATE = getEnum(net.minecraft.world.level.block.VaultBlock.class, "vault_state"); - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OMINOUS = getBoolean(net.minecraft.world.level.block.VaultBlock.class, "ominous"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum VAULT_STATE = getEnum(net.minecraft.world.level.block.VaultBlock.class, "vault_state"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OMINOUS = getBoolean(net.minecraft.world.level.block.VaultBlock.class, "ominous"); @Override public org.bukkit.block.data.type.Vault.State getTrialSpawnerState() { - return this.get(CraftVault.VAULT_STATE, org.bukkit.block.data.type.Vault.State.class); + return get(VAULT_STATE, org.bukkit.block.data.type.Vault.State.class); } @Override public void setTrialSpawnerState(org.bukkit.block.data.type.Vault.State state) { - this.set(CraftVault.VAULT_STATE, state); + set(VAULT_STATE, state); } @Override public boolean isOminous() { - return this.get(CraftVault.OMINOUS); + return get(OMINOUS); } @Override public void setOminous(boolean ominous) { - this.set(CraftVault.OMINOUS, ominous); + set(OMINOUS, ominous); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.VaultBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.VaultBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftVault.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftVault.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftVault.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java index d595dac1..f954ea54 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java @@ -9,40 +9,40 @@ public CraftVine() { super(); } - public CraftVine(net.minecraft.world.level.block.state.BlockState state) { + public CraftVine(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - private static final net.minecraft.world.level.block.state.properties.BooleanProperty[] FACES = new net.minecraft.world.level.block.state.properties.BooleanProperty[]{ - getBoolean(net.minecraft.world.level.block.VineBlock.class, "north", true), getBoolean(net.minecraft.world.level.block.VineBlock.class, "east", true), getBoolean(net.minecraft.world.level.block.VineBlock.class, "south", true), getBoolean(net.minecraft.world.level.block.VineBlock.class, "west", true), getBoolean(net.minecraft.world.level.block.VineBlock.class, "up", true), getBoolean(net.minecraft.world.level.block.VineBlock.class, "down", true) + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean[] FACES = new net.minecraft.world.level.block.state.properties.BlockStateBoolean[]{ + getBoolean(net.minecraft.world.level.block.BlockVine.class, "north", true), getBoolean(net.minecraft.world.level.block.BlockVine.class, "east", true), getBoolean(net.minecraft.world.level.block.BlockVine.class, "south", true), getBoolean(net.minecraft.world.level.block.BlockVine.class, "west", true), getBoolean(net.minecraft.world.level.block.BlockVine.class, "up", true), getBoolean(net.minecraft.world.level.block.BlockVine.class, "down", true) }; @Override public boolean hasFace(org.bukkit.block.BlockFace face) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftVine.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - return this.get(state); + return get(state); } @Override public void setFace(org.bukkit.block.BlockFace face, boolean has) { - net.minecraft.world.level.block.state.properties.BooleanProperty state = CraftVine.FACES[face.ordinal()]; + net.minecraft.world.level.block.state.properties.BlockStateBoolean state = FACES[face.ordinal()]; if (state == null) { throw new IllegalArgumentException("Non-allowed face " + face + ". Check MultipleFacing.getAllowedFaces."); } - this.set(state, has); + set(state, has); } @Override public java.util.Set getFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftVine.FACES.length; i++) { - if (CraftVine.FACES[i] != null && this.get(CraftVine.FACES[i])) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null && get(FACES[i])) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } @@ -54,8 +54,8 @@ public java.util.Set getFaces() { public java.util.Set getAllowedFaces() { com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - for (int i = 0; i < CraftVine.FACES.length; i++) { - if (CraftVine.FACES[i] != null) { + for (int i = 0; i < FACES.length; i++) { + if (FACES[i] != null) { faces.add(org.bukkit.block.BlockFace.values()[i]); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallHangingSign.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallHangingSign.java index 1f30973f..68b65d34 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallHangingSign.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallHangingSign.java @@ -9,40 +9,40 @@ public CraftWallHangingSign() { super(); } - public CraftWallHangingSign(net.minecraft.world.level.block.state.BlockState state) { + public CraftWallHangingSign(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WallHangingSignBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.WallHangingSignBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftWallHangingSign.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftWallHangingSign.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftWallHangingSign.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WallHangingSignBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.WallHangingSignBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWallHangingSign.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWallHangingSign.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java index 573d189b..e8f92efa 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java @@ -9,40 +9,40 @@ public CraftWallSign() { super(); } - public CraftWallSign(net.minecraft.world.level.block.state.BlockState state) { + public CraftWallSign(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WallSignBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockWallSign.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftWallSign.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftWallSign.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftWallSign.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WallSignBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.BlockWallSign.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWallSign.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWallSign.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWaterloggedTransparent.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWaterloggedTransparent.java index 4bde4b7b..ccb76421 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWaterloggedTransparent.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWaterloggedTransparent.java @@ -9,21 +9,21 @@ public CraftWaterloggedTransparent() { super(); } - public CraftWaterloggedTransparent(net.minecraft.world.level.block.state.BlockState state) { + public CraftWaterloggedTransparent(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WaterloggedTransparentBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.WaterloggedTransparentBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWaterloggedTransparent.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWaterloggedTransparent.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperBulb.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperBulb.java index bb4aa085..58b56323 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperBulb.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperBulb.java @@ -9,35 +9,35 @@ public CraftWeatheringCopperBulb() { super(); } - public CraftWeatheringCopperBulb(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeatheringCopperBulb(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftLightable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty LIT = getBoolean(net.minecraft.world.level.block.WeatheringCopperBulbBlock.class, "lit"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean LIT = getBoolean(net.minecraft.world.level.block.WeatheringCopperBulbBlock.class, "lit"); @Override public boolean isLit() { - return this.get(CraftWeatheringCopperBulb.LIT); + return get(LIT); } @Override public void setLit(boolean lit) { - this.set(CraftWeatheringCopperBulb.LIT, lit); + set(LIT, lit); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.WeatheringCopperBulbBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.WeatheringCopperBulbBlock.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftWeatheringCopperBulb.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftWeatheringCopperBulb.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperDoor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperDoor.java index 32371d49..792095fa 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperDoor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperDoor.java @@ -9,82 +9,82 @@ public CraftWeatheringCopperDoor() { super(); } - public CraftWeatheringCopperDoor(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeatheringCopperDoor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftDoor - private static final net.minecraft.world.level.block.state.properties.EnumProperty HINGE = getEnum(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "hinge"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HINGE = getEnum(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "hinge"); @Override public org.bukkit.block.data.type.Door.Hinge getHinge() { - return this.get(CraftWeatheringCopperDoor.HINGE, org.bukkit.block.data.type.Door.Hinge.class); + return get(HINGE, org.bukkit.block.data.type.Door.Hinge.class); } @Override public void setHinge(org.bukkit.block.data.type.Door.Hinge hinge) { - this.set(CraftWeatheringCopperDoor.HINGE, hinge); + set(HINGE, hinge); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftWeatheringCopperDoor.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftWeatheringCopperDoor.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftWeatheringCopperDoor.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftWeatheringCopperDoor.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftWeatheringCopperDoor.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftOpenable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "open"); @Override public boolean isOpen() { - return this.get(CraftWeatheringCopperDoor.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftWeatheringCopperDoor.OPEN, open); + set(OPEN, open); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.WeatheringCopperDoorBlock.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftWeatheringCopperDoor.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftWeatheringCopperDoor.POWERED, powered); + set(POWERED, powered); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperGrate.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperGrate.java index 8c695d8f..dd7d5523 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperGrate.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperGrate.java @@ -9,21 +9,21 @@ public CraftWeatheringCopperGrate() { super(); } - public CraftWeatheringCopperGrate(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeatheringCopperGrate(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperGrateBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperGrateBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWeatheringCopperGrate.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWeatheringCopperGrate.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperSlab.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperSlab.java index 61ba7ded..4b62dc64 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperSlab.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperSlab.java @@ -9,35 +9,35 @@ public CraftWeatheringCopperSlab() { super(); } - public CraftWeatheringCopperSlab(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeatheringCopperSlab(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftSlab - private static final net.minecraft.world.level.block.state.properties.EnumProperty TYPE = getEnum(net.minecraft.world.level.block.WeatheringCopperSlabBlock.class, "type"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum TYPE = getEnum(net.minecraft.world.level.block.WeatheringCopperSlabBlock.class, "type"); @Override public org.bukkit.block.data.type.Slab.Type getType() { - return this.get(CraftWeatheringCopperSlab.TYPE, org.bukkit.block.data.type.Slab.Type.class); + return get(TYPE, org.bukkit.block.data.type.Slab.Type.class); } @Override public void setType(org.bukkit.block.data.type.Slab.Type type) { - this.set(CraftWeatheringCopperSlab.TYPE, type); + set(TYPE, type); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperSlabBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperSlabBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWeatheringCopperSlab.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWeatheringCopperSlab.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperStair.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperStair.java index 1229a286..41f34f98 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperStair.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperStair.java @@ -9,68 +9,68 @@ public CraftWeatheringCopperStair() { super(); } - public CraftWeatheringCopperStair(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeatheringCopperStair(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.type.CraftStairs - private static final net.minecraft.world.level.block.state.properties.EnumProperty SHAPE = getEnum(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "shape"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum SHAPE = getEnum(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "shape"); @Override public org.bukkit.block.data.type.Stairs.Shape getShape() { - return this.get(CraftWeatheringCopperStair.SHAPE, org.bukkit.block.data.type.Stairs.Shape.class); + return get(SHAPE, org.bukkit.block.data.type.Stairs.Shape.class); } @Override public void setShape(org.bukkit.block.data.type.Stairs.Shape shape) { - this.set(CraftWeatheringCopperStair.SHAPE, shape); + set(SHAPE, shape); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftWeatheringCopperStair.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftWeatheringCopperStair.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftWeatheringCopperStair.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftWeatheringCopperStair.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftWeatheringCopperStair.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperStairBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWeatheringCopperStair.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWeatheringCopperStair.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperTrapDoor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperTrapDoor.java index c50a8f6b..e0ad47c6 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperTrapDoor.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeatheringCopperTrapDoor.java @@ -9,82 +9,82 @@ public CraftWeatheringCopperTrapDoor() { super(); } - public CraftWeatheringCopperTrapDoor(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeatheringCopperTrapDoor(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftBisected - private static final net.minecraft.world.level.block.state.properties.EnumProperty HALF = getEnum(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "half"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum HALF = getEnum(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "half"); @Override public org.bukkit.block.data.Bisected.Half getHalf() { - return this.get(CraftWeatheringCopperTrapDoor.HALF, org.bukkit.block.data.Bisected.Half.class); + return get(HALF, org.bukkit.block.data.Bisected.Half.class); } @Override public void setHalf(org.bukkit.block.data.Bisected.Half half) { - this.set(CraftWeatheringCopperTrapDoor.HALF, half); + set(HALF, half); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftWeatheringCopperTrapDoor.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftWeatheringCopperTrapDoor.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftWeatheringCopperTrapDoor.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftOpenable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty OPEN = getBoolean(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "open"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean OPEN = getBoolean(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "open"); @Override public boolean isOpen() { - return this.get(CraftWeatheringCopperTrapDoor.OPEN); + return get(OPEN); } @Override public void setOpen(boolean open) { - this.set(CraftWeatheringCopperTrapDoor.OPEN, open); + set(OPEN, open); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "powered"); @Override public boolean isPowered() { - return this.get(CraftWeatheringCopperTrapDoor.POWERED); + return get(POWERED); } @Override public void setPowered(boolean powered) { - this.set(CraftWeatheringCopperTrapDoor.POWERED, powered); + set(POWERED, powered); } // org.bukkit.craftbukkit.block.data.CraftWaterlogged - private static final net.minecraft.world.level.block.state.properties.BooleanProperty WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "waterlogged"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.world.level.block.WeatheringCopperTrapDoorBlock.class, "waterlogged"); @Override public boolean isWaterlogged() { - return this.get(CraftWeatheringCopperTrapDoor.WATERLOGGED); + return get(WATERLOGGED); } @Override public void setWaterlogged(boolean waterlogged) { - this.set(CraftWeatheringCopperTrapDoor.WATERLOGGED, waterlogged); + set(WATERLOGGED, waterlogged); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeepingVines.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeepingVines.java index 6a7202cb..f54f798c 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeepingVines.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWeepingVines.java @@ -9,26 +9,26 @@ public CraftWeepingVines() { super(); } - public CraftWeepingVines(net.minecraft.world.level.block.state.BlockState state) { + public CraftWeepingVines(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftAgeable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty AGE = getInteger(net.minecraft.world.level.block.WeepingVinesBlock.class, "age"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockWeepingVines.class, "age"); @Override public int getAge() { - return this.get(CraftWeepingVines.AGE); + return get(AGE); } @Override public void setAge(int age) { - this.set(CraftWeepingVines.AGE, age); + set(AGE, age); } @Override public int getMaximumAge() { - return getMax(CraftWeepingVines.AGE); + return getMax(AGE); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java index 1c3b5c10..f7dc11ee 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java @@ -9,13 +9,13 @@ public CraftWitherSkull() { super(); } - public CraftWitherSkull(net.minecraft.world.level.block.state.BlockState state) { + public CraftWitherSkull(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.WitherSkullBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockWitherSkull.class, "powered"); @Override public boolean isPowered() { @@ -29,11 +29,11 @@ public void setPowered(boolean powered) { // org.bukkit.craftbukkit.block.data.CraftRotatable - private static final net.minecraft.world.level.block.state.properties.IntegerProperty ROTATION = getInteger(net.minecraft.world.level.block.WitherSkullBlock.class, "rotation"); + private static final net.minecraft.world.level.block.state.properties.BlockStateInteger ROTATION = getInteger(net.minecraft.world.level.block.BlockWitherSkull.class, "rotation"); @Override public org.bukkit.block.BlockFace getRotation() { - int data = this.get(CraftWitherSkull.ROTATION); + int data = get(ROTATION); switch (data) { case 0x0: return org.bukkit.block.BlockFace.SOUTH; @@ -127,6 +127,6 @@ public void setRotation(org.bukkit.block.BlockFace rotation) { default: throw new IllegalArgumentException("Illegal rotation " + rotation); } - this.set(CraftWitherSkull.ROTATION, val); + set(ROTATION, val); } } diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java index 96d9c94e..72985806 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java +++ b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java @@ -9,32 +9,32 @@ public CraftWitherSkullWall() { super(); } - public CraftWitherSkullWall(net.minecraft.world.level.block.state.BlockState state) { + public CraftWitherSkullWall(net.minecraft.world.level.block.state.IBlockData state) { super(state); } // org.bukkit.craftbukkit.block.data.CraftDirectional - private static final net.minecraft.world.level.block.state.properties.EnumProperty FACING = getEnum(net.minecraft.world.level.block.WitherWallSkullBlock.class, "facing"); + private static final net.minecraft.world.level.block.state.properties.BlockStateEnum FACING = getEnum(net.minecraft.world.level.block.BlockWitherSkullWall.class, "facing"); @Override public org.bukkit.block.BlockFace getFacing() { - return this.get(CraftWitherSkullWall.FACING, org.bukkit.block.BlockFace.class); + return get(FACING, org.bukkit.block.BlockFace.class); } @Override public void setFacing(org.bukkit.block.BlockFace facing) { - this.set(CraftWitherSkullWall.FACING, facing); + set(FACING, facing); } @Override public java.util.Set getFaces() { - return this.getValues(CraftWitherSkullWall.FACING, org.bukkit.block.BlockFace.class); + return getValues(FACING, org.bukkit.block.BlockFace.class); } // org.bukkit.craftbukkit.block.data.CraftPowerable - private static final net.minecraft.world.level.block.state.properties.BooleanProperty POWERED = getBoolean(net.minecraft.world.level.block.WitherWallSkullBlock.class, "powered"); + private static final net.minecraft.world.level.block.state.properties.BlockStateBoolean POWERED = getBoolean(net.minecraft.world.level.block.BlockWitherSkullWall.class, "powered"); @Override public boolean isPowered() { diff --git a/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java b/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java index d4724c81..4a6d7a14 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java +++ b/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.block.sign; -import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.world.item.EnumColor; import net.minecraft.world.level.block.entity.SignText; import org.bukkit.DyeColor; import org.bukkit.block.sign.SignSide; @@ -23,60 +24,60 @@ public CraftSignSide(SignText signText) { @NotNull @Override public String[] getLines() { - if (this.lines == null) { + if (lines == null) { // Lazy initialization: - Component[] messages = this.signText.getMessages(false); - this.lines = new String[messages.length]; - System.arraycopy(CraftSign.revertComponents(messages), 0, this.lines, 0, this.lines.length); - this.originalLines = new String[this.lines.length]; - System.arraycopy(this.lines, 0, this.originalLines, 0, this.originalLines.length); + IChatBaseComponent[] messages = signText.getMessages(false); + lines = new String[messages.length]; + System.arraycopy(CraftSign.revertComponents(messages), 0, lines, 0, lines.length); + originalLines = new String[lines.length]; + System.arraycopy(lines, 0, originalLines, 0, originalLines.length); } - return this.lines; + return lines; } @NotNull @Override public String getLine(int index) throws IndexOutOfBoundsException { - return this.getLines()[index]; + return getLines()[index]; } @Override public void setLine(int index, @NotNull String line) throws IndexOutOfBoundsException { - this.getLines()[index] = line; + getLines()[index] = line; } @Override public boolean isGlowingText() { - return this.signText.hasGlowingText(); + return signText.hasGlowingText(); } @Override public void setGlowingText(boolean glowing) { - this.signText = this.signText.setHasGlowingText(glowing); + signText = signText.setHasGlowingText(glowing); } @Nullable @Override public DyeColor getColor() { - return DyeColor.getByWoolData((byte) this.signText.getColor().getId()); + return DyeColor.getByWoolData((byte) signText.getColor().getId()); } @Override public void setColor(@NotNull DyeColor color) { - this.signText = this.signText.setColor(net.minecraft.world.item.DyeColor.byId(color.getWoolData())); + signText = signText.setColor(EnumColor.byId(color.getWoolData())); } public SignText applyLegacyStringToSignSide() { - if (this.lines != null) { - for (int i = 0; i < this.lines.length; i++) { - String line = (this.lines[i] == null) ? "" : this.lines[i]; - if (line.equals(this.originalLines[i])) { + if (lines != null) { + for (int i = 0; i < lines.length; i++) { + String line = (lines[i] == null) ? "" : lines[i]; + if (line.equals(originalLines[i])) { continue; // The line contents are still the same, skip. } - this.signText = this.signText.setMessage(i, CraftChatMessage.fromString(line)[0]); + signText = signText.setMessage(i, CraftChatMessage.fromString(line)[0]); } } - return this.signText; + return signText; } } diff --git a/src/main/java/org/bukkit/craftbukkit/bootstrap/Main.java b/src/main/java/org/bukkit/craftbukkit/bootstrap/Main.java index 8a4f9504..02c6eb19 100644 --- a/src/main/java/org/bukkit/craftbukkit/bootstrap/Main.java +++ b/src/main/java/org/bukkit/craftbukkit/bootstrap/Main.java @@ -29,7 +29,7 @@ public static void main(String[] argv) { private void run(String[] argv) { try { - String defaultMainClassName = this.readResource("main-class", BufferedReader::readLine); + String defaultMainClassName = readResource("main-class", BufferedReader::readLine); String mainClassName = System.getProperty("bundlerMainClass", defaultMainClassName); String repoDir = System.getProperty("bundlerRepoDir", "bundler"); @@ -42,8 +42,8 @@ private void run(String[] argv) { boolean readOnly = Boolean.getBoolean("bundlerReadOnly"); List extractedUrls = new ArrayList<>(); - this.readAndExtractDir("versions", outputDir, extractedUrls, readOnly); - this.readAndExtractDir("libraries", outputDir, extractedUrls, readOnly); + readAndExtractDir("versions", outputDir, extractedUrls, readOnly); + readAndExtractDir("libraries", outputDir, extractedUrls, readOnly); if (mainClassName == null || mainClassName.isEmpty()) { System.out.println("Empty main class specified, exiting"); @@ -73,7 +73,7 @@ private void run(String[] argv) { private T readResource(String resource, ResourceParser parser) throws Exception { String fullPath = "/META-INF/" + resource; - try (InputStream is = this.getClass().getResourceAsStream(fullPath)) { + try (InputStream is = getClass().getResourceAsStream(fullPath)) { if (is == null) { throw new IllegalStateException("Resource " + fullPath + " not found"); } @@ -82,7 +82,7 @@ private T readResource(String resource, ResourceParser parser) throws Exc } private void readAndExtractDir(String subdir, Path outputDir, List extractedUrls, boolean readOnly) throws Exception { - List entries = this.readResource(subdir + ".list", reader -> reader.lines().map(FileEntry::parseLine).toList()); + List entries = readResource(subdir + ".list", reader -> reader.lines().map(FileEntry::parseLine).toList()); Path subdirPath = outputDir.resolve(subdir); for (FileEntry entry : entries) { if (entry.path.startsWith("minecraft-server")) { @@ -90,23 +90,23 @@ private void readAndExtractDir(String subdir, Path outputDir, List extracte } Path outputFile = subdirPath.resolve(entry.path); if (!readOnly) { - this.checkAndExtractJar(subdir, entry, outputFile); + checkAndExtractJar(subdir, entry, outputFile); } extractedUrls.add(outputFile.toUri().toURL()); } } private void checkAndExtractJar(String subdir, FileEntry entry, Path outputFile) throws Exception { - if (!Files.exists(outputFile) || !Main.checkIntegrity(outputFile, entry.hash())) { + if (!Files.exists(outputFile) || !checkIntegrity(outputFile, entry.hash())) { System.out.printf("Unpacking %s (%s:%s) to %s%n", entry.path, subdir, entry.id, outputFile); - this.extractJar(subdir, entry.path, outputFile); + extractJar(subdir, entry.path, outputFile); } } private void extractJar(String subdir, String jarPath, Path outputFile) throws IOException { Files.createDirectories(outputFile.getParent()); - try (InputStream input = this.getClass().getResourceAsStream("/META-INF/" + subdir + "/" + jarPath)) { + try (InputStream input = getClass().getResourceAsStream("/META-INF/" + subdir + "/" + jarPath)) { if (input == null) { throw new IllegalStateException("Declared library " + jarPath + " not found"); } @@ -121,7 +121,7 @@ private static boolean checkIntegrity(Path file, String expectedHash) throws Exc try (InputStream output = Files.newInputStream(file)) { output.transferTo(new DigestOutputStream(OutputStream.nullOutputStream(), digest)); - String actualHash = Main.byteToHex(digest.digest()); + String actualHash = byteToHex(digest.digest()); if (actualHash.equalsIgnoreCase(expectedHash)) { return true; } diff --git a/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java b/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java index a2e195f6..39870873 100644 --- a/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java +++ b/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java @@ -7,10 +7,10 @@ import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; -import net.minecraft.network.protocol.game.ClientboundBossEventPacket; -import net.minecraft.server.level.ServerBossEvent; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.BossEvent; +import net.minecraft.network.protocol.game.PacketPlayOutBoss; +import net.minecraft.server.level.BossBattleServer; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.BossBattle; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarFlag; import org.bukkit.boss.BarStyle; @@ -21,14 +21,14 @@ public class CraftBossBar implements BossBar { - private final ServerBossEvent handle; + private final BossBattleServer handle; private Map flags; public CraftBossBar(String title, BarColor color, BarStyle style, BarFlag... flags) { - this.handle = new ServerBossEvent( + handle = new BossBattleServer( CraftChatMessage.fromString(title, true)[0], - this.convertColor(color), - this.convertStyle(style) + convertColor(color), + convertStyle(style) ); this.initialize(); @@ -41,7 +41,7 @@ public CraftBossBar(String title, BarColor color, BarStyle style, BarFlag... fla this.setStyle(style); } - public CraftBossBar(ServerBossEvent bossBattleServer) { + public CraftBossBar(BossBattleServer bossBattleServer) { this.handle = bossBattleServer; this.initialize(); } @@ -53,33 +53,33 @@ private void initialize() { this.flags.put(BarFlag.CREATE_FOG, new FlagContainer(handle::shouldCreateWorldFog, handle::setCreateWorldFog)); } - private BarColor convertColor(BossEvent.BossBarColor color) { + private BarColor convertColor(BossBattle.BarColor color) { BarColor bukkitColor = BarColor.valueOf(color.name()); return (bukkitColor == null) ? BarColor.WHITE : bukkitColor; } - private BossEvent.BossBarColor convertColor(BarColor color) { - BossEvent.BossBarColor nmsColor = BossEvent.BossBarColor.valueOf(color.name()); - return (nmsColor == null) ? BossEvent.BossBarColor.WHITE : nmsColor; + private BossBattle.BarColor convertColor(BarColor color) { + BossBattle.BarColor nmsColor = BossBattle.BarColor.valueOf(color.name()); + return (nmsColor == null) ? BossBattle.BarColor.WHITE : nmsColor; } - private BossEvent.BossBarOverlay convertStyle(BarStyle style) { + private BossBattle.BarStyle convertStyle(BarStyle style) { switch (style) { default: case SOLID: - return BossEvent.BossBarOverlay.PROGRESS; + return BossBattle.BarStyle.PROGRESS; case SEGMENTED_6: - return BossEvent.BossBarOverlay.NOTCHED_6; + return BossBattle.BarStyle.NOTCHED_6; case SEGMENTED_10: - return BossEvent.BossBarOverlay.NOTCHED_10; + return BossBattle.BarStyle.NOTCHED_10; case SEGMENTED_12: - return BossEvent.BossBarOverlay.NOTCHED_12; + return BossBattle.BarStyle.NOTCHED_12; case SEGMENTED_20: - return BossEvent.BossBarOverlay.NOTCHED_20; + return BossBattle.BarStyle.NOTCHED_20; } } - private BarStyle convertStyle(BossEvent.BossBarOverlay style) { + private BarStyle convertStyle(BossBattle.BarStyle style) { switch (style) { default: case PROGRESS: @@ -97,40 +97,40 @@ private BarStyle convertStyle(BossEvent.BossBarOverlay style) { @Override public String getTitle() { - return CraftChatMessage.fromComponent(this.handle.name); + return CraftChatMessage.fromComponent(handle.name); } @Override public void setTitle(String title) { - this.handle.name = CraftChatMessage.fromString(title, true)[0]; - this.handle.broadcast(ClientboundBossEventPacket::createUpdateNamePacket); + handle.name = CraftChatMessage.fromString(title, true)[0]; + handle.broadcast(PacketPlayOutBoss::createUpdateNamePacket); } @Override public BarColor getColor() { - return this.convertColor(this.handle.color); + return convertColor(handle.color); } @Override public void setColor(BarColor color) { - this.handle.color = this.convertColor(color); - this.handle.broadcast(ClientboundBossEventPacket::createUpdateStylePacket); + handle.color = convertColor(color); + handle.broadcast(PacketPlayOutBoss::createUpdateStylePacket); } @Override public BarStyle getStyle() { - return this.convertStyle(this.handle.overlay); + return convertStyle(handle.overlay); } @Override public void setStyle(BarStyle style) { - this.handle.overlay = this.convertStyle(style); - this.handle.broadcast(ClientboundBossEventPacket::createUpdateStylePacket); + handle.overlay = convertStyle(style); + handle.broadcast(PacketPlayOutBoss::createUpdateStylePacket); } @Override public void addFlag(BarFlag flag) { - FlagContainer flagContainer = this.flags.get(flag); + FlagContainer flagContainer = flags.get(flag); if (flagContainer != null) { flagContainer.set.accept(true); } @@ -138,7 +138,7 @@ public void addFlag(BarFlag flag) { @Override public void removeFlag(BarFlag flag) { - FlagContainer flagContainer = this.flags.get(flag); + FlagContainer flagContainer = flags.get(flag); if (flagContainer != null) { flagContainer.set.accept(false); } @@ -146,7 +146,7 @@ public void removeFlag(BarFlag flag) { @Override public boolean hasFlag(BarFlag flag) { - FlagContainer flagContainer = this.flags.get(flag); + FlagContainer flagContainer = flags.get(flag); if (flagContainer != null) { return flagContainer.get.get(); } @@ -156,12 +156,12 @@ public boolean hasFlag(BarFlag flag) { @Override public void setProgress(double progress) { Preconditions.checkArgument(progress >= 0.0 && progress <= 1.0, "Progress must be between 0.0 and 1.0 (%s)", progress); - this.handle.setProgress((float) progress); + handle.setProgress((float) progress); } @Override public double getProgress() { - return this.handle.getProgress(); + return handle.getProgress(); } @Override @@ -169,20 +169,20 @@ public void addPlayer(Player player) { Preconditions.checkArgument(player != null, "player == null"); Preconditions.checkArgument(((CraftPlayer) player).getHandle().connection != null, "player is not fully connected (wait for PlayerJoinEvent)"); - this.handle.addPlayer(((CraftPlayer) player).getHandle()); + handle.addPlayer(((CraftPlayer) player).getHandle()); } @Override public void removePlayer(Player player) { Preconditions.checkArgument(player != null, "player == null"); - this.handle.removePlayer(((CraftPlayer) player).getHandle()); + handle.removePlayer(((CraftPlayer) player).getHandle()); } @Override public List getPlayers() { ImmutableList.Builder players = ImmutableList.builder(); - for (ServerPlayer p : this.handle.getPlayers()) { + for (EntityPlayer p : handle.getPlayers()) { players.add(p.getBukkitEntity()); } return players.build(); @@ -190,28 +190,28 @@ public List getPlayers() { @Override public void setVisible(boolean visible) { - this.handle.setVisible(visible); + handle.setVisible(visible); } @Override public boolean isVisible() { - return this.handle.visible; + return handle.visible; } @Override public void show() { - this.handle.setVisible(true); + handle.setVisible(true); } @Override public void hide() { - this.handle.setVisible(false); + handle.setVisible(false); } @Override public void removeAll() { - for (Player player : this.getPlayers()) { - this.removePlayer(player); + for (Player player : getPlayers()) { + removePlayer(player); } } @@ -226,7 +226,7 @@ private FlagContainer(Supplier get, Consumer set) { } } - public ServerBossEvent getHandle() { - return this.handle; + public BossBattleServer getHandle() { + return handle; } } diff --git a/src/main/java/org/bukkit/craftbukkit/boss/CraftDragonBattle.java b/src/main/java/org/bukkit/craftbukkit/boss/CraftDragonBattle.java index 4402511a..0506fc3f 100644 --- a/src/main/java/org/bukkit/craftbukkit/boss/CraftDragonBattle.java +++ b/src/main/java/org/bukkit/craftbukkit/boss/CraftDragonBattle.java @@ -6,9 +6,9 @@ import java.util.Collections; import java.util.stream.Collectors; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.block.state.pattern.BlockPattern; -import net.minecraft.world.level.dimension.end.DragonRespawnAnimation; -import net.minecraft.world.level.dimension.end.EndDragonFight; +import net.minecraft.world.level.block.state.pattern.ShapeDetector; +import net.minecraft.world.level.dimension.end.EnderDragonBattle; +import net.minecraft.world.level.dimension.end.EnumDragonRespawn; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.boss.BossBar; @@ -21,26 +21,26 @@ public class CraftDragonBattle implements DragonBattle { - private final EndDragonFight handle; + private final EnderDragonBattle handle; - public CraftDragonBattle(EndDragonFight handle) { + public CraftDragonBattle(EnderDragonBattle handle) { this.handle = handle; } @Override public EnderDragon getEnderDragon() { - Entity entity = this.handle.level.getEntity(this.handle.dragonUUID); + Entity entity = handle.level.getEntity(handle.dragonUUID); return (entity != null) ? (EnderDragon) entity.getBukkitEntity() : null; } @Override public BossBar getBossBar() { - return new CraftBossBar(this.handle.dragonEvent); + return new CraftBossBar(handle.dragonEvent); } @Override public Location getEndPortalLocation() { - if (this.handle.portalLocation == null) { + if (handle.portalLocation == null) { return null; } @@ -49,7 +49,7 @@ public Location getEndPortalLocation() { @Override public boolean generateEndPortal(boolean withPortals) { - if (this.handle.portalLocation != null || this.handle.findExitPortal() != null) { + if (handle.portalLocation != null || handle.findExitPortal() != null) { return false; } @@ -59,12 +59,12 @@ public boolean generateEndPortal(boolean withPortals) { @Override public boolean hasBeenPreviouslyKilled() { - return this.handle.hasPreviouslyKilledDragon(); + return handle.hasPreviouslyKilledDragon(); } @Override public void setPreviouslyKilled(boolean previouslyKilled) { - this.handle.previouslyKilled = previouslyKilled; + handle.previouslyKilled = previouslyKilled; } @Override @@ -74,10 +74,10 @@ public void initiateRespawn() { @Override public boolean initiateRespawn(Collection list) { - if (this.hasBeenPreviouslyKilled() && this.getRespawnPhase() == RespawnPhase.NONE) { + if (hasBeenPreviouslyKilled() && getRespawnPhase() == RespawnPhase.NONE) { // Copy from EnderDragonBattle#tryRespawn for generate exit portal if not exists if (this.handle.portalLocation == null) { - BlockPattern.BlockPatternMatch shapedetector_shapedetectorcollection = this.handle.findExitPortal(); + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = this.handle.findExitPortal(); if (shapedetector_shapedetectorcollection == null) { this.handle.spawnExitPortal(true); } @@ -90,29 +90,28 @@ public boolean initiateRespawn(Collection list) { } World world = enderCrystal.getWorld(); - return !((CraftWorld) world).getHandle().equals(this.handle.level); + return !((CraftWorld) world).getHandle().equals(handle.level); }); - this.handle.respawnDragon(list.stream().map(enderCrystal -> ((CraftEnderCrystal) enderCrystal).getHandle()).collect(Collectors.toList())); - return this.handle.respawnDragon; + return this.handle.respawnDragon(list.stream().map(enderCrystal -> ((CraftEnderCrystal) enderCrystal).getHandle()).collect(Collectors.toList())); } return false; } @Override public RespawnPhase getRespawnPhase() { - return this.toBukkitRespawnPhase(this.handle.respawnStage); + return toBukkitRespawnPhase(handle.respawnStage); } @Override public boolean setRespawnPhase(RespawnPhase phase) { Preconditions.checkArgument(phase != null && phase != RespawnPhase.NONE, "Invalid respawn phase provided: %s", phase); - if (this.handle.respawnStage == null) { + if (handle.respawnStage == null) { return false; } - this.handle.setRespawnStage(this.toNMSRespawnPhase(phase)); + this.handle.setRespawnStage(toNMSRespawnPhase(phase)); return true; } @@ -123,7 +122,7 @@ public void resetCrystals() { @Override public int hashCode() { - return this.handle.hashCode(); + return handle.hashCode(); } @Override @@ -131,11 +130,11 @@ public boolean equals(Object obj) { return obj instanceof CraftDragonBattle && ((CraftDragonBattle) obj).handle == this.handle; } - private RespawnPhase toBukkitRespawnPhase(DragonRespawnAnimation phase) { + private RespawnPhase toBukkitRespawnPhase(EnumDragonRespawn phase) { return (phase != null) ? RespawnPhase.values()[phase.ordinal()] : RespawnPhase.NONE; } - private DragonRespawnAnimation toNMSRespawnPhase(RespawnPhase phase) { - return (phase != RespawnPhase.NONE) ? DragonRespawnAnimation.values()[phase.ordinal()] : null; + private EnumDragonRespawn toNMSRespawnPhase(RespawnPhase phase) { + return (phase != RespawnPhase.NONE) ? EnumDragonRespawn.values()[phase.ordinal()] : null; } } diff --git a/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java b/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java index e380793e..cf4a9b15 100644 --- a/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java +++ b/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java @@ -1,23 +1,23 @@ package org.bukkit.craftbukkit.boss; -import net.minecraft.server.bossevents.CustomBossEvent; +import net.minecraft.server.bossevents.BossBattleCustom; import org.bukkit.NamespacedKey; import org.bukkit.boss.KeyedBossBar; import org.bukkit.craftbukkit.util.CraftNamespacedKey; public class CraftKeyedBossbar extends CraftBossBar implements KeyedBossBar { - public CraftKeyedBossbar(CustomBossEvent bossBattleCustom) { + public CraftKeyedBossbar(BossBattleCustom bossBattleCustom) { super(bossBattleCustom); } @Override public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(this.getHandle().getTextId()); + return CraftNamespacedKey.fromMinecraft(getHandle().getTextId()); } @Override - public CustomBossEvent getHandle() { - return (CustomBossEvent) super.getHandle(); + public BossBattleCustom getHandle() { + return (BossBattleCustom) super.getHandle(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java b/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java index 83d81b93..0c50cddd 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java +++ b/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java @@ -14,13 +14,13 @@ import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import java.util.logging.Level; -import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.CommandListenerWrapper; import org.bukkit.command.Command; import org.bukkit.command.CommandException; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.CraftServer; -public class BukkitCommandWrapper implements com.mojang.brigadier.Command, Predicate, SuggestionProvider { +public class BukkitCommandWrapper implements com.mojang.brigadier.Command, Predicate, SuggestionProvider { private final CraftServer server; private final Command command; @@ -30,34 +30,34 @@ public BukkitCommandWrapper(CraftServer server, Command command) { this.command = command; } - public LiteralCommandNode register(CommandDispatcher dispatcher, String label) { + public LiteralCommandNode register(CommandDispatcher dispatcher, String label) { return dispatcher.register( - LiteralArgumentBuilder.literal(label).requires(this).executes(this) - .then(RequiredArgumentBuilder.argument("args", StringArgumentType.greedyString()).suggests(this).executes(this)) + LiteralArgumentBuilder.literal(label).requires(this).executes(this) + .then(RequiredArgumentBuilder.argument("args", StringArgumentType.greedyString()).suggests(this).executes(this)) ); } @Override - public boolean test(CommandSourceStack wrapper) { - return this.command.testPermissionSilent(wrapper.getBukkitSender()); + public boolean test(CommandListenerWrapper wrapper) { + return command.testPermissionSilent(wrapper.getBukkitSender()); } @Override - public int run(CommandContext context) throws CommandSyntaxException { + public int run(CommandContext context) throws CommandSyntaxException { CommandSender sender = context.getSource().getBukkitSender(); try { - return this.server.dispatchCommand(sender, context.getInput()) ? 1 : 0; + return server.dispatchCommand(sender, context.getInput()) ? 1 : 0; } catch (CommandException ex) { sender.sendMessage(org.bukkit.ChatColor.RED + "An internal error occurred while attempting to perform this command"); - this.server.getLogger().log(Level.SEVERE, null, ex); + server.getLogger().log(Level.SEVERE, null, ex); return 0; } } @Override - public CompletableFuture getSuggestions(CommandContext context, SuggestionsBuilder builder) throws CommandSyntaxException { - List results = this.server.tabComplete(context.getSource().getBukkitSender(), builder.getInput(), context.getSource().getLevel(), context.getSource().getPosition(), true); + public CompletableFuture getSuggestions(CommandContext context, SuggestionsBuilder builder) throws CommandSyntaxException { + List results = server.tabComplete(context.getSource().getBukkitSender(), builder.getInput(), context.getSource().getLevel(), context.getSource().getPosition(), true); // Defaults to sub nodes, but we have just one giant args node, so offset accordingly builder = builder.createOffset(builder.getInput().lastIndexOf(' ') + 1); diff --git a/src/main/java/org/bukkit/craftbukkit/command/ColouredConsoleSender.java b/src/main/java/org/bukkit/craftbukkit/command/ColouredConsoleSender.java index bde7bb0b..4580642e 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/ColouredConsoleSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/ColouredConsoleSender.java @@ -6,8 +6,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import jline.Terminal; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.ConsoleCommandSender; @@ -16,51 +14,65 @@ import org.fusesource.jansi.Ansi.Attribute; public class ColouredConsoleSender extends CraftConsoleCommandSender { + private final Terminal terminal; private final Map replacements = new EnumMap(ChatColor.class); private final ChatColor[] colors = ChatColor.values(); private final boolean jansiPassthrough; private static final char ANSI_ESC_CHAR = '\u001B'; - private static final String RGB_STRING = String.valueOf(ColouredConsoleSender.ANSI_ESC_CHAR) + "[38;2;%d;%d;%dm"; + private static final String RGB_STRING = String.valueOf(ANSI_ESC_CHAR) + "[38;2;%d;%d;%dm"; private static final Pattern RBG_TRANSLATE = Pattern.compile(String.valueOf(ChatColor.COLOR_CHAR) + "x(" + String.valueOf(ChatColor.COLOR_CHAR) + "[A-F0-9]){6}", Pattern.CASE_INSENSITIVE); - private static final Logger LOGGER = LogManager.getLogger("Console"); protected ColouredConsoleSender() { super(); + this.terminal = ((CraftServer) getServer()).getReader().getTerminal(); this.jansiPassthrough = Boolean.getBoolean("jansi.passthrough"); - this.replacements.put(ChatColor.BLACK, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString()); - this.replacements.put(ChatColor.DARK_BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString()); - this.replacements.put(ChatColor.DARK_GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString()); - this.replacements.put(ChatColor.DARK_AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString()); - this.replacements.put(ChatColor.DARK_RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString()); - this.replacements.put(ChatColor.DARK_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString()); - this.replacements.put(ChatColor.GOLD, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString()); - this.replacements.put(ChatColor.GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString()); - this.replacements.put(ChatColor.DARK_GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString()); - this.replacements.put(ChatColor.BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString()); - this.replacements.put(ChatColor.GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString()); - this.replacements.put(ChatColor.AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString()); - this.replacements.put(ChatColor.RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).bold().toString()); - this.replacements.put(ChatColor.LIGHT_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString()); - this.replacements.put(ChatColor.YELLOW, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString()); - this.replacements.put(ChatColor.WHITE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString()); - this.replacements.put(ChatColor.MAGIC, Ansi.ansi().a(Attribute.BLINK_SLOW).toString()); - this.replacements.put(ChatColor.BOLD, Ansi.ansi().a(Attribute.UNDERLINE_DOUBLE).toString()); - this.replacements.put(ChatColor.STRIKETHROUGH, Ansi.ansi().a(Attribute.STRIKETHROUGH_ON).toString()); - this.replacements.put(ChatColor.UNDERLINE, Ansi.ansi().a(Attribute.UNDERLINE).toString()); - this.replacements.put(ChatColor.ITALIC, Ansi.ansi().a(Attribute.ITALIC).toString()); - this.replacements.put(ChatColor.RESET, Ansi.ansi().a(Attribute.RESET).toString()); + replacements.put(ChatColor.BLACK, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString()); + replacements.put(ChatColor.DARK_BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString()); + replacements.put(ChatColor.DARK_GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString()); + replacements.put(ChatColor.DARK_AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString()); + replacements.put(ChatColor.DARK_RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString()); + replacements.put(ChatColor.DARK_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString()); + replacements.put(ChatColor.GOLD, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString()); + replacements.put(ChatColor.GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString()); + replacements.put(ChatColor.DARK_GRAY, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString()); + replacements.put(ChatColor.BLUE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString()); + replacements.put(ChatColor.GREEN, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString()); + replacements.put(ChatColor.AQUA, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString()); + replacements.put(ChatColor.RED, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.RED).bold().toString()); + replacements.put(ChatColor.LIGHT_PURPLE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString()); + replacements.put(ChatColor.YELLOW, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString()); + replacements.put(ChatColor.WHITE, Ansi.ansi().a(Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString()); + replacements.put(ChatColor.MAGIC, Ansi.ansi().a(Attribute.BLINK_SLOW).toString()); + replacements.put(ChatColor.BOLD, Ansi.ansi().a(Attribute.UNDERLINE_DOUBLE).toString()); + replacements.put(ChatColor.STRIKETHROUGH, Ansi.ansi().a(Attribute.STRIKETHROUGH_ON).toString()); + replacements.put(ChatColor.UNDERLINE, Ansi.ansi().a(Attribute.UNDERLINE).toString()); + replacements.put(ChatColor.ITALIC, Ansi.ansi().a(Attribute.ITALIC).toString()); + replacements.put(ChatColor.RESET, Ansi.ansi().a(Attribute.RESET).toString()); } @Override public void sendMessage(String message) { - if (!this.conversationTracker.isConversingModaly()) { - LOGGER.info(convertRGBColors(message)); + // support jansi passthrough VM option when jansi doesn't detect an ANSI supported terminal + if (jansiPassthrough || terminal.isAnsiSupported()) { + if (!conversationTracker.isConversingModaly()) { + String result = convertRGBColors(message); + for (ChatColor color : colors) { + if (replacements.containsKey(color)) { + result = result.replaceAll("(?i)" + color.toString(), replacements.get(color)); + } else { + result = result.replaceAll("(?i)" + color.toString(), ""); + } + } + System.out.println(result + Ansi.ansi().reset().toString()); + } + } else { + super.sendMessage(message); } } private static String convertRGBColors(String input) { - Matcher matcher = ColouredConsoleSender.RBG_TRANSLATE.matcher(input); + Matcher matcher = RBG_TRANSLATE.matcher(input); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String s = matcher.group().replace("§", "").replace('x', '#'); @@ -68,7 +80,7 @@ private static String convertRGBColors(String input) { int red = color.getRed(); int blue = color.getBlue(); int green = color.getGreen(); - String replacement = String.format(ColouredConsoleSender.RGB_STRING, red, green, blue); + String replacement = String.format(RGB_STRING, red, green, blue); matcher.appendReplacement(buffer, replacement); } matcher.appendTail(buffer); diff --git a/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java b/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java index 0b4c6238..befcc19f 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java +++ b/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java @@ -21,10 +21,10 @@ public int complete(final String buffer, final int cursor, final List> waitable = new Waitable>() { @Override protected List evaluate() { - List offers = ConsoleCommandCompleter.this.server.getCommandMap().tabComplete(ConsoleCommandCompleter.this.server.getConsoleSender(), buffer); + List offers = server.getCommandMap().tabComplete(server.getConsoleSender(), buffer); - TabCompleteEvent tabEvent = new TabCompleteEvent(ConsoleCommandCompleter.this.server.getConsoleSender(), buffer, (offers == null) ? Collections.EMPTY_LIST : offers); - ConsoleCommandCompleter.this.server.getPluginManager().callEvent(tabEvent); + TabCompleteEvent tabEvent = new TabCompleteEvent(server.getConsoleSender(), buffer, (offers == null) ? Collections.EMPTY_LIST : offers); + server.getPluginManager().callEvent(tabEvent); return tabEvent.isCancelled() ? Collections.EMPTY_LIST : tabEvent.getCompletions(); } diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java index f2e8b63d..39d7ac62 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.command; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.network.chat.Component; -import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.commands.CommandListenerWrapper; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.world.level.block.entity.TileEntity; import org.bukkit.block.Block; import org.bukkit.command.BlockCommandSender; import org.bukkit.craftbukkit.block.CraftBlock; @@ -28,50 +28,50 @@ public void setOp(boolean value) { throw new UnsupportedOperationException("Cannot change operator status of a block"); } }); - private final CommandSourceStack block; - private final BlockEntity tile; + private final CommandListenerWrapper block; + private final TileEntity tile; - public CraftBlockCommandSender(CommandSourceStack commandBlockListenerAbstract, BlockEntity tile) { - super(CraftBlockCommandSender.SHARED_PERM); + public CraftBlockCommandSender(CommandListenerWrapper commandBlockListenerAbstract, TileEntity tile) { + super(SHARED_PERM); this.block = commandBlockListenerAbstract; this.tile = tile; } @Override public Block getBlock() { - return CraftBlock.at(this.tile.getLevel(), this.tile.getBlockPos()); + return CraftBlock.at(tile.getLevel(), tile.getBlockPos()); } @Override public void sendMessage(String message) { - for (Component component : CraftChatMessage.fromString(message)) { - this.block.source.sendSystemMessage(component); + for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { + block.source.sendSystemMessage(component); } } @Override public void sendMessage(String... messages) { for (String message : messages) { - this.sendMessage(message); + sendMessage(message); } } @Override public String getName() { - return this.block.getTextName(); + return block.getTextName(); } @Override public boolean isOp() { - return CraftBlockCommandSender.SHARED_PERM.isOp(); + return SHARED_PERM.isOp(); } @Override public void setOp(boolean value) { - CraftBlockCommandSender.SHARED_PERM.setOp(value); + SHARED_PERM.setOp(value); } - public CommandSourceStack getWrapper() { - return this.block; + public CommandListenerWrapper getWrapper() { + return block; } } diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java b/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java index 4b1ac1fe..2fd69c0f 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java +++ b/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java @@ -12,6 +12,6 @@ public CraftCommandMap(Server server) { } public Map getKnownCommands() { - return this.knownCommands; + return knownCommands; } } diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java index f3cb4102..f6f0aeec 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java @@ -21,7 +21,7 @@ protected CraftConsoleCommandSender() { @Override public void sendMessage(String message) { - this.sendRawMessage(message); + sendRawMessage(message); } @Override @@ -37,7 +37,7 @@ public void sendRawMessage(UUID sender, String message) { @Override public void sendMessage(String... messages) { for (String message : messages) { - this.sendMessage(message); + sendMessage(message); } } @@ -58,26 +58,26 @@ public void setOp(boolean value) { @Override public boolean beginConversation(Conversation conversation) { - return this.conversationTracker.beginConversation(conversation); + return conversationTracker.beginConversation(conversation); } @Override public void abandonConversation(Conversation conversation) { - this.conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); + conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); } @Override public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { - this.conversationTracker.abandonConversation(conversation, details); + conversationTracker.abandonConversation(conversation, details); } @Override public void acceptConversationInput(String input) { - this.conversationTracker.acceptConversationInput(input); + conversationTracker.acceptConversationInput(input); } @Override public boolean isConversing() { - return this.conversationTracker.isConversing(); + return conversationTracker.isConversing(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java index e3c7fa50..3d7381bb 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java @@ -1,36 +1,36 @@ package org.bukkit.craftbukkit.command; import java.net.SocketAddress; -import net.minecraft.network.chat.Component; -import net.minecraft.server.rcon.RconConsoleSource; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.server.rcon.RemoteControlCommandListener; import org.bukkit.command.RemoteConsoleCommandSender; public class CraftRemoteConsoleCommandSender extends ServerCommandSender implements RemoteConsoleCommandSender { - private final RconConsoleSource listener; + private final RemoteControlCommandListener listener; - public CraftRemoteConsoleCommandSender(RconConsoleSource listener) { + public CraftRemoteConsoleCommandSender(RemoteControlCommandListener listener) { this.listener = listener; } - public RconConsoleSource getListener() { - return this.listener; + public RemoteControlCommandListener getListener() { + return listener; } @Override public SocketAddress getAddress() { - return this.listener.socketAddress; + return listener.socketAddress; } @Override public void sendMessage(String message) { - this.listener.sendSystemMessage(Component.literal(message + "\n")); // Send a newline after each message, to preserve formatting. + listener.sendSystemMessage(IChatBaseComponent.literal(message + "\n")); // Send a newline after each message, to preserve formatting. } @Override public void sendMessage(String... messages) { for (String message : messages) { - this.sendMessage(message); + sendMessage(message); } } diff --git a/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java index 53d6950a..f9d3b5a4 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java @@ -2,7 +2,7 @@ import java.util.Set; import java.util.UUID; -import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.CommandListenerWrapper; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.ProxiedCommandSender; @@ -13,130 +13,123 @@ public class ProxiedNativeCommandSender implements ProxiedCommandSender { - private final CommandSourceStack orig; + private final CommandListenerWrapper orig; private final CommandSender caller; private final CommandSender callee; - public ProxiedNativeCommandSender(CommandSourceStack orig, CommandSender caller, CommandSender callee) { + public ProxiedNativeCommandSender(CommandListenerWrapper orig, CommandSender caller, CommandSender callee) { this.orig = orig; this.caller = caller; this.callee = callee; } - public CommandSourceStack getHandle() { - return this.orig; + public CommandListenerWrapper getHandle() { + return orig; } @Override public CommandSender getCaller() { - return this.caller; + return caller; } @Override public CommandSender getCallee() { - return this.callee; + return callee; } @Override public void sendMessage(String message) { - this.getCaller().sendMessage(message); + getCaller().sendMessage(message); } @Override public void sendMessage(String... messages) { - this.getCaller().sendMessage(messages); + getCaller().sendMessage(messages); } @Override public void sendMessage(UUID sender, String message) { - this.getCaller().sendMessage(sender, message); + getCaller().sendMessage(sender, message); } @Override public void sendMessage(UUID sender, String... messages) { - this.getCaller().sendMessage(sender, messages); + getCaller().sendMessage(sender, messages); } @Override public Server getServer() { - return this.getCallee().getServer(); + return getCallee().getServer(); } @Override public String getName() { - return this.getCallee().getName(); + return getCallee().getName(); } @Override public boolean isPermissionSet(String name) { - return this.getCaller().isPermissionSet(name); + return getCaller().isPermissionSet(name); } @Override public boolean isPermissionSet(Permission perm) { - return this.getCaller().isPermissionSet(perm); + return getCaller().isPermissionSet(perm); } @Override public boolean hasPermission(String name) { - return this.getCaller().hasPermission(name); + return getCaller().hasPermission(name); } @Override public boolean hasPermission(Permission perm) { - return this.getCaller().hasPermission(perm); + return getCaller().hasPermission(perm); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return this.getCaller().addAttachment(plugin, name, value); + return getCaller().addAttachment(plugin, name, value); } @Override public PermissionAttachment addAttachment(Plugin plugin) { - return this.getCaller().addAttachment(plugin); + return getCaller().addAttachment(plugin); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return this.getCaller().addAttachment(plugin, name, value, ticks); + return getCaller().addAttachment(plugin, name, value, ticks); } @Override public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return this.getCaller().addAttachment(plugin, ticks); + return getCaller().addAttachment(plugin, ticks); } @Override public void removeAttachment(PermissionAttachment attachment) { - this.getCaller().removeAttachment(attachment); + getCaller().removeAttachment(attachment); } @Override public void recalculatePermissions() { - this.getCaller().recalculatePermissions(); + getCaller().recalculatePermissions(); } @Override public Set getEffectivePermissions() { - return this.getCaller().getEffectivePermissions(); + return getCaller().getEffectivePermissions(); } @Override public boolean isOp() { - return this.getCaller().isOp(); + return getCaller().isOp(); } @Override public void setOp(boolean value) { - this.getCaller().setOp(value); + getCaller().setOp(value); } - // Spigot start - @Override - public org.bukkit.command.CommandSender.Spigot spigot() - { - return this.getCaller().spigot(); - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java index 1e82312c..be10d200 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java @@ -24,7 +24,7 @@ protected ServerCommandSender(PermissibleBase perm) { @Override public boolean isPermissionSet(String name) { - return this.perm.isPermissionSet(name); + return perm.isPermissionSet(name); } @Override @@ -34,7 +34,7 @@ public boolean isPermissionSet(Permission perm) { @Override public boolean hasPermission(String name) { - return this.perm.hasPermission(name); + return perm.hasPermission(name); } @Override @@ -44,37 +44,37 @@ public boolean hasPermission(Permission perm) { @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return this.perm.addAttachment(plugin, name, value); + return perm.addAttachment(plugin, name, value); } @Override public PermissionAttachment addAttachment(Plugin plugin) { - return this.perm.addAttachment(plugin); + return perm.addAttachment(plugin); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return this.perm.addAttachment(plugin, name, value, ticks); + return perm.addAttachment(plugin, name, value, ticks); } @Override public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return this.perm.addAttachment(plugin, ticks); + return perm.addAttachment(plugin, ticks); } @Override public void removeAttachment(PermissionAttachment attachment) { - this.perm.removeAttachment(attachment); + perm.removeAttachment(attachment); } @Override public void recalculatePermissions() { - this.perm.recalculatePermissions(); + perm.recalculatePermissions(); } @Override public Set getEffectivePermissions() { - return this.perm.getEffectivePermissions(); + return perm.getEffectivePermissions(); } public boolean isPlayer() { @@ -95,39 +95,4 @@ public void sendMessage(UUID uuid, String message) { public void sendMessage(UUID uuid, String... messages) { this.sendMessage(messages); // ServerCommandSenders have no use for senders } - - // Spigot start - private final org.bukkit.command.CommandSender.Spigot spigot = new org.bukkit.command.CommandSender.Spigot() - { - @Override - public void sendMessage(net.md_5.bungee.api.chat.BaseComponent component) - { - ServerCommandSender.this.sendMessage(net.md_5.bungee.api.chat.TextComponent.toLegacyText(component)); - } - - @Override - public void sendMessage(net.md_5.bungee.api.chat.BaseComponent... components) - { - ServerCommandSender.this.sendMessage(net.md_5.bungee.api.chat.TextComponent.toLegacyText(components)); - } - - @Override - public void sendMessage(UUID sender, net.md_5.bungee.api.chat.BaseComponent... components) - { - this.sendMessage(components); - } - - @Override - public void sendMessage(UUID sender, net.md_5.bungee.api.chat.BaseComponent component) - { - this.sendMessage(component); - } - }; - - @Override - public org.bukkit.command.CommandSender.Spigot spigot() - { - return this.spigot; - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java b/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java index 5e6645e1..6b2ddc33 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java +++ b/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java @@ -7,9 +7,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.world.entity.vehicle.MinecartCommandBlock; +import net.minecraft.commands.CommandDispatcher; +import net.minecraft.commands.CommandListenerWrapper; +import net.minecraft.server.level.WorldServer; +import net.minecraft.world.entity.vehicle.EntityMinecartCommandBlock; import org.bukkit.Location; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; @@ -20,27 +21,26 @@ import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.entity.CraftEntity; import org.bukkit.craftbukkit.entity.CraftMinecartCommand; -import org.bukkit.entity.Entity; import org.bukkit.entity.minecart.CommandMinecart; public final class VanillaCommandWrapper extends BukkitCommand { - private final Commands dispatcher; - public final CommandNode vanillaCommand; + private final CommandDispatcher dispatcher; + public final CommandNode vanillaCommand; - public VanillaCommandWrapper(Commands dispatcher, CommandNode vanillaCommand) { + public VanillaCommandWrapper(CommandDispatcher dispatcher, CommandNode vanillaCommand) { super(vanillaCommand.getName(), "A Mojang provided command.", vanillaCommand.getUsageText(), Collections.EMPTY_LIST); this.dispatcher = dispatcher; this.vanillaCommand = vanillaCommand; - this.setPermission(VanillaCommandWrapper.getPermission(vanillaCommand)); + this.setPermission(getPermission(vanillaCommand)); } @Override public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!this.testPermission(sender)) return true; + if (!testPermission(sender)) return true; - CommandSourceStack icommandlistener = VanillaCommandWrapper.getListener(sender); - this.dispatcher.performPrefixedCommand(icommandlistener, this.toDispatcher(args, this.getName()), this.toDispatcher(args, commandLabel)); + CommandListenerWrapper icommandlistener = getListener(sender); + dispatcher.performPrefixedCommand(icommandlistener, toDispatcher(args, getName()), toDispatcher(args, commandLabel)); return true; } @@ -50,24 +50,24 @@ public List tabComplete(CommandSender sender, String alias, String[] arg Preconditions.checkArgument(args != null, "Arguments cannot be null"); Preconditions.checkArgument(alias != null, "Alias cannot be null"); - CommandSourceStack icommandlistener = VanillaCommandWrapper.getListener(sender); - ParseResults parsed = this.dispatcher.getDispatcher().parse(this.toDispatcher(args, this.getName()), icommandlistener); + CommandListenerWrapper icommandlistener = getListener(sender); + ParseResults parsed = dispatcher.getDispatcher().parse(toDispatcher(args, getName()), icommandlistener); List results = new ArrayList<>(); - this.dispatcher.getDispatcher().getCompletionSuggestions(parsed).thenAccept((suggestions) -> { + dispatcher.getDispatcher().getCompletionSuggestions(parsed).thenAccept((suggestions) -> { suggestions.getList().forEach((s) -> results.add(s.getText())); }); return results; } - public static CommandSourceStack getListener(CommandSender sender) { - if (sender instanceof Entity) { + public static CommandListenerWrapper getListener(CommandSender sender) { + if (sender instanceof CraftEntity entity) { if (sender instanceof CommandMinecart) { - return ((MinecartCommandBlock) ((CraftMinecartCommand) sender).getHandle()).getCommandBlock().createCommandSourceStack(); + return ((EntityMinecartCommandBlock) ((CraftMinecartCommand) sender).getHandle()).getCommandBlock().createCommandSourceStack(); } - return ((CraftEntity) sender).getHandle().createCommandSourceStack(); + return entity.getHandle().createCommandSourceStackForNameResolution((WorldServer) entity.getHandle().level()); } if (sender instanceof BlockCommandSender) { return ((CraftBlockCommandSender) sender).getWrapper(); @@ -85,7 +85,7 @@ public static CommandSourceStack getListener(CommandSender sender) { throw new IllegalArgumentException("Cannot make " + sender + " a vanilla command listener"); } - public static String getPermission(CommandNode vanillaCommand) { + public static String getPermission(CommandNode vanillaCommand) { return "minecraft.command." + ((vanillaCommand.getRedirect() == null) ? vanillaCommand.getName() : vanillaCommand.getRedirect().getName()); } diff --git a/src/main/java/org/bukkit/craftbukkit/configuration/ConfigSerializationUtil.java b/src/main/java/org/bukkit/craftbukkit/configuration/ConfigSerializationUtil.java index 4bf58b0b..6548814b 100644 --- a/src/main/java/org/bukkit/craftbukkit/configuration/ConfigSerializationUtil.java +++ b/src/main/java/org/bukkit/craftbukkit/configuration/ConfigSerializationUtil.java @@ -11,7 +11,7 @@ public final class ConfigSerializationUtil { public static String getString(Map map, String key, boolean nullable) { - return ConfigSerializationUtil.getObject(String.class, map, key, nullable); + return getObject(String.class, map, key, nullable); } public static UUID getUuid(Map map, String key, boolean nullable) { diff --git a/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java b/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java index 335939ac..72127dde 100644 --- a/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java +++ b/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java @@ -14,9 +14,9 @@ public class ConversationTracker { private LinkedList conversationQueue = new LinkedList(); public synchronized boolean beginConversation(Conversation conversation) { - if (!this.conversationQueue.contains(conversation)) { - this.conversationQueue.addLast(conversation); - if (this.conversationQueue.getFirst() == conversation) { + if (!conversationQueue.contains(conversation)) { + conversationQueue.addLast(conversation); + if (conversationQueue.getFirst() == conversation) { conversation.begin(); conversation.outputNextPrompt(); return true; @@ -26,23 +26,23 @@ public synchronized boolean beginConversation(Conversation conversation) { } public synchronized void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { - if (!this.conversationQueue.isEmpty()) { - if (this.conversationQueue.getFirst() == conversation) { + if (!conversationQueue.isEmpty()) { + if (conversationQueue.getFirst() == conversation) { conversation.abandon(details); } - if (this.conversationQueue.contains(conversation)) { - this.conversationQueue.remove(conversation); + if (conversationQueue.contains(conversation)) { + conversationQueue.remove(conversation); } - if (!this.conversationQueue.isEmpty()) { - this.conversationQueue.getFirst().outputNextPrompt(); + if (!conversationQueue.isEmpty()) { + conversationQueue.getFirst().outputNextPrompt(); } } } public synchronized void abandonAllConversations() { - LinkedList oldQueue = this.conversationQueue; - this.conversationQueue = new LinkedList(); + LinkedList oldQueue = conversationQueue; + conversationQueue = new LinkedList(); for (Conversation conversation : oldQueue) { try { conversation.abandon(new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); @@ -53,8 +53,8 @@ public synchronized void abandonAllConversations() { } public synchronized void acceptConversationInput(String input) { - if (this.isConversing()) { - Conversation conversation = this.conversationQueue.getFirst(); + if (isConversing()) { + Conversation conversation = conversationQueue.getFirst(); try { conversation.acceptInput(input); } catch (Throwable t) { @@ -67,10 +67,10 @@ public synchronized void acceptConversationInput(String input) { } public synchronized boolean isConversing() { - return !this.conversationQueue.isEmpty(); + return !conversationQueue.isEmpty(); } public synchronized boolean isConversingModaly() { - return this.isConversing() && this.conversationQueue.getFirst().isModal(); + return isConversing() && conversationQueue.getFirst().isModal(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageEffect.java b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageEffect.java index e472a61c..1f1474bb 100644 --- a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageEffect.java +++ b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageEffect.java @@ -25,7 +25,7 @@ public Sound getSound() { public static DamageEffect getById(String id) { for (DamageEffects damageEffects : DamageEffects.values()) { if (damageEffects.getSerializedName().equalsIgnoreCase(id)) { - return CraftDamageEffect.toBukkit(damageEffects); + return toBukkit(damageEffects); } } return null; diff --git a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSource.java b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSource.java index 3d31bb0e..907f95dd 100644 --- a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSource.java +++ b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSource.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.damage; import java.util.Objects; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.Vec3D; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; @@ -26,7 +26,7 @@ public net.minecraft.world.damagesource.DamageSource getHandle() { } public World getCausingEntityWorld() { - org.bukkit.entity.Entity causingEntity = this.getCausingEntity(); + org.bukkit.entity.Entity causingEntity = getCausingEntity(); return causingEntity != null ? causingEntity.getWorld() : null; } @@ -41,7 +41,7 @@ public DamageType getDamageType() { @Override public org.bukkit.entity.Entity getCausingEntity() { - net.minecraft.world.entity.Entity entity = this.getHandle().getEntity(); + net.minecraft.world.entity.Entity entity = this.getHandle().getCausingDamager(); return (entity != null) ? entity.getBukkitEntity() : null; } @@ -53,13 +53,13 @@ public org.bukkit.entity.Entity getDirectEntity() { @Override public Location getDamageLocation() { - Vec3 vec3D = this.getHandle().sourcePositionRaw(); + Vec3D vec3D = this.getHandle().sourcePositionRaw(); return (vec3D != null) ? CraftLocation.toBukkit(vec3D, this.getCausingEntityWorld()) : null; } @Override public Location getSourceLocation() { - Vec3 vec3D = this.getHandle().getSourcePosition(); + Vec3D vec3D = this.getHandle().getSourcePosition(); return (vec3D != null) ? CraftLocation.toBukkit(vec3D, this.getCausingEntityWorld()) : null; } @@ -121,7 +121,7 @@ public static DamageSource buildFromBukkit(DamageType damageType, Entity causing nmsDirectEntity = craftDirectEntity.getHandle(); } - Vec3 vec3D = (damageLocation == null) ? null : CraftLocation.toVec3D(damageLocation); + Vec3D vec3D = (damageLocation == null) ? null : CraftLocation.toVec3D(damageLocation); return new CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(holderDamageType, nmsDirectEntity, nmsCausingEntity, vec3D)); } diff --git a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSourceBuilder.java b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSourceBuilder.java index 4c6e1553..c9b12caa 100644 --- a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSourceBuilder.java +++ b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageSourceBuilder.java @@ -41,6 +41,6 @@ public DamageSource.Builder withDamageLocation(Location location) { @Override public DamageSource build() { - return CraftDamageSource.buildFromBukkit(this.damageType, this.causingEntity, this.directEntity, this.damageLocation); + return CraftDamageSource.buildFromBukkit(damageType, causingEntity, directEntity, damageLocation); } } diff --git a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageType.java b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageType.java index d4864124..9ec7b6c9 100644 --- a/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageType.java +++ b/src/main/java/org/bukkit/craftbukkit/damage/CraftDamageType.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -34,7 +35,7 @@ public String getTranslationKey() { @Override public DamageScaling getDamageScaling() { - return CraftDamageType.damageScalingToBukkit(this.getHandle().scaling()); + return damageScalingToBukkit(this.getHandle().scaling()); } @Override @@ -44,7 +45,7 @@ public DamageEffect getDamageEffect() { @Override public DeathMessageType getDeathMessageType() { - return CraftDamageType.deathMessageTypeToBukkit(this.getHandle().deathMessageType()); + return deathMessageTypeToBukkit(this.getHandle().deathMessageType()); } @Override @@ -99,15 +100,15 @@ public static net.minecraft.world.damagesource.DamageScaling damageScalingToNMS( } public static DamageType minecraftHolderToBukkit(Holder minecraftHolder) { - return CraftDamageType.minecraftToBukkit(minecraftHolder.value()); + return minecraftToBukkit(minecraftHolder.value()); } public static Holder bukkitToMinecraftHolder(DamageType bukkitDamageType) { Preconditions.checkArgument(bukkitDamageType != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.DAMAGE_TYPE); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.DAMAGE_TYPE); - if (registry.wrapAsHolder(CraftDamageType.bukkitToMinecraft(bukkitDamageType)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkitDamageType)) instanceof Holder.c holder) { return holder; } diff --git a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java index f63cf317..a8d96dfd 100644 --- a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java +++ b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java @@ -2,7 +2,7 @@ import com.google.common.base.Preconditions; import java.util.Locale; -import net.minecraft.Util; +import net.minecraft.SystemUtils; import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.tags.EnchantmentTags; @@ -25,7 +25,7 @@ public static Enchantment minecraftToBukkit(net.minecraft.world.item.enchantment } public static Enchantment minecraftHolderToBukkit(Holder minecraft) { - return CraftEnchantment.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static net.minecraft.world.item.enchantment.Enchantment bukkitToMinecraft(Enchantment bukkit) { @@ -65,22 +65,22 @@ public CraftEnchantment(NamespacedKey key, net.minecraft.world.item.enchantment. @Override public net.minecraft.world.item.enchantment.Enchantment getHandle() { - return this.handle.value(); + return handle.value(); } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public int getMaxLevel() { - return this.getHandle().getMaxLevel(); + return getHandle().getMaxLevel(); } @Override public int getStartLevel() { - return this.getHandle().getMinLevel(); + return getHandle().getMinLevel(); } @Override @@ -100,7 +100,7 @@ public boolean isCursed() { @Override public boolean canEnchantItem(ItemStack item) { - return this.getHandle().canEnchant(CraftItemStack.asNMSCopy(item)); + return getHandle().canEnchant(CraftItemStack.asNMSCopy(item)); } @Override @@ -148,7 +148,7 @@ public boolean conflictsWith(Enchantment other) { @Override public String getTranslationKey() { - return Util.makeDescriptionId("enchantment", handle.unwrapKey().get().location()); + return SystemUtils.makeDescriptionId("enchantment", handle.unwrapKey().get().location()); } @Override @@ -161,16 +161,16 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((Enchantment) other).getKey()); + return getKey().equals(((Enchantment) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } @Override public String toString() { - return "CraftEnchantment[" + this.getKey() + "]"; + return "CraftEnchantment[" + getKey() + "]"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractArrow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractArrow.java index 72b16428..6e2fc6cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractArrow.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractArrow.java @@ -2,6 +2,8 @@ import com.google.common.base.Preconditions; import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.projectile.EntityArrow; +import net.minecraft.world.item.Items; import org.bukkit.block.Block; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; @@ -12,7 +14,7 @@ public class CraftAbstractArrow extends AbstractProjectile implements AbstractArrow { - public CraftAbstractArrow(CraftServer server, net.minecraft.world.entity.projectile.AbstractArrow entity) { + public CraftAbstractArrow(CraftServer server, EntityArrow entity) { super(server, entity); } @@ -27,76 +29,76 @@ public int getKnockbackStrength() { @Override public double getDamage() { - return this.getHandle().getBaseDamage(); + return getHandle().getBaseDamage(); } @Override public void setDamage(double damage) { Preconditions.checkArgument(damage >= 0, "Damage value (%s) must be positive", damage); - this.getHandle().setBaseDamage(damage); + getHandle().setBaseDamage(damage); } @Override public int getPierceLevel() { - return this.getHandle().getPierceLevel(); + return getHandle().getPierceLevel(); } @Override public void setPierceLevel(int pierceLevel) { Preconditions.checkArgument(0 <= pierceLevel && pierceLevel <= Byte.MAX_VALUE, "Pierce level (%s) out of range, expected 0 < level < 127", pierceLevel); - this.getHandle().setPierceLevel((byte) pierceLevel); + getHandle().setPierceLevel((byte) pierceLevel); } @Override public boolean isCritical() { - return this.getHandle().isCritArrow(); + return getHandle().isCritArrow(); } @Override public void setCritical(boolean critical) { - this.getHandle().setCritArrow(critical); + getHandle().setCritArrow(critical); } @Override public ProjectileSource getShooter() { - return this.getHandle().projectileSource; + return getHandle().projectileSource; } @Override public void setShooter(ProjectileSource shooter) { if (shooter instanceof Entity) { - this.getHandle().setOwner(((CraftEntity) shooter).getHandle()); + getHandle().setOwner(((CraftEntity) shooter).getHandle()); } else { - this.getHandle().setOwner(null); + getHandle().setOwner(null); } - this.getHandle().projectileSource = shooter; + getHandle().projectileSource = shooter; } @Override public boolean isInBlock() { - return this.getHandle().inGround; + return getHandle().isInGround(); } @Override public Block getAttachedBlock() { - if (!this.isInBlock()) { + if (!isInBlock()) { return null; } - BlockPos pos = this.getHandle().blockPosition(); - return this.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); + BlockPos pos = getHandle().blockPosition(); + return getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); } @Override public PickupStatus getPickupStatus() { - return PickupStatus.values()[this.getHandle().pickup.ordinal()]; + return PickupStatus.values()[getHandle().pickup.ordinal()]; } @Override public void setPickupStatus(PickupStatus status) { Preconditions.checkArgument(status != null, "PickupStatus cannot be null"); - this.getHandle().pickup = net.minecraft.world.entity.projectile.AbstractArrow.Pickup.byOrdinal(status.ordinal()); + getHandle().pickup = EntityArrow.PickupStatus.byOrdinal(status.ordinal()); } @Override @@ -104,12 +106,14 @@ public void setTicksLived(int value) { super.setTicksLived(value); // Second field for EntityArrow - this.getHandle().life = value; + getHandle().life = value; } @Override public boolean isShotFromCrossbow() { - return this.getHandle().shotFromCrossbow(); + net.minecraft.world.item.ItemStack firedFromWeapon = getHandle().getWeaponItem(); + + return firedFromWeapon != null && firedFromWeapon.is(Items.CROSSBOW); } @Override @@ -118,14 +122,14 @@ public void setShotFromCrossbow(boolean shotFromCrossbow) { @Override public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getHandle().pickupItemStack); + return CraftItemStack.asBukkitCopy(getHandle().pickupItemStack); } @Override public void setItem(ItemStack item) { Preconditions.checkArgument(item != null, "ItemStack cannot be null"); - this.getHandle().pickupItemStack = CraftItemStack.asNMSCopy(item); + getHandle().pickupItemStack = CraftItemStack.asNMSCopy(item); } @Override @@ -141,8 +145,8 @@ public void setWeapon(ItemStack item) { } @Override - public net.minecraft.world.entity.projectile.AbstractArrow getHandle() { - return (net.minecraft.world.entity.projectile.AbstractArrow) this.entity; + public EntityArrow getHandle() { + return (EntityArrow) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java index 3b7a3559..830e84f3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java @@ -2,7 +2,8 @@ import com.google.common.base.Preconditions; import java.util.UUID; -import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.attributes.GenericAttributes; +import net.minecraft.world.entity.animal.horse.EntityHorseAbstract; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventoryAbstractHorse; import org.bukkit.entity.AbstractHorse; @@ -12,13 +13,13 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements AbstractHorse { - public CraftAbstractHorse(CraftServer server, net.minecraft.world.entity.animal.horse.AbstractHorse entity) { + public CraftAbstractHorse(CraftServer server, EntityHorseAbstract entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.horse.AbstractHorse getHandle() { - return (net.minecraft.world.entity.animal.horse.AbstractHorse) this.entity; + public EntityHorseAbstract getHandle() { + return (EntityHorseAbstract) entity; } @Override @@ -28,85 +29,85 @@ public void setVariant(Horse.Variant variant) { @Override public int getDomestication() { - return this.getHandle().getTemper(); + return getHandle().getTemper(); } @Override public void setDomestication(int value) { Preconditions.checkArgument(value >= 0 && value <= this.getMaxDomestication(), "Domestication level (%s) need to be between %s and %s (max domestication)", value, 0, this.getMaxDomestication()); - this.getHandle().setTemper(value); + getHandle().setTemper(value); } @Override public int getMaxDomestication() { - return this.getHandle().getMaxTemper(); + return getHandle().getMaxTemper(); } @Override public void setMaxDomestication(int value) { Preconditions.checkArgument(value > 0, "Max domestication (%s) cannot be zero or less", value); - this.getHandle().maxDomestication = value; + getHandle().maxDomestication = value; } @Override public double getJumpStrength() { - return this.getHandle().getAttributeValue(Attributes.JUMP_STRENGTH); + return getHandle().getAttributeValue(GenericAttributes.JUMP_STRENGTH); } @Override public void setJumpStrength(double strength) { Preconditions.checkArgument(strength >= 0, "Jump strength (%s) cannot be less than zero", strength); - this.getHandle().getAttribute(Attributes.JUMP_STRENGTH).setBaseValue(strength); + getHandle().getAttribute(GenericAttributes.JUMP_STRENGTH).setBaseValue(strength); } @Override public boolean isTamed() { - return this.getHandle().isTamed(); + return getHandle().isTamed(); } @Override public void setTamed(boolean tamed) { - this.getHandle().setTamed(tamed); + getHandle().setTamed(tamed); } @Override public AnimalTamer getOwner() { - if (this.getOwnerUUID() == null) return null; - return this.getServer().getOfflinePlayer(this.getOwnerUUID()); + if (getOwnerUUID() == null) return null; + return getServer().getOfflinePlayer(getOwnerUUID()); } @Override public void setOwner(AnimalTamer owner) { if (owner != null) { - this.setTamed(true); - this.getHandle().setTarget(null, null, false); - this.setOwnerUUID(owner.getUniqueId()); + setTamed(true); + getHandle().setTarget(null, null, false); + setOwnerUUID(owner.getUniqueId()); } else { - this.setTamed(false); - this.setOwnerUUID(null); + setTamed(false); + setOwnerUUID(null); } } public UUID getOwnerUUID() { - return this.getHandle().getOwnerUUID(); + return getHandle().getOwnerUUID(); } public void setOwnerUUID(UUID uuid) { - this.getHandle().setOwnerUUID(uuid); + getHandle().setOwnerUUID(uuid); } @Override public boolean isEatingHaystack() { - return this.getHandle().isEating(); + return getHandle().isEating(); } @Override public void setEatingHaystack(boolean eatingHaystack) { - this.getHandle().setEating(eatingHaystack); + getHandle().setEating(eatingHaystack); } @Override public AbstractHorseInventory getInventory() { - return new CraftInventoryAbstractHorse(this.getHandle().inventory); + return new CraftInventoryAbstractHorse(getHandle().inventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractSkeleton.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractSkeleton.java index db6ad6ee..650556fd 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractSkeleton.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractSkeleton.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntitySkeletonAbstract; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.AbstractSkeleton; import org.bukkit.entity.Skeleton; public abstract class CraftAbstractSkeleton extends CraftMonster implements AbstractSkeleton { - public CraftAbstractSkeleton(CraftServer server, net.minecraft.world.entity.monster.AbstractSkeleton entity) { + public CraftAbstractSkeleton(CraftServer server, EntitySkeletonAbstract entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java index 6893e97b..7d721335 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java @@ -1,6 +1,8 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.npc.Villager; +import net.minecraft.world.entity.npc.EntityVillager; +import net.minecraft.world.entity.npc.EntityVillagerAbstract; +import net.minecraft.world.item.trading.IMerchant; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.craftbukkit.inventory.CraftMerchant; @@ -10,16 +12,17 @@ public class CraftAbstractVillager extends CraftAgeable implements CraftMerchant, AbstractVillager, InventoryHolder { - public CraftAbstractVillager(CraftServer server, net.minecraft.world.entity.npc.AbstractVillager entity) { + public CraftAbstractVillager(CraftServer server, EntityVillagerAbstract entity) { super(server, entity); } @Override - public net.minecraft.world.entity.npc.AbstractVillager getHandle() { - return (Villager) this.entity; + public EntityVillagerAbstract getHandle() { + return (EntityVillager) entity; } - public net.minecraft.world.item.trading.Merchant getMerchant() { + @Override + public IMerchant getMerchant() { return getHandle(); } @@ -30,6 +33,6 @@ public String toString() { @Override public Inventory getInventory() { - return new CraftInventory(this.getHandle().getInventory()); + return new CraftInventory(getHandle().getInventory()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java index ae16e8d1..e8f57ccb 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java @@ -1,71 +1,71 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.AgeableMob; +import net.minecraft.world.entity.EntityAgeable; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Ageable; public class CraftAgeable extends CraftCreature implements Ageable { - public CraftAgeable(CraftServer server, AgeableMob entity) { + public CraftAgeable(CraftServer server, EntityAgeable entity) { super(server, entity); } @Override public int getAge() { - return this.getHandle().getAge(); + return getHandle().getAge(); } @Override public void setAge(int age) { - this.getHandle().setAge(age); + getHandle().setAge(age); } @Override public void setAgeLock(boolean lock) { - this.getHandle().ageLocked = lock; + getHandle().ageLocked = lock; } @Override public boolean getAgeLock() { - return this.getHandle().ageLocked; + return getHandle().ageLocked; } @Override public void setBaby() { - if (this.isAdult()) { - this.setAge(-24000); + if (isAdult()) { + setAge(-24000); } } @Override public void setAdult() { - if (!this.isAdult()) { - this.setAge(0); + if (!isAdult()) { + setAge(0); } } @Override public boolean isAdult() { - return this.getAge() >= 0; + return getAge() >= 0; } @Override public boolean canBreed() { - return this.getAge() == 0; + return getAge() == 0; } @Override public void setBreed(boolean breed) { if (breed) { - this.setAge(0); - } else if (this.isAdult()) { - this.setAge(6000); + setAge(0); + } else if (isAdult()) { + setAge(6000); } } @Override - public AgeableMob getHandle() { - return (AgeableMob) this.entity; + public EntityAgeable getHandle() { + return (EntityAgeable) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAllay.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAllay.java index 765a2f73..d085b1eb 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAllay.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAllay.java @@ -18,7 +18,7 @@ public CraftAllay(CraftServer server, Allay entity) { @Override public Allay getHandle() { - return (Allay) this.entity; + return (Allay) entity; } @Override @@ -28,67 +28,67 @@ public String toString() { @Override public Inventory getInventory() { - return new CraftInventory(this.getHandle().getInventory()); + return new CraftInventory(getHandle().getInventory()); } @Override public boolean canDuplicate() { - return this.getHandle().canDuplicate(); + return getHandle().canDuplicate(); } @Override public void setCanDuplicate(boolean canDuplicate) { - this.getHandle().setCanDuplicate(canDuplicate); + getHandle().setCanDuplicate(canDuplicate); } @Override public long getDuplicationCooldown() { - return this.getHandle().duplicationCooldown; + return getHandle().duplicationCooldown; } @Override public void setDuplicationCooldown(long l) { - this.getHandle().duplicationCooldown = l; + getHandle().duplicationCooldown = l; } @Override public void resetDuplicationCooldown() { - this.getHandle().resetDuplicationCooldown(); + getHandle().resetDuplicationCooldown(); } @Override public boolean isDancing() { - return this.getHandle().isDancing(); + return getHandle().isDancing(); } @Override public void startDancing(Location location) { Preconditions.checkArgument(location != null, "Location cannot be null"); Preconditions.checkArgument(location.getBlock().getType().equals(Material.JUKEBOX), "The Block in the Location need to be a JukeBox"); - this.getHandle().setJukeboxPlaying(CraftLocation.toBlockPosition(location), true); + getHandle().setJukeboxPlaying(CraftLocation.toBlockPos(location), true); } @Override public void startDancing() { - this.getHandle().forceDancing = true; - this.getHandle().setDancing(true); + getHandle().forceDancing = true; + getHandle().setDancing(true); } @Override public void stopDancing() { - this.getHandle().forceDancing = false; - this.getHandle().jukeboxPos = null; - this.getHandle().setJukeboxPlaying(null, false); + getHandle().forceDancing = false; + getHandle().jukeboxPos = null; + getHandle().setJukeboxPlaying(null, false); } @Override public org.bukkit.entity.Allay duplicateAllay() { - Allay nmsAllay = this.getHandle().duplicateAllay0(); + Allay nmsAllay = getHandle().duplicateAllay(); return (nmsAllay != null) ? (org.bukkit.entity.Allay) nmsAllay.getBukkitEntity() : null; } public Location getJukebox() { - BlockPos nmsJukeboxPos = this.getHandle().jukeboxPos; - return (nmsJukeboxPos != null) ? CraftLocation.toBukkit(nmsJukeboxPos, this.getWorld()) : null; + BlockPos nmsJukeboxPos = getHandle().jukeboxPos; + return (nmsJukeboxPos != null) ? CraftLocation.toBukkit(nmsJukeboxPos, getWorld()) : null; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java index 2a2f9f09..7f0ba4f5 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.ambient.AmbientCreature; +import net.minecraft.world.entity.ambient.EntityAmbient; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Ambient; public class CraftAmbient extends CraftMob implements Ambient { - public CraftAmbient(CraftServer server, AmbientCreature entity) { + public CraftAmbient(CraftServer server, EntityAmbient entity) { super(server, entity); } @Override - public AmbientCreature getHandle() { - return (AmbientCreature) this.entity; + public EntityAmbient getHandle() { + return (EntityAmbient) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java index ab42bc72..83d00577 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java @@ -2,7 +2,7 @@ import com.google.common.base.Preconditions; import java.util.UUID; -import net.minecraft.world.entity.animal.Animal; +import net.minecraft.world.entity.animal.EntityAnimal; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; @@ -11,13 +11,13 @@ public class CraftAnimals extends CraftAgeable implements Animals { - public CraftAnimals(CraftServer server, Animal entity) { + public CraftAnimals(CraftServer server, EntityAnimal entity) { super(server, entity); } @Override - public Animal getHandle() { - return (Animal) this.entity; + public EntityAnimal getHandle() { + return (EntityAnimal) entity; } @Override @@ -27,37 +27,37 @@ public String toString() { @Override public UUID getBreedCause() { - return this.getHandle().loveCause; + return getHandle().loveCause; } @Override public void setBreedCause(UUID uuid) { - this.getHandle().loveCause = uuid; + getHandle().loveCause = uuid; } @Override public boolean isLoveMode() { - return this.getHandle().isInLove(); + return getHandle().isInLove(); } @Override public void setLoveModeTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "Love mode ticks must be positive or 0"); - this.getHandle().setInLoveTime(ticks); + getHandle().setInLoveTime(ticks); } @Override public int getLoveModeTicks() { - return this.getHandle().inLove; + return getHandle().inLove; } @Override public boolean isBreedItem(ItemStack itemStack) { - return this.getHandle().isFood(CraftItemStack.asNMSCopy(itemStack)); + return getHandle().isFood(CraftItemStack.asNMSCopy(itemStack)); } @Override public boolean isBreedItem(Material material) { - return this.isBreedItem(new ItemStack(material)); + return isBreedItem(new ItemStack(material)); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java index 33c6aaf4..218e9874 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java @@ -5,7 +5,9 @@ import java.util.Optional; import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffectList; +import net.minecraft.world.entity.EntityAreaEffectCloud; +import net.minecraft.world.entity.EntityLiving; import net.minecraft.world.item.alchemy.PotionContents; import org.bukkit.Color; import org.bukkit.Particle; @@ -24,13 +26,13 @@ public class CraftAreaEffectCloud extends CraftEntity implements AreaEffectCloud { - public CraftAreaEffectCloud(CraftServer server, net.minecraft.world.entity.AreaEffectCloud entity) { + public CraftAreaEffectCloud(CraftServer server, EntityAreaEffectCloud entity) { super(server, entity); } @Override - public net.minecraft.world.entity.AreaEffectCloud getHandle() { - return (net.minecraft.world.entity.AreaEffectCloud) super.getHandle(); + public EntityAreaEffectCloud getHandle() { + return (EntityAreaEffectCloud) super.getHandle(); } @Override @@ -40,124 +42,124 @@ public String toString() { @Override public int getDuration() { - return this.getHandle().getDuration(); + return getHandle().getDuration(); } @Override public void setDuration(int duration) { - this.getHandle().setDuration(duration); + getHandle().setDuration(duration); } @Override public int getWaitTime() { - return this.getHandle().waitTime; + return getHandle().waitTime; } @Override public void setWaitTime(int waitTime) { - this.getHandle().setWaitTime(waitTime); + getHandle().setWaitTime(waitTime); } @Override public int getReapplicationDelay() { - return this.getHandle().reapplicationDelay; + return getHandle().reapplicationDelay; } @Override public void setReapplicationDelay(int delay) { - this.getHandle().reapplicationDelay = delay; + getHandle().reapplicationDelay = delay; } @Override public int getDurationOnUse() { - return this.getHandle().durationOnUse; + return getHandle().durationOnUse; } @Override public void setDurationOnUse(int duration) { - this.getHandle().durationOnUse = duration; + getHandle().durationOnUse = duration; } @Override public float getRadius() { - return this.getHandle().getRadius(); + return getHandle().getRadius(); } @Override public void setRadius(float radius) { - this.getHandle().setRadius(radius); + getHandle().setRadius(radius); } @Override public float getRadiusOnUse() { - return this.getHandle().radiusOnUse; + return getHandle().radiusOnUse; } @Override public void setRadiusOnUse(float radius) { - this.getHandle().setRadiusOnUse(radius); + getHandle().setRadiusOnUse(radius); } @Override public float getRadiusPerTick() { - return this.getHandle().radiusPerTick; + return getHandle().radiusPerTick; } @Override public void setRadiusPerTick(float radius) { - this.getHandle().setRadiusPerTick(radius); + getHandle().setRadiusPerTick(radius); } @Override public Particle getParticle() { - return CraftParticle.minecraftToBukkit(this.getHandle().getParticle().getType()); + return CraftParticle.minecraftToBukkit(getHandle().getParticle().getType()); } @Override public void setParticle(Particle particle) { - this.setParticle(particle, null); + setParticle(particle, null); } @Override public void setParticle(Particle particle, T data) { - this.getHandle().setParticle(CraftParticle.createParticleParam(particle, data)); + getHandle().setParticle(CraftParticle.createParticleParam(particle, data)); } @Override public Color getColor() { - return Color.fromRGB(this.getHandle().potionContents.getColor()); + return Color.fromRGB(getHandle().potionContents.getColor()); } @Override public void setColor(Color color) { - PotionContents old = this.getHandle().potionContents; - this.getHandle().setPotionContents(new PotionContents(old.potion(), Optional.of(color.asRGB()), old.customEffects())); + PotionContents old = getHandle().potionContents; + getHandle().setPotionContents(new PotionContents(old.potion(), Optional.of(color.asRGB()), old.customEffects(), old.customName())); } @Override public boolean addCustomEffect(PotionEffect effect, boolean override) { - if (this.hasCustomEffect(effect.getType())) { + if (hasCustomEffect(effect.getType())) { if (!override) { return false; } - this.removeCustomEffect(effect.getType()); + removeCustomEffect(effect.getType()); } - this.getHandle().addEffect(CraftPotionUtil.fromBukkit(effect)); - this.getHandle().updateColor(); + getHandle().addEffect(CraftPotionUtil.fromBukkit(effect)); + getHandle().updateColor(); return true; } @Override public void clearCustomEffects() { - PotionContents old = this.getHandle().potionContents; - this.getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), List.of())); - this.getHandle().updateColor(); + PotionContents old = getHandle().potionContents; + getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), List.of(), old.customName())); + getHandle().updateColor(); } @Override public List getCustomEffects() { ImmutableList.Builder builder = ImmutableList.builder(); - for (MobEffectInstance effect : this.getHandle().potionContents.customEffects()) { + for (MobEffect effect : getHandle().potionContents.customEffects()) { builder.add(CraftPotionUtil.toBukkit(effect)); } return builder.build(); @@ -165,7 +167,7 @@ public List getCustomEffects() { @Override public boolean hasCustomEffect(PotionEffectType type) { - for (MobEffectInstance effect : this.getHandle().potionContents.customEffects()) { + for (MobEffect effect : getHandle().potionContents.customEffects()) { if (CraftPotionUtil.equals(effect.getEffect(), type)) { return true; } @@ -175,18 +177,18 @@ public boolean hasCustomEffect(PotionEffectType type) { @Override public boolean hasCustomEffects() { - return !this.getHandle().potionContents.customEffects().isEmpty(); + return !getHandle().potionContents.customEffects().isEmpty(); } @Override public boolean removeCustomEffect(PotionEffectType effect) { - if (!this.hasCustomEffect(effect)) { + if (!hasCustomEffect(effect)) { return false; } - Holder minecraft = CraftPotionEffectType.bukkitToMinecraftHolder(effect); + Holder minecraft = CraftPotionEffectType.bukkitToMinecraftHolder(effect); - PotionContents old = this.getHandle().potionContents; - this.getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), old.customEffects().stream().filter((mobEffect) -> !mobEffect.getEffect().equals(minecraft)).toList())); + PotionContents old = getHandle().potionContents; + getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), old.customEffects().stream().filter((mobEffect) -> !mobEffect.getEffect().equals(minecraft)).toList(), old.customName())); return true; } @@ -203,30 +205,30 @@ public PotionData getBasePotionData() { @Override public void setBasePotionType(PotionType potionType) { if (potionType != null) { - this.getHandle().setPotionContents(this.getHandle().potionContents.withPotion(CraftPotionType.bukkitToMinecraftHolder(potionType))); + getHandle().setPotionContents(getHandle().potionContents.withPotion(CraftPotionType.bukkitToMinecraftHolder(potionType))); } else { - PotionContents old = this.getHandle().potionContents; - this.getHandle().setPotionContents(new PotionContents(Optional.empty(), old.customColor(), old.customEffects())); + PotionContents old = getHandle().potionContents; + getHandle().setPotionContents(new PotionContents(Optional.empty(), old.customColor(), old.customEffects(), old.customName())); } } @Override public PotionType getBasePotionType() { - return this.getHandle().potionContents.potion().map(CraftPotionType::minecraftHolderToBukkit).orElse(null); + return getHandle().potionContents.potion().map(CraftPotionType::minecraftHolderToBukkit).orElse(null); } @Override public ProjectileSource getSource() { - net.minecraft.world.entity.LivingEntity source = this.getHandle().getOwner(); + EntityLiving source = getHandle().getOwner(); return (source == null) ? null : (LivingEntity) source.getBukkitEntity(); } @Override public void setSource(ProjectileSource shooter) { if (shooter instanceof CraftLivingEntity craftLivingEntity) { - this.getHandle().setOwner(craftLivingEntity.getHandle()); + getHandle().setOwner(craftLivingEntity.getHandle()); } else { - this.getHandle().setOwner(null); + getHandle().setOwner(null); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java index 04a7735d..33f8cd2c 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.core.Rotations; +import net.minecraft.core.Vector3f; +import net.minecraft.world.entity.decoration.EntityArmorStand; import org.bukkit.craftbukkit.CraftEquipmentSlot; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.ArmorStand; @@ -11,7 +12,7 @@ public class CraftArmorStand extends CraftLivingEntity implements ArmorStand { - public CraftArmorStand(CraftServer server, net.minecraft.world.entity.decoration.ArmorStand entity) { + public CraftArmorStand(CraftServer server, EntityArmorStand entity) { super(server, entity); } @@ -21,168 +22,168 @@ public String toString() { } @Override - public net.minecraft.world.entity.decoration.ArmorStand getHandle() { - return (net.minecraft.world.entity.decoration.ArmorStand) super.getHandle(); + public EntityArmorStand getHandle() { + return (EntityArmorStand) super.getHandle(); } @Override public ItemStack getItemInHand() { - return this.getEquipment().getItemInHand(); + return getEquipment().getItemInHand(); } @Override public void setItemInHand(ItemStack item) { - this.getEquipment().setItemInHand(item); + getEquipment().setItemInHand(item); } @Override public ItemStack getBoots() { - return this.getEquipment().getBoots(); + return getEquipment().getBoots(); } @Override public void setBoots(ItemStack item) { - this.getEquipment().setBoots(item); + getEquipment().setBoots(item); } @Override public ItemStack getLeggings() { - return this.getEquipment().getLeggings(); + return getEquipment().getLeggings(); } @Override public void setLeggings(ItemStack item) { - this.getEquipment().setLeggings(item); + getEquipment().setLeggings(item); } @Override public ItemStack getChestplate() { - return this.getEquipment().getChestplate(); + return getEquipment().getChestplate(); } @Override public void setChestplate(ItemStack item) { - this.getEquipment().setChestplate(item); + getEquipment().setChestplate(item); } @Override public ItemStack getHelmet() { - return this.getEquipment().getHelmet(); + return getEquipment().getHelmet(); } @Override public void setHelmet(ItemStack item) { - this.getEquipment().setHelmet(item); + getEquipment().setHelmet(item); } @Override public EulerAngle getBodyPose() { - return CraftArmorStand.fromNMS(this.getHandle().bodyPose); + return fromNMS(getHandle().bodyPose); } @Override public void setBodyPose(EulerAngle pose) { - this.getHandle().setBodyPose(CraftArmorStand.toNMS(pose)); + getHandle().setBodyPose(toNMS(pose)); } @Override public EulerAngle getLeftArmPose() { - return CraftArmorStand.fromNMS(this.getHandle().leftArmPose); + return fromNMS(getHandle().leftArmPose); } @Override public void setLeftArmPose(EulerAngle pose) { - this.getHandle().setLeftArmPose(CraftArmorStand.toNMS(pose)); + getHandle().setLeftArmPose(toNMS(pose)); } @Override public EulerAngle getRightArmPose() { - return CraftArmorStand.fromNMS(this.getHandle().rightArmPose); + return fromNMS(getHandle().rightArmPose); } @Override public void setRightArmPose(EulerAngle pose) { - this.getHandle().setRightArmPose(CraftArmorStand.toNMS(pose)); + getHandle().setRightArmPose(toNMS(pose)); } @Override public EulerAngle getLeftLegPose() { - return CraftArmorStand.fromNMS(this.getHandle().leftLegPose); + return fromNMS(getHandle().leftLegPose); } @Override public void setLeftLegPose(EulerAngle pose) { - this.getHandle().setLeftLegPose(CraftArmorStand.toNMS(pose)); + getHandle().setLeftLegPose(toNMS(pose)); } @Override public EulerAngle getRightLegPose() { - return CraftArmorStand.fromNMS(this.getHandle().rightLegPose); + return fromNMS(getHandle().rightLegPose); } @Override public void setRightLegPose(EulerAngle pose) { - this.getHandle().setRightLegPose(CraftArmorStand.toNMS(pose)); + getHandle().setRightLegPose(toNMS(pose)); } @Override public EulerAngle getHeadPose() { - return CraftArmorStand.fromNMS(this.getHandle().headPose); + return fromNMS(getHandle().headPose); } @Override public void setHeadPose(EulerAngle pose) { - this.getHandle().setHeadPose(CraftArmorStand.toNMS(pose)); + getHandle().setHeadPose(toNMS(pose)); } @Override public boolean hasBasePlate() { - return !this.getHandle().isNoBasePlate(); + return getHandle().showBasePlate(); } @Override public void setBasePlate(boolean basePlate) { - this.getHandle().setNoBasePlate(!basePlate); + getHandle().setNoBasePlate(!basePlate); } @Override public void setGravity(boolean gravity) { super.setGravity(gravity); // Armor stands are special - this.getHandle().noPhysics = !gravity; + getHandle().noPhysics = !gravity; } @Override public boolean isVisible() { - return !this.getHandle().isInvisible(); + return !getHandle().isInvisible(); } @Override public void setVisible(boolean visible) { - this.getHandle().setInvisible(!visible); + getHandle().setInvisible(!visible); } @Override public boolean hasArms() { - return this.getHandle().isShowArms(); + return getHandle().showArms(); } @Override public void setArms(boolean arms) { - this.getHandle().setShowArms(arms); + getHandle().setShowArms(arms); } @Override public boolean isSmall() { - return this.getHandle().isSmall(); + return getHandle().isSmall(); } @Override public void setSmall(boolean small) { - this.getHandle().setSmall(small); + getHandle().setSmall(small); } - private static EulerAngle fromNMS(Rotations old) { + private static EulerAngle fromNMS(Vector3f old) { return new EulerAngle( Math.toRadians(old.getX()), Math.toRadians(old.getY()), @@ -190,8 +191,8 @@ private static EulerAngle fromNMS(Rotations old) { ); } - private static Rotations toNMS(EulerAngle old) { - return new Rotations( + private static Vector3f toNMS(EulerAngle old) { + return new Vector3f( (float) Math.toDegrees(old.getX()), (float) Math.toDegrees(old.getY()), (float) Math.toDegrees(old.getZ()) @@ -200,26 +201,26 @@ private static Rotations toNMS(EulerAngle old) { @Override public boolean isMarker() { - return this.getHandle().isMarker(); + return getHandle().isMarker(); } @Override public void setMarker(boolean marker) { - this.getHandle().setMarker(marker); + getHandle().setMarker(marker); } @Override public void addEquipmentLock(EquipmentSlot equipmentSlot, LockType lockType) { - this.getHandle().disabledSlots |= (1 << CraftEquipmentSlot.getNMS(equipmentSlot).getFilterFlag() + lockType.ordinal() * 8); + getHandle().disabledSlots |= (1 << CraftEquipmentSlot.getNMS(equipmentSlot).getFilterBit(lockType.ordinal() * 8)); } @Override public void removeEquipmentLock(EquipmentSlot equipmentSlot, LockType lockType) { - this.getHandle().disabledSlots &= ~(1 << CraftEquipmentSlot.getNMS(equipmentSlot).getFilterFlag() + lockType.ordinal() * 8); + getHandle().disabledSlots &= ~(1 << CraftEquipmentSlot.getNMS(equipmentSlot).getFilterBit(lockType.ordinal() * 8)); } @Override public boolean hasEquipmentLock(EquipmentSlot equipmentSlot, LockType lockType) { - return (this.getHandle().disabledSlots & (1 << CraftEquipmentSlot.getNMS(equipmentSlot).getFilterFlag() + lockType.ordinal() * 8)) != 0; + return (getHandle().disabledSlots & (1 << CraftEquipmentSlot.getNMS(equipmentSlot).getFilterBit(lockType.ordinal() * 8))) != 0; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java index 54e44781..980b295b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java @@ -5,7 +5,8 @@ import java.util.Optional; import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffectList; +import net.minecraft.world.entity.projectile.EntityTippedArrow; import net.minecraft.world.item.alchemy.PotionContents; import org.bukkit.Color; import org.bukkit.craftbukkit.CraftServer; @@ -20,13 +21,13 @@ public class CraftArrow extends CraftAbstractArrow implements Arrow { - public CraftArrow(CraftServer server, net.minecraft.world.entity.projectile.Arrow entity) { + public CraftArrow(CraftServer server, EntityTippedArrow entity) { super(server, entity); } @Override - public net.minecraft.world.entity.projectile.Arrow getHandle() { - return (net.minecraft.world.entity.projectile.Arrow) this.entity; + public EntityTippedArrow getHandle() { + return (EntityTippedArrow) entity; } @Override @@ -36,28 +37,28 @@ public String toString() { @Override public boolean addCustomEffect(PotionEffect effect, boolean override) { - if (this.hasCustomEffect(effect.getType())) { + if (hasCustomEffect(effect.getType())) { if (!override) { return false; } - this.removeCustomEffect(effect.getType()); + removeCustomEffect(effect.getType()); } - this.getHandle().addEffect(CraftPotionUtil.fromBukkit(effect)); - this.getHandle().updateColor(); + getHandle().addEffect(CraftPotionUtil.fromBukkit(effect)); + getHandle().updateColor(); return true; } @Override public void clearCustomEffects() { - PotionContents old = this.getHandle().getPotionContents(); - this.getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), List.of())); - this.getHandle().updateColor(); + PotionContents old = getHandle().getPotionContents(); + getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), List.of(), old.customName())); + getHandle().updateColor(); } @Override public List getCustomEffects() { ImmutableList.Builder builder = ImmutableList.builder(); - for (MobEffectInstance effect : this.getHandle().getPotionContents().customEffects()) { + for (MobEffect effect : getHandle().getPotionContents().customEffects()) { builder.add(CraftPotionUtil.toBukkit(effect)); } return builder.build(); @@ -65,7 +66,7 @@ public List getCustomEffects() { @Override public boolean hasCustomEffect(PotionEffectType type) { - for (MobEffectInstance effect : this.getHandle().getPotionContents().customEffects()) { + for (MobEffect effect : getHandle().getPotionContents().customEffects()) { if (CraftPotionUtil.equals(effect.getEffect(), type)) { return true; } @@ -75,18 +76,18 @@ public boolean hasCustomEffect(PotionEffectType type) { @Override public boolean hasCustomEffects() { - return !this.getHandle().getPotionContents().customEffects().isEmpty(); + return !getHandle().getPotionContents().customEffects().isEmpty(); } @Override public boolean removeCustomEffect(PotionEffectType effect) { - if (!this.hasCustomEffect(effect)) { + if (!hasCustomEffect(effect)) { return false; } - Holder minecraft = CraftPotionEffectType.bukkitToMinecraftHolder(effect); + Holder minecraft = CraftPotionEffectType.bukkitToMinecraftHolder(effect); - PotionContents old = this.getHandle().getPotionContents(); - this.getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), old.customEffects().stream().filter((mobEffect) -> !mobEffect.getEffect().equals(minecraft)).toList())); + PotionContents old = getHandle().getPotionContents(); + getHandle().setPotionContents(new PotionContents(old.potion(), old.customColor(), old.customEffects().stream().filter((mobEffect) -> !mobEffect.getEffect().equals(minecraft)).toList(), old.customName())); return true; } @@ -103,30 +104,30 @@ public PotionData getBasePotionData() { @Override public void setBasePotionType(PotionType potionType) { if (potionType != null) { - this.getHandle().setPotionContents(this.getHandle().getPotionContents().withPotion(CraftPotionType.bukkitToMinecraftHolder(potionType))); + getHandle().setPotionContents(getHandle().getPotionContents().withPotion(CraftPotionType.bukkitToMinecraftHolder(potionType))); } else { - PotionContents old = this.getHandle().getPotionContents(); - this.getHandle().setPotionContents(new PotionContents(Optional.empty(), old.customColor(), old.customEffects())); + PotionContents old = getHandle().getPotionContents(); + getHandle().setPotionContents(new PotionContents(Optional.empty(), old.customColor(), old.customEffects(), old.customName())); } } @Override public PotionType getBasePotionType() { - return this.getHandle().getPotionContents().potion().map(CraftPotionType::minecraftHolderToBukkit).orElse(null); + return getHandle().getPotionContents().potion().map(CraftPotionType::minecraftHolderToBukkit).orElse(null); } @Override public void setColor(Color color) { int colorRGB = (color == null) ? -1 : color.asRGB(); - PotionContents old = this.getHandle().getPotionContents(); - this.getHandle().setPotionContents(new PotionContents(old.potion(), Optional.of(colorRGB), old.customEffects())); + PotionContents old = getHandle().getPotionContents(); + getHandle().setPotionContents(new PotionContents(old.potion(), Optional.of(colorRGB), old.customEffects(), old.customName())); } @Override public Color getColor() { - if (this.getHandle().getColor() <= -1) { + if (getHandle().getColor() <= -1) { return null; } - return Color.fromRGB(this.getHandle().getColor()); + return Color.fromRGB(getHandle().getColor()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAxolotl.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAxolotl.java index e730292e..366f573c 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAxolotl.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftAxolotl.java @@ -22,23 +22,23 @@ public String toString() { @Override public boolean isPlayingDead() { - return this.getHandle().isPlayingDead(); + return getHandle().isPlayingDead(); } @Override public void setPlayingDead(boolean playingDead) { - this.getHandle().setPlayingDead(playingDead); + getHandle().setPlayingDead(playingDead); } @Override public Variant getVariant() { - return Variant.values()[this.getHandle().getVariant().ordinal()]; + return Variant.values()[getHandle().getVariant().ordinal()]; } @Override public void setVariant(Variant variant) { Preconditions.checkArgument(variant != null, "variant"); - this.getHandle().setVariant(net.minecraft.world.entity.animal.axolotl.Axolotl.Variant.byId(variant.ordinal())); + getHandle().setVariant(net.minecraft.world.entity.animal.axolotl.Axolotl.Variant.byId(variant.ordinal())); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java index b0a35314..5f633d63 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.ambient.EntityBat; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Bat; public class CraftBat extends CraftAmbient implements Bat { - public CraftBat(CraftServer server, net.minecraft.world.entity.ambient.Bat entity) { + public CraftBat(CraftServer server, EntityBat entity) { super(server, entity); } @Override - public net.minecraft.world.entity.ambient.Bat getHandle() { - return (net.minecraft.world.entity.ambient.Bat) this.entity; + public EntityBat getHandle() { + return (EntityBat) entity; } @Override @@ -20,11 +21,11 @@ public String toString() { @Override public boolean isAwake() { - return !this.getHandle().isResting(); + return !getHandle().isResting(); } @Override public void setAwake(boolean state) { - this.getHandle().setResting(!state); + getHandle().setResting(!state); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBee.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBee.java index cfff1be6..147562da 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBee.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBee.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.animal.EntityBee; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftLocation; @@ -9,13 +10,13 @@ public class CraftBee extends CraftAnimals implements Bee { - public CraftBee(CraftServer server, net.minecraft.world.entity.animal.Bee entity) { + public CraftBee(CraftServer server, EntityBee entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Bee getHandle() { - return (net.minecraft.world.entity.animal.Bee) this.entity; + public EntityBee getHandle() { + return (EntityBee) entity; } @Override @@ -25,65 +26,65 @@ public String toString() { @Override public Location getHive() { - BlockPos hive = this.getHandle().getHivePos(); - return (hive == null) ? null : CraftLocation.toBukkit(hive, this.getWorld()); + BlockPos hive = getHandle().getHivePos(); + return (hive == null) ? null : CraftLocation.toBukkit(hive, getWorld()); } @Override public void setHive(Location location) { Preconditions.checkArgument(location == null || this.getWorld().equals(location.getWorld()), "Hive must be in same world"); - this.getHandle().hivePos = (location == null) ? null : CraftLocation.toBlockPosition(location); + getHandle().hivePos = (location == null) ? null : CraftLocation.toBlockPos(location); } @Override public Location getFlower() { - BlockPos flower = this.getHandle().getSavedFlowerPos(); - return (flower == null) ? null : CraftLocation.toBukkit(flower, this.getWorld()); + BlockPos flower = getHandle().getSavedFlowerPos(); + return (flower == null) ? null : CraftLocation.toBukkit(flower, getWorld()); } @Override public void setFlower(Location location) { Preconditions.checkArgument(location == null || this.getWorld().equals(location.getWorld()), "Flower must be in same world"); - this.getHandle().setSavedFlowerPos(location == null ? null : CraftLocation.toBlockPosition(location)); + getHandle().setSavedFlowerPos(location == null ? null : CraftLocation.toBlockPos(location)); } @Override public boolean hasNectar() { - return this.getHandle().hasNectar(); + return getHandle().hasNectar(); } @Override public void setHasNectar(boolean nectar) { - this.getHandle().setHasNectar(nectar); + getHandle().setHasNectar(nectar); } @Override public boolean hasStung() { - return this.getHandle().hasStung(); + return getHandle().hasStung(); } @Override public void setHasStung(boolean stung) { - this.getHandle().setHasStung(stung); + getHandle().setHasStung(stung); } @Override public int getAnger() { - return this.getHandle().getRemainingPersistentAngerTime(); + return getHandle().getRemainingPersistentAngerTime(); } @Override public void setAnger(int anger) { - this.getHandle().setRemainingPersistentAngerTime(anger); + getHandle().setRemainingPersistentAngerTime(anger); } @Override public int getCannotEnterHiveTicks() { - return this.getHandle().stayOutOfHiveCountdown; + return getHandle().stayOutOfHiveCountdown; } @Override public void setCannotEnterHiveTicks(int ticks) { - this.getHandle().setStayOutOfHiveCountdown(ticks); + getHandle().setStayOutOfHiveCountdown(ticks); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java index a4c9c736..973d8b89 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityBlaze; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Blaze; public class CraftBlaze extends CraftMonster implements Blaze { - public CraftBlaze(CraftServer server, net.minecraft.world.entity.monster.Blaze entity) { + public CraftBlaze(CraftServer server, EntityBlaze entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Blaze getHandle() { - return (net.minecraft.world.entity.monster.Blaze) this.entity; + public EntityBlaze getHandle() { + return (EntityBlaze) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockAttachedEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockAttachedEntity.java index e3fb8ebf..d26d4a50 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockAttachedEntity.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockAttachedEntity.java @@ -4,7 +4,6 @@ import org.bukkit.craftbukkit.CraftServer; public class CraftBlockAttachedEntity extends CraftEntity { - public CraftBlockAttachedEntity(CraftServer server, BlockAttachedEntity entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockDisplay.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockDisplay.java index dd91de8f..a2095d5d 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockDisplay.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlockDisplay.java @@ -24,13 +24,13 @@ public String toString() { @Override public BlockData getBlock() { - return CraftBlockData.fromData(this.getHandle().getBlockState()); + return CraftBlockData.fromData(getHandle().getBlockState()); } @Override public void setBlock(BlockData block) { Preconditions.checkArgument(block != null, "Block cannot be null"); - this.getHandle().setBlockState(((CraftBlockData) block).getState()); + getHandle().setBlockState(((CraftBlockData) block).getState()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java index f332bd4e..d92cc51e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java @@ -1,130 +1,140 @@ package org.bukkit.craftbukkit.entity; -import com.google.common.base.Preconditions; import java.util.stream.Collectors; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.vehicle.AbstractBoat; +import net.minecraft.world.entity.vehicle.EntityBoat; import org.bukkit.TreeSpecies; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Boat; import org.bukkit.entity.Entity; -public class CraftBoat extends CraftVehicle implements Boat { +public abstract class CraftBoat extends CraftVehicle implements Boat { - public CraftBoat(CraftServer server, net.minecraft.world.entity.vehicle.Boat entity) { + public CraftBoat(CraftServer server, AbstractBoat entity) { super(server, entity); } @Override public TreeSpecies getWoodType() { - return CraftBoat.getTreeSpecies(this.getHandle().getVariant()); + return getTreeSpecies(getHandle().getType()); } @Override public void setWoodType(TreeSpecies species) { - this.getHandle().setVariant(CraftBoat.getBoatType(species)); + throw new UnsupportedOperationException("Not supported - you must spawn a new entity to change boat type."); } @Override public Type getBoatType() { - return CraftBoat.boatTypeFromNms(this.getHandle().getVariant()); + return boatTypeFromNms(getHandle().getType()); } @Override public void setBoatType(Type type) { - Preconditions.checkArgument(type != null, "Boat.Type cannot be null"); - - this.getHandle().setVariant(CraftBoat.boatTypeToNms(type)); + throw new UnsupportedOperationException("Not supported - you must spawn a new entity to change boat type."); } @Override public double getMaxSpeed() { - return this.getHandle().maxSpeed; + return getHandle().maxSpeed; } @Override public void setMaxSpeed(double speed) { if (speed >= 0D) { - this.getHandle().maxSpeed = speed; + getHandle().maxSpeed = speed; } } @Override public double getOccupiedDeceleration() { - return this.getHandle().occupiedDeceleration; + return getHandle().occupiedDeceleration; } @Override public void setOccupiedDeceleration(double speed) { if (speed >= 0D) { - this.getHandle().occupiedDeceleration = speed; + getHandle().occupiedDeceleration = speed; } } @Override public double getUnoccupiedDeceleration() { - return this.getHandle().unoccupiedDeceleration; + return getHandle().unoccupiedDeceleration; } @Override public void setUnoccupiedDeceleration(double speed) { - this.getHandle().unoccupiedDeceleration = speed; + getHandle().unoccupiedDeceleration = speed; } @Override public boolean getWorkOnLand() { - return this.getHandle().landBoats; + return getHandle().landBoats; } @Override public void setWorkOnLand(boolean workOnLand) { - this.getHandle().landBoats = workOnLand; + getHandle().landBoats = workOnLand; } @Override public Status getStatus() { - return CraftBoat.boatStatusFromNms(this.getHandle().status); + return boatStatusFromNms(getHandle().status); } @Override - public net.minecraft.world.entity.vehicle.Boat getHandle() { - return (net.minecraft.world.entity.vehicle.Boat) this.entity; + public AbstractBoat getHandle() { + return (AbstractBoat) entity; } @Override public String toString() { - return "CraftBoat{boatType=" + this.getBoatType() + ",status=" + this.getStatus() + ",passengers=" + this.getPassengers().stream().map(Entity::toString).collect(Collectors.joining("-", "{", "}")) + "}"; - } - - public static Boat.Type boatTypeFromNms(net.minecraft.world.entity.vehicle.Boat.Type boatType) { - return switch (boatType) { - default -> throw new EnumConstantNotPresentException(Type.class, boatType.name()); - case OAK -> Type.OAK; - case BIRCH -> Type.BIRCH; - case ACACIA -> Type.ACACIA; - case CHERRY -> Type.CHERRY; - case JUNGLE -> Type.JUNGLE; - case SPRUCE -> Type.SPRUCE; - case DARK_OAK -> Type.DARK_OAK; - case MANGROVE -> Type.MANGROVE; - case BAMBOO -> Type.BAMBOO; - }; + return "CraftBoat{boatType=" + getBoatType() + ",status=" + getStatus() + ",passengers=" + getPassengers().stream().map(Entity::toString).collect(Collectors.joining("-", "{", "}")) + "}"; } - public static net.minecraft.world.entity.vehicle.Boat.Type boatTypeToNms(Boat.Type type) { - return switch (type) { - default -> throw new EnumConstantNotPresentException(net.minecraft.world.entity.vehicle.Boat.Type.class, type.name()); - case BAMBOO -> net.minecraft.world.entity.vehicle.Boat.Type.BAMBOO; - case MANGROVE -> net.minecraft.world.entity.vehicle.Boat.Type.MANGROVE; - case SPRUCE -> net.minecraft.world.entity.vehicle.Boat.Type.SPRUCE; - case DARK_OAK -> net.minecraft.world.entity.vehicle.Boat.Type.DARK_OAK; - case JUNGLE -> net.minecraft.world.entity.vehicle.Boat.Type.JUNGLE; - case CHERRY -> net.minecraft.world.entity.vehicle.Boat.Type.CHERRY; - case ACACIA -> net.minecraft.world.entity.vehicle.Boat.Type.ACACIA; - case BIRCH -> net.minecraft.world.entity.vehicle.Boat.Type.BIRCH; - case OAK -> net.minecraft.world.entity.vehicle.Boat.Type.OAK; - }; + public static Boat.Type boatTypeFromNms(EntityTypes boatType) { + if (boatType == EntityTypes.OAK_BOAT || boatType == EntityTypes.OAK_CHEST_BOAT) { + return Type.OAK; + } + + if (boatType == EntityTypes.BIRCH_BOAT || boatType == EntityTypes.BIRCH_CHEST_BOAT) { + return Type.BIRCH; + } + + if (boatType == EntityTypes.ACACIA_BOAT || boatType == EntityTypes.ACACIA_CHEST_BOAT) { + return Type.ACACIA; + } + + if (boatType == EntityTypes.CHERRY_BOAT || boatType == EntityTypes.CHERRY_CHEST_BOAT) { + return Type.CHERRY; + } + + if (boatType == EntityTypes.JUNGLE_BOAT || boatType == EntityTypes.JUNGLE_CHEST_BOAT) { + return Type.JUNGLE; + } + + if (boatType == EntityTypes.SPRUCE_BOAT || boatType == EntityTypes.SPRUCE_CHEST_BOAT) { + return Type.SPRUCE; + } + + if (boatType == EntityTypes.DARK_OAK_BOAT || boatType == EntityTypes.DARK_OAK_CHEST_BOAT) { + return Type.DARK_OAK; + } + + if (boatType == EntityTypes.MANGROVE_BOAT || boatType == EntityTypes.MANGROVE_CHEST_BOAT) { + return Type.MANGROVE; + } + + if (boatType == EntityTypes.BAMBOO_RAFT || boatType == EntityTypes.BAMBOO_CHEST_RAFT) { + return Type.BAMBOO; + } + + throw new EnumConstantNotPresentException(Type.class, boatType.toString()); } - public static Status boatStatusFromNms(net.minecraft.world.entity.vehicle.Boat.Status enumStatus) { + public static Status boatStatusFromNms(EntityBoat.EnumStatus enumStatus) { return switch (enumStatus) { default -> throw new EnumConstantNotPresentException(Status.class, enumStatus.name()); case IN_AIR -> Status.IN_AIR; @@ -136,40 +146,27 @@ public static Status boatStatusFromNms(net.minecraft.world.entity.vehicle.Boat.S } @Deprecated - public static TreeSpecies getTreeSpecies(net.minecraft.world.entity.vehicle.Boat.Type boatType) { - switch (boatType) { - case SPRUCE: - return TreeSpecies.REDWOOD; - case BIRCH: - return TreeSpecies.BIRCH; - case JUNGLE: - return TreeSpecies.JUNGLE; - case ACACIA: - return TreeSpecies.ACACIA; - case DARK_OAK: - return TreeSpecies.DARK_OAK; - case OAK: - default: - return TreeSpecies.GENERIC; + public static TreeSpecies getTreeSpecies(EntityTypes boatType) { + if (boatType == EntityTypes.SPRUCE_BOAT || boatType == EntityTypes.SPRUCE_CHEST_BOAT) { + return TreeSpecies.REDWOOD; } - } - @Deprecated - public static net.minecraft.world.entity.vehicle.Boat.Type getBoatType(TreeSpecies species) { - switch (species) { - case REDWOOD: - return net.minecraft.world.entity.vehicle.Boat.Type.SPRUCE; - case BIRCH: - return net.minecraft.world.entity.vehicle.Boat.Type.BIRCH; - case JUNGLE: - return net.minecraft.world.entity.vehicle.Boat.Type.JUNGLE; - case ACACIA: - return net.minecraft.world.entity.vehicle.Boat.Type.ACACIA; - case DARK_OAK: - return net.minecraft.world.entity.vehicle.Boat.Type.DARK_OAK; - case GENERIC: - default: - return net.minecraft.world.entity.vehicle.Boat.Type.OAK; + if (boatType == EntityTypes.BIRCH_BOAT || boatType == EntityTypes.BIRCH_CHEST_BOAT) { + return TreeSpecies.BIRCH; } + + if (boatType == EntityTypes.JUNGLE_BOAT || boatType == EntityTypes.JUNGLE_CHEST_BOAT) { + return TreeSpecies.JUNGLE; + } + + if (boatType == EntityTypes.ACACIA_BOAT || boatType == EntityTypes.ACACIA_CHEST_BOAT) { + return TreeSpecies.ACACIA; + } + + if (boatType == EntityTypes.DARK_OAK_BOAT || boatType == EntityTypes.DARK_OAK_CHEST_BOAT) { + return TreeSpecies.DARK_OAK; + } + + return TreeSpecies.GENERIC; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBogged.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBogged.java index 0139e85c..aac6d153 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBogged.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBogged.java @@ -12,7 +12,7 @@ public CraftBogged(CraftServer server, net.minecraft.world.entity.monster.Bogged @Override public net.minecraft.world.entity.monster.Bogged getHandle() { - return (net.minecraft.world.entity.monster.Bogged) this.entity; + return (net.minecraft.world.entity.monster.Bogged) entity; } @Override @@ -27,11 +27,11 @@ public Skeleton.SkeletonType getSkeletonType() { @Override public boolean isSheared() { - return this.getHandle().isSheared(); + return getHandle().isSheared(); } @Override public void setSheared(boolean flag) { - this.getHandle().setSheared(flag); + getHandle().setSheared(flag); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBreeze.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBreeze.java index 3f3d0873..0edefad5 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBreeze.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftBreeze.java @@ -11,7 +11,7 @@ public CraftBreeze(CraftServer server, net.minecraft.world.entity.monster.breeze @Override public net.minecraft.world.entity.monster.breeze.Breeze getHandle() { - return (net.minecraft.world.entity.monster.breeze.Breeze) this.entity; + return (net.minecraft.world.entity.monster.breeze.Breeze) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCamel.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCamel.java index 80e571c9..ee0727ce 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCamel.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCamel.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.EntityPose; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Camel; import org.bukkit.entity.Horse; @@ -28,25 +28,25 @@ public Horse.Variant getVariant() { @Override public boolean isDashing() { - return this.getHandle().isDashing(); + return getHandle().isDashing(); } @Override public void setDashing(boolean dashing) { - this.getHandle().setDashing(dashing); + getHandle().setDashing(dashing); } @Override public boolean isSitting() { - return this.getHandle().getPose() == Pose.SITTING; + return getHandle().getPose() == EntityPose.SITTING; } @Override public void setSitting(boolean sitting) { if (sitting) { - this.getHandle().sitDown(); + getHandle().sitDown(); } else { - this.getHandle().standUp(); + getHandle().standUp(); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java index 5e66064a..221bf57e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java @@ -5,6 +5,8 @@ import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.animal.CatVariant; +import net.minecraft.world.entity.animal.EntityCat; +import net.minecraft.world.item.EnumColor; import org.bukkit.DyeColor; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -15,13 +17,13 @@ public class CraftCat extends CraftTameableAnimal implements Cat { - public CraftCat(CraftServer server, net.minecraft.world.entity.animal.Cat entity) { + public CraftCat(CraftServer server, EntityCat entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Cat getHandle() { - return (net.minecraft.world.entity.animal.Cat) super.getHandle(); + public EntityCat getHandle() { + return (EntityCat) super.getHandle(); } @Override @@ -31,24 +33,24 @@ public String toString() { @Override public Type getCatType() { - return CraftType.minecraftHolderToBukkit(this.getHandle().getVariant()); + return CraftType.minecraftHolderToBukkit(getHandle().getVariant()); } @Override public void setCatType(Type type) { Preconditions.checkArgument(type != null, "Cannot have null Type"); - this.getHandle().setVariant(CraftType.bukkitToMinecraftHolder(type)); + getHandle().setVariant(CraftType.bukkitToMinecraftHolder(type)); } @Override public DyeColor getCollarColor() { - return DyeColor.getByWoolData((byte) this.getHandle().getCollarColor().getId()); + return DyeColor.getByWoolData((byte) getHandle().getCollarColor().getId()); } @Override public void setCollarColor(DyeColor color) { - this.getHandle().setCollarColor(net.minecraft.world.item.DyeColor.byId(color.getWoolData())); + getHandle().setCollarColor(EnumColor.byId(color.getWoolData())); } public static class CraftType implements Type, Handleable { @@ -59,7 +61,7 @@ public static Type minecraftToBukkit(CatVariant minecraft) { } public static Type minecraftHolderToBukkit(Holder minecraft) { - return CraftType.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static CatVariant bukkitToMinecraft(Type bukkit) { diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java index 4f661fbd..bc780cd0 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityCaveSpider; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.CaveSpider; public class CraftCaveSpider extends CraftSpider implements CaveSpider { - public CraftCaveSpider(CraftServer server, net.minecraft.world.entity.monster.CaveSpider entity) { + public CraftCaveSpider(CraftServer server, EntityCaveSpider entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.CaveSpider getHandle() { - return (net.minecraft.world.entity.monster.CaveSpider) this.entity; + public EntityCaveSpider getHandle() { + return (EntityCaveSpider) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftChestBoat.java index cfde210e..a359e8a2 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftChestBoat.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftChestBoat.java @@ -1,24 +1,24 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.vehicle.ChestBoat; +import net.minecraft.world.entity.vehicle.AbstractChestBoat; import org.bukkit.craftbukkit.CraftLootTable; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.inventory.Inventory; import org.bukkit.loot.LootTable; -public class CraftChestBoat extends CraftBoat implements org.bukkit.entity.ChestBoat { +public abstract class CraftChestBoat extends CraftBoat implements org.bukkit.entity.ChestBoat { private final Inventory inventory; - public CraftChestBoat(CraftServer server, ChestBoat entity) { + public CraftChestBoat(CraftServer server, AbstractChestBoat entity) { super(server, entity); - this.inventory = new CraftInventory(entity); + inventory = new CraftInventory(entity); } @Override - public ChestBoat getHandle() { - return (ChestBoat) this.entity; + public AbstractChestBoat getHandle() { + return (AbstractChestBoat) entity; } @Override @@ -28,31 +28,31 @@ public String toString() { @Override public Inventory getInventory() { - return this.inventory; + return inventory; } @Override public void setLootTable(LootTable table) { - this.setLootTable(table, this.getSeed()); + setLootTable(table, getSeed()); } @Override public LootTable getLootTable() { - return CraftLootTable.minecraftToBukkit(this.getHandle().getLootTable()); + return CraftLootTable.minecraftToBukkit(getHandle().getContainerLootTable()); } @Override public void setSeed(long seed) { - this.setLootTable(this.getLootTable(), seed); + setLootTable(getLootTable(), seed); } @Override public long getSeed() { - return this.getHandle().getLootTableSeed(); + return getHandle().getContainerLootTableSeed(); } private void setLootTable(LootTable table, long seed) { - this.getHandle().setLootTable(CraftLootTable.bukkitToMinecraft(table)); - this.getHandle().setLootTableSeed(seed); + getHandle().setContainerLootTable(CraftLootTable.bukkitToMinecraft(table)); + getHandle().setContainerLootTableSeed(seed); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java index 40ee96e3..723a429a 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java @@ -1,29 +1,29 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.animal.horse.AbstractChestedHorse; +import net.minecraft.world.entity.animal.horse.EntityHorseChestedAbstract; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.ChestedHorse; public abstract class CraftChestedHorse extends CraftAbstractHorse implements ChestedHorse { - public CraftChestedHorse(CraftServer server, AbstractChestedHorse entity) { + public CraftChestedHorse(CraftServer server, EntityHorseChestedAbstract entity) { super(server, entity); } @Override - public AbstractChestedHorse getHandle() { - return (AbstractChestedHorse) super.getHandle(); + public EntityHorseChestedAbstract getHandle() { + return (EntityHorseChestedAbstract) super.getHandle(); } @Override public boolean isCarryingChest() { - return this.getHandle().hasChest(); + return getHandle().hasChest(); } @Override public void setCarryingChest(boolean chest) { - if (chest == this.isCarryingChest()) return; - this.getHandle().setChest(chest); - this.getHandle().createInventory(); + if (chest == isCarryingChest()) return; + getHandle().setChest(chest); + getHandle().createInventory(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java index 64b75682..0cd52167 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityChicken; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Chicken; public class CraftChicken extends CraftAnimals implements Chicken { - public CraftChicken(CraftServer server, net.minecraft.world.entity.animal.Chicken entity) { + public CraftChicken(CraftServer server, EntityChicken entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Chicken getHandle() { - return (net.minecraft.world.entity.animal.Chicken) this.entity; + public EntityChicken getHandle() { + return (EntityChicken) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java index fa0bf7db..a6562842 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityCod; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Cod; public class CraftCod extends CraftFish implements Cod { - public CraftCod(CraftServer server, net.minecraft.world.entity.animal.Cod entity) { + public CraftCod(CraftServer server, EntityCod entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Cod getHandle() { - return (net.minecraft.world.entity.animal.Cod) super.getHandle(); + public EntityCod getHandle() { + return (EntityCod) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java index c2583982..6b43294c 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java @@ -1,40 +1,40 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.boss.EnderDragonPart; -import net.minecraft.world.entity.boss.enderdragon.EnderDragon; +import net.minecraft.world.entity.boss.EntityComplexPart; +import net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.ComplexEntityPart; import org.bukkit.entity.ComplexLivingEntity; import org.bukkit.event.entity.EntityDamageEvent; public class CraftComplexPart extends CraftEntity implements ComplexEntityPart { - public CraftComplexPart(CraftServer server, EnderDragonPart entity) { + public CraftComplexPart(CraftServer server, EntityComplexPart entity) { super(server, entity); } @Override public ComplexLivingEntity getParent() { - return (ComplexLivingEntity) ((EnderDragon) this.getHandle().parentMob).getBukkitEntity(); + return (ComplexLivingEntity) ((EntityEnderDragon) getHandle().parentMob).getBukkitEntity(); } @Override public void setLastDamageCause(EntityDamageEvent cause) { - this.getParent().setLastDamageCause(cause); + getParent().setLastDamageCause(cause); } @Override public EntityDamageEvent getLastDamageCause() { - return this.getParent().getLastDamageCause(); + return getParent().getLastDamageCause(); } @Override public boolean isValid() { - return this.getParent().isValid(); + return getParent().isValid(); } @Override - public EnderDragonPart getHandle() { - return (EnderDragonPart) this.entity; + public EntityComplexPart getHandle() { + return (EntityComplexPart) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java index 7babc404..ac0143a6 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityCow; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Cow; public class CraftCow extends CraftAnimals implements Cow { - public CraftCow(CraftServer server, net.minecraft.world.entity.animal.Cow entity) { + public CraftCow(CraftServer server, EntityCow entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Cow getHandle() { - return (net.minecraft.world.entity.animal.Cow) this.entity; + public EntityCow getHandle() { + return (EntityCow) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreaking.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreaking.java new file mode 100644 index 00000000..a896da43 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreaking.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.world.entity.monster.creaking.Creaking; +import org.bukkit.craftbukkit.CraftServer; + +public class CraftCreaking extends CraftMonster implements org.bukkit.entity.Creaking { + + public CraftCreaking(CraftServer server, Creaking entity) { + super(server, entity); + } + + @Override + public Creaking getHandle() { + return (Creaking) entity; + } + + @Override + public String toString() { + return "CraftCreaking"; + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreakingTransient.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreakingTransient.java new file mode 100644 index 00000000..4366c358 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreakingTransient.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.world.entity.monster.creaking.CreakingTransient; +import org.bukkit.craftbukkit.CraftServer; + +public class CraftCreakingTransient extends CraftCreaking implements org.bukkit.entity.CreakingTransient { + + public CraftCreakingTransient(CraftServer server, CreakingTransient entity) { + super(server, entity); + } + + @Override + public CreakingTransient getHandle() { + return (CreakingTransient) entity; + } + + @Override + public String toString() { + return "CraftCreakingTransient"; + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java index 664d9c17..b9f2e5e8 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.EntityCreature; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Creature; public class CraftCreature extends CraftMob implements Creature { - public CraftCreature(CraftServer server, PathfinderMob entity) { + public CraftCreature(CraftServer server, EntityCreature entity) { super(server, entity); } @Override - public PathfinderMob getHandle() { - return (PathfinderMob) this.entity; + public EntityCreature getHandle() { + return (EntityCreature) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java index f2209225..fd3adff5 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.monster.EntityCreeper; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Creeper; import org.bukkit.entity.Entity; @@ -8,13 +9,13 @@ public class CraftCreeper extends CraftMonster implements Creeper { - public CraftCreeper(CraftServer server, net.minecraft.world.entity.monster.Creeper entity) { + public CraftCreeper(CraftServer server, EntityCreeper entity) { super(server, entity); } @Override public boolean isPowered() { - return this.getHandle().isPowered(); + return getHandle().isPowered(); } @Override @@ -22,14 +23,14 @@ public void setPowered(boolean powered) { CreeperPowerEvent.PowerCause cause = powered ? CreeperPowerEvent.PowerCause.SET_ON : CreeperPowerEvent.PowerCause.SET_OFF; // only call event when we are not in world generation - if (this.getHandle().generation || !this.callPowerEvent(cause)) { - this.getHandle().setPowered(powered); + if (getHandle().generation || !callPowerEvent(cause)) { + getHandle().setPowered(powered); } } private boolean callPowerEvent(CreeperPowerEvent.PowerCause cause) { - CreeperPowerEvent event = new CreeperPowerEvent((Creeper) this.getHandle().getBukkitEntity(), cause); - this.server.getPluginManager().callEvent(event); + CreeperPowerEvent event = new CreeperPowerEvent((Creeper) getHandle().getBukkitEntity(), cause); + server.getPluginManager().callEvent(event); return event.isCancelled(); } @@ -37,42 +38,42 @@ private boolean callPowerEvent(CreeperPowerEvent.PowerCause cause) { public void setMaxFuseTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks < 0"); - this.getHandle().maxSwell = ticks; + getHandle().maxSwell = ticks; } @Override public int getMaxFuseTicks() { - return this.getHandle().maxSwell; + return getHandle().maxSwell; } @Override public void setFuseTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks < 0"); - Preconditions.checkArgument(ticks <= this.getMaxFuseTicks(), "ticks > maxFuseTicks"); + Preconditions.checkArgument(ticks <= getMaxFuseTicks(), "ticks > maxFuseTicks"); - this.getHandle().swell = ticks; + getHandle().swell = ticks; } @Override public int getFuseTicks() { - return this.getHandle().swell; + return getHandle().swell; } @Override public void setExplosionRadius(int radius) { Preconditions.checkArgument(radius >= 0, "radius < 0"); - this.getHandle().explosionRadius = radius; + getHandle().explosionRadius = radius; } @Override public int getExplosionRadius() { - return this.getHandle().explosionRadius; + return getHandle().explosionRadius; } @Override public void explode() { - this.getHandle().explodeCreeper(); + getHandle().explodeCreeper(); } @Override @@ -84,7 +85,7 @@ public void ignite(Entity entity) { @Override public void ignite() { - this.getHandle().ignite(); + getHandle().ignite(); } @Override @@ -93,8 +94,8 @@ public Entity getIgniter() { } @Override - public net.minecraft.world.entity.monster.Creeper getHandle() { - return (net.minecraft.world.entity.monster.Creeper) this.entity; + public EntityCreeper getHandle() { + return (EntityCreeper) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDisplay.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDisplay.java index 48eeb1d9..0f70d076 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDisplay.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftDisplay.java @@ -24,7 +24,7 @@ public String toString() { @Override public Transformation getTransformation() { - com.mojang.math.Transformation nms = net.minecraft.world.entity.Display.createTransformation(this.getHandle().getEntityData()); + com.mojang.math.Transformation nms = net.minecraft.world.entity.Display.createTransformation(getHandle().getEntityData()); return new Transformation(nms.getTranslation(), nms.getLeftRotation(), nms.getScale(), nms.getRightRotation()); } @@ -33,24 +33,24 @@ public Transformation getTransformation() { public void setTransformation(Transformation transformation) { Preconditions.checkArgument(transformation != null, "Transformation cannot be null"); - this.getHandle().setTransformation(new com.mojang.math.Transformation(transformation.getTranslation(), transformation.getLeftRotation(), transformation.getScale(), transformation.getRightRotation())); + getHandle().setTransformation(new com.mojang.math.Transformation(transformation.getTranslation(), transformation.getLeftRotation(), transformation.getScale(), transformation.getRightRotation())); } @Override public void setTransformationMatrix(org.joml.Matrix4f transformationMatrix) { Preconditions.checkArgument(transformationMatrix != null, "Transformation matrix cannot be null"); - this.getHandle().setTransformation(new com.mojang.math.Transformation(transformationMatrix)); + getHandle().setTransformation(new com.mojang.math.Transformation(transformationMatrix)); } @Override public int getInterpolationDuration() { - return this.getHandle().getTransformationInterpolationDuration(); + return getHandle().getTransformationInterpolationDuration(); } @Override public void setInterpolationDuration(int duration) { - this.getHandle().setTransformationInterpolationDuration(duration); + getHandle().setTransformationInterpolationDuration(duration); } @Override @@ -66,79 +66,79 @@ public void setTeleportDuration(int duration) { @Override public float getViewRange() { - return this.getHandle().getViewRange(); + return getHandle().getViewRange(); } @Override public void setViewRange(float range) { - this.getHandle().setViewRange(range); + getHandle().setViewRange(range); } @Override public float getShadowRadius() { - return this.getHandle().getShadowRadius(); + return getHandle().getShadowRadius(); } @Override public void setShadowRadius(float radius) { - this.getHandle().setShadowRadius(radius); + getHandle().setShadowRadius(radius); } @Override public float getShadowStrength() { - return this.getHandle().getShadowStrength(); + return getHandle().getShadowStrength(); } @Override public void setShadowStrength(float strength) { - this.getHandle().setShadowStrength(strength); + getHandle().setShadowStrength(strength); } @Override public float getDisplayWidth() { - return this.getHandle().getWidth(); + return getHandle().getWidth(); } @Override public void setDisplayWidth(float width) { - this.getHandle().setWidth(width); + getHandle().setWidth(width); } @Override public float getDisplayHeight() { - return this.getHandle().getHeight(); + return getHandle().getHeight(); } @Override public void setDisplayHeight(float height) { - this.getHandle().setHeight(height); + getHandle().setHeight(height); } @Override public int getInterpolationDelay() { - return this.getHandle().getTransformationInterpolationDelay(); + return getHandle().getTransformationInterpolationDelay(); } @Override public void setInterpolationDelay(int ticks) { - this.getHandle().setTransformationInterpolationDelay(ticks); + getHandle().setTransformationInterpolationDelay(ticks); } @Override public Billboard getBillboard() { - return Billboard.valueOf(this.getHandle().getBillboardConstraints().name()); + return Billboard.valueOf(getHandle().getBillboardConstraints().name()); } @Override public void setBillboard(Billboard billboard) { Preconditions.checkArgument(billboard != null, "Billboard cannot be null"); - this.getHandle().setBillboardConstraints(net.minecraft.world.entity.Display.BillboardConstraints.valueOf(billboard.name())); + getHandle().setBillboardConstraints(net.minecraft.world.entity.Display.BillboardConstraints.valueOf(billboard.name())); } @Override public Color getGlowColorOverride() { - int color = this.getHandle().getGlowColorOverride(); + int color = getHandle().getGlowColorOverride(); return (color == -1) ? null : Color.fromARGB(color); } @@ -146,15 +146,15 @@ public Color getGlowColorOverride() { @Override public void setGlowColorOverride(Color color) { if (color == null) { - this.getHandle().setGlowColorOverride(-1); + getHandle().setGlowColorOverride(-1); } else { - this.getHandle().setGlowColorOverride(color.asARGB()); + getHandle().setGlowColorOverride(color.asARGB()); } } @Override public Brightness getBrightness() { - net.minecraft.util.Brightness nms = this.getHandle().getBrightnessOverride(); + net.minecraft.util.Brightness nms = getHandle().getBrightnessOverride(); return (nms != null) ? new Brightness(nms.block(), nms.sky()) : null; } @@ -162,9 +162,9 @@ public Brightness getBrightness() { @Override public void setBrightness(Brightness brightness) { if (brightness != null) { - this.getHandle().setBrightnessOverride(new net.minecraft.util.Brightness(brightness.getBlockLight(), brightness.getSkyLight())); + getHandle().setBrightnessOverride(new net.minecraft.util.Brightness(brightness.getBlockLight(), brightness.getSkyLight())); } else { - this.getHandle().setBrightnessOverride(null); + getHandle().setBrightnessOverride(null); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java index af432f9a..13ee061e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityDolphin; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Dolphin; -public class CraftDolphin extends CraftWaterMob implements Dolphin { +public class CraftDolphin extends CraftAgeable implements Dolphin { - public CraftDolphin(CraftServer server, net.minecraft.world.entity.animal.Dolphin entity) { + public CraftDolphin(CraftServer server, EntityDolphin entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Dolphin getHandle() { - return (net.minecraft.world.entity.animal.Dolphin) super.getHandle(); + public EntityDolphin getHandle() { + return (EntityDolphin) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java index 955a1c92..9b534229 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.horse.EntityHorseDonkey; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Donkey; import org.bukkit.entity.Horse.Variant; public class CraftDonkey extends CraftChestedHorse implements Donkey { - public CraftDonkey(CraftServer server, net.minecraft.world.entity.animal.horse.Donkey entity) { + public CraftDonkey(CraftServer server, EntityHorseDonkey entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java index b884c6b0..1ab864f3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java @@ -1,10 +1,11 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntityDragonFireball; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.DragonFireball; public class CraftDragonFireball extends CraftFireball implements DragonFireball { - public CraftDragonFireball(CraftServer server, net.minecraft.world.entity.projectile.DragonFireball entity) { + public CraftDragonFireball(CraftServer server, EntityDragonFireball entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java index c0e59845..ea524837 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityDrowned; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Drowned; public class CraftDrowned extends CraftZombie implements Drowned { - public CraftDrowned(CraftServer server, net.minecraft.world.entity.monster.Drowned entity) { + public CraftDrowned(CraftServer server, EntityDrowned entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Drowned getHandle() { - return (net.minecraft.world.entity.monster.Drowned) this.entity; + public EntityDrowned getHandle() { + return (EntityDrowned) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java index 010e9e92..fe3dbd13 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.projectile.ThrownEgg; +import net.minecraft.world.entity.projectile.EntityEgg; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Egg; public class CraftEgg extends CraftThrowableProjectile implements Egg { - public CraftEgg(CraftServer server, ThrownEgg entity) { + public CraftEgg(CraftServer server, EntityEgg entity) { super(server, entity); } @Override - public ThrownEgg getHandle() { - return (ThrownEgg) this.entity; + public EntityEgg getHandle() { + return (EntityEgg) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java index 0e5d7ba2..91d954f6 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java @@ -1,11 +1,12 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityGuardianElder; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.ElderGuardian; public class CraftElderGuardian extends CraftGuardian implements ElderGuardian { - public CraftElderGuardian(CraftServer server, net.minecraft.world.entity.monster.ElderGuardian entity) { + public CraftElderGuardian(CraftServer server, EntityGuardianElder entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java index 676dd533..1292f741 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java @@ -1,47 +1,47 @@ package org.bukkit.craftbukkit.entity; import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.boss.enderdragon.EntityEnderCrystal; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftLocation; import org.bukkit.entity.EnderCrystal; public class CraftEnderCrystal extends CraftEntity implements EnderCrystal { - public CraftEnderCrystal(CraftServer server, EndCrystal entity) { + public CraftEnderCrystal(CraftServer server, EntityEnderCrystal entity) { super(server, entity); } @Override public boolean isShowingBottom() { - return this.getHandle().showsBottom(); + return getHandle().showsBottom(); } @Override public void setShowingBottom(boolean showing) { - this.getHandle().setShowBottom(showing); + getHandle().setShowBottom(showing); } @Override public Location getBeamTarget() { - BlockPos pos = this.getHandle().getBeamTarget(); - return pos == null ? null : CraftLocation.toBukkit(pos, this.getWorld()); + BlockPos pos = getHandle().getBeamTarget(); + return pos == null ? null : CraftLocation.toBukkit(pos, getWorld()); } @Override public void setBeamTarget(Location location) { if (location == null) { - this.getHandle().setBeamTarget((BlockPos) null); - } else if (location.getWorld() != this.getWorld()) { + getHandle().setBeamTarget((BlockPos) null); + } else if (location.getWorld() != getWorld()) { throw new IllegalArgumentException("Cannot set beam target location to different world"); } else { - this.getHandle().setBeamTarget(CraftLocation.toBlockPosition(location)); + getHandle().setBeamTarget(CraftLocation.toBlockPos(location)); } } @Override - public EndCrystal getHandle() { - return (EndCrystal) this.entity; + public EntityEnderCrystal getHandle() { + return (EntityEnderCrystal) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java index 25b3d889..e676b2ef 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java @@ -3,8 +3,9 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import java.util.Set; -import net.minecraft.world.entity.boss.EnderDragonPart; -import net.minecraft.world.entity.boss.enderdragon.phases.EnderDragonPhase; +import net.minecraft.world.entity.boss.EntityComplexPart; +import net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon; +import net.minecraft.world.entity.boss.enderdragon.phases.DragonControllerPhase; import org.bukkit.boss.BossBar; import org.bukkit.boss.DragonBattle; import org.bukkit.craftbukkit.CraftServer; @@ -15,7 +16,7 @@ public class CraftEnderDragon extends CraftMob implements EnderDragon, CraftEnemy { - public CraftEnderDragon(CraftServer server, net.minecraft.world.entity.boss.enderdragon.EnderDragon entity) { + public CraftEnderDragon(CraftServer server, EntityEnderDragon entity) { super(server, entity); } @@ -23,7 +24,7 @@ public CraftEnderDragon(CraftServer server, net.minecraft.world.entity.boss.ende public Set getParts() { Builder builder = ImmutableSet.builder(); - for (EnderDragonPart part : this.getHandle().subEntities) { + for (EntityComplexPart part : getHandle().subEntities) { builder.add((ComplexEntityPart) part.getBukkitEntity()); } @@ -31,8 +32,8 @@ public Set getParts() { } @Override - public net.minecraft.world.entity.boss.enderdragon.EnderDragon getHandle() { - return (net.minecraft.world.entity.boss.enderdragon.EnderDragon) this.entity; + public EntityEnderDragon getHandle() { + return (EntityEnderDragon) entity; } @Override @@ -42,35 +43,35 @@ public String toString() { @Override public Phase getPhase() { - return Phase.values()[this.getHandle().getEntityData().get(net.minecraft.world.entity.boss.enderdragon.EnderDragon.DATA_PHASE)]; + return Phase.values()[getHandle().getEntityData().get(EntityEnderDragon.DATA_PHASE)]; } @Override public void setPhase(Phase phase) { - this.getHandle().getPhaseManager().setPhase(CraftEnderDragon.getMinecraftPhase(phase)); + getHandle().getPhaseManager().setPhase(getMinecraftPhase(phase)); } - public static Phase getBukkitPhase(EnderDragonPhase phase) { + public static Phase getBukkitPhase(DragonControllerPhase phase) { return Phase.values()[phase.getId()]; } - public static EnderDragonPhase getMinecraftPhase(Phase phase) { - return EnderDragonPhase.getById(phase.ordinal()); + public static DragonControllerPhase getMinecraftPhase(Phase phase) { + return DragonControllerPhase.getById(phase.ordinal()); } @Override public BossBar getBossBar() { - DragonBattle battle = this.getDragonBattle(); + DragonBattle battle = getDragonBattle(); return battle != null ? battle.getBossBar() : null; } @Override public DragonBattle getDragonBattle() { - return this.getHandle().getDragonFight() != null ? new CraftDragonBattle(this.getHandle().getDragonFight()) : null; + return getHandle().getDragonFight() != null ? new CraftDragonBattle(getHandle().getDragonFight()) : null; } @Override public int getDeathAnimationTicks() { - return this.getHandle().dragonDeathTime; + return getHandle().dragonDeathTime; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java index cc4194ac..d4000873 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.boss.EntityComplexPart; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.damage.DamageSource; import org.bukkit.entity.EnderDragon; @@ -7,7 +8,7 @@ import org.bukkit.entity.Entity; public class CraftEnderDragonPart extends CraftComplexPart implements EnderDragonPart { - public CraftEnderDragonPart(CraftServer server, net.minecraft.world.entity.boss.EnderDragonPart entity) { + public CraftEnderDragonPart(CraftServer server, EntityComplexPart entity) { super(server, entity); } @@ -17,8 +18,8 @@ public EnderDragon getParent() { } @Override - public net.minecraft.world.entity.boss.EnderDragonPart getHandle() { - return (net.minecraft.world.entity.boss.EnderDragonPart) this.entity; + public EntityComplexPart getHandle() { + return (EntityComplexPart) entity; } @Override @@ -28,51 +29,51 @@ public String toString() { @Override public void damage(double amount, DamageSource damageSource) { - this.getParent().damage(amount, damageSource); + getParent().damage(amount, damageSource); } @Override public void damage(double amount) { - this.getParent().damage(amount); + getParent().damage(amount); } @Override public void damage(double amount, Entity source) { - this.getParent().damage(amount, source); + getParent().damage(amount, source); } @Override public double getHealth() { - return this.getParent().getHealth(); + return getParent().getHealth(); } @Override public void setHealth(double health) { - this.getParent().setHealth(health); + getParent().setHealth(health); } @Override public double getAbsorptionAmount() { - return this.getParent().getAbsorptionAmount(); + return getParent().getAbsorptionAmount(); } @Override public void setAbsorptionAmount(double amount) { - this.getParent().setAbsorptionAmount(amount); + getParent().setAbsorptionAmount(amount); } @Override public double getMaxHealth() { - return this.getParent().getMaxHealth(); + return getParent().getMaxHealth(); } @Override public void setMaxHealth(double health) { - this.getParent().setMaxHealth(health); + getParent().setMaxHealth(health); } @Override public void resetMaxHealth() { - this.getParent().resetMaxHealth(); + getParent().resetMaxHealth(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java index 3bb8d74f..5d7e5f79 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.projectile.ThrownEnderpearl; +import net.minecraft.world.entity.projectile.EntityEnderPearl; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.EnderPearl; public class CraftEnderPearl extends CraftThrowableProjectile implements EnderPearl { - public CraftEnderPearl(CraftServer server, ThrownEnderpearl entity) { + public CraftEnderPearl(CraftServer server, EntityEnderPearl entity) { super(server, entity); } @Override - public ThrownEnderpearl getHandle() { - return (ThrownEnderpearl) this.entity; + public EntityEnderPearl getHandle() { + return (EntityEnderPearl) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java index d4dfc7a0..9cb13e32 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.projectile.EyeOfEnder; +import net.minecraft.world.entity.projectile.EntityEnderSignal; import net.minecraft.world.item.Items; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; @@ -11,13 +11,13 @@ import org.bukkit.inventory.ItemStack; public class CraftEnderSignal extends CraftEntity implements EnderSignal { - public CraftEnderSignal(CraftServer server, EyeOfEnder entity) { + public CraftEnderSignal(CraftServer server, EntityEnderSignal entity) { super(server, entity); } @Override - public EyeOfEnder getHandle() { - return (EyeOfEnder) this.entity; + public EntityEnderSignal getHandle() { + return (EntityEnderSignal) entity; } @Override @@ -27,42 +27,42 @@ public String toString() { @Override public Location getTargetLocation() { - return new Location(this.getWorld(), this.getHandle().tx, this.getHandle().ty, this.getHandle().tz, this.getHandle().getYRot(), this.getHandle().getXRot()); + return new Location(getWorld(), getHandle().tx, getHandle().ty, getHandle().tz, getHandle().getYRot(), getHandle().getXRot()); } @Override public void setTargetLocation(Location location) { - Preconditions.checkArgument(this.getWorld().equals(location.getWorld()), "Cannot target EnderSignal across worlds"); - this.getHandle().signalTo(CraftLocation.toBlockPosition(location)); + Preconditions.checkArgument(getWorld().equals(location.getWorld()), "Cannot target EnderSignal across worlds"); + getHandle().signalTo(CraftLocation.toBlockPos(location)); } @Override public boolean getDropItem() { - return this.getHandle().surviveAfterDeath; + return getHandle().surviveAfterDeath; } @Override public void setDropItem(boolean shouldDropItem) { - this.getHandle().surviveAfterDeath = shouldDropItem; + getHandle().surviveAfterDeath = shouldDropItem; } @Override public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getHandle().getItem()); + return CraftItemStack.asBukkitCopy(getHandle().getItem()); } @Override public void setItem(ItemStack item) { - this.getHandle().setItem(item != null ? CraftItemStack.asNMSCopy(item) : Items.ENDER_EYE.getDefaultInstance()); + getHandle().setItem(item != null ? CraftItemStack.asNMSCopy(item) : Items.ENDER_EYE.getDefaultInstance()); } @Override public int getDespawnTimer() { - return this.getHandle().life; + return getHandle().life; } @Override public void setDespawnTimer(int time) { - this.getHandle().life = time; + getHandle().life = time; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java index 9074ef54..05441b86 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.monster.EnderMan; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.entity.monster.EntityEnderman; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Material; import org.bukkit.block.data.BlockData; import org.bukkit.craftbukkit.CraftServer; @@ -13,35 +13,35 @@ import org.bukkit.material.MaterialData; public class CraftEnderman extends CraftMonster implements Enderman { - public CraftEnderman(CraftServer server, EnderMan entity) { + public CraftEnderman(CraftServer server, EntityEnderman entity) { super(server, entity); } @Override public MaterialData getCarriedMaterial() { - BlockState blockData = this.getHandle().getCarriedBlock(); + IBlockData blockData = getHandle().getCarriedBlock(); return (blockData == null) ? Material.AIR.getNewData((byte) 0) : CraftMagicNumbers.getMaterial(blockData); } @Override public BlockData getCarriedBlock() { - BlockState blockData = this.getHandle().getCarriedBlock(); + IBlockData blockData = getHandle().getCarriedBlock(); return (blockData == null) ? null : CraftBlockData.fromData(blockData); } @Override public void setCarriedMaterial(MaterialData data) { - this.getHandle().setCarriedBlock(CraftMagicNumbers.getBlock(data)); + getHandle().setCarriedBlock(CraftMagicNumbers.getBlock(data)); } @Override public void setCarriedBlock(BlockData blockData) { - this.getHandle().setCarriedBlock(blockData == null ? null : ((CraftBlockData) blockData).getState()); + getHandle().setCarriedBlock(blockData == null ? null : ((CraftBlockData) blockData).getState()); } @Override - public EnderMan getHandle() { - return (EnderMan) this.entity; + public EntityEnderman getHandle() { + return (EntityEnderman) entity; } @Override @@ -51,13 +51,13 @@ public String toString() { @Override public boolean teleport() { - return this.getHandle().teleport(); + return getHandle().teleport(); } @Override public boolean teleportTowards(Entity entity) { Preconditions.checkArgument(entity != null, "entity cannot be null"); - return this.getHandle().teleportTowards(((CraftEntity) entity).getHandle()); + return getHandle().teleportTowards(((CraftEntity) entity).getHandle()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java index fc0f0e84..bb72a1a7 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityEndermite; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Endermite; public class CraftEndermite extends CraftMonster implements Endermite { - public CraftEndermite(CraftServer server, net.minecraft.world.entity.monster.Endermite entity) { + public CraftEndermite(CraftServer server, EntityEndermite entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Endermite getHandle() { - return (net.minecraft.world.entity.monster.Endermite) super.getHandle(); + public EntityEndermite getHandle() { + return (EntityEndermite) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnemy.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnemy.java index 123979a0..f17df438 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnemy.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnemy.java @@ -1,8 +1,9 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.IMonster; import org.bukkit.entity.Enemy; public interface CraftEnemy extends Enemy { - net.minecraft.world.entity.monster.Enemy getHandle(); + IMonster getHandle(); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java index f11faff5..1ffd1152 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java @@ -4,31 +4,27 @@ import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; import com.google.common.collect.Lists; -import com.mohistmc.youer.bukkit.entity.MohistModsEntity; -import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ChunkMap; -import net.minecraft.server.level.ChunkMap.TrackedEntity; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.server.level.PlayerChunkMap; +import net.minecraft.server.level.WorldServer; import net.minecraft.server.network.ServerPlayerConnection; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.boss.EnderDragonPart; -import net.minecraft.world.entity.boss.enderdragon.EnderDragon; -import net.minecraft.world.entity.projectile.AbstractArrow; -import net.minecraft.world.entity.vehicle.VehicleEntity; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.portal.DimensionTransition; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.boss.EntityComplexPart; +import net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.entity.projectile.EntityArrow; +import net.minecraft.world.level.portal.TeleportTransition; +import net.minecraft.world.phys.AxisAlignedBB; +import net.minecraft.world.phys.Vec3D; import org.bukkit.EntityEffect; import org.bukkit.Location; import org.bukkit.Server; @@ -40,7 +36,6 @@ import org.bukkit.craftbukkit.CraftSound; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.entity.CraftEntityTypes.EntityTypeData; import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry; import org.bukkit.craftbukkit.util.CraftChatMessage; @@ -54,7 +49,6 @@ import org.bukkit.entity.SpawnCategory; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityRemoveEvent; -import org.bukkit.event.entity.EntityRemoveEvent.Cause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.metadata.MetadataValue; import org.bukkit.permissions.PermissibleBase; @@ -67,9 +61,6 @@ import org.bukkit.util.NumberConversions; import org.bukkit.util.Vector; -import net.md_5.bungee.api.chat.BaseComponent; // Spigot -import org.spigotmc.AsyncCatcher; - public abstract class CraftEntity implements org.bukkit.entity.Entity { private static PermissibleBase perm; private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry(); @@ -78,7 +69,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { protected Entity entity; private final EntityType entityType; private EntityDamageEvent lastDamageEvent; - private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(CraftEntity.DATA_TYPE_REGISTRY); + private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(DATA_TYPE_REGISTRY); public CraftEntity(final CraftServer server, final Entity entity) { this.server = server; @@ -90,53 +81,42 @@ public static CraftEntity getEntity(CraftServer server, T ent Preconditions.checkArgument(entity != null, "Unknown entity"); // Special case human, since bukkit use Player interface for ... - if (entity instanceof net.minecraft.world.entity.player.Player && !(entity instanceof ServerPlayer)) { - return new CraftHumanEntity(server, (net.minecraft.world.entity.player.Player) entity); + if (entity instanceof EntityHuman && !(entity instanceof EntityPlayer)) { + return new CraftHumanEntity(server, (EntityHuman) entity); } // Special case complex part, since there is no extra entity type for them - if (entity instanceof EnderDragonPart complexPart) { - if (complexPart.parentMob instanceof EnderDragon) { + if (entity instanceof EntityComplexPart complexPart) { + if (complexPart.parentMob instanceof EntityEnderDragon) { return new CraftEnderDragonPart(server, complexPart); } else { return new CraftComplexPart(server, complexPart); } } - EntityTypeData entityTypeData = CraftEntityTypes.getEntityTypeData(CraftEntityType.minecraftToBukkit(entity.getType())); + CraftEntityTypes.EntityTypeData entityTypeData = CraftEntityTypes.getEntityTypeData(CraftEntityType.minecraftToBukkit(entity.getType())); if (entityTypeData != null) { return (CraftEntity) entityTypeData.convertFunction().apply(server, entity); } - - CraftEntity modsEntity = null; - switch (entity) { - case VehicleEntity vehicle -> modsEntity = new MohistModsVehicle(server, vehicle); - case LivingEntity livingEntity -> modsEntity = new CraftLivingEntity(server, livingEntity); - case Entity entity1 -> modsEntity = new MohistModsEntity(server, entity1); - } - - if (modsEntity != null) { - return modsEntity; - } throw new AssertionError("Unknown entity " + (entity == null ? null : entity.getClass())); } @Override public Location getLocation() { - return CraftLocation.toBukkit(this.entity.position(), this.getWorld(), this.entity.getBukkitYaw(), this.entity.getXRot()); + return CraftLocation.toBukkit(entity.position(), getWorld(), entity.getBukkitYaw(), entity.getXRot()); } @Override public Location getLocation(Location loc) { if (loc != null) { - loc.setWorld(this.getWorld()); - loc.setX(this.entity.getX()); - loc.setY(this.entity.getY()); - loc.setZ(this.entity.getZ()); - loc.setYaw(this.entity.getBukkitYaw()); - loc.setPitch(this.entity.getXRot()); + loc.setWorld(getWorld()); + loc.setX(entity.getX()); + loc.setY(entity.getY()); + loc.setZ(entity.getZ()); + loc.setYaw(entity.getBukkitYaw()); + loc.setPitch(entity.getXRot()); } return loc; @@ -144,49 +124,49 @@ public Location getLocation(Location loc) { @Override public Vector getVelocity() { - return CraftVector.toBukkit(this.entity.getDeltaMovement()); + return CraftVector.toBukkit(entity.getDeltaMovement()); } @Override public void setVelocity(Vector velocity) { Preconditions.checkArgument(velocity != null, "velocity"); velocity.checkFinite(); - this.entity.setDeltaMovement(CraftVector.toNMS(velocity)); - this.entity.hurtMarked = true; + entity.setDeltaMovement(CraftVector.toNMS(velocity)); + entity.hurtMarked = true; } @Override public double getHeight() { - return this.getHandle().getBbHeight(); + return getHandle().getBbHeight(); } @Override public double getWidth() { - return this.getHandle().getBbWidth(); + return getHandle().getBbWidth(); } @Override public BoundingBox getBoundingBox() { - AABB bb = this.getHandle().getBoundingBox(); + AxisAlignedBB bb = getHandle().getBoundingBox(); return new BoundingBox(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); } @Override public boolean isOnGround() { - if (this.entity instanceof AbstractArrow) { - return ((AbstractArrow) this.entity).inGround; + if (entity instanceof EntityArrow) { + return ((EntityArrow) entity).isInGround(); } - return this.entity.onGround(); + return entity.onGround(); } @Override public boolean isInWater() { - return this.entity.isInWater(); + return entity.isInWater(); } @Override public World getWorld() { - return this.entity.level().getWorld(); + return entity.level().getWorld(); } @Override @@ -197,16 +177,16 @@ public void setRotation(float yaw, float pitch) { yaw = Location.normalizeYaw(yaw); pitch = Location.normalizePitch(pitch); - this.entity.setYRot(yaw); - this.entity.setXRot(pitch); - this.entity.yRotO = yaw; - this.entity.xRotO = pitch; - this.entity.setYHeadRot(yaw); + entity.setYRot(yaw); + entity.setXRot(pitch); + entity.yRotO = yaw; + entity.xRotO = pitch; + entity.setYHeadRot(yaw); } @Override public boolean teleport(Location location) { - return this.teleport(location, TeleportCause.PLUGIN); + return teleport(location, TeleportCause.PLUGIN); } @Override @@ -214,47 +194,45 @@ public boolean teleport(Location location, TeleportCause cause) { Preconditions.checkArgument(location != null, "location cannot be null"); location.checkFinite(); - if (this.entity.isVehicle() || this.entity.isRemoved()) { + if (entity.isVehicle() || entity.isRemoved()) { return false; } // If this entity is riding another entity, we must dismount before teleporting. - this.entity.stopRiding(); + entity.stopRiding(); // Let the server handle cross world teleports - if (location.getWorld() != null && !location.getWorld().equals(this.getWorld())) { + if (location.getWorld() != null && !location.getWorld().equals(getWorld())) { // Prevent teleportation to an other world during world generation - Preconditions.checkState(!this.entity.generation, "Cannot teleport entity to an other world during world generation"); - // Mohist TODO - // this.entity.changeDimension(new DimensionTransition(((CraftWorld) location.getWorld()).getHandle(), CraftLocation.toVec3D(location), Vec3.ZERO, location.getPitch(), location.getYaw(), DimensionTransition.DO_NOTHING, TeleportCause.PLUGIN)); + Preconditions.checkState(!entity.generation, "Cannot teleport entity to an other world during world generation"); + entity.teleport(new TeleportTransition(((CraftWorld) location.getWorld()).getHandle(), CraftLocation.toVec3D(location), Vec3D.ZERO, location.getPitch(), location.getYaw(), Set.of(), TeleportTransition.DO_NOTHING, TeleportCause.PLUGIN)); return true; } // entity.setLocation() throws no event, and so cannot be cancelled - this.entity.absMoveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + entity.absMoveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); // SPIGOT-619: Force sync head rotation also - this.entity.setYHeadRot(location.getYaw()); + entity.setYHeadRot(location.getYaw()); return true; } @Override public boolean teleport(org.bukkit.entity.Entity destination) { - return this.teleport(destination.getLocation()); + return teleport(destination.getLocation()); } @Override public boolean teleport(org.bukkit.entity.Entity destination, TeleportCause cause) { - return this.teleport(destination.getLocation(), cause); + return teleport(destination.getLocation(), cause); } @Override public List getNearbyEntities(double x, double y, double z) { - Preconditions.checkState(!this.entity.generation, "Cannot get nearby entities during world generation"); - AsyncCatcher.catchOp("getNearbyEntities"); // Spigot + Preconditions.checkState(!entity.generation, "Cannot get nearby entities during world generation"); - List notchEntityList = this.entity.level().getEntities(this.entity, this.entity.getBoundingBox().inflate(x, y, z), Predicates.alwaysTrue()); - List bukkitEntityList = new ArrayList(notchEntityList.size()); + List notchEntityList = entity.level().getEntities(entity, entity.getBoundingBox().inflate(x, y, z), Predicates.alwaysTrue()); + List bukkitEntityList = new java.util.ArrayList(notchEntityList.size()); for (Entity e : notchEntityList) { bukkitEntityList.add(e.getBukkitEntity()); @@ -264,106 +242,106 @@ public List getNearbyEntities(double x, double y, doub @Override public int getEntityId() { - return this.entity.getId(); + return entity.getId(); } @Override public int getFireTicks() { - return this.entity.getRemainingFireTicks(); + return entity.getRemainingFireTicks(); } @Override public int getMaxFireTicks() { - return this.entity.getFireImmuneTicks(); + return entity.getFireImmuneTicks(); } @Override public void setFireTicks(int ticks) { - this.entity.setRemainingFireTicks(ticks); + entity.setRemainingFireTicks(ticks); } @Override public void setVisualFire(boolean fire) { - this.getHandle().hasVisualFire = fire; + getHandle().hasVisualFire = fire; } @Override public boolean isVisualFire() { - return this.getHandle().hasVisualFire; + return getHandle().hasVisualFire; } @Override public int getFreezeTicks() { - return this.getHandle().getTicksFrozen(); + return getHandle().getTicksFrozen(); } @Override public int getMaxFreezeTicks() { - return this.getHandle().getTicksRequiredToFreeze(); + return getHandle().getTicksRequiredToFreeze(); } @Override public void setFreezeTicks(int ticks) { Preconditions.checkArgument(0 <= ticks, "Ticks (%s) cannot be less than 0", ticks); - this.getHandle().setTicksFrozen(ticks); + getHandle().setTicksFrozen(ticks); } @Override public boolean isFrozen() { - return this.getHandle().isFullyFrozen(); + return getHandle().isFullyFrozen(); } @Override public void remove() { - this.entity.pluginRemoved = true; - this.entity.discard(this.getHandle().generation ? null : Cause.PLUGIN); + entity.pluginRemoved = true; + entity.discard(getHandle().generation ? null : EntityRemoveEvent.Cause.PLUGIN); } @Override public boolean isDead() { - return !this.entity.isAlive(); + return !entity.isAlive(); } @Override public boolean isValid() { - return this.entity.isAlive() && this.entity.valid && this.entity.isChunkLoaded() && this.isInWorld(); + return entity.isAlive() && entity.valid && entity.isChunkLoaded() && isInWorld(); } @Override public Server getServer() { - return this.server; + return server; } @Override public boolean isPersistent() { - return this.entity.persist; + return entity.persist; } @Override public void setPersistent(boolean persistent) { - this.entity.persist = persistent; + entity.persist = persistent; } public Vector getMomentum() { - return this.getVelocity(); + return getVelocity(); } public void setMomentum(Vector value) { - this.setVelocity(value); + setVelocity(value); } @Override public org.bukkit.entity.Entity getPassenger() { - return this.isEmpty() ? null : this.getHandle().passengers.get(0).getBukkitEntity(); + return isEmpty() ? null : getHandle().passengers.get(0).getBukkitEntity(); } @Override public boolean setPassenger(org.bukkit.entity.Entity passenger) { Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself."); if (passenger instanceof CraftEntity) { - this.eject(); - return ((CraftEntity) passenger).getHandle().startRiding(this.getHandle()); + eject(); + return ((CraftEntity) passenger).getHandle().startRiding(getHandle()); } else { return false; } @@ -371,7 +349,7 @@ public boolean setPassenger(org.bukkit.entity.Entity passenger) { @Override public List getPassengers() { - return Lists.newArrayList(Lists.transform(this.getHandle().passengers, (Function) input -> input.getBukkitEntity())); + return Lists.newArrayList(Lists.transform(getHandle().passengers, (Function) input -> input.getBukkitEntity())); } @Override @@ -379,7 +357,7 @@ public boolean addPassenger(org.bukkit.entity.Entity passenger) { Preconditions.checkArgument(passenger != null, "Entity passenger cannot be null"); Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself."); - return ((CraftEntity) passenger).getHandle().startRiding(this.getHandle(), true); + return ((CraftEntity) passenger).getHandle().startRiding(getHandle(), true); } @Override @@ -392,87 +370,87 @@ public boolean removePassenger(org.bukkit.entity.Entity passenger) { @Override public boolean isEmpty() { - return !this.getHandle().isVehicle(); + return !getHandle().isVehicle(); } @Override public boolean eject() { - if (this.isEmpty()) { + if (isEmpty()) { return false; } - this.getHandle().ejectPassengers(); + getHandle().ejectPassengers(); return true; } @Override public float getFallDistance() { - return this.getHandle().fallDistance; + return getHandle().fallDistance; } @Override public void setFallDistance(float distance) { - this.getHandle().fallDistance = distance; + getHandle().fallDistance = distance; } @Override public void setLastDamageCause(EntityDamageEvent event) { - this.lastDamageEvent = event; + lastDamageEvent = event; } @Override public EntityDamageEvent getLastDamageCause() { - return this.lastDamageEvent; + return lastDamageEvent; } @Override public UUID getUniqueId() { - return this.getHandle().getUUID(); + return getHandle().getUUID(); } @Override public int getTicksLived() { - return this.getHandle().tickCount; + return getHandle().tickCount; } @Override public void setTicksLived(int value) { Preconditions.checkArgument(value > 0, "Age value (%s) must be greater than 0", value); - this.getHandle().tickCount = value; + getHandle().tickCount = value; } public Entity getHandle() { - return this.entity; + return entity; } @Override public final EntityType getType() { - return this.entityType; + return entityType; } @Override public void playEffect(EntityEffect type) { Preconditions.checkArgument(type != null, "Type cannot be null"); - Preconditions.checkState(!this.entity.generation, "Cannot play effect during world generation"); + Preconditions.checkState(!entity.generation, "Cannot play effect during world generation"); if (type.getApplicable().isInstance(this)) { - this.getHandle().level().broadcastEntityEvent(this.getHandle(), type.getData()); + this.getHandle().level().broadcastEntityEvent(getHandle(), type.getData()); } } @Override public Sound getSwimSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getSwimSound0()); + return CraftSound.minecraftToBukkit(getHandle().getSwimSound0()); } @Override public Sound getSwimSplashSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getSwimSplashSound0()); + return CraftSound.minecraftToBukkit(getHandle().getSwimSplashSound0()); } @Override public Sound getSwimHighSpeedSplashSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getSwimHighSpeedSplashSound0()); + return CraftSound.minecraftToBukkit(getHandle().getSwimHighSpeedSplashSound0()); } public void setHandle(final Entity entity) { @@ -481,7 +459,7 @@ public void setHandle(final Entity entity) { @Override public String toString() { - return "CraftEntity{" + "id=" + this.getEntityId() + '}'; + return "CraftEntity{" + "id=" + getEntityId() + '}'; } @Override @@ -489,7 +467,7 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (this.getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final CraftEntity other = (CraftEntity) obj; @@ -505,46 +483,46 @@ public int hashCode() { @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - this.server.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue); + server.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List getMetadata(String metadataKey) { - return this.server.getEntityMetadata().getMetadata(this, metadataKey); + return server.getEntityMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { - return this.server.getEntityMetadata().hasMetadata(this, metadataKey); + return server.getEntityMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { - this.server.getEntityMetadata().removeMetadata(this, metadataKey, owningPlugin); + server.getEntityMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override public boolean isInsideVehicle() { - return this.getHandle().isPassenger(); + return getHandle().isPassenger(); } @Override public boolean leaveVehicle() { - if (!this.isInsideVehicle()) { + if (!isInsideVehicle()) { return false; } - this.getHandle().stopRiding(); + getHandle().stopRiding(); return true; } @Override public org.bukkit.entity.Entity getVehicle() { - if (!this.isInsideVehicle()) { + if (!isInsideVehicle()) { return null; } - return this.getHandle().getVehicle().getBukkitEntity(); + return getHandle().getVehicle().getBukkitEntity(); } @Override @@ -554,12 +532,12 @@ public void setCustomName(String name) { name = name.substring(0, 256); } - this.getHandle().setCustomName(CraftChatMessage.fromStringOrNull(name)); + getHandle().setCustomName(CraftChatMessage.fromStringOrNull(name)); } @Override public String getCustomName() { - Component name = this.getHandle().getCustomName(); + IChatBaseComponent name = getHandle().getCustomName(); if (name == null) { return null; @@ -570,45 +548,45 @@ public String getCustomName() { @Override public void setCustomNameVisible(boolean flag) { - this.getHandle().setCustomNameVisible(flag); + getHandle().setCustomNameVisible(flag); } @Override public boolean isCustomNameVisible() { - return this.getHandle().isCustomNameVisible(); + return getHandle().isCustomNameVisible(); } @Override public void setVisibleByDefault(boolean visible) { - if (this.getHandle().visibleByDefault != visible) { + if (getHandle().visibleByDefault != visible) { if (visible) { // Making visible by default, reset and show to all players - for (Player player : this.server.getOnlinePlayers()) { + for (Player player : server.getOnlinePlayers()) { ((CraftPlayer) player).resetAndShowEntity(this); } } else { // Hiding by default, reset and hide from all players - for (Player player : this.server.getOnlinePlayers()) { + for (Player player : server.getOnlinePlayers()) { ((CraftPlayer) player).resetAndHideEntity(this); } } - this.getHandle().visibleByDefault = visible; + getHandle().visibleByDefault = visible; } } @Override public boolean isVisibleByDefault() { - return this.getHandle().visibleByDefault; + return getHandle().visibleByDefault; } @Override public Set getTrackedBy() { - Preconditions.checkState(!this.entity.generation, "Cannot get tracking players during world generation"); - Builder players = ImmutableSet.builder(); + Preconditions.checkState(!entity.generation, "Cannot get tracking players during world generation"); + ImmutableSet.Builder players = ImmutableSet.builder(); - ServerLevel world = ((CraftWorld) this.getWorld()).getHandle(); - TrackedEntity entityTracker = world.getChunkSource().chunkMap.entityMap.get(this.getEntityId()); + WorldServer world = ((CraftWorld) getWorld()).getHandle(); + PlayerChunkMap.EntityTracker entityTracker = world.getChunkSource().chunkMap.entityMap.get(getEntityId()); if (entityTracker != null) { for (ServerPlayerConnection connection : entityTracker.seenBy) { @@ -641,12 +619,12 @@ public void sendMessage(UUID sender, String... messages) { @Override public String getName() { - return CraftChatMessage.fromComponent(this.getHandle().getName()); + return CraftChatMessage.fromComponent(getHandle().getName()); } @Override public boolean isPermissionSet(String name) { - return CraftEntity.getPermissibleBase().isPermissionSet(name); + return getPermissibleBase().isPermissionSet(name); } @Override @@ -656,159 +634,159 @@ public boolean isPermissionSet(Permission perm) { @Override public boolean hasPermission(String name) { - return CraftEntity.getPermissibleBase().hasPermission(name); + return getPermissibleBase().hasPermission(name); } @Override public boolean hasPermission(Permission perm) { - return CraftEntity.getPermissibleBase().hasPermission(perm); + return getPermissibleBase().hasPermission(perm); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return CraftEntity.getPermissibleBase().addAttachment(plugin, name, value); + return getPermissibleBase().addAttachment(plugin, name, value); } @Override public PermissionAttachment addAttachment(Plugin plugin) { - return CraftEntity.getPermissibleBase().addAttachment(plugin); + return getPermissibleBase().addAttachment(plugin); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return CraftEntity.getPermissibleBase().addAttachment(plugin, name, value, ticks); + return getPermissibleBase().addAttachment(plugin, name, value, ticks); } @Override public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return CraftEntity.getPermissibleBase().addAttachment(plugin, ticks); + return getPermissibleBase().addAttachment(plugin, ticks); } @Override public void removeAttachment(PermissionAttachment attachment) { - CraftEntity.getPermissibleBase().removeAttachment(attachment); + getPermissibleBase().removeAttachment(attachment); } @Override public void recalculatePermissions() { - CraftEntity.getPermissibleBase().recalculatePermissions(); + getPermissibleBase().recalculatePermissions(); } @Override public Set getEffectivePermissions() { - return CraftEntity.getPermissibleBase().getEffectivePermissions(); + return getPermissibleBase().getEffectivePermissions(); } @Override public boolean isOp() { - return CraftEntity.getPermissibleBase().isOp(); + return getPermissibleBase().isOp(); } @Override public void setOp(boolean value) { - CraftEntity.getPermissibleBase().setOp(value); + getPermissibleBase().setOp(value); } @Override public void setGlowing(boolean flag) { - this.getHandle().setGlowingTag(flag); + getHandle().setGlowingTag(flag); } @Override public boolean isGlowing() { - return this.getHandle().isCurrentlyGlowing(); + return getHandle().isCurrentlyGlowing(); } @Override public void setInvulnerable(boolean flag) { - this.getHandle().setInvulnerable(flag); + getHandle().setInvulnerable(flag); } @Override public boolean isInvulnerable() { - return this.getHandle().isInvulnerableTo(this.getHandle().damageSources().generic()); + return getHandle().isInvulnerableToBase(getHandle().damageSources().generic()); } @Override public boolean isSilent() { - return this.getHandle().isSilent(); + return getHandle().isSilent(); } @Override public void setSilent(boolean flag) { - this.getHandle().setSilent(flag); + getHandle().setSilent(flag); } @Override public boolean hasGravity() { - return !this.getHandle().isNoGravity(); + return !getHandle().isNoGravity(); } @Override public void setGravity(boolean gravity) { - this.getHandle().setNoGravity(!gravity); + getHandle().setNoGravity(!gravity); } @Override public int getPortalCooldown() { - return this.getHandle().portalCooldown; + return getHandle().portalCooldown; } @Override public void setPortalCooldown(int cooldown) { - this.getHandle().portalCooldown = cooldown; + getHandle().portalCooldown = cooldown; } @Override public Set getScoreboardTags() { - return this.getHandle().getTags(); + return getHandle().getTags(); } @Override public boolean addScoreboardTag(String tag) { - return this.getHandle().addTag(tag); + return getHandle().addTag(tag); } @Override public boolean removeScoreboardTag(String tag) { - return this.getHandle().removeTag(tag); + return getHandle().removeTag(tag); } @Override public PistonMoveReaction getPistonMoveReaction() { - return PistonMoveReaction.getById(this.getHandle().getPistonPushReaction().ordinal()); + return PistonMoveReaction.getById(getHandle().getPistonPushReaction().ordinal()); } @Override public BlockFace getFacing() { // Use this method over getDirection because it handles boats and minecarts. - return CraftBlock.notchToBlockFace(this.getHandle().getMotionDirection()); + return CraftBlock.notchToBlockFace(getHandle().getMotionDirection()); } @Override public CraftPersistentDataContainer getPersistentDataContainer() { - return this.persistentDataContainer; + return persistentDataContainer; } @Override public Pose getPose() { - return Pose.values()[this.getHandle().getPose().ordinal()]; + return Pose.values()[getHandle().getPose().ordinal()]; } @Override public SpawnCategory getSpawnCategory() { - return CraftSpawnCategory.toBukkit(this.getHandle().getType().getCategory()); + return CraftSpawnCategory.toBukkit(getHandle().getType().getCategory()); } @Override public boolean isInWorld() { - return this.getHandle().inWorld; + return getHandle().inWorld; } @Override public String getAsString() { - CompoundTag tag = new CompoundTag(); - if (!this.getHandle().saveAsPassenger(tag, false)) { + NBTTagCompound tag = new NBTTagCompound(); + if (!getHandle().saveAsPassenger(tag, false)) { return null; } @@ -822,7 +800,7 @@ public EntitySnapshot createSnapshot() { @Override public org.bukkit.entity.Entity copy() { - Entity copy = this.copy(this.getHandle().level()); + Entity copy = copy(getHandle().level()); Preconditions.checkArgument(copy != null, "Error creating new entity."); return copy.getBukkitEntity(); @@ -832,50 +810,50 @@ public org.bukkit.entity.Entity copy() { public org.bukkit.entity.Entity copy(Location location) { Preconditions.checkArgument(location.getWorld() != null, "Location has no world"); - Entity copy = this.copy(((CraftWorld) location.getWorld()).getHandle()); + Entity copy = copy(((CraftWorld) location.getWorld()).getHandle()); Preconditions.checkArgument(copy != null, "Error creating new entity."); copy.setPos(location.getX(), location.getY(), location.getZ()); return location.getWorld().addEntity(copy.getBukkitEntity()); } - private Entity copy(Level level) { - CompoundTag compoundTag = new CompoundTag(); - this.getHandle().saveAsPassenger(compoundTag, false); + private Entity copy(net.minecraft.world.level.World level) { + NBTTagCompound compoundTag = new NBTTagCompound(); + getHandle().saveAsPassenger(compoundTag, false); - return net.minecraft.world.entity.EntityType.loadEntityRecursive(compoundTag, level, java.util.function.Function.identity()); + return EntityTypes.loadEntityRecursive(compoundTag, level, EntitySpawnReason.LOAD, java.util.function.Function.identity()); } - public void storeBukkitValues(CompoundTag c) { + public void storeBukkitValues(NBTTagCompound c) { if (!this.persistentDataContainer.isEmpty()) { c.put("BukkitValues", this.persistentDataContainer.toTagCompound()); } } - public void readBukkitValues(CompoundTag c) { - Tag base = c.get("BukkitValues"); - if (base instanceof CompoundTag) { - this.persistentDataContainer.putAll((CompoundTag) base); + public void readBukkitValues(NBTTagCompound c) { + NBTBase base = c.get("BukkitValues"); + if (base instanceof NBTTagCompound) { + this.persistentDataContainer.putAll((NBTTagCompound) base); } } - protected CompoundTag save() { - CompoundTag nbttagcompound = new CompoundTag(); + protected NBTTagCompound save() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.putString("id", this.getHandle().getEncodeId()); - this.getHandle().saveWithoutId(nbttagcompound); + nbttagcompound.putString("id", getHandle().getEncodeId()); + getHandle().saveWithoutId(nbttagcompound); return nbttagcompound; } // re-sends the spawn entity packet to updated values which cannot be updated otherwise protected void update() { - if (!this.getHandle().isAlive()) { + if (!getHandle().isAlive()) { return; } - ServerLevel world = ((CraftWorld) this.getWorld()).getHandle(); - TrackedEntity entityTracker = world.getChunkSource().chunkMap.entityMap.get(this.getEntityId()); + WorldServer world = ((CraftWorld) getWorld()).getHandle(); + PlayerChunkMap.EntityTracker entityTracker = world.getChunkSource().chunkMap.entityMap.get(getEntityId()); if (entityTracker == null) { return; @@ -884,13 +862,13 @@ protected void update() { entityTracker.broadcast(getHandle().getAddEntityPacket(entityTracker.serverEntity)); } - public void update(ServerPlayer player) { + public void update(EntityPlayer player) { if (!getHandle().isAlive()) { return; } - ServerLevel world = ((CraftWorld) getWorld()).getHandle(); - ChunkMap.TrackedEntity entityTracker = world.getChunkSource().chunkMap.entityMap.get(getEntityId()); + WorldServer world = ((CraftWorld) getWorld()).getHandle(); + PlayerChunkMap.EntityTracker entityTracker = world.getChunkSource().chunkMap.entityMap.get(getEntityId()); if (entityTracker == null) { return; @@ -900,8 +878,8 @@ public void update(ServerPlayer player) { } private static PermissibleBase getPermissibleBase() { - if (CraftEntity.perm == null) { - CraftEntity.perm = new PermissibleBase(new ServerOperator() { + if (perm == null) { + perm = new PermissibleBase(new ServerOperator() { @Override public boolean isOp() { @@ -914,37 +892,6 @@ public void setOp(boolean value) { } }); } - return CraftEntity.perm; - } - - // Spigot start - private final Spigot spigot = new Spigot() - { - - @Override - public void sendMessage(BaseComponent component) - { - } - - @Override - public void sendMessage(BaseComponent... components) - { - } - - @Override - public void sendMessage(UUID sender, BaseComponent... components) - { - } - - @Override - public void sendMessage(UUID sender, BaseComponent component) - { - } - }; - - public Spigot spigot() - { - return this.spigot; + return perm; } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityFactory.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityFactory.java index b605924b..caa492d9 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityFactory.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityFactory.java @@ -2,9 +2,9 @@ import com.google.common.base.Preconditions; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.TagParser; -import net.minecraft.world.entity.EntityType; +import net.minecraft.nbt.MojangsonParser; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.entity.EntityTypes; import org.bukkit.entity.EntityFactory; import org.bukkit.entity.EntitySnapshot; @@ -23,14 +23,14 @@ private CraftEntityFactory() { public EntitySnapshot createEntitySnapshot(String input) { Preconditions.checkArgument(input != null, "Input string cannot be null"); - CompoundTag tag; + NBTTagCompound tag; try { - tag = TagParser.parseTag(input); + tag = MojangsonParser.parseTag(input); } catch (CommandSyntaxException e) { throw new IllegalArgumentException("Could not parse Entity: " + input, e); } - EntityType type = EntityType.by(tag).orElse(null); + EntityTypes type = EntityTypes.by(tag).orElse(null); if (type == null) { throw new IllegalArgumentException("Could not parse Entity: " + input); } @@ -39,6 +39,6 @@ public EntitySnapshot createEntitySnapshot(String input) { } public static CraftEntityFactory instance() { - return CraftEntityFactory.instance; + return instance; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntitySnapshot.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntitySnapshot.java index 7b014b39..b3409ee1 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntitySnapshot.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntitySnapshot.java @@ -2,7 +2,9 @@ import com.google.common.base.Preconditions; import java.util.function.Function; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.craftbukkit.CraftWorld; @@ -11,22 +13,22 @@ import org.bukkit.entity.EntityType; public class CraftEntitySnapshot implements EntitySnapshot { - private final CompoundTag data; + private final NBTTagCompound data; private final EntityType type; - private CraftEntitySnapshot(CompoundTag data, EntityType type) { + private CraftEntitySnapshot(NBTTagCompound data, EntityType type) { this.data = data; this.type = type; } @Override public EntityType getEntityType() { - return this.type; + return type; } @Override public Entity createEntity(World world) { - net.minecraft.world.entity.Entity internal = this.createInternal(world); + net.minecraft.world.entity.Entity internal = createInternal(world); return internal.getBukkitEntity(); } @@ -35,7 +37,7 @@ public Entity createEntity(World world) { public Entity createEntity(Location location) { Preconditions.checkArgument(location.getWorld() != null, "Location has no world"); - net.minecraft.world.entity.Entity internal = this.createInternal(location.getWorld()); + net.minecraft.world.entity.Entity internal = createInternal(location.getWorld()); internal.setPos(location.getX(), location.getY(), location.getZ()); return location.getWorld().addEntity(internal.getBukkitEntity()); @@ -43,28 +45,28 @@ public Entity createEntity(Location location) { @Override public String getAsString() { - return this.data.getAsString(); + return data.getAsString(); } private net.minecraft.world.entity.Entity createInternal(World world) { - net.minecraft.world.level.Level nms = ((CraftWorld) world).getHandle(); - net.minecraft.world.entity.Entity internal = net.minecraft.world.entity.EntityType.loadEntityRecursive(this.data, nms, Function.identity()); + net.minecraft.world.level.World nms = ((CraftWorld) world).getHandle(); + net.minecraft.world.entity.Entity internal = EntityTypes.loadEntityRecursive(data, nms, EntitySpawnReason.LOAD, Function.identity()); if (internal == null) { // Try creating by type - internal = CraftEntityType.bukkitToMinecraft(this.type).create(nms); + internal = CraftEntityType.bukkitToMinecraft(type).create(nms, EntitySpawnReason.LOAD); } Preconditions.checkArgument(internal != null, "Error creating new entity."); // This should only fail if the stored NBTTagCompound is malformed. - internal.load(this.data); + internal.load(data); return internal; } - public CompoundTag getData() { - return this.data; + public NBTTagCompound getData() { + return data; } public static CraftEntitySnapshot create(CraftEntity entity) { - CompoundTag tag = new CompoundTag(); + NBTTagCompound tag = new NBTTagCompound(); if (!entity.getHandle().saveAsPassenger(tag, false)) { return null; } @@ -72,7 +74,7 @@ public static CraftEntitySnapshot create(CraftEntity entity) { return new CraftEntitySnapshot(tag, entity.getType()); } - public static CraftEntitySnapshot create(CompoundTag tag, EntityType type) { + public static CraftEntitySnapshot create(NBTTagCompound tag, EntityType type) { if (tag == null || tag.isEmpty() || type == null) { return null; } @@ -80,8 +82,8 @@ public static CraftEntitySnapshot create(CompoundTag tag, EntityType type) { return new CraftEntitySnapshot(tag, type); } - public static CraftEntitySnapshot create(CompoundTag tag) { - EntityType type = net.minecraft.world.entity.EntityType.by(tag).map(CraftEntityType::minecraftToBukkit).orElse(null); - return CraftEntitySnapshot.create(tag, type); + public static CraftEntitySnapshot create(NBTTagCompound tag) { + EntityType type = EntityTypes.by(tag).map(CraftEntityType::minecraftToBukkit).orElse(null); + return create(tag, type); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityType.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityType.java index b749bb7c..a561fd00 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityType.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityType.java @@ -1,9 +1,11 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import com.mohistmc.youer.forge.ForgeInjectBukkit; import java.util.Locale; +import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; +import net.minecraft.world.entity.EntityTypes; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.craftbukkit.CraftRegistry; @@ -14,28 +16,37 @@ public class CraftEntityType { - public static EntityType minecraftToBukkit(net.minecraft.world.entity.EntityType minecraft) { + public static EntityType minecraftToBukkit(EntityTypes minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry> registry = CraftRegistry.getMinecraftRegistry(Registries.ENTITY_TYPE); - NamespacedKey key = CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location()); - if (ForgeInjectBukkit.entityTypeMap.containsKey(key)) { - return ForgeInjectBukkit.entityTypeMap.get(key); - } - EntityType bukkit = Registry.ENTITY_TYPE.get(key); + IRegistry> registry = CraftRegistry.getMinecraftRegistry(Registries.ENTITY_TYPE); + EntityType bukkit = Registry.ENTITY_TYPE.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); return bukkit; } - public static net.minecraft.world.entity.EntityType bukkitToMinecraft(EntityType bukkit) { + public static EntityTypes bukkitToMinecraft(EntityType bukkit) { Preconditions.checkArgument(bukkit != null); return CraftRegistry.getMinecraftRegistry(Registries.ENTITY_TYPE) .getOptional(CraftNamespacedKey.toMinecraft(bukkit.getKey())).orElseThrow(); } + public static Holder> bukkitToMinecraftHolder(EntityType bukkit) { + Preconditions.checkArgument(bukkit != null); + + IRegistry> registry = CraftRegistry.getMinecraftRegistry(Registries.ENTITY_TYPE); + + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c> holder) { + return holder; + } + + throw new IllegalArgumentException("No Reference holder found for " + bukkit + + ", this can happen if a plugin creates its own sound effect with out properly registering it."); + } + public static String bukkitToString(EntityType bukkit) { Preconditions.checkArgument(bukkit != null); diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityTypes.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityTypes.java index 278b5ec4..c445b330 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityTypes.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntityTypes.java @@ -9,37 +9,60 @@ import java.util.function.BiFunction; import java.util.function.Function; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.entity.decoration.HangingEntity; -import net.minecraft.world.entity.decoration.LeashFenceKnotEntity; -import net.minecraft.world.entity.item.FallingBlockEntity; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.item.PrimedTnt; -import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; -import net.minecraft.world.entity.projectile.EyeOfEnder; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; -import net.minecraft.world.entity.projectile.ThrownEgg; -import net.minecraft.world.entity.vehicle.Minecart; -import net.minecraft.world.entity.vehicle.MinecartChest; -import net.minecraft.world.entity.vehicle.MinecartCommandBlock; -import net.minecraft.world.entity.vehicle.MinecartFurnace; -import net.minecraft.world.entity.vehicle.MinecartHopper; -import net.minecraft.world.entity.vehicle.MinecartSpawner; -import net.minecraft.world.entity.vehicle.MinecartTNT; +import net.minecraft.core.EnumDirection; +import net.minecraft.world.entity.EntityAreaEffectCloud; +import net.minecraft.world.entity.EntityExperienceOrb; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon; +import net.minecraft.world.entity.decoration.EntityHanging; +import net.minecraft.world.entity.decoration.EntityItemFrame; +import net.minecraft.world.entity.decoration.EntityLeash; +import net.minecraft.world.entity.decoration.EntityPainting; +import net.minecraft.world.entity.item.EntityFallingBlock; +import net.minecraft.world.entity.item.EntityItem; +import net.minecraft.world.entity.item.EntityTNTPrimed; +import net.minecraft.world.entity.projectile.EntityEgg; +import net.minecraft.world.entity.projectile.EntityEnderSignal; +import net.minecraft.world.entity.projectile.EntityEvokerFangs; +import net.minecraft.world.entity.projectile.EntityFireball; +import net.minecraft.world.entity.projectile.EntityFireworks; +import net.minecraft.world.entity.projectile.EntityPotion; +import net.minecraft.world.entity.projectile.EntitySnowball; +import net.minecraft.world.entity.vehicle.EntityMinecartAbstract; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.DiodeBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.level.GeneratorAccessSeed; +import net.minecraft.world.level.World; +import net.minecraft.world.level.block.BlockDiodeAbstract; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.phys.AxisAlignedBB; +import net.minecraft.world.phys.Vec3D; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.entity.boat.CraftAcaciaBoat; +import org.bukkit.craftbukkit.entity.boat.CraftAcaciaChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftBambooChestRaft; +import org.bukkit.craftbukkit.entity.boat.CraftBambooRaft; +import org.bukkit.craftbukkit.entity.boat.CraftBirchBoat; +import org.bukkit.craftbukkit.entity.boat.CraftBirchChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftCherryBoat; +import org.bukkit.craftbukkit.entity.boat.CraftCherryChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftDarkOakBoat; +import org.bukkit.craftbukkit.entity.boat.CraftDarkOakChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftJungleBoat; +import org.bukkit.craftbukkit.entity.boat.CraftJungleChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftMangroveBoat; +import org.bukkit.craftbukkit.entity.boat.CraftMangroveChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftOakBoat; +import org.bukkit.craftbukkit.entity.boat.CraftOakChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftPaleOakBoat; +import org.bukkit.craftbukkit.entity.boat.CraftPaleOakChestBoat; +import org.bukkit.craftbukkit.entity.boat.CraftSpruceBoat; +import org.bukkit.craftbukkit.entity.boat.CraftSpruceChestBoat; import org.bukkit.entity.Allay; import org.bukkit.entity.AreaEffectCloud; import org.bukkit.entity.Armadillo; @@ -50,17 +73,17 @@ import org.bukkit.entity.Bee; import org.bukkit.entity.Blaze; import org.bukkit.entity.BlockDisplay; -import org.bukkit.entity.Boat; import org.bukkit.entity.Bogged; import org.bukkit.entity.Breeze; import org.bukkit.entity.BreezeWindCharge; import org.bukkit.entity.Camel; import org.bukkit.entity.Cat; import org.bukkit.entity.CaveSpider; -import org.bukkit.entity.ChestBoat; import org.bukkit.entity.Chicken; import org.bukkit.entity.Cod; import org.bukkit.entity.Cow; +import org.bukkit.entity.Creaking; +import org.bukkit.entity.CreakingTransient; import org.bukkit.entity.Creeper; import org.bukkit.entity.Dolphin; import org.bukkit.entity.Donkey; @@ -166,6 +189,26 @@ import org.bukkit.entity.Zombie; import org.bukkit.entity.ZombieHorse; import org.bukkit.entity.ZombieVillager; +import org.bukkit.entity.boat.AcaciaBoat; +import org.bukkit.entity.boat.AcaciaChestBoat; +import org.bukkit.entity.boat.BambooChestRaft; +import org.bukkit.entity.boat.BambooRaft; +import org.bukkit.entity.boat.BirchBoat; +import org.bukkit.entity.boat.BirchChestBoat; +import org.bukkit.entity.boat.CherryBoat; +import org.bukkit.entity.boat.CherryChestBoat; +import org.bukkit.entity.boat.DarkOakBoat; +import org.bukkit.entity.boat.DarkOakChestBoat; +import org.bukkit.entity.boat.JungleBoat; +import org.bukkit.entity.boat.JungleChestBoat; +import org.bukkit.entity.boat.MangroveBoat; +import org.bukkit.entity.boat.MangroveChestBoat; +import org.bukkit.entity.boat.OakBoat; +import org.bukkit.entity.boat.OakChestBoat; +import org.bukkit.entity.boat.PaleOakBoat; +import org.bukkit.entity.boat.PaleOakChestBoat; +import org.bukkit.entity.boat.SpruceBoat; +import org.bukkit.entity.boat.SpruceChestBoat; import org.bukkit.entity.minecart.CommandMinecart; import org.bukkit.entity.minecart.ExplosiveMinecart; import org.bukkit.entity.minecart.HopperMinecart; @@ -173,7 +216,6 @@ import org.bukkit.entity.minecart.RideableMinecart; import org.bukkit.entity.minecart.SpawnerMinecart; import org.bukkit.entity.minecart.StorageMinecart; -import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; public final class CraftEntityTypes { @@ -184,29 +226,29 @@ public record EntityTypeData spawnFunction) { } - public record SpawnData(WorldGenLevel world, Location location, boolean randomizeData, boolean normalWorld) { + public record SpawnData(GeneratorAccessSeed world, Location location, boolean randomizeData, boolean normalWorld) { double x() { - return this.location().getX(); + return location().getX(); } double y() { - return this.location().getY(); + return location().getY(); } double z() { - return this.location().getZ(); + return location().getZ(); } float yaw() { - return this.location().getYaw(); + return location().getYaw(); } float pitch() { - return this.location().getPitch(); + return location().getPitch(); } - Level minecraftWorld() { - return this.world().getMinecraftWorld(); + World minecraftWorld() { + return world().getMinecraftWorld(); } } @@ -217,187 +259,207 @@ Level minecraftWorld() { }; private static final BiConsumer MOVE = (spawnData, entity) -> entity.moveTo(spawnData.x(), spawnData.y(), spawnData.z(), spawnData.yaw(), spawnData.pitch()); private static final BiConsumer MOVE_EMPTY_ROT = (spawnData, entity) -> entity.moveTo(spawnData.x(), spawnData.y(), spawnData.z(), 0, 0); - private static final BiConsumer DIRECTION = (spawnData, entity) -> { - Vector direction = spawnData.location().getDirection().multiply(10); - entity.assignDirectionalMovement(new Vec3(direction.getX(), direction.getY(), direction.getZ()), 1.0); + private static final BiConsumer DIRECTION = (spawnData, entity) -> { + Vector direction = spawnData.location().getDirection(); + entity.assignDirectionalMovement(new Vec3D(direction.getX(), direction.getY(), direction.getZ()), 1.0); }; private static final Map, EntityTypeData> CLASS_TYPE_DATA = new HashMap<>(); private static final Map> ENTITY_TYPE_DATA = new HashMap<>(); static { // Living - register(new EntityTypeData<>(EntityType.ELDER_GUARDIAN, ElderGuardian.class, CraftElderGuardian::new, createLiving(net.minecraft.world.entity.EntityType.ELDER_GUARDIAN))); - register(new EntityTypeData<>(EntityType.WITHER_SKELETON, WitherSkeleton.class, CraftWitherSkeleton::new, createLiving(net.minecraft.world.entity.EntityType.WITHER_SKELETON))); - register(new EntityTypeData<>(EntityType.STRAY, Stray.class, CraftStray::new, createLiving(net.minecraft.world.entity.EntityType.STRAY))); - register(new EntityTypeData<>(EntityType.BOGGED, Bogged.class, CraftBogged::new, createLiving(net.minecraft.world.entity.EntityType.BOGGED))); - register(new EntityTypeData<>(EntityType.HUSK, Husk.class, CraftHusk::new, createLiving(net.minecraft.world.entity.EntityType.HUSK))); - register(new EntityTypeData<>(EntityType.ZOMBIE_VILLAGER, ZombieVillager.class, CraftVillagerZombie::new, createLiving(net.minecraft.world.entity.EntityType.ZOMBIE_VILLAGER))); - register(new EntityTypeData<>(EntityType.SKELETON_HORSE, SkeletonHorse.class, CraftSkeletonHorse::new, createLiving(net.minecraft.world.entity.EntityType.SKELETON_HORSE))); - register(new EntityTypeData<>(EntityType.ZOMBIE_HORSE, ZombieHorse.class, CraftZombieHorse::new, createLiving(net.minecraft.world.entity.EntityType.ZOMBIE_HORSE))); - register(new EntityTypeData<>(EntityType.ARMOR_STAND, ArmorStand.class, CraftArmorStand::new, createLiving(net.minecraft.world.entity.EntityType.ARMOR_STAND))); - register(new EntityTypeData<>(EntityType.DONKEY, Donkey.class, CraftDonkey::new, createLiving(net.minecraft.world.entity.EntityType.DONKEY))); - register(new EntityTypeData<>(EntityType.MULE, Mule.class, CraftMule::new, createLiving(net.minecraft.world.entity.EntityType.MULE))); - register(new EntityTypeData<>(EntityType.EVOKER, Evoker.class, CraftEvoker::new, createLiving(net.minecraft.world.entity.EntityType.EVOKER))); - register(new EntityTypeData<>(EntityType.VEX, Vex.class, CraftVex::new, createLiving(net.minecraft.world.entity.EntityType.VEX))); - register(new EntityTypeData<>(EntityType.VINDICATOR, Vindicator.class, CraftVindicator::new, createLiving(net.minecraft.world.entity.EntityType.VINDICATOR))); - register(new EntityTypeData<>(EntityType.ILLUSIONER, Illusioner.class, CraftIllusioner::new, createLiving(net.minecraft.world.entity.EntityType.ILLUSIONER))); - register(new EntityTypeData<>(EntityType.CREEPER, Creeper.class, CraftCreeper::new, createLiving(net.minecraft.world.entity.EntityType.CREEPER))); - register(new EntityTypeData<>(EntityType.SKELETON, Skeleton.class, CraftSkeleton::new, createLiving(net.minecraft.world.entity.EntityType.SKELETON))); - register(new EntityTypeData<>(EntityType.SPIDER, Spider.class, CraftSpider::new, createLiving(net.minecraft.world.entity.EntityType.SPIDER))); - register(new EntityTypeData<>(EntityType.GIANT, Giant.class, CraftGiant::new, createLiving(net.minecraft.world.entity.EntityType.GIANT))); - register(new EntityTypeData<>(EntityType.ZOMBIE, Zombie.class, CraftZombie::new, createLiving(net.minecraft.world.entity.EntityType.ZOMBIE))); - register(new EntityTypeData<>(EntityType.SLIME, Slime.class, CraftSlime::new, createLiving(net.minecraft.world.entity.EntityType.SLIME))); - register(new EntityTypeData<>(EntityType.GHAST, Ghast.class, CraftGhast::new, createLiving(net.minecraft.world.entity.EntityType.GHAST))); - register(new EntityTypeData<>(EntityType.ZOMBIFIED_PIGLIN, PigZombie.class, CraftPigZombie::new, createLiving(net.minecraft.world.entity.EntityType.ZOMBIFIED_PIGLIN))); - register(new EntityTypeData<>(EntityType.ENDERMAN, Enderman.class, CraftEnderman::new, createLiving(net.minecraft.world.entity.EntityType.ENDERMAN))); - register(new EntityTypeData<>(EntityType.CAVE_SPIDER, CaveSpider.class, CraftCaveSpider::new, createLiving(net.minecraft.world.entity.EntityType.CAVE_SPIDER))); - register(new EntityTypeData<>(EntityType.SILVERFISH, Silverfish.class, CraftSilverfish::new, createLiving(net.minecraft.world.entity.EntityType.SILVERFISH))); - register(new EntityTypeData<>(EntityType.BLAZE, Blaze.class, CraftBlaze::new, createLiving(net.minecraft.world.entity.EntityType.BLAZE))); - register(new EntityTypeData<>(EntityType.MAGMA_CUBE, MagmaCube.class, CraftMagmaCube::new, createLiving(net.minecraft.world.entity.EntityType.MAGMA_CUBE))); - register(new EntityTypeData<>(EntityType.WITHER, Wither.class, CraftWither::new, createLiving(net.minecraft.world.entity.EntityType.WITHER))); - register(new EntityTypeData<>(EntityType.BAT, Bat.class, CraftBat::new, createLiving(net.minecraft.world.entity.EntityType.BAT))); - register(new EntityTypeData<>(EntityType.WITCH, Witch.class, CraftWitch::new, createLiving(net.minecraft.world.entity.EntityType.WITCH))); - register(new EntityTypeData<>(EntityType.ENDERMITE, Endermite.class, CraftEndermite::new, createLiving(net.minecraft.world.entity.EntityType.ENDERMITE))); - register(new EntityTypeData<>(EntityType.GUARDIAN, Guardian.class, CraftGuardian::new, createLiving(net.minecraft.world.entity.EntityType.GUARDIAN))); - register(new EntityTypeData<>(EntityType.SHULKER, Shulker.class, CraftShulker::new, createLiving(net.minecraft.world.entity.EntityType.SHULKER))); - register(new EntityTypeData<>(EntityType.PIG, Pig.class, CraftPig::new, createLiving(net.minecraft.world.entity.EntityType.PIG))); - register(new EntityTypeData<>(EntityType.SHEEP, Sheep.class, CraftSheep::new, createLiving(net.minecraft.world.entity.EntityType.SHEEP))); - register(new EntityTypeData<>(EntityType.COW, Cow.class, CraftCow::new, createLiving(net.minecraft.world.entity.EntityType.COW))); - register(new EntityTypeData<>(EntityType.CHICKEN, Chicken.class, CraftChicken::new, createLiving(net.minecraft.world.entity.EntityType.CHICKEN))); - register(new EntityTypeData<>(EntityType.SQUID, Squid.class, CraftSquid::new, createLiving(net.minecraft.world.entity.EntityType.SQUID))); - register(new EntityTypeData<>(EntityType.WOLF, Wolf.class, CraftWolf::new, createLiving(net.minecraft.world.entity.EntityType.WOLF))); - register(new EntityTypeData<>(EntityType.MOOSHROOM, MushroomCow.class, CraftMushroomCow::new, createLiving(net.minecraft.world.entity.EntityType.MOOSHROOM))); - register(new EntityTypeData<>(EntityType.SNOW_GOLEM, Snowman.class, CraftSnowman::new, createLiving(net.minecraft.world.entity.EntityType.SNOW_GOLEM))); - register(new EntityTypeData<>(EntityType.OCELOT, Ocelot.class, CraftOcelot::new, createLiving(net.minecraft.world.entity.EntityType.OCELOT))); - register(new EntityTypeData<>(EntityType.IRON_GOLEM, IronGolem.class, CraftIronGolem::new, createLiving(net.minecraft.world.entity.EntityType.IRON_GOLEM))); - register(new EntityTypeData<>(EntityType.HORSE, Horse.class, CraftHorse::new, createLiving(net.minecraft.world.entity.EntityType.HORSE))); - register(new EntityTypeData<>(EntityType.RABBIT, Rabbit.class, CraftRabbit::new, createLiving(net.minecraft.world.entity.EntityType.RABBIT))); - register(new EntityTypeData<>(EntityType.POLAR_BEAR, PolarBear.class, CraftPolarBear::new, createLiving(net.minecraft.world.entity.EntityType.POLAR_BEAR))); - register(new EntityTypeData<>(EntityType.LLAMA, Llama.class, CraftLlama::new, createLiving(net.minecraft.world.entity.EntityType.LLAMA))); - register(new EntityTypeData<>(EntityType.PARROT, Parrot.class, CraftParrot::new, createLiving(net.minecraft.world.entity.EntityType.PARROT))); - register(new EntityTypeData<>(EntityType.VILLAGER, Villager.class, CraftVillager::new, createLiving(net.minecraft.world.entity.EntityType.VILLAGER))); - register(new EntityTypeData<>(EntityType.TURTLE, Turtle.class, CraftTurtle::new, createLiving(net.minecraft.world.entity.EntityType.TURTLE))); - register(new EntityTypeData<>(EntityType.PHANTOM, Phantom.class, CraftPhantom::new, createLiving(net.minecraft.world.entity.EntityType.PHANTOM))); - register(new EntityTypeData<>(EntityType.COD, Cod.class, CraftCod::new, createLiving(net.minecraft.world.entity.EntityType.COD))); - register(new EntityTypeData<>(EntityType.SALMON, Salmon.class, CraftSalmon::new, createLiving(net.minecraft.world.entity.EntityType.SALMON))); - register(new EntityTypeData<>(EntityType.PUFFERFISH, PufferFish.class, CraftPufferFish::new, createLiving(net.minecraft.world.entity.EntityType.PUFFERFISH))); - register(new EntityTypeData<>(EntityType.TROPICAL_FISH, TropicalFish.class, CraftTropicalFish::new, createLiving(net.minecraft.world.entity.EntityType.TROPICAL_FISH))); - register(new EntityTypeData<>(EntityType.DROWNED, Drowned.class, CraftDrowned::new, createLiving(net.minecraft.world.entity.EntityType.DROWNED))); - register(new EntityTypeData<>(EntityType.DOLPHIN, Dolphin.class, CraftDolphin::new, createLiving(net.minecraft.world.entity.EntityType.DOLPHIN))); - register(new EntityTypeData<>(EntityType.CAT, Cat.class, CraftCat::new, createLiving(net.minecraft.world.entity.EntityType.CAT))); - register(new EntityTypeData<>(EntityType.PANDA, Panda.class, CraftPanda::new, createLiving(net.minecraft.world.entity.EntityType.PANDA))); - register(new EntityTypeData<>(EntityType.PILLAGER, Pillager.class, CraftPillager::new, createLiving(net.minecraft.world.entity.EntityType.PILLAGER))); - register(new EntityTypeData<>(EntityType.RAVAGER, Ravager.class, CraftRavager::new, createLiving(net.minecraft.world.entity.EntityType.RAVAGER))); - register(new EntityTypeData<>(EntityType.TRADER_LLAMA, TraderLlama.class, CraftTraderLlama::new, createLiving(net.minecraft.world.entity.EntityType.TRADER_LLAMA))); - register(new EntityTypeData<>(EntityType.WANDERING_TRADER, WanderingTrader.class, CraftWanderingTrader::new, createLiving(net.minecraft.world.entity.EntityType.WANDERING_TRADER))); - register(new EntityTypeData<>(EntityType.FOX, Fox.class, CraftFox::new, createLiving(net.minecraft.world.entity.EntityType.FOX))); - register(new EntityTypeData<>(EntityType.BEE, Bee.class, CraftBee::new, createLiving(net.minecraft.world.entity.EntityType.BEE))); - register(new EntityTypeData<>(EntityType.HOGLIN, Hoglin.class, CraftHoglin::new, createLiving(net.minecraft.world.entity.EntityType.HOGLIN))); - register(new EntityTypeData<>(EntityType.PIGLIN, Piglin.class, CraftPiglin::new, createLiving(net.minecraft.world.entity.EntityType.PIGLIN))); - register(new EntityTypeData<>(EntityType.STRIDER, Strider.class, CraftStrider::new, createLiving(net.minecraft.world.entity.EntityType.STRIDER))); - register(new EntityTypeData<>(EntityType.ZOGLIN, Zoglin.class, CraftZoglin::new, createLiving(net.minecraft.world.entity.EntityType.ZOGLIN))); - register(new EntityTypeData<>(EntityType.PIGLIN_BRUTE, PiglinBrute.class, CraftPiglinBrute::new, createLiving(net.minecraft.world.entity.EntityType.PIGLIN_BRUTE))); - register(new EntityTypeData<>(EntityType.AXOLOTL, Axolotl.class, CraftAxolotl::new, createLiving(net.minecraft.world.entity.EntityType.AXOLOTL))); - register(new EntityTypeData<>(EntityType.GLOW_SQUID, GlowSquid.class, CraftGlowSquid::new, createLiving(net.minecraft.world.entity.EntityType.GLOW_SQUID))); - register(new EntityTypeData<>(EntityType.GOAT, Goat.class, CraftGoat::new, createLiving(net.minecraft.world.entity.EntityType.GOAT))); - register(new EntityTypeData<>(EntityType.ALLAY, Allay.class, CraftAllay::new, createLiving(net.minecraft.world.entity.EntityType.ALLAY))); - register(new EntityTypeData<>(EntityType.FROG, Frog.class, CraftFrog::new, createLiving(net.minecraft.world.entity.EntityType.FROG))); - register(new EntityTypeData<>(EntityType.TADPOLE, Tadpole.class, CraftTadpole::new, createLiving(net.minecraft.world.entity.EntityType.TADPOLE))); - register(new EntityTypeData<>(EntityType.WARDEN, Warden.class, CraftWarden::new, createLiving(net.minecraft.world.entity.EntityType.WARDEN))); - register(new EntityTypeData<>(EntityType.CAMEL, Camel.class, CraftCamel::new, createLiving(net.minecraft.world.entity.EntityType.CAMEL))); - register(new EntityTypeData<>(EntityType.SNIFFER, Sniffer.class, CraftSniffer::new, createLiving(net.minecraft.world.entity.EntityType.SNIFFER))); - register(new EntityTypeData<>(EntityType.BREEZE, Breeze.class, CraftBreeze::new, createLiving(net.minecraft.world.entity.EntityType.BREEZE))); - register(new EntityTypeData<>(EntityType.ARMADILLO, Armadillo.class, CraftArmadillo::new, createLiving(net.minecraft.world.entity.EntityType.ARMADILLO))); - - Function dragonFunction = createLiving(net.minecraft.world.entity.EntityType.ENDER_DRAGON); + register(new EntityTypeData<>(EntityType.ELDER_GUARDIAN, ElderGuardian.class, CraftElderGuardian::new, createLiving(EntityTypes.ELDER_GUARDIAN))); + register(new EntityTypeData<>(EntityType.WITHER_SKELETON, WitherSkeleton.class, CraftWitherSkeleton::new, createLiving(EntityTypes.WITHER_SKELETON))); + register(new EntityTypeData<>(EntityType.STRAY, Stray.class, CraftStray::new, createLiving(EntityTypes.STRAY))); + register(new EntityTypeData<>(EntityType.BOGGED, Bogged.class, CraftBogged::new, createLiving(EntityTypes.BOGGED))); + register(new EntityTypeData<>(EntityType.HUSK, Husk.class, CraftHusk::new, createLiving(EntityTypes.HUSK))); + register(new EntityTypeData<>(EntityType.ZOMBIE_VILLAGER, ZombieVillager.class, CraftVillagerZombie::new, createLiving(EntityTypes.ZOMBIE_VILLAGER))); + register(new EntityTypeData<>(EntityType.SKELETON_HORSE, SkeletonHorse.class, CraftSkeletonHorse::new, createLiving(EntityTypes.SKELETON_HORSE))); + register(new EntityTypeData<>(EntityType.ZOMBIE_HORSE, ZombieHorse.class, CraftZombieHorse::new, createLiving(EntityTypes.ZOMBIE_HORSE))); + register(new EntityTypeData<>(EntityType.ARMOR_STAND, ArmorStand.class, CraftArmorStand::new, createLiving(EntityTypes.ARMOR_STAND))); + register(new EntityTypeData<>(EntityType.DONKEY, Donkey.class, CraftDonkey::new, createLiving(EntityTypes.DONKEY))); + register(new EntityTypeData<>(EntityType.MULE, Mule.class, CraftMule::new, createLiving(EntityTypes.MULE))); + register(new EntityTypeData<>(EntityType.EVOKER, Evoker.class, CraftEvoker::new, createLiving(EntityTypes.EVOKER))); + register(new EntityTypeData<>(EntityType.VEX, Vex.class, CraftVex::new, createLiving(EntityTypes.VEX))); + register(new EntityTypeData<>(EntityType.VINDICATOR, Vindicator.class, CraftVindicator::new, createLiving(EntityTypes.VINDICATOR))); + register(new EntityTypeData<>(EntityType.ILLUSIONER, Illusioner.class, CraftIllusioner::new, createLiving(EntityTypes.ILLUSIONER))); + register(new EntityTypeData<>(EntityType.CREEPER, Creeper.class, CraftCreeper::new, createLiving(EntityTypes.CREEPER))); + register(new EntityTypeData<>(EntityType.SKELETON, Skeleton.class, CraftSkeleton::new, createLiving(EntityTypes.SKELETON))); + register(new EntityTypeData<>(EntityType.SPIDER, Spider.class, CraftSpider::new, createLiving(EntityTypes.SPIDER))); + register(new EntityTypeData<>(EntityType.GIANT, Giant.class, CraftGiant::new, createLiving(EntityTypes.GIANT))); + register(new EntityTypeData<>(EntityType.ZOMBIE, Zombie.class, CraftZombie::new, createLiving(EntityTypes.ZOMBIE))); + register(new EntityTypeData<>(EntityType.SLIME, Slime.class, CraftSlime::new, createLiving(EntityTypes.SLIME))); + register(new EntityTypeData<>(EntityType.GHAST, Ghast.class, CraftGhast::new, createLiving(EntityTypes.GHAST))); + register(new EntityTypeData<>(EntityType.ZOMBIFIED_PIGLIN, PigZombie.class, CraftPigZombie::new, createLiving(EntityTypes.ZOMBIFIED_PIGLIN))); + register(new EntityTypeData<>(EntityType.ENDERMAN, Enderman.class, CraftEnderman::new, createLiving(EntityTypes.ENDERMAN))); + register(new EntityTypeData<>(EntityType.CAVE_SPIDER, CaveSpider.class, CraftCaveSpider::new, createLiving(EntityTypes.CAVE_SPIDER))); + register(new EntityTypeData<>(EntityType.SILVERFISH, Silverfish.class, CraftSilverfish::new, createLiving(EntityTypes.SILVERFISH))); + register(new EntityTypeData<>(EntityType.BLAZE, Blaze.class, CraftBlaze::new, createLiving(EntityTypes.BLAZE))); + register(new EntityTypeData<>(EntityType.MAGMA_CUBE, MagmaCube.class, CraftMagmaCube::new, createLiving(EntityTypes.MAGMA_CUBE))); + register(new EntityTypeData<>(EntityType.WITHER, Wither.class, CraftWither::new, createLiving(EntityTypes.WITHER))); + register(new EntityTypeData<>(EntityType.BAT, Bat.class, CraftBat::new, createLiving(EntityTypes.BAT))); + register(new EntityTypeData<>(EntityType.WITCH, Witch.class, CraftWitch::new, createLiving(EntityTypes.WITCH))); + register(new EntityTypeData<>(EntityType.ENDERMITE, Endermite.class, CraftEndermite::new, createLiving(EntityTypes.ENDERMITE))); + register(new EntityTypeData<>(EntityType.GUARDIAN, Guardian.class, CraftGuardian::new, createLiving(EntityTypes.GUARDIAN))); + register(new EntityTypeData<>(EntityType.SHULKER, Shulker.class, CraftShulker::new, createLiving(EntityTypes.SHULKER))); + register(new EntityTypeData<>(EntityType.PIG, Pig.class, CraftPig::new, createLiving(EntityTypes.PIG))); + register(new EntityTypeData<>(EntityType.SHEEP, Sheep.class, CraftSheep::new, createLiving(EntityTypes.SHEEP))); + register(new EntityTypeData<>(EntityType.COW, Cow.class, CraftCow::new, createLiving(EntityTypes.COW))); + register(new EntityTypeData<>(EntityType.CHICKEN, Chicken.class, CraftChicken::new, createLiving(EntityTypes.CHICKEN))); + register(new EntityTypeData<>(EntityType.SQUID, Squid.class, CraftSquid::new, createLiving(EntityTypes.SQUID))); + register(new EntityTypeData<>(EntityType.WOLF, Wolf.class, CraftWolf::new, createLiving(EntityTypes.WOLF))); + register(new EntityTypeData<>(EntityType.MOOSHROOM, MushroomCow.class, CraftMushroomCow::new, createLiving(EntityTypes.MOOSHROOM))); + register(new EntityTypeData<>(EntityType.SNOW_GOLEM, Snowman.class, CraftSnowman::new, createLiving(EntityTypes.SNOW_GOLEM))); + register(new EntityTypeData<>(EntityType.OCELOT, Ocelot.class, CraftOcelot::new, createLiving(EntityTypes.OCELOT))); + register(new EntityTypeData<>(EntityType.IRON_GOLEM, IronGolem.class, CraftIronGolem::new, createLiving(EntityTypes.IRON_GOLEM))); + register(new EntityTypeData<>(EntityType.HORSE, Horse.class, CraftHorse::new, createLiving(EntityTypes.HORSE))); + register(new EntityTypeData<>(EntityType.RABBIT, Rabbit.class, CraftRabbit::new, createLiving(EntityTypes.RABBIT))); + register(new EntityTypeData<>(EntityType.POLAR_BEAR, PolarBear.class, CraftPolarBear::new, createLiving(EntityTypes.POLAR_BEAR))); + register(new EntityTypeData<>(EntityType.LLAMA, Llama.class, CraftLlama::new, createLiving(EntityTypes.LLAMA))); + register(new EntityTypeData<>(EntityType.PARROT, Parrot.class, CraftParrot::new, createLiving(EntityTypes.PARROT))); + register(new EntityTypeData<>(EntityType.VILLAGER, Villager.class, CraftVillager::new, createLiving(EntityTypes.VILLAGER))); + register(new EntityTypeData<>(EntityType.TURTLE, Turtle.class, CraftTurtle::new, createLiving(EntityTypes.TURTLE))); + register(new EntityTypeData<>(EntityType.PHANTOM, Phantom.class, CraftPhantom::new, createLiving(EntityTypes.PHANTOM))); + register(new EntityTypeData<>(EntityType.COD, Cod.class, CraftCod::new, createLiving(EntityTypes.COD))); + register(new EntityTypeData<>(EntityType.SALMON, Salmon.class, CraftSalmon::new, createLiving(EntityTypes.SALMON))); + register(new EntityTypeData<>(EntityType.PUFFERFISH, PufferFish.class, CraftPufferFish::new, createLiving(EntityTypes.PUFFERFISH))); + register(new EntityTypeData<>(EntityType.TROPICAL_FISH, TropicalFish.class, CraftTropicalFish::new, createLiving(EntityTypes.TROPICAL_FISH))); + register(new EntityTypeData<>(EntityType.DROWNED, Drowned.class, CraftDrowned::new, createLiving(EntityTypes.DROWNED))); + register(new EntityTypeData<>(EntityType.DOLPHIN, Dolphin.class, CraftDolphin::new, createLiving(EntityTypes.DOLPHIN))); + register(new EntityTypeData<>(EntityType.CAT, Cat.class, CraftCat::new, createLiving(EntityTypes.CAT))); + register(new EntityTypeData<>(EntityType.PANDA, Panda.class, CraftPanda::new, createLiving(EntityTypes.PANDA))); + register(new EntityTypeData<>(EntityType.PILLAGER, Pillager.class, CraftPillager::new, createLiving(EntityTypes.PILLAGER))); + register(new EntityTypeData<>(EntityType.RAVAGER, Ravager.class, CraftRavager::new, createLiving(EntityTypes.RAVAGER))); + register(new EntityTypeData<>(EntityType.TRADER_LLAMA, TraderLlama.class, CraftTraderLlama::new, createLiving(EntityTypes.TRADER_LLAMA))); + register(new EntityTypeData<>(EntityType.WANDERING_TRADER, WanderingTrader.class, CraftWanderingTrader::new, createLiving(EntityTypes.WANDERING_TRADER))); + register(new EntityTypeData<>(EntityType.FOX, Fox.class, CraftFox::new, createLiving(EntityTypes.FOX))); + register(new EntityTypeData<>(EntityType.BEE, Bee.class, CraftBee::new, createLiving(EntityTypes.BEE))); + register(new EntityTypeData<>(EntityType.HOGLIN, Hoglin.class, CraftHoglin::new, createLiving(EntityTypes.HOGLIN))); + register(new EntityTypeData<>(EntityType.PIGLIN, Piglin.class, CraftPiglin::new, createLiving(EntityTypes.PIGLIN))); + register(new EntityTypeData<>(EntityType.STRIDER, Strider.class, CraftStrider::new, createLiving(EntityTypes.STRIDER))); + register(new EntityTypeData<>(EntityType.ZOGLIN, Zoglin.class, CraftZoglin::new, createLiving(EntityTypes.ZOGLIN))); + register(new EntityTypeData<>(EntityType.PIGLIN_BRUTE, PiglinBrute.class, CraftPiglinBrute::new, createLiving(EntityTypes.PIGLIN_BRUTE))); + register(new EntityTypeData<>(EntityType.AXOLOTL, Axolotl.class, CraftAxolotl::new, createLiving(EntityTypes.AXOLOTL))); + register(new EntityTypeData<>(EntityType.GLOW_SQUID, GlowSquid.class, CraftGlowSquid::new, createLiving(EntityTypes.GLOW_SQUID))); + register(new EntityTypeData<>(EntityType.GOAT, Goat.class, CraftGoat::new, createLiving(EntityTypes.GOAT))); + register(new EntityTypeData<>(EntityType.ALLAY, Allay.class, CraftAllay::new, createLiving(EntityTypes.ALLAY))); + register(new EntityTypeData<>(EntityType.FROG, Frog.class, CraftFrog::new, createLiving(EntityTypes.FROG))); + register(new EntityTypeData<>(EntityType.TADPOLE, Tadpole.class, CraftTadpole::new, createLiving(EntityTypes.TADPOLE))); + register(new EntityTypeData<>(EntityType.WARDEN, Warden.class, CraftWarden::new, createLiving(EntityTypes.WARDEN))); + register(new EntityTypeData<>(EntityType.CAMEL, Camel.class, CraftCamel::new, createLiving(EntityTypes.CAMEL))); + register(new EntityTypeData<>(EntityType.SNIFFER, Sniffer.class, CraftSniffer::new, createLiving(EntityTypes.SNIFFER))); + register(new EntityTypeData<>(EntityType.BREEZE, Breeze.class, CraftBreeze::new, createLiving(EntityTypes.BREEZE))); + register(new EntityTypeData<>(EntityType.ARMADILLO, Armadillo.class, CraftArmadillo::new, createLiving(EntityTypes.ARMADILLO))); + register(new EntityTypeData<>(EntityType.CREAKING, Creaking.class, CraftCreaking::new, createLiving(EntityTypes.CREAKING))); + register(new EntityTypeData<>(EntityType.CREAKING_TRANSIENT, CreakingTransient.class, CraftCreakingTransient::new, createLiving(EntityTypes.CREAKING_TRANSIENT))); + + Function dragonFunction = createLiving(EntityTypes.ENDER_DRAGON); register(new EntityTypeData<>(EntityType.ENDER_DRAGON, EnderDragon.class, CraftEnderDragon::new, spawnData -> { Preconditions.checkArgument(spawnData.normalWorld(), "Cannot spawn entity %s during world generation", EnderDragon.class.getName()); return dragonFunction.apply(spawnData); })); // Fireball - register(new EntityTypeData<>(EntityType.FIREBALL, LargeFireball.class, CraftLargeFireball::new, createFireball(net.minecraft.world.entity.EntityType.FIREBALL))); - register(new EntityTypeData<>(EntityType.SMALL_FIREBALL, SmallFireball.class, CraftSmallFireball::new, createFireball(net.minecraft.world.entity.EntityType.SMALL_FIREBALL))); - register(new EntityTypeData<>(EntityType.WITHER_SKULL, WitherSkull.class, CraftWitherSkull::new, createFireball(net.minecraft.world.entity.EntityType.WITHER_SKULL))); - register(new EntityTypeData<>(EntityType.DRAGON_FIREBALL, DragonFireball.class, CraftDragonFireball::new, createFireball(net.minecraft.world.entity.EntityType.DRAGON_FIREBALL))); - register(new EntityTypeData<>(EntityType.WIND_CHARGE, WindCharge.class, CraftWindCharge::new, createFireball(net.minecraft.world.entity.EntityType.WIND_CHARGE))); - register(new EntityTypeData<>(EntityType.BREEZE_WIND_CHARGE, BreezeWindCharge.class, CraftBreezeWindCharge::new, createFireball(net.minecraft.world.entity.EntityType.BREEZE_WIND_CHARGE))); + register(new EntityTypeData<>(EntityType.FIREBALL, LargeFireball.class, CraftLargeFireball::new, createFireball(EntityTypes.FIREBALL))); + register(new EntityTypeData<>(EntityType.SMALL_FIREBALL, SmallFireball.class, CraftSmallFireball::new, createFireball(EntityTypes.SMALL_FIREBALL))); + register(new EntityTypeData<>(EntityType.WITHER_SKULL, WitherSkull.class, CraftWitherSkull::new, createFireball(EntityTypes.WITHER_SKULL))); + register(new EntityTypeData<>(EntityType.DRAGON_FIREBALL, DragonFireball.class, CraftDragonFireball::new, createFireball(EntityTypes.DRAGON_FIREBALL))); + register(new EntityTypeData<>(EntityType.WIND_CHARGE, WindCharge.class, CraftWindCharge::new, createFireball(EntityTypes.WIND_CHARGE))); + register(new EntityTypeData<>(EntityType.BREEZE_WIND_CHARGE, BreezeWindCharge.class, CraftBreezeWindCharge::new, createFireball(EntityTypes.BREEZE_WIND_CHARGE))); // Hanging register(new EntityTypeData<>(EntityType.PAINTING, Painting.class, CraftPainting::new, createHanging(Painting.class, (spawnData, hangingData) -> { if (spawnData.normalWorld && hangingData.randomize()) { - return net.minecraft.world.entity.decoration.Painting.create(spawnData.minecraftWorld(), hangingData.position(), hangingData.direction()).orElse(null); + return EntityPainting.create(spawnData.minecraftWorld(), hangingData.position(), hangingData.direction()).orElse(null); } else { - net.minecraft.world.entity.decoration.Painting entity = new net.minecraft.world.entity.decoration.Painting(net.minecraft.world.entity.EntityType.PAINTING, spawnData.minecraftWorld()); + EntityPainting entity = new EntityPainting(EntityTypes.PAINTING, spawnData.minecraftWorld()); entity.absMoveTo(spawnData.x(), spawnData.y(), spawnData.z(), spawnData.yaw(), spawnData.pitch()); entity.setDirection(hangingData.direction()); return entity; } } ))); - register(new EntityTypeData<>(EntityType.ITEM_FRAME, ItemFrame.class, CraftItemFrame::new, createHanging(ItemFrame.class, (spawnData, hangingData) -> new net.minecraft.world.entity.decoration.ItemFrame(spawnData.minecraftWorld(), hangingData.position(), hangingData.direction())))); + register(new EntityTypeData<>(EntityType.ITEM_FRAME, ItemFrame.class, CraftItemFrame::new, createHanging(ItemFrame.class, (spawnData, hangingData) -> new EntityItemFrame(spawnData.minecraftWorld(), hangingData.position(), hangingData.direction())))); register(new EntityTypeData<>(EntityType.GLOW_ITEM_FRAME, GlowItemFrame.class, CraftGlowItemFrame::new, createHanging(GlowItemFrame.class, (spawnData, hangingData) -> new net.minecraft.world.entity.decoration.GlowItemFrame(spawnData.minecraftWorld(), hangingData.position(), hangingData.direction())))); // Move no rotation - register(new EntityTypeData<>(EntityType.ARROW, Arrow.class, CraftArrow::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.ARROW))); - register(new EntityTypeData<>(EntityType.ENDER_PEARL, EnderPearl.class, CraftEnderPearl::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.ENDER_PEARL))); - register(new EntityTypeData<>(EntityType.EXPERIENCE_BOTTLE, ThrownExpBottle.class, CraftThrownExpBottle::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.EXPERIENCE_BOTTLE))); - register(new EntityTypeData<>(EntityType.SPECTRAL_ARROW, SpectralArrow.class, CraftSpectralArrow::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.SPECTRAL_ARROW))); - register(new EntityTypeData<>(EntityType.END_CRYSTAL, EnderCrystal.class, CraftEnderCrystal::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.END_CRYSTAL))); - register(new EntityTypeData<>(EntityType.TRIDENT, Trident.class, CraftTrident::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.TRIDENT))); - register(new EntityTypeData<>(EntityType.LIGHTNING_BOLT, LightningStrike.class, CraftLightningStrike::new, createAndMoveEmptyRot(net.minecraft.world.entity.EntityType.LIGHTNING_BOLT))); + register(new EntityTypeData<>(EntityType.ARROW, Arrow.class, CraftArrow::new, createAndMoveEmptyRot(EntityTypes.ARROW))); + register(new EntityTypeData<>(EntityType.ENDER_PEARL, EnderPearl.class, CraftEnderPearl::new, createAndMoveEmptyRot(EntityTypes.ENDER_PEARL))); + register(new EntityTypeData<>(EntityType.EXPERIENCE_BOTTLE, ThrownExpBottle.class, CraftThrownExpBottle::new, createAndMoveEmptyRot(EntityTypes.EXPERIENCE_BOTTLE))); + register(new EntityTypeData<>(EntityType.SPECTRAL_ARROW, SpectralArrow.class, CraftSpectralArrow::new, createAndMoveEmptyRot(EntityTypes.SPECTRAL_ARROW))); + register(new EntityTypeData<>(EntityType.END_CRYSTAL, EnderCrystal.class, CraftEnderCrystal::new, createAndMoveEmptyRot(EntityTypes.END_CRYSTAL))); + register(new EntityTypeData<>(EntityType.TRIDENT, Trident.class, CraftTrident::new, createAndMoveEmptyRot(EntityTypes.TRIDENT))); + register(new EntityTypeData<>(EntityType.LIGHTNING_BOLT, LightningStrike.class, CraftLightningStrike::new, createAndMoveEmptyRot(EntityTypes.LIGHTNING_BOLT))); // Move - register(new EntityTypeData<>(EntityType.SHULKER_BULLET, ShulkerBullet.class, CraftShulkerBullet::new, createAndMove(net.minecraft.world.entity.EntityType.SHULKER_BULLET))); - register(new EntityTypeData<>(EntityType.BOAT, Boat.class, CraftBoat::new, createAndMove(net.minecraft.world.entity.EntityType.BOAT))); - register(new EntityTypeData<>(EntityType.LLAMA_SPIT, LlamaSpit.class, CraftLlamaSpit::new, createAndMove(net.minecraft.world.entity.EntityType.LLAMA_SPIT))); - register(new EntityTypeData<>(EntityType.CHEST_BOAT, ChestBoat.class, CraftChestBoat::new, createAndMove(net.minecraft.world.entity.EntityType.CHEST_BOAT))); - register(new EntityTypeData<>(EntityType.OMINOUS_ITEM_SPAWNER, OminousItemSpawner.class, CraftOminousItemSpawner::new, createAndMove(net.minecraft.world.entity.EntityType.OMINOUS_ITEM_SPAWNER))); + register(new EntityTypeData<>(EntityType.SHULKER_BULLET, ShulkerBullet.class, CraftShulkerBullet::new, createAndMove(EntityTypes.SHULKER_BULLET))); + register(new EntityTypeData<>(EntityType.LLAMA_SPIT, LlamaSpit.class, CraftLlamaSpit::new, createAndMove(EntityTypes.LLAMA_SPIT))); + register(new EntityTypeData<>(EntityType.OMINOUS_ITEM_SPAWNER, OminousItemSpawner.class, CraftOminousItemSpawner::new, createAndMove(EntityTypes.OMINOUS_ITEM_SPAWNER))); + // Move (boats) + register(new EntityTypeData<>(EntityType.ACACIA_BOAT, AcaciaBoat.class, CraftAcaciaBoat::new, createAndMove(EntityTypes.ACACIA_BOAT))); + register(new EntityTypeData<>(EntityType.ACACIA_CHEST_BOAT, AcaciaChestBoat.class, CraftAcaciaChestBoat::new, createAndMove(EntityTypes.ACACIA_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.BAMBOO_RAFT, BambooRaft.class, CraftBambooRaft::new, createAndMove(EntityTypes.BAMBOO_RAFT))); + register(new EntityTypeData<>(EntityType.BAMBOO_CHEST_RAFT, BambooChestRaft.class, CraftBambooChestRaft::new, createAndMove(EntityTypes.BAMBOO_CHEST_RAFT))); + register(new EntityTypeData<>(EntityType.BIRCH_BOAT, BirchBoat.class, CraftBirchBoat::new, createAndMove(EntityTypes.BIRCH_BOAT))); + register(new EntityTypeData<>(EntityType.BIRCH_CHEST_BOAT, BirchChestBoat.class, CraftBirchChestBoat::new, createAndMove(EntityTypes.BIRCH_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.CHERRY_BOAT, CherryBoat.class, CraftCherryBoat::new, createAndMove(EntityTypes.CHERRY_BOAT))); + register(new EntityTypeData<>(EntityType.CHERRY_CHEST_BOAT, CherryChestBoat.class, CraftCherryChestBoat::new, createAndMove(EntityTypes.CHERRY_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.DARK_OAK_BOAT, DarkOakBoat.class, CraftDarkOakBoat::new, createAndMove(EntityTypes.DARK_OAK_BOAT))); + register(new EntityTypeData<>(EntityType.DARK_OAK_CHEST_BOAT, DarkOakChestBoat.class, CraftDarkOakChestBoat::new, createAndMove(EntityTypes.DARK_OAK_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.JUNGLE_BOAT, JungleBoat.class, CraftJungleBoat::new, createAndMove(EntityTypes.JUNGLE_BOAT))); + register(new EntityTypeData<>(EntityType.JUNGLE_CHEST_BOAT, JungleChestBoat.class, CraftJungleChestBoat::new, createAndMove(EntityTypes.JUNGLE_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.MANGROVE_BOAT, MangroveBoat.class, CraftMangroveBoat::new, createAndMove(EntityTypes.MANGROVE_BOAT))); + register(new EntityTypeData<>(EntityType.MANGROVE_CHEST_BOAT, MangroveChestBoat.class, CraftMangroveChestBoat::new, createAndMove(EntityTypes.MANGROVE_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.OAK_BOAT, OakBoat.class, CraftOakBoat::new, createAndMove(EntityTypes.OAK_BOAT))); + register(new EntityTypeData<>(EntityType.OAK_CHEST_BOAT, OakChestBoat.class, CraftOakChestBoat::new, createAndMove(EntityTypes.OAK_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.PALE_OAK_BOAT, PaleOakBoat.class, CraftPaleOakBoat::new, createAndMove(EntityTypes.PALE_OAK_BOAT))); + register(new EntityTypeData<>(EntityType.PALE_OAK_CHEST_BOAT, PaleOakChestBoat.class, CraftPaleOakChestBoat::new, createAndMove(EntityTypes.PALE_OAK_CHEST_BOAT))); + register(new EntityTypeData<>(EntityType.SPRUCE_BOAT, SpruceBoat.class, CraftSpruceBoat::new, createAndMove(EntityTypes.SPRUCE_BOAT))); + register(new EntityTypeData<>(EntityType.SPRUCE_CHEST_BOAT, SpruceChestBoat.class, CraftSpruceChestBoat::new, createAndMove(EntityTypes.SPRUCE_CHEST_BOAT))); // Set pos - register(new EntityTypeData<>(EntityType.MARKER, Marker.class, CraftMarker::new, createAndSetPos(net.minecraft.world.entity.EntityType.MARKER))); - register(new EntityTypeData<>(EntityType.BLOCK_DISPLAY, BlockDisplay.class, CraftBlockDisplay::new, createAndSetPos(net.minecraft.world.entity.EntityType.BLOCK_DISPLAY))); - register(new EntityTypeData<>(EntityType.INTERACTION, Interaction.class, CraftInteraction::new, createAndSetPos(net.minecraft.world.entity.EntityType.INTERACTION))); - register(new EntityTypeData<>(EntityType.ITEM_DISPLAY, ItemDisplay.class, CraftItemDisplay::new, createAndSetPos(net.minecraft.world.entity.EntityType.ITEM_DISPLAY))); - register(new EntityTypeData<>(EntityType.TEXT_DISPLAY, TextDisplay.class, CraftTextDisplay::new, createAndSetPos(net.minecraft.world.entity.EntityType.TEXT_DISPLAY))); + register(new EntityTypeData<>(EntityType.MARKER, Marker.class, CraftMarker::new, createAndSetPos(EntityTypes.MARKER))); + register(new EntityTypeData<>(EntityType.BLOCK_DISPLAY, BlockDisplay.class, CraftBlockDisplay::new, createAndSetPos(EntityTypes.BLOCK_DISPLAY))); + register(new EntityTypeData<>(EntityType.INTERACTION, Interaction.class, CraftInteraction::new, createAndSetPos(EntityTypes.INTERACTION))); + register(new EntityTypeData<>(EntityType.ITEM_DISPLAY, ItemDisplay.class, CraftItemDisplay::new, createAndSetPos(EntityTypes.ITEM_DISPLAY))); + register(new EntityTypeData<>(EntityType.TEXT_DISPLAY, TextDisplay.class, CraftTextDisplay::new, createAndSetPos(EntityTypes.TEXT_DISPLAY))); // MISC register(new EntityTypeData<>(EntityType.ITEM, Item.class, CraftItem::new, spawnData -> { // We use stone instead of empty, to give the plugin developer a visual clue, that the spawn method is working, // and that the item stack should probably be changed. net.minecraft.world.item.ItemStack itemStack = new net.minecraft.world.item.ItemStack(Items.STONE); - ItemEntity item = new ItemEntity(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), itemStack); + EntityItem item = new EntityItem(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), itemStack); item.setPickUpDelay(10); return item; })); register(new EntityTypeData<>(EntityType.EXPERIENCE_ORB, ExperienceOrb.class, CraftExperienceOrb::new, - spawnData -> new net.minecraft.world.entity.ExperienceOrb(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), 0) + spawnData -> new EntityExperienceOrb(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), 0) )); - register(new EntityTypeData<>(EntityType.AREA_EFFECT_CLOUD, AreaEffectCloud.class, CraftAreaEffectCloud::new, spawnData -> new net.minecraft.world.entity.AreaEffectCloud(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.EGG, Egg.class, CraftEgg::new, spawnData -> new ThrownEgg(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.LEASH_KNOT, LeashHitch.class, CraftLeash::new, spawnData -> new LeashFenceKnotEntity(spawnData.minecraftWorld(), BlockPos.containing(spawnData.x(), spawnData.y(), spawnData.z())))); // SPIGOT-5732: LeashHitch has no direction and is always centered at a block - register(new EntityTypeData<>(EntityType.SNOWBALL, Snowball.class, CraftSnowball::new, spawnData -> new net.minecraft.world.entity.projectile.Snowball(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.EYE_OF_ENDER, EnderSignal.class, CraftEnderSignal::new, spawnData -> new EyeOfEnder(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); + register(new EntityTypeData<>(EntityType.AREA_EFFECT_CLOUD, AreaEffectCloud.class, CraftAreaEffectCloud::new, spawnData -> new EntityAreaEffectCloud(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); + register(new EntityTypeData<>(EntityType.EGG, Egg.class, CraftEgg::new, spawnData -> new EntityEgg(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), new net.minecraft.world.item.ItemStack(Items.EGG)))); + register(new EntityTypeData<>(EntityType.LEASH_KNOT, LeashHitch.class, CraftLeash::new, spawnData -> new EntityLeash(spawnData.minecraftWorld(), BlockPos.containing(spawnData.x(), spawnData.y(), spawnData.z())))); // SPIGOT-5732: LeashHitch has no direction and is always centered at a block + register(new EntityTypeData<>(EntityType.SNOWBALL, Snowball.class, CraftSnowball::new, spawnData -> new EntitySnowball(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), new net.minecraft.world.item.ItemStack(Items.SNOWBALL)))); + register(new EntityTypeData<>(EntityType.EYE_OF_ENDER, EnderSignal.class, CraftEnderSignal::new, spawnData -> new EntityEnderSignal(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); register(new EntityTypeData<>(EntityType.POTION, ThrownPotion.class, CraftThrownPotion::new, spawnData -> { - net.minecraft.world.entity.projectile.ThrownPotion entity = new net.minecraft.world.entity.projectile.ThrownPotion(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()); - entity.setItem(CraftItemStack.asNMSCopy(new ItemStack(Material.SPLASH_POTION, 1))); + EntityPotion entity = new EntityPotion(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), new net.minecraft.world.item.ItemStack(Items.SPLASH_POTION)); return entity; })); - register(new EntityTypeData<>(EntityType.TNT, TNTPrimed.class, CraftTNTPrimed::new, spawnData -> new PrimedTnt(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), null))); + register(new EntityTypeData<>(EntityType.TNT, TNTPrimed.class, CraftTNTPrimed::new, spawnData -> new EntityTNTPrimed(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), null))); register(new EntityTypeData<>(EntityType.FALLING_BLOCK, FallingBlock.class, CraftFallingBlock::new, spawnData -> { BlockPos pos = BlockPos.containing(spawnData.x(), spawnData.y(), spawnData.z()); - return FallingBlockEntity.fall(spawnData.minecraftWorld(), pos, spawnData.world().getBlockState(pos)); + return EntityFallingBlock.fall(spawnData.minecraftWorld(), pos, spawnData.world().getBlockState(pos)); })); - register(new EntityTypeData<>(EntityType.FIREWORK_ROCKET, Firework.class, CraftFirework::new, spawnData -> new FireworkRocketEntity(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), net.minecraft.world.item.ItemStack.EMPTY))); - register(new EntityTypeData<>(EntityType.EVOKER_FANGS, EvokerFangs.class, CraftEvokerFangs::new, spawnData -> new net.minecraft.world.entity.projectile.EvokerFangs(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), (float) Math.toRadians(spawnData.yaw()), 0, null))); - register(new EntityTypeData<>(EntityType.COMMAND_BLOCK_MINECART, CommandMinecart.class, CraftMinecartCommand::new, spawnData -> new MinecartCommandBlock(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.MINECART, RideableMinecart.class, CraftMinecartRideable::new, spawnData -> new Minecart(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.CHEST_MINECART, StorageMinecart.class, CraftMinecartChest::new, spawnData -> new MinecartChest(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.FURNACE_MINECART, PoweredMinecart.class, CraftMinecartFurnace::new, spawnData -> new MinecartFurnace(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.TNT_MINECART, ExplosiveMinecart.class, CraftMinecartTNT::new, spawnData -> new MinecartTNT(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.HOPPER_MINECART, HopperMinecart.class, CraftMinecartHopper::new, spawnData -> new MinecartHopper(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); - register(new EntityTypeData<>(EntityType.SPAWNER_MINECART, SpawnerMinecart.class, CraftMinecartMobSpawner::new, spawnData -> new MinecartSpawner(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z()))); + register(new EntityTypeData<>(EntityType.FIREWORK_ROCKET, Firework.class, CraftFirework::new, spawnData -> new EntityFireworks(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), net.minecraft.world.item.ItemStack.EMPTY))); + register(new EntityTypeData<>(EntityType.EVOKER_FANGS, EvokerFangs.class, CraftEvokerFangs::new, spawnData -> new EntityEvokerFangs(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), (float) Math.toRadians(spawnData.yaw()), 0, null))); + register(new EntityTypeData<>(EntityType.COMMAND_BLOCK_MINECART, CommandMinecart.class, CraftMinecartCommand::new, createMinecart(EntityTypes.COMMAND_BLOCK_MINECART))); + register(new EntityTypeData<>(EntityType.MINECART, RideableMinecart.class, CraftMinecartRideable::new, createMinecart(EntityTypes.MINECART))); + register(new EntityTypeData<>(EntityType.CHEST_MINECART, StorageMinecart.class, CraftMinecartChest::new, createMinecart(EntityTypes.CHEST_MINECART))); + register(new EntityTypeData<>(EntityType.FURNACE_MINECART, PoweredMinecart.class, CraftMinecartFurnace::new, createMinecart(EntityTypes.FURNACE_MINECART))); + register(new EntityTypeData<>(EntityType.TNT_MINECART, ExplosiveMinecart.class, CraftMinecartTNT::new, createMinecart(EntityTypes.TNT_MINECART))); + register(new EntityTypeData<>(EntityType.HOPPER_MINECART, HopperMinecart.class, CraftMinecartHopper::new, createMinecart(EntityTypes.HOPPER_MINECART))); + register(new EntityTypeData<>(EntityType.SPAWNER_MINECART, SpawnerMinecart.class, CraftMinecartMobSpawner::new, createMinecart(EntityTypes.SPAWNER_MINECART))); // None spawn able register(new EntityTypeData<>(EntityType.FISHING_BOBBER, FishHook.class, CraftFishHook::new, null)); // Cannot spawn a fish hook @@ -405,45 +467,49 @@ Level minecraftWorld() { } private static void register(EntityTypeData typeData) { - EntityTypeData other = CraftEntityTypes.CLASS_TYPE_DATA.put(typeData.entityClass(), typeData); + EntityTypeData other = CLASS_TYPE_DATA.put(typeData.entityClass(), typeData); if (other != null) { Bukkit.getLogger().warning(String.format("Found multiple entity type data for class %s, replacing '%s' with new value '%s'", typeData.entityClass().getName(), other, typeData)); } - other = CraftEntityTypes.ENTITY_TYPE_DATA.put(typeData.entityType(), typeData); + other = ENTITY_TYPE_DATA.put(typeData.entityType(), typeData); if (other != null) { Bukkit.getLogger().warning(String.format("Found multiple entity type data for entity type %s, replacing '%s' with new value '%s'", typeData.entityType().getKey(), other, typeData)); } } - private static Function fromEntityType(net.minecraft.world.entity.EntityType entityTypes) { - return spawnData -> entityTypes.create(spawnData.minecraftWorld()); + private static Function fromEntityType(EntityTypes entityTypes) { + return spawnData -> entityTypes.create(spawnData.minecraftWorld(), EntitySpawnReason.COMMAND); } - private static Function createLiving(net.minecraft.world.entity.EntityType entityTypes) { - return CraftEntityTypes.combine(CraftEntityTypes.fromEntityType(entityTypes), CraftEntityTypes.ABS_MOVE); + private static Function createLiving(EntityTypes entityTypes) { + return combine(fromEntityType(entityTypes), ABS_MOVE); } - private static Function createFireball(net.minecraft.world.entity.EntityType entityTypes) { - return CraftEntityTypes.combine(CraftEntityTypes.createAndMove(entityTypes), CraftEntityTypes.DIRECTION); + private static Function createFireball(EntityTypes entityTypes) { + return combine(createAndMove(entityTypes), DIRECTION); } - private static Function createAndMove(net.minecraft.world.entity.EntityType entityTypes) { - return CraftEntityTypes.combine(CraftEntityTypes.fromEntityType(entityTypes), CraftEntityTypes.MOVE); + private static Function createMinecart(EntityTypes entityTypes) { + return spawnData -> EntityMinecartAbstract.createMinecart(spawnData.minecraftWorld(), spawnData.x(), spawnData.y(), spawnData.z(), entityTypes, EntitySpawnReason.TRIGGERED, ItemStack.EMPTY, null); } - private static Function createAndMoveEmptyRot(net.minecraft.world.entity.EntityType entityTypes) { - return CraftEntityTypes.combine(CraftEntityTypes.fromEntityType(entityTypes), CraftEntityTypes.MOVE_EMPTY_ROT); + private static Function createAndMove(EntityTypes entityTypes) { + return combine(fromEntityType(entityTypes), MOVE); } - private static Function createAndSetPos(net.minecraft.world.entity.EntityType entityTypes) { - return CraftEntityTypes.combine(CraftEntityTypes.fromEntityType(entityTypes), CraftEntityTypes.POS); + private static Function createAndMoveEmptyRot(EntityTypes entityTypes) { + return combine(fromEntityType(entityTypes), MOVE_EMPTY_ROT); } - private record HangingData(boolean randomize, BlockPos position, Direction direction) { + private static Function createAndSetPos(EntityTypes entityTypes) { + return combine(fromEntityType(entityTypes), POS); } - private static Function createHanging(Class clazz, BiFunction spawnFunction) { + private record HangingData(boolean randomize, BlockPos position, EnumDirection direction) { + } + + private static Function createHanging(Class clazz, BiFunction spawnFunction) { return spawnData -> { boolean randomizeData = spawnData.randomizeData(); BlockFace face = BlockFace.SELF; @@ -460,16 +526,16 @@ private static Function list = spawnData.world().getEntities(null, bb); for (Iterator it = list.iterator(); !taken && it.hasNext(); ) { net.minecraft.world.entity.Entity e = it.next(); - if (e instanceof HangingEntity) { + if (e instanceof EntityHanging) { taken = true; // Hanging entities do not like hanging entities which intersect them. } } @@ -488,7 +554,7 @@ private static Function Function combine(Function before, BiConsumer EntityTypeData getEntityTypeData(EntityType entityType) { - return (EntityTypeData) CraftEntityTypes.ENTITY_TYPE_DATA.get(entityType); + return (EntityTypeData) ENTITY_TYPE_DATA.get(entityType); } public static EntityTypeData getEntityTypeData(Class entityClass) { - return (EntityTypeData) CraftEntityTypes.CLASS_TYPE_DATA.get(entityClass); + return (EntityTypeData) CLASS_TYPE_DATA.get(entityClass); } private CraftEntityTypes() { diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java index 93ffe2ac..d5d37668 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java @@ -1,18 +1,19 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.monster.SpellcasterIllager; +import net.minecraft.world.entity.monster.EntityEvoker; +import net.minecraft.world.entity.monster.EntityIllagerWizard; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Evoker; public class CraftEvoker extends CraftSpellcaster implements Evoker { - public CraftEvoker(CraftServer server, net.minecraft.world.entity.monster.Evoker entity) { + public CraftEvoker(CraftServer server, EntityEvoker entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Evoker getHandle() { - return (net.minecraft.world.entity.monster.Evoker) super.getHandle(); + public EntityEvoker getHandle() { + return (EntityEvoker) super.getHandle(); } @Override @@ -22,11 +23,11 @@ public String toString() { @Override public Evoker.Spell getCurrentSpell() { - return Evoker.Spell.values()[this.getHandle().getCurrentSpell().ordinal()]; + return Evoker.Spell.values()[getHandle().getCurrentSpell().ordinal()]; } @Override public void setCurrentSpell(Evoker.Spell spell) { - this.getHandle().setIsCastingSpell(spell == null ? SpellcasterIllager.IllagerSpell.NONE : SpellcasterIllager.IllagerSpell.byId(spell.ordinal())); + getHandle().setIsCastingSpell(spell == null ? EntityIllagerWizard.Spell.NONE : EntityIllagerWizard.Spell.byId(spell.ordinal())); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java index 19b368cc..885fc3b2 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java @@ -1,19 +1,21 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.projectile.EntityEvokerFangs; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.EvokerFangs; import org.bukkit.entity.LivingEntity; public class CraftEvokerFangs extends CraftEntity implements EvokerFangs { - public CraftEvokerFangs(CraftServer server, net.minecraft.world.entity.projectile.EvokerFangs entity) { + public CraftEvokerFangs(CraftServer server, EntityEvokerFangs entity) { super(server, entity); } @Override - public net.minecraft.world.entity.projectile.EvokerFangs getHandle() { - return (net.minecraft.world.entity.projectile.EvokerFangs) super.getHandle(); + public EntityEvokerFangs getHandle() { + return (EntityEvokerFangs) super.getHandle(); } @Override @@ -23,25 +25,25 @@ public String toString() { @Override public LivingEntity getOwner() { - net.minecraft.world.entity.LivingEntity owner = this.getHandle().getOwner(); + EntityLiving owner = getHandle().getOwner(); return (owner == null) ? null : (LivingEntity) owner.getBukkitEntity(); } @Override public void setOwner(LivingEntity owner) { - this.getHandle().setOwner(owner == null ? null : ((CraftLivingEntity) owner).getHandle()); + getHandle().setOwner(owner == null ? null : ((CraftLivingEntity) owner).getHandle()); } @Override public int getAttackDelay() { - return this.getHandle().warmupDelayTicks; + return getHandle().warmupDelayTicks; } @Override public void setAttackDelay(int delay) { Preconditions.checkArgument(delay >= 0, "Delay must be positive"); - this.getHandle().warmupDelayTicks = delay; + getHandle().warmupDelayTicks = delay; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java index 9231511a..c3524a3b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java @@ -1,26 +1,27 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.EntityExperienceOrb; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.ExperienceOrb; public class CraftExperienceOrb extends CraftEntity implements ExperienceOrb { - public CraftExperienceOrb(CraftServer server, net.minecraft.world.entity.ExperienceOrb entity) { + public CraftExperienceOrb(CraftServer server, EntityExperienceOrb entity) { super(server, entity); } @Override public int getExperience() { - return this.getHandle().value; + return getHandle().value; } @Override public void setExperience(int value) { - this.getHandle().value = value; + getHandle().value = value; } @Override - public net.minecraft.world.entity.ExperienceOrb getHandle() { - return (net.minecraft.world.entity.ExperienceOrb) this.entity; + public EntityExperienceOrb getHandle() { + return (EntityExperienceOrb) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java index a7a3f74b..b5b6ce63 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.item.FallingBlockEntity; +import net.minecraft.world.entity.item.EntityFallingBlock; import org.bukkit.Material; import org.bukkit.block.data.BlockData; import org.bukkit.craftbukkit.CraftServer; @@ -10,13 +10,13 @@ public class CraftFallingBlock extends CraftEntity implements FallingBlock { - public CraftFallingBlock(CraftServer server, FallingBlockEntity entity) { + public CraftFallingBlock(CraftServer server, EntityFallingBlock entity) { super(server, entity); } @Override - public FallingBlockEntity getHandle() { - return (FallingBlockEntity) this.entity; + public EntityFallingBlock getHandle() { + return (EntityFallingBlock) entity; } @Override @@ -26,42 +26,42 @@ public String toString() { @Override public Material getMaterial() { - return this.getBlockData().getMaterial(); + return getBlockData().getMaterial(); } @Override public BlockData getBlockData() { - return CraftBlockData.fromData(this.getHandle().getBlockState()); + return CraftBlockData.fromData(getHandle().getBlockState()); } @Override public boolean getDropItem() { - return this.getHandle().dropItem; + return getHandle().dropItem; } @Override public void setDropItem(boolean drop) { - this.getHandle().dropItem = drop; + getHandle().dropItem = drop; } @Override public boolean getCancelDrop() { - return this.getHandle().cancelDrop; + return getHandle().cancelDrop; } @Override public void setCancelDrop(boolean cancelDrop) { - this.getHandle().cancelDrop = cancelDrop; + getHandle().cancelDrop = cancelDrop; } @Override public boolean canHurtEntities() { - return this.getHandle().hurtEntities; + return getHandle().hurtEntities; } @Override public void setHurtEntities(boolean hurtEntities) { - this.getHandle().hurtEntities = hurtEntities; + getHandle().hurtEntities = hurtEntities; } @Override @@ -69,19 +69,19 @@ public void setTicksLived(int value) { super.setTicksLived(value); // Second field for EntityFallingBlock - this.getHandle().time = value; + getHandle().time = value; } @Override public float getDamagePerBlock() { - return this.getHandle().fallDamagePerDistance; + return getHandle().fallDamagePerDistance; } @Override public void setDamagePerBlock(float damage) { Preconditions.checkArgument(damage >= 0.0, "damage must be >= 0.0, given %s", damage); - this.getHandle().fallDamagePerDistance = damage; + getHandle().fallDamagePerDistance = damage; if (damage > 0.0) { this.setHurtEntities(true); } @@ -89,14 +89,14 @@ public void setDamagePerBlock(float damage) { @Override public int getMaxDamage() { - return this.getHandle().fallDamageMax; + return getHandle().fallDamageMax; } @Override public void setMaxDamage(int damage) { Preconditions.checkArgument(damage >= 0, "damage must be >= 0, given %s", damage); - this.getHandle().fallDamageMax = damage; + getHandle().fallDamageMax = damage; if (damage > 0) { this.setHurtEntities(true); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java index d05a2c0c..7e510737 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.entity.projectile.EntityFireball; +import net.minecraft.world.phys.Vec3D; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Fireball; import org.bukkit.projectiles.ProjectileSource; @@ -10,43 +10,43 @@ import org.jetbrains.annotations.NotNull; public class CraftFireball extends AbstractProjectile implements Fireball { - public CraftFireball(CraftServer server, AbstractHurtingProjectile entity) { + public CraftFireball(CraftServer server, EntityFireball entity) { super(server, entity); } @Override public float getYield() { - return this.getHandle().bukkitYield; + return getHandle().bukkitYield; } @Override public boolean isIncendiary() { - return this.getHandle().isIncendiary; + return getHandle().isIncendiary; } @Override public void setIsIncendiary(boolean isIncendiary) { - this.getHandle().isIncendiary = isIncendiary; + getHandle().isIncendiary = isIncendiary; } @Override public void setYield(float yield) { - this.getHandle().bukkitYield = yield; + getHandle().bukkitYield = yield; } @Override public ProjectileSource getShooter() { - return this.getHandle().projectileSource; + return getHandle().projectileSource; } @Override public void setShooter(ProjectileSource shooter) { if (shooter instanceof CraftLivingEntity) { - this.getHandle().setOwner(((CraftLivingEntity) shooter).getHandle()); + getHandle().setOwner(((CraftLivingEntity) shooter).getHandle()); } else { - this.getHandle().setOwner(null); + getHandle().setOwner(null); } - this.getHandle().projectileSource = shooter; + getHandle().projectileSource = shooter; } @Override @@ -62,6 +62,7 @@ public void setDirection(Vector direction) { setAcceleration(direction); return; } + direction = direction.clone().normalize(); setVelocity(direction.clone().multiply(getVelocity().length())); setAcceleration(direction.multiply(getAcceleration().length())); @@ -72,20 +73,20 @@ public void setAcceleration(@NotNull Vector acceleration) { Preconditions.checkArgument(acceleration != null, "Vector acceleration cannot be null"); // SPIGOT-6993: EntityFireball#assignPower will normalize the given values // Note: Because of MC-80142 the fireball will stutter on the client when setting the power to something other than 0 or the normalized vector * 0.1 - getHandle().assignDirectionalMovement(new Vec3(acceleration.getX(), acceleration.getY(), acceleration.getZ()), acceleration.length()); + getHandle().assignDirectionalMovement(new Vec3D(acceleration.getX(), acceleration.getY(), acceleration.getZ()), acceleration.length()); update(); // SPIGOT-6579 } @NotNull @Override public Vector getAcceleration() { - Vec3 delta = getHandle().getDeltaMovement(); + Vec3D delta = getHandle().getDeltaMovement(); return new Vector(delta.x, delta.y, delta.z); } @Override - public AbstractHurtingProjectile getHandle() { - return (AbstractHurtingProjectile) this.entity; + public EntityFireball getHandle() { + return (EntityFireball) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java index 5ae87c37..cb76204d 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java @@ -2,7 +2,8 @@ import com.google.common.base.Preconditions; import java.util.Random; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.projectile.EntityFireworks; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import org.bukkit.Material; @@ -17,14 +18,14 @@ public class CraftFirework extends CraftProjectile implements Firework { private final Random random = new Random(); private final CraftItemStack item; - public CraftFirework(CraftServer server, FireworkRocketEntity entity) { + public CraftFirework(CraftServer server, EntityFireworks entity) { super(server, entity); - ItemStack item = this.getHandle().getEntityData().get(FireworkRocketEntity.DATA_ID_FIREWORKS_ITEM); + ItemStack item = getHandle().getEntityData().get(EntityFireworks.DATA_ID_FIREWORKS_ITEM); if (item.isEmpty()) { item = new ItemStack(Items.FIREWORK_ROCKET); - this.getHandle().getEntityData().set(FireworkRocketEntity.DATA_ID_FIREWORKS_ITEM, item); + getHandle().getEntityData().set(EntityFireworks.DATA_ID_FIREWORKS_ITEM, item); } this.item = CraftItemStack.asCraftMirror(item); @@ -36,8 +37,8 @@ public CraftFirework(CraftServer server, FireworkRocketEntity entity) { } @Override - public FireworkRocketEntity getHandle() { - return (FireworkRocketEntity) this.entity; + public EntityFireworks getHandle() { + return (EntityFireworks) entity; } @Override @@ -47,32 +48,32 @@ public String toString() { @Override public FireworkMeta getFireworkMeta() { - return (FireworkMeta) this.item.getItemMeta(); + return (FireworkMeta) item.getItemMeta(); } @Override public void setFireworkMeta(FireworkMeta meta) { - this.item.setItemMeta(meta); + item.setItemMeta(meta); // Copied from EntityFireworks constructor, update firework lifetime/power - this.getHandle().lifetime = 10 * (1 + meta.getPower()) + this.random.nextInt(6) + this.random.nextInt(7); + getHandle().lifetime = 10 * (1 + meta.getPower()) + random.nextInt(6) + random.nextInt(7); - this.getHandle().getEntityData().markDirty(FireworkRocketEntity.DATA_ID_FIREWORKS_ITEM); + getHandle().getEntityData().markDirty(EntityFireworks.DATA_ID_FIREWORKS_ITEM); } @Override public boolean setAttachedTo(LivingEntity entity) { - if (this.isDetonated()) { + if (isDetonated()) { return false; } - this.getHandle().attachedToEntity = (entity != null) ? ((CraftLivingEntity) entity).getHandle() : null; + getHandle().attachedToEntity = (entity != null) ? ((CraftLivingEntity) entity).getHandle() : null; return true; } @Override public LivingEntity getAttachedTo() { - net.minecraft.world.entity.LivingEntity entity = this.getHandle().attachedToEntity; + EntityLiving entity = getHandle().attachedToEntity; return (entity != null) ? (LivingEntity) entity.getBukkitEntity() : null; } @@ -80,53 +81,53 @@ public LivingEntity getAttachedTo() { public boolean setLife(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks must be greater than or equal to 0"); - if (this.isDetonated()) { + if (isDetonated()) { return false; } - this.getHandle().life = ticks; + getHandle().life = ticks; return true; } @Override public int getLife() { - return this.getHandle().life; + return getHandle().life; } @Override public boolean setMaxLife(int ticks) { Preconditions.checkArgument(ticks > 0, "ticks must be greater than 0"); - if (this.isDetonated()) { + if (isDetonated()) { return false; } - this.getHandle().lifetime = ticks; + getHandle().lifetime = ticks; return true; } @Override public int getMaxLife() { - return this.getHandle().lifetime; + return getHandle().lifetime; } @Override public void detonate() { - this.setLife(this.getMaxLife() + 1); + this.setLife(getMaxLife() + 1); } @Override public boolean isDetonated() { - return this.getHandle().life > this.getHandle().lifetime; + return getHandle().life > getHandle().lifetime; } @Override public boolean isShotAtAngle() { - return this.getHandle().isShotAtAngle(); + return getHandle().isShotAtAngle(); } @Override public void setShotAtAngle(boolean shotAtAngle) { - this.getHandle().getEntityData().set(FireworkRocketEntity.DATA_SHOT_AT_ANGLE, shotAtAngle); + getHandle().getEntityData().set(EntityFireworks.DATA_SHOT_AT_ANGLE, shotAtAngle); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java index da5150f4..ec4aa908 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java @@ -1,18 +1,18 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.animal.AbstractFish; +import net.minecraft.world.entity.animal.EntityFish; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Fish; public class CraftFish extends CraftWaterMob implements Fish { - public CraftFish(CraftServer server, AbstractFish entity) { + public CraftFish(CraftServer server, EntityFish entity) { super(server, entity); } @Override - public AbstractFish getHandle() { - return (AbstractFish) this.entity; + public EntityFish getHandle() { + return (EntityFish) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java index 6e2f9142..8b249a2a 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java @@ -2,7 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.projectile.FishingHook; +import net.minecraft.world.entity.projectile.EntityFishingHook; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Entity; import org.bukkit.entity.FishHook; @@ -10,13 +10,13 @@ public class CraftFishHook extends CraftProjectile implements FishHook { private double biteChance = -1; - public CraftFishHook(CraftServer server, FishingHook entity) { + public CraftFishHook(CraftServer server, EntityFishingHook entity) { super(server, entity); } @Override - public FishingHook getHandle() { - return (FishingHook) this.entity; + public EntityFishingHook getHandle() { + return (EntityFishingHook) entity; } @Override @@ -26,126 +26,126 @@ public String toString() { @Override public int getMinWaitTime() { - return this.getHandle().minWaitTime; + return getHandle().minWaitTime; } @Override public void setMinWaitTime(int minWaitTime) { Preconditions.checkArgument(minWaitTime >= 0 && minWaitTime <= this.getMaxWaitTime(), "The minimum wait time should be between %s and %s (the maximum wait time)", 0, this.getMaxWaitTime()); - FishingHook hook = this.getHandle(); + EntityFishingHook hook = getHandle(); hook.minWaitTime = minWaitTime; } @Override public int getMaxWaitTime() { - return this.getHandle().maxWaitTime; + return getHandle().maxWaitTime; } @Override public void setMaxWaitTime(int maxWaitTime) { Preconditions.checkArgument(maxWaitTime >= 0 && maxWaitTime >= this.getMinWaitTime(), "The maximum wait time should be between %s and %s (the minimum wait time)", 0, this.getMinWaitTime()); - FishingHook hook = this.getHandle(); + EntityFishingHook hook = getHandle(); hook.maxWaitTime = maxWaitTime; } @Override public void setWaitTime(int min, int max) { Preconditions.checkArgument(min >= 0 && max >= 0 && min <= max, "The minimum/maximum wait time should be higher than or equal to 0 and the minimum wait time"); - this.getHandle().minWaitTime = min; - this.getHandle().maxWaitTime = max; + getHandle().minWaitTime = min; + getHandle().maxWaitTime = max; } @Override public int getMinLureTime() { - return this.getHandle().minLureTime; + return getHandle().minLureTime; } @Override public void setMinLureTime(int minLureTime) { Preconditions.checkArgument(minLureTime >= 0 && minLureTime <= this.getMaxLureTime(), "The minimum lure time (%s) should be between 0 and %s (the maximum wait time)", minLureTime, this.getMaxLureTime()); - this.getHandle().minLureTime = minLureTime; + getHandle().minLureTime = minLureTime; } @Override public int getMaxLureTime() { - return this.getHandle().maxLureTime; + return getHandle().maxLureTime; } @Override public void setMaxLureTime(int maxLureTime) { Preconditions.checkArgument(maxLureTime >= 0 && maxLureTime >= this.getMinLureTime(), "The maximum lure time (%s) should be higher than or equal to 0 and %s (the minimum wait time)", maxLureTime, this.getMinLureTime()); - this.getHandle().maxLureTime = maxLureTime; + getHandle().maxLureTime = maxLureTime; } @Override public void setLureTime(int min, int max) { Preconditions.checkArgument(min >= 0 && max >= 0 && min <= max, "The minimum/maximum lure time should be higher than or equal to 0 and the minimum wait time."); - this.getHandle().minLureTime = min; - this.getHandle().maxLureTime = max; + getHandle().minLureTime = min; + getHandle().maxLureTime = max; } @Override public float getMinLureAngle() { - return this.getHandle().minLureAngle; + return getHandle().minLureAngle; } @Override public void setMinLureAngle(float minLureAngle) { Preconditions.checkArgument(minLureAngle <= this.getMaxLureAngle(), "The minimum lure angle (%s) should be less than %s (the maximum lure angle)", minLureAngle, this.getMaxLureAngle()); - this.getHandle().minLureAngle = minLureAngle; + getHandle().minLureAngle = minLureAngle; } @Override public float getMaxLureAngle() { - return this.getHandle().maxLureAngle; + return getHandle().maxLureAngle; } @Override public void setMaxLureAngle(float maxLureAngle) { Preconditions.checkArgument(maxLureAngle >= this.getMinLureAngle(), "The minimum lure angle (%s) should be less than %s (the maximum lure angle)", maxLureAngle, this.getMinLureAngle()); - this.getHandle().maxLureAngle = maxLureAngle; + getHandle().maxLureAngle = maxLureAngle; } @Override public void setLureAngle(float min, float max) { Preconditions.checkArgument(min <= max, "The minimum lure (%s) angle should be less than the maximum lure angle (%s)", min, max); - this.getHandle().minLureAngle = min; - this.getHandle().maxLureAngle = max; + getHandle().minLureAngle = min; + getHandle().maxLureAngle = max; } @Override public boolean isSkyInfluenced() { - return this.getHandle().skyInfluenced; + return getHandle().skyInfluenced; } @Override public void setSkyInfluenced(boolean skyInfluenced) { - this.getHandle().skyInfluenced = skyInfluenced; + getHandle().skyInfluenced = skyInfluenced; } @Override public boolean isRainInfluenced() { - return this.getHandle().rainInfluenced; + return getHandle().rainInfluenced; } @Override public void setRainInfluenced(boolean rainInfluenced) { - this.getHandle().rainInfluenced = rainInfluenced; + getHandle().rainInfluenced = rainInfluenced; } @Override public boolean getApplyLure() { - return this.getHandle().applyLure; + return getHandle().applyLure; } @Override public void setApplyLure(boolean applyLure) { - this.getHandle().applyLure = applyLure; + getHandle().applyLure = applyLure; } @Override public double getBiteChance() { - FishingHook hook = this.getHandle(); + EntityFishingHook hook = getHandle(); if (this.biteChance == -1) { if (hook.level().isRainingAt(BlockPos.containing(hook.position()).offset(0, 1, 0))) { @@ -164,26 +164,26 @@ public void setBiteChance(double chance) { @Override public boolean isInOpenWater() { - return this.getHandle().isOpenWaterFishing(); + return getHandle().isOpenWaterFishing(); } @Override public Entity getHookedEntity() { - net.minecraft.world.entity.Entity hooked = this.getHandle().hookedIn; + net.minecraft.world.entity.Entity hooked = getHandle().hookedIn; return (hooked != null) ? hooked.getBukkitEntity() : null; } @Override public void setHookedEntity(Entity entity) { - FishingHook hook = this.getHandle(); + EntityFishingHook hook = getHandle(); hook.hookedIn = (entity != null) ? ((CraftEntity) entity).getHandle() : null; - hook.getEntityData().set(FishingHook.DATA_HOOKED_ENTITY, hook.hookedIn != null ? hook.hookedIn.getId() + 1 : 0); + hook.getEntityData().set(EntityFishingHook.DATA_HOOKED_ENTITY, hook.hookedIn != null ? hook.hookedIn.getId() + 1 : 0); } @Override public boolean pullHookedEntity() { - FishingHook hook = this.getHandle(); + EntityFishingHook hook = getHandle(); if (hook.hookedIn == null) { return false; } @@ -194,6 +194,6 @@ public boolean pullHookedEntity() { @Override public HookState getState() { - return HookState.values()[this.getHandle().currentState.ordinal()]; + return HookState.values()[getHandle().currentState.ordinal()]; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java index 8117faa0..a5ebbe73 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java @@ -1,18 +1,18 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.FlyingMob; +import net.minecraft.world.entity.EntityFlying; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Flying; public class CraftFlying extends CraftMob implements Flying { - public CraftFlying(CraftServer server, FlyingMob entity) { + public CraftFlying(CraftServer server, EntityFlying entity) { super(server, entity); } @Override - public FlyingMob getHandle() { - return (FlyingMob) this.entity; + public EntityFlying getHandle() { + return (EntityFlying) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java index 17164811..efcb213e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java @@ -3,6 +3,7 @@ import com.google.common.base.Preconditions; import java.util.Optional; import java.util.UUID; +import net.minecraft.world.entity.animal.EntityFox; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Fox; @@ -10,13 +11,13 @@ public class CraftFox extends CraftAnimals implements Fox { - public CraftFox(CraftServer server, net.minecraft.world.entity.animal.Fox entity) { + public CraftFox(CraftServer server, EntityFox entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Fox getHandle() { - return (net.minecraft.world.entity.animal.Fox) super.getHandle(); + public EntityFox getHandle() { + return (EntityFox) super.getHandle(); } @Override @@ -26,51 +27,51 @@ public String toString() { @Override public Type getFoxType() { - return Type.values()[this.getHandle().getVariant().ordinal()]; + return Type.values()[getHandle().getVariant().ordinal()]; } @Override public void setFoxType(Type type) { Preconditions.checkArgument(type != null, "type"); - this.getHandle().setVariant(net.minecraft.world.entity.animal.Fox.Type.values()[type.ordinal()]); + getHandle().setVariant(EntityFox.Type.values()[type.ordinal()]); } @Override public boolean isCrouching() { - return this.getHandle().isCrouching(); + return getHandle().isCrouching(); } @Override public void setCrouching(boolean crouching) { - this.getHandle().setIsCrouching(crouching); + getHandle().setIsCrouching(crouching); } @Override public boolean isSitting() { - return this.getHandle().isSitting(); + return getHandle().isSitting(); } @Override public void setSitting(boolean sitting) { - this.getHandle().setSitting(sitting); + getHandle().setSitting(sitting); } @Override public void setSleeping(boolean sleeping) { - this.getHandle().setSleeping(sleeping); + getHandle().setSleeping(sleeping); } @Override public AnimalTamer getFirstTrustedPlayer() { - UUID uuid = this.getHandle().getEntityData().get(net.minecraft.world.entity.animal.Fox.DATA_TRUSTED_ID_0).orElse(null); + UUID uuid = getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_0).orElse(null); if (uuid == null) { return null; } - AnimalTamer player = this.getServer().getPlayer(uuid); + AnimalTamer player = getServer().getPlayer(uuid); if (player == null) { - player = this.getServer().getOfflinePlayer(uuid); + player = getServer().getOfflinePlayer(uuid); } return player; @@ -79,22 +80,22 @@ public AnimalTamer getFirstTrustedPlayer() { @Override public void setFirstTrustedPlayer(AnimalTamer player) { if (player == null) { - Preconditions.checkState(this.getHandle().getEntityData().get(net.minecraft.world.entity.animal.Fox.DATA_TRUSTED_ID_1).isEmpty(), "Must remove second trusted player first"); + Preconditions.checkState(getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_1).isEmpty(), "Must remove second trusted player first"); } - this.getHandle().getEntityData().set(net.minecraft.world.entity.animal.Fox.DATA_TRUSTED_ID_0, player == null ? Optional.empty() : Optional.of(player.getUniqueId())); + getHandle().getEntityData().set(EntityFox.DATA_TRUSTED_ID_0, player == null ? Optional.empty() : Optional.of(player.getUniqueId())); } @Override public AnimalTamer getSecondTrustedPlayer() { - UUID uuid = this.getHandle().getEntityData().get(net.minecraft.world.entity.animal.Fox.DATA_TRUSTED_ID_1).orElse(null); + UUID uuid = getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_1).orElse(null); if (uuid == null) { return null; } - AnimalTamer player = this.getServer().getPlayer(uuid); + AnimalTamer player = getServer().getPlayer(uuid); if (player == null) { - player = this.getServer().getOfflinePlayer(uuid); + player = getServer().getOfflinePlayer(uuid); } return player; @@ -103,14 +104,14 @@ public AnimalTamer getSecondTrustedPlayer() { @Override public void setSecondTrustedPlayer(AnimalTamer player) { if (player != null) { - Preconditions.checkState(this.getHandle().getEntityData().get(net.minecraft.world.entity.animal.Fox.DATA_TRUSTED_ID_0).isPresent(), "Must add first trusted player first"); + Preconditions.checkState(getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_0).isPresent(), "Must add first trusted player first"); } - this.getHandle().getEntityData().set(net.minecraft.world.entity.animal.Fox.DATA_TRUSTED_ID_1, player == null ? Optional.empty() : Optional.of(player.getUniqueId())); + getHandle().getEntityData().set(EntityFox.DATA_TRUSTED_ID_1, player == null ? Optional.empty() : Optional.of(player.getUniqueId())); } @Override public boolean isFaceplanted() { - return this.getHandle().isFaceplanted(); + return getHandle().isFaceplanted(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFrog.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFrog.java index 2738e128..4a8e20bf 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFrog.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFrog.java @@ -10,7 +10,6 @@ import org.bukkit.Registry; import org.bukkit.craftbukkit.CraftRegistry; import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.craftbukkit.util.Handleable; import org.bukkit.entity.Entity; @@ -22,7 +21,7 @@ public CraftFrog(CraftServer server, Frog entity) { @Override public Frog getHandle() { - return (Frog) this.entity; + return (Frog) entity; } @Override @@ -32,28 +31,28 @@ public String toString() { @Override public Entity getTongueTarget() { - return this.getHandle().getTongueTarget().map(net.minecraft.world.entity.Entity::getBukkitEntity).orElse(null); + return getHandle().getTongueTarget().map(net.minecraft.world.entity.Entity::getBukkitEntity).orElse(null); } @Override public void setTongueTarget(Entity target) { if (target == null) { - this.getHandle().eraseTongueTarget(); + getHandle().eraseTongueTarget(); } else { - this.getHandle().setTongueTarget(((CraftEntity) target).getHandle()); + getHandle().setTongueTarget(((CraftEntity) target).getHandle()); } } @Override public Variant getVariant() { - return CraftVariant.minecraftHolderToBukkit(this.getHandle().getVariant()); + return CraftVariant.minecraftHolderToBukkit(getHandle().getVariant()); } @Override public void setVariant(Variant variant) { Preconditions.checkArgument(variant != null, "variant"); - this.getHandle().setVariant(CraftVariant.bukkitToMinecraftHolder(variant)); + getHandle().setVariant(CraftVariant.bukkitToMinecraftHolder(variant)); } public static class CraftVariant implements Variant, Handleable { @@ -64,7 +63,7 @@ public static Variant minecraftToBukkit(FrogVariant minecraft) { } public static Variant minecraftHolderToBukkit(Holder minecraft) { - return CraftVariant.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static FrogVariant bukkitToMinecraft(Variant bukkit) { @@ -92,38 +91,38 @@ public CraftVariant(NamespacedKey key, FrogVariant frogVariant) { } else { this.name = key.toString(); } - this.ordinal = CraftVariant.count++; + this.ordinal = count++; } @Override public FrogVariant getHandle() { - return this.frogVariant; + return frogVariant; } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public int compareTo(Variant variant) { - return this.ordinal - variant.ordinal(); + return ordinal - variant.ordinal(); } @Override public String name() { - return this.name; + return name; } @Override public int ordinal() { - return this.ordinal; + return ordinal; } @Override public String toString() { // For backwards compatibility - return this.name(); + return name(); } @Override @@ -136,12 +135,12 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((Variant) other).getKey()); + return getKey().equals(((Variant) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java index 2cec61a1..c3fc57a2 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityGhast; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Ghast; public class CraftGhast extends CraftFlying implements Ghast, CraftEnemy { - public CraftGhast(CraftServer server, net.minecraft.world.entity.monster.Ghast entity) { + public CraftGhast(CraftServer server, EntityGhast entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Ghast getHandle() { - return (net.minecraft.world.entity.monster.Ghast) this.entity; + public EntityGhast getHandle() { + return (EntityGhast) entity; } @Override @@ -21,11 +22,11 @@ public String toString() { @Override public boolean isCharging() { - return this.getHandle().isCharging(); + return getHandle().isCharging(); } @Override public void setCharging(boolean flag) { - this.getHandle().setCharging(flag); + getHandle().setCharging(flag); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java index 58262053..c06fe4c0 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityGiantZombie; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Giant; public class CraftGiant extends CraftMonster implements Giant { - public CraftGiant(CraftServer server, net.minecraft.world.entity.monster.Giant entity) { + public CraftGiant(CraftServer server, EntityGiantZombie entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Giant getHandle() { - return (net.minecraft.world.entity.monster.Giant) this.entity; + public EntityGiantZombie getHandle() { + return (EntityGiantZombie) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowItemFrame.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowItemFrame.java index b9a7576d..7dd9d670 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowItemFrame.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowItemFrame.java @@ -16,6 +16,6 @@ public net.minecraft.world.entity.decoration.GlowItemFrame getHandle() { @Override public String toString() { - return "CraftGlowItemFrame{item=" + this.getItem() + ", rotation=" + this.getRotation() + "}"; + return "CraftGlowItemFrame{item=" + getItem() + ", rotation=" + getRotation() + "}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowSquid.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowSquid.java index 253a0d2f..21a0da52 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowSquid.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGlowSquid.java @@ -22,12 +22,12 @@ public String toString() { @Override public int getDarkTicksRemaining() { - return this.getHandle().getDarkTicksRemaining(); + return getHandle().getDarkTicksRemaining(); } @Override public void setDarkTicksRemaining(int darkTicksRemaining) { Preconditions.checkArgument(darkTicksRemaining >= 0, "darkTicksRemaining must be >= 0"); - this.getHandle().setDarkTicks(darkTicksRemaining); + getHandle().setDarkTicks(darkTicksRemaining); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGoat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGoat.java index 65fcb36e..a07106dd 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGoat.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGoat.java @@ -21,31 +21,31 @@ public String toString() { @Override public boolean hasLeftHorn() { - return this.getHandle().hasLeftHorn(); + return getHandle().hasLeftHorn(); } @Override public void setLeftHorn(boolean hasHorn) { - this.getHandle().getEntityData().set(net.minecraft.world.entity.animal.goat.Goat.DATA_HAS_LEFT_HORN, hasHorn); + getHandle().getEntityData().set(net.minecraft.world.entity.animal.goat.Goat.DATA_HAS_LEFT_HORN, hasHorn); } @Override public boolean hasRightHorn() { - return this.getHandle().hasRightHorn(); + return getHandle().hasRightHorn(); } @Override public void setRightHorn(boolean hasHorn) { - this.getHandle().getEntityData().set(net.minecraft.world.entity.animal.goat.Goat.DATA_HAS_RIGHT_HORN, hasHorn); + getHandle().getEntityData().set(net.minecraft.world.entity.animal.goat.Goat.DATA_HAS_RIGHT_HORN, hasHorn); } @Override public boolean isScreaming() { - return this.getHandle().isScreamingGoat(); + return getHandle().isScreamingGoat(); } @Override public void setScreaming(boolean screaming) { - this.getHandle().setScreamingGoat(screaming); + getHandle().setScreamingGoat(screaming); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java index e27e4698..12fa1a09 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.animal.AbstractGolem; +import net.minecraft.world.entity.animal.EntityGolem; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Golem; public class CraftGolem extends CraftCreature implements Golem { - public CraftGolem(CraftServer server, AbstractGolem entity) { + public CraftGolem(CraftServer server, EntityGolem entity) { super(server, entity); } @Override - public AbstractGolem getHandle() { - return (AbstractGolem) this.entity; + public EntityGolem getHandle() { + return (EntityGolem) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java index e232350f..b1ad0243 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.monster.EntityGuardian; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Guardian; import org.bukkit.entity.LivingEntity; @@ -9,13 +10,13 @@ public class CraftGuardian extends CraftMonster implements Guardian { private static final int MINIMUM_ATTACK_TICKS = -10; - public CraftGuardian(CraftServer server, net.minecraft.world.entity.monster.Guardian entity) { + public CraftGuardian(CraftServer server, EntityGuardian entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Guardian getHandle() { - return (net.minecraft.world.entity.monster.Guardian) super.getHandle(); + public EntityGuardian getHandle() { + return (EntityGuardian) super.getHandle(); } @Override @@ -29,21 +30,21 @@ public void setTarget(LivingEntity target) { // clean up laser target, when target is removed if (target == null) { - this.getHandle().setActiveAttackTarget(0); + getHandle().setActiveAttackTarget(0); } } @Override public boolean setLaser(boolean activated) { if (activated) { - LivingEntity target = this.getTarget(); + LivingEntity target = getTarget(); if (target == null) { return false; } - this.getHandle().setActiveAttackTarget(target.getEntityId()); + getHandle().setActiveAttackTarget(target.getEntityId()); } else { - this.getHandle().setActiveAttackTarget(0); + getHandle().setActiveAttackTarget(0); } return true; @@ -51,19 +52,19 @@ public boolean setLaser(boolean activated) { @Override public boolean hasLaser() { - return this.getHandle().hasActiveAttackTarget(); + return getHandle().hasActiveAttackTarget(); } @Override public int getLaserDuration() { - return this.getHandle().getAttackDuration(); + return getHandle().getAttackDuration(); } @Override public void setLaserTicks(int ticks) { - Preconditions.checkArgument(ticks >= CraftGuardian.MINIMUM_ATTACK_TICKS, "ticks must be >= %s. Given %s", CraftGuardian.MINIMUM_ATTACK_TICKS, ticks); + Preconditions.checkArgument(ticks >= MINIMUM_ATTACK_TICKS, "ticks must be >= %s. Given %s", MINIMUM_ATTACK_TICKS, ticks); - net.minecraft.world.entity.monster.Guardian.GuardianAttackGoal goal = this.getHandle().guardianAttackGoal; + EntityGuardian.PathfinderGoalGuardianAttack goal = getHandle().guardianAttackGoal; if (goal != null) { goal.attackTime = ticks; } @@ -71,8 +72,8 @@ public void setLaserTicks(int ticks) { @Override public int getLaserTicks() { - net.minecraft.world.entity.monster.Guardian.GuardianAttackGoal goal = this.getHandle().guardianAttackGoal; - return (goal != null) ? goal.attackTime : CraftGuardian.MINIMUM_ATTACK_TICKS; + EntityGuardian.PathfinderGoalGuardianAttack goal = getHandle().guardianAttackGoal; + return (goal != null) ? goal.attackTime : MINIMUM_ATTACK_TICKS; } @Override @@ -87,6 +88,6 @@ public void setElder(boolean shouldBeElder) { @Override public boolean isMoving() { - return this.getHandle().isMoving(); + return getHandle().isMoving(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java index f1e3f2b8..753f5102 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java @@ -1,48 +1,48 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.core.Direction; -import net.minecraft.world.entity.decoration.HangingEntity; +import net.minecraft.core.EnumDirection; +import net.minecraft.world.entity.decoration.EntityHanging; import org.bukkit.block.BlockFace; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.block.CraftBlock; import org.bukkit.entity.Hanging; public class CraftHanging extends CraftBlockAttachedEntity implements Hanging { - public CraftHanging(CraftServer server, HangingEntity entity) { + public CraftHanging(CraftServer server, EntityHanging entity) { super(server, entity); } @Override public BlockFace getAttachedFace() { - return this.getFacing().getOppositeFace(); + return getFacing().getOppositeFace(); } @Override public void setFacingDirection(BlockFace face) { - this.setFacingDirection(face, false); + setFacingDirection(face, false); } @Override public boolean setFacingDirection(BlockFace face, boolean force) { - HangingEntity hanging = this.getHandle(); - Direction dir = hanging.getDirection(); + EntityHanging hanging = getHandle(); + EnumDirection dir = hanging.getDirection(); switch (face) { case SOUTH: - this.getHandle().setDirection(Direction.SOUTH); + getHandle().setDirection(EnumDirection.SOUTH); break; case WEST: - this.getHandle().setDirection(Direction.WEST); + getHandle().setDirection(EnumDirection.WEST); break; case NORTH: - this.getHandle().setDirection(Direction.NORTH); + getHandle().setDirection(EnumDirection.NORTH); break; case EAST: - this.getHandle().setDirection(Direction.EAST); + getHandle().setDirection(EnumDirection.EAST); break; default: throw new IllegalArgumentException(String.format("%s is not a valid facing direction", face)); } - if (!force && !this.getHandle().generation && !hanging.survives()) { + if (!force && !getHandle().generation && !hanging.survives()) { // Revert since it doesn't fit hanging.setDirection(dir); return false; @@ -52,14 +52,14 @@ public boolean setFacingDirection(BlockFace face, boolean force) { @Override public BlockFace getFacing() { - Direction direction = this.getHandle().getDirection(); + EnumDirection direction = this.getHandle().getDirection(); if (direction == null) return BlockFace.SELF; return CraftBlock.notchToBlockFace(direction); } @Override - public HangingEntity getHandle() { - return (HangingEntity) this.entity; + public EntityHanging getHandle() { + return (EntityHanging) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHoglin.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHoglin.java index 37007775..0a5391b0 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHoglin.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHoglin.java @@ -1,59 +1,60 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.monster.hoglin.EntityHoglin; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Hoglin; public class CraftHoglin extends CraftAnimals implements Hoglin, CraftEnemy { - public CraftHoglin(CraftServer server, net.minecraft.world.entity.monster.hoglin.Hoglin entity) { + public CraftHoglin(CraftServer server, EntityHoglin entity) { super(server, entity); } @Override public boolean isImmuneToZombification() { - return this.getHandle().isImmuneToZombification(); + return getHandle().isImmuneToZombification(); } @Override public void setImmuneToZombification(boolean flag) { - this.getHandle().setImmuneToZombification(flag); + getHandle().setImmuneToZombification(flag); } @Override public boolean isAbleToBeHunted() { - return this.getHandle().cannotBeHunted; + return getHandle().cannotBeHunted; } @Override public void setIsAbleToBeHunted(boolean flag) { - this.getHandle().cannotBeHunted = flag; + getHandle().cannotBeHunted = flag; } @Override public int getConversionTime() { - Preconditions.checkState(this.isConverting(), "Entity not converting"); - return this.getHandle().timeInOverworld; + Preconditions.checkState(isConverting(), "Entity not converting"); + return getHandle().timeInOverworld; } @Override public void setConversionTime(int time) { if (time < 0) { - this.getHandle().timeInOverworld = -1; - this.getHandle().setImmuneToZombification(false); + getHandle().timeInOverworld = -1; + getHandle().setImmuneToZombification(false); } else { - this.getHandle().timeInOverworld = time; + getHandle().timeInOverworld = time; } } @Override public boolean isConverting() { - return this.getHandle().isConverting(); + return getHandle().isConverting(); } @Override - public net.minecraft.world.entity.monster.hoglin.Hoglin getHandle() { - return (net.minecraft.world.entity.monster.hoglin.Hoglin) this.entity; + public EntityHoglin getHandle() { + return (EntityHoglin) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java index 6b2a4d85..61f1fef5 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java @@ -1,7 +1,9 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.animal.horse.Markings; +import net.minecraft.world.entity.animal.horse.EntityHorse; +import net.minecraft.world.entity.animal.horse.HorseColor; +import net.minecraft.world.entity.animal.horse.HorseStyle; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventoryHorse; import org.bukkit.entity.Horse; @@ -9,13 +11,13 @@ public class CraftHorse extends CraftAbstractHorse implements Horse { - public CraftHorse(CraftServer server, net.minecraft.world.entity.animal.horse.Horse entity) { + public CraftHorse(CraftServer server, EntityHorse entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.horse.Horse getHandle() { - return (net.minecraft.world.entity.animal.horse.Horse) super.getHandle(); + public EntityHorse getHandle() { + return (EntityHorse) super.getHandle(); } @Override @@ -25,24 +27,24 @@ public Variant getVariant() { @Override public Color getColor() { - return Color.values()[this.getHandle().getVariant().getId()]; + return Color.values()[getHandle().getVariant().getId()]; } @Override public void setColor(Color color) { Preconditions.checkArgument(color != null, "Color cannot be null"); - this.getHandle().setVariantAndMarkings(net.minecraft.world.entity.animal.horse.Variant.byId(color.ordinal()), this.getHandle().getMarkings()); + getHandle().setVariantAndMarkings(HorseColor.byId(color.ordinal()), getHandle().getMarkings()); } @Override public Style getStyle() { - return Style.values()[this.getHandle().getMarkings().getId()]; + return Style.values()[getHandle().getMarkings().getId()]; } @Override public void setStyle(Style style) { Preconditions.checkArgument(style != null, "Style cannot be null"); - this.getHandle().setVariantAndMarkings(this.getHandle().getVariant(), Markings.byId(style.ordinal())); + getHandle().setVariantAndMarkings(getHandle().getVariant(), HorseStyle.byId(style.ordinal())); } @Override @@ -57,11 +59,11 @@ public void setCarryingChest(boolean chest) { @Override public HorseInventory getInventory() { - return new CraftInventoryHorse(this.getHandle().inventory, getHandle().getBodyArmorAccess()); + return new CraftInventoryHorse(getHandle().inventory, getHandle().getBodyArmorAccess()); } @Override public String toString() { - return "CraftHorse{variant=" + this.getVariant() + ", owner=" + this.getOwner() + '}'; + return "CraftHorse{variant=" + getVariant() + ", owner=" + getOwner() + '}'; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java index c01b8d9c..ddeb3356 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java @@ -8,26 +8,29 @@ import java.util.Optional; import java.util.Set; import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket; -import net.minecraft.network.protocol.game.ServerboundContainerClosePacket; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.MenuProvider; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.network.protocol.game.PacketPlayInCloseWindow; +import net.minecraft.network.protocol.game.PacketPlayOutOpenWindow; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.ITileInventory; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.HumanoidArm; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.item.ItemCooldowns; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EnumMainHand; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.entity.projectile.EntityFireworks; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.Containers; +import net.minecraft.world.item.ItemCooldown; +import net.minecraft.world.item.crafting.CraftingManager; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraft.world.level.block.BedBlock; +import net.minecraft.world.item.trading.IMerchant; +import net.minecraft.world.level.block.BlockBed; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; @@ -44,11 +47,10 @@ import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftItemType; import org.bukkit.craftbukkit.inventory.CraftMerchantCustom; +import org.bukkit.craftbukkit.inventory.CraftRecipe; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftLocation; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.entity.Firework; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Villager; @@ -73,90 +75,90 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity { private boolean op; private GameMode mode; - public CraftHumanEntity(final CraftServer server, final Player entity) { + public CraftHumanEntity(final CraftServer server, final EntityHuman entity) { super(server, entity); - this.mode = server.getDefaultGameMode(); + mode = server.getDefaultGameMode(); this.inventory = new CraftInventoryPlayer(entity.getInventory()); - this.enderChest = new CraftInventory(entity.getEnderChestInventory()); + enderChest = new CraftInventory(entity.getEnderChestInventory()); } @Override public PlayerInventory getInventory() { - return this.inventory; + return inventory; } @Override public EntityEquipment getEquipment() { - return this.inventory; + return inventory; } @Override public Inventory getEnderChest() { - return this.enderChest; + return enderChest; } @Override public MainHand getMainHand() { - return this.getHandle().getMainArm() == HumanoidArm.LEFT ? MainHand.LEFT : MainHand.RIGHT; + return getHandle().getMainArm() == EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT; } @Override public ItemStack getItemInHand() { - return this.getInventory().getItemInHand(); + return getInventory().getItemInHand(); } @Override public void setItemInHand(ItemStack item) { - this.getInventory().setItemInHand(item); + getInventory().setItemInHand(item); } @Override public ItemStack getItemOnCursor() { - return CraftItemStack.asCraftMirror(this.getHandle().containerMenu.getCarried()); + return CraftItemStack.asCraftMirror(getHandle().containerMenu.getCarried()); } @Override public void setItemOnCursor(ItemStack item) { net.minecraft.world.item.ItemStack stack = CraftItemStack.asNMSCopy(item); - this.getHandle().containerMenu.setCarried(stack); + getHandle().containerMenu.setCarried(stack); if (this instanceof CraftPlayer) { - this.getHandle().containerMenu.broadcastCarriedItem(); // Send set slot for cursor + getHandle().containerMenu.broadcastCarriedItem(); // Send set slot for cursor } } @Override public int getSleepTicks() { - return this.getHandle().sleepCounter; + return getHandle().sleepCounter; } @Override public boolean sleep(Location location, boolean force) { Preconditions.checkArgument(location != null, "Location cannot be null"); Preconditions.checkArgument(location.getWorld() != null, "Location needs to be in a world"); - Preconditions.checkArgument(location.getWorld().equals(this.getWorld()), "Cannot sleep across worlds"); + Preconditions.checkArgument(location.getWorld().equals(getWorld()), "Cannot sleep across worlds"); - BlockPos blockposition = CraftLocation.toBlockPosition(location); - BlockState iblockdata = this.getHandle().level().getBlockState(blockposition); - if (!(iblockdata.getBlock() instanceof BedBlock)) { + BlockPos blockposition = CraftLocation.toBlockPos(location); + IBlockData iblockdata = getHandle().level().getBlockState(blockposition); + if (!(iblockdata.getBlock() instanceof BlockBed)) { return false; } - if (this.getHandle().forceSleepInBed(force).startSleepInBed(blockposition).left().isPresent()) { + if (getHandle().startSleepInBed(blockposition, force).left().isPresent()) { return false; } // From BlockBed - iblockdata = iblockdata.setValue(BedBlock.OCCUPIED, true); - this.getHandle().level().setBlock(blockposition, iblockdata, 4); + iblockdata = iblockdata.setValue(BlockBed.OCCUPIED, true); + getHandle().level().setBlock(blockposition, iblockdata, 4); return true; } @Override public void wakeup(boolean setSpawnLocation) { - Preconditions.checkState(this.isSleeping(), "Cannot wakeup if not sleeping"); + Preconditions.checkState(isSleeping(), "Cannot wakeup if not sleeping"); - this.getHandle().stopSleepInBed(true, setSpawnLocation); + getHandle().stopSleepInBed(true, setSpawnLocation); } @Override @@ -169,25 +171,25 @@ public void startRiptideAttack(int duration, float damage, ItemStack attackItem) @Override public Location getBedLocation() { - Preconditions.checkState(this.isSleeping(), "Not sleeping"); + Preconditions.checkState(isSleeping(), "Not sleeping"); - BlockPos bed = this.getHandle().getSleepingPos().get(); - return CraftLocation.toBukkit(bed, this.getWorld()); + BlockPos bed = getHandle().getSleepingPos().get(); + return CraftLocation.toBukkit(bed, getWorld()); } @Override public String getName() { - return this.getHandle().getScoreboardName(); + return getHandle().getScoreboardName(); } @Override public boolean isOp() { - return this.op; + return op; } @Override public boolean isPermissionSet(String name) { - return this.perm.isPermissionSet(name); + return perm.isPermissionSet(name); } @Override @@ -197,7 +199,7 @@ public boolean isPermissionSet(Permission perm) { @Override public boolean hasPermission(String name) { - return this.perm.hasPermission(name); + return perm.hasPermission(name); } @Override @@ -207,48 +209,48 @@ public boolean hasPermission(Permission perm) { @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return this.perm.addAttachment(plugin, name, value); + return perm.addAttachment(plugin, name, value); } @Override public PermissionAttachment addAttachment(Plugin plugin) { - return this.perm.addAttachment(plugin); + return perm.addAttachment(plugin); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return this.perm.addAttachment(plugin, name, value, ticks); + return perm.addAttachment(plugin, name, value, ticks); } @Override public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return this.perm.addAttachment(plugin, ticks); + return perm.addAttachment(plugin, ticks); } @Override public void removeAttachment(PermissionAttachment attachment) { - this.perm.removeAttachment(attachment); + perm.removeAttachment(attachment); } @Override public void recalculatePermissions() { - this.perm.recalculatePermissions(); + perm.recalculatePermissions(); } @Override public void setOp(boolean value) { this.op = value; - this.perm.recalculatePermissions(); + perm.recalculatePermissions(); } @Override public Set getEffectivePermissions() { - return this.perm.getEffectivePermissions(); + return perm.getEffectivePermissions(); } @Override public GameMode getGameMode() { - return this.mode; + return mode; } @Override @@ -259,79 +261,79 @@ public void setGameMode(GameMode mode) { } @Override - public Player getHandle() { - return (Player) this.entity; + public EntityHuman getHandle() { + return (EntityHuman) entity; } - public void setHandle(final Player entity) { + public void setHandle(final EntityHuman entity) { super.setHandle(entity); this.inventory = new CraftInventoryPlayer(entity.getInventory()); } @Override public String toString() { - return "CraftHumanEntity{" + "id=" + this.getEntityId() + "name=" + this.getName() + '}'; + return "CraftHumanEntity{" + "id=" + getEntityId() + "name=" + getName() + '}'; } @Override public InventoryView getOpenInventory() { - return this.getHandle().containerMenu.getBukkitView(); + return getHandle().containerMenu.getBukkitView(); } @Override public InventoryView openInventory(Inventory inventory) { - if (!(this.getHandle() instanceof ServerPlayer)) return null; - ServerPlayer player = (ServerPlayer) this.getHandle(); - AbstractContainerMenu formerContainer = this.getHandle().containerMenu; + if (!(getHandle() instanceof EntityPlayer)) return null; + EntityPlayer player = (EntityPlayer) getHandle(); + Container formerContainer = getHandle().containerMenu; - MenuProvider tileInventory = null; + ITileInventory tileInventory = null; if (inventory instanceof CraftInventoryDoubleChest) { tileInventory = ((CraftInventoryDoubleChest) inventory).tile; } else if (inventory instanceof CraftInventoryLectern) { tileInventory = ((CraftInventoryLectern) inventory).tile; } else if (inventory instanceof CraftInventory) { CraftInventory craft = (CraftInventory) inventory; - if (craft.getInventory() instanceof MenuProvider) { - tileInventory = (MenuProvider) craft.getInventory(); + if (craft.getInventory() instanceof ITileInventory) { + tileInventory = (ITileInventory) craft.getInventory(); } } - if (tileInventory instanceof MenuProvider) { - if (tileInventory instanceof BlockEntity) { - BlockEntity te = (BlockEntity) tileInventory; + if (tileInventory instanceof ITileInventory) { + if (tileInventory instanceof TileEntity) { + TileEntity te = (TileEntity) tileInventory; if (!te.hasLevel()) { - te.setLevel(this.getHandle().level()); + te.setLevel(getHandle().level()); } } } - if (tileInventory instanceof MenuProvider) { - this.getHandle().openMenu(tileInventory); + if (tileInventory instanceof ITileInventory) { + getHandle().openMenu(tileInventory); } else if (inventory instanceof CraftInventoryAbstractHorse craft && craft.getInventory().getOwner() instanceof CraftAbstractHorse horse) { - this.getHandle().openHorseInventory(horse.getHandle(), craft.getInventory()); + getHandle().openHorseInventory(horse.getHandle(), craft.getInventory()); } else { - MenuType container = CraftContainer.getNotchInventoryType(inventory); - CraftHumanEntity.openCustomInventory(inventory, player, container); + Containers container = CraftContainer.getNotchInventoryType(inventory); + openCustomInventory(inventory, player, container); } - if (this.getHandle().containerMenu == formerContainer) { + if (getHandle().containerMenu == formerContainer) { return null; } - this.getHandle().containerMenu.checkReachable = false; - return this.getHandle().containerMenu.getBukkitView(); + getHandle().containerMenu.checkReachable = false; + return getHandle().containerMenu.getBukkitView(); } - private static void openCustomInventory(Inventory inventory, ServerPlayer player, MenuType windowType) { + private static void openCustomInventory(Inventory inventory, EntityPlayer player, Containers windowType) { if (player.connection == null) return; Preconditions.checkArgument(windowType != null, "Unknown windowType"); - AbstractContainerMenu container = new CraftContainer(inventory, player, player.nextContainerCounterInt()); + Container container = new CraftContainer(inventory, player, player.nextContainerCounter()); container = CraftEventFactory.callInventoryOpenEvent(player, container); if (container == null) return; String title = container.getBukkitView().getTitle(); - player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); + player.connection.send(new PacketPlayOutOpenWindow(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); player.containerMenu = container; player.initMenu(container); } @@ -339,7 +341,7 @@ private static void openCustomInventory(Inventory inventory, ServerPlayer player @Override public InventoryView openWorkbench(Location location, boolean force) { if (location == null) { - location = this.getLocation(); + location = getLocation(); } if (!force) { Block block = location.getBlock(); @@ -347,17 +349,17 @@ public InventoryView openWorkbench(Location location, boolean force) { return null; } } - this.getHandle().openMenu(Blocks.CRAFTING_TABLE.defaultBlockState().getMenuProvider(this.getHandle().level(), CraftLocation.toBlockPosition(location))); + getHandle().openMenu(Blocks.CRAFTING_TABLE.defaultBlockState().getMenuProvider(getHandle().level(), CraftLocation.toBlockPos(location))); if (force) { - this.getHandle().containerMenu.checkReachable = false; + getHandle().containerMenu.checkReachable = false; } - return this.getHandle().containerMenu.getBukkitView(); + return getHandle().containerMenu.getBukkitView(); } @Override public InventoryView openEnchanting(Location location, boolean force) { if (location == null) { - location = this.getLocation(); + location = getLocation(); } if (!force) { Block block = location.getBlock(); @@ -367,30 +369,30 @@ public InventoryView openEnchanting(Location location, boolean force) { } // If there isn't an enchant table we can force create one, won't be very useful though. - BlockPos pos = CraftLocation.toBlockPosition(location); - this.getHandle().openMenu(Blocks.ENCHANTING_TABLE.defaultBlockState().getMenuProvider(this.getHandle().level(), pos)); + BlockPos pos = CraftLocation.toBlockPos(location); + getHandle().openMenu(Blocks.ENCHANTING_TABLE.defaultBlockState().getMenuProvider(getHandle().level(), pos)); if (force) { - this.getHandle().containerMenu.checkReachable = false; + getHandle().containerMenu.checkReachable = false; } - return this.getHandle().containerMenu.getBukkitView(); + return getHandle().containerMenu.getBukkitView(); } @Override public void openInventory(InventoryView inventory) { Preconditions.checkArgument(this.equals(inventory.getPlayer()), "InventoryView must belong to the opening player"); - if (!(this.getHandle() instanceof ServerPlayer)) return; // TODO: NPC support? - if (((ServerPlayer) this.getHandle()).connection == null) return; - if (this.getHandle().containerMenu != this.getHandle().inventoryMenu) { + if (!(getHandle() instanceof EntityPlayer)) return; // TODO: NPC support? + if (((EntityPlayer) getHandle()).connection == null) return; + if (getHandle().containerMenu != getHandle().inventoryMenu) { // fire INVENTORY_CLOSE if one already open - ((ServerPlayer) this.getHandle()).connection.handleContainerClose(new ServerboundContainerClosePacket(this.getHandle().containerMenu.containerId)); + ((EntityPlayer) getHandle()).connection.handleContainerClose(new PacketPlayInCloseWindow(getHandle().containerMenu.containerId)); } - ServerPlayer player = (ServerPlayer) this.getHandle(); - AbstractContainerMenu container; + EntityPlayer player = (EntityPlayer) getHandle(); + Container container; if (inventory instanceof CraftInventoryView) { container = ((CraftInventoryView) inventory).getHandle(); } else { - container = new CraftContainer(inventory, this.getHandle(), player.nextContainerCounterInt()); + container = new CraftContainer(inventory, this.getHandle(), player.nextContainerCounter()); } // Trigger an INVENTORY_OPEN event @@ -400,9 +402,9 @@ public void openInventory(InventoryView inventory) { } // Now open the window - MenuType windowType = CraftContainer.getNotchInventoryType(inventory.getTopInventory()); + Containers windowType = CraftContainer.getNotchInventoryType(inventory.getTopInventory()); String title = inventory.getTitle(); - player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); + player.connection.send(new PacketPlayOutOpenWindow(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); player.containerMenu = container; player.initMenu(container); } @@ -425,8 +427,8 @@ public InventoryView openMerchant(Merchant merchant, boolean force) { merchant.getTrader().closeInventory(); } - net.minecraft.world.item.trading.Merchant mcMerchant; - Component name; + IMerchant mcMerchant; + IChatBaseComponent name; int level = 1; // note: using level 0 with active 'is-regular-villager'-flag allows hiding the name suffix if (merchant instanceof CraftAbstractVillager) { mcMerchant = ((CraftAbstractVillager) merchant).getHandle(); @@ -449,17 +451,17 @@ public InventoryView openMerchant(Merchant merchant, boolean force) { @Override public void closeInventory() { - this.getHandle().closeContainer(); + getHandle().closeContainer(); } @Override public boolean isBlocking() { - return this.getHandle().isBlocking(); + return getHandle().isBlocking(); } @Override public boolean isHandRaised() { - return this.getHandle().isUsingItem(); + return getHandle().isUsingItem(); } @Override @@ -469,22 +471,22 @@ public boolean setWindowProperty(InventoryView.Property prop, int value) { @Override public int getEnchantmentSeed() { - return this.getHandle().enchantmentSeed; + return getHandle().enchantmentSeed; } @Override public void setEnchantmentSeed(int i) { - this.getHandle().enchantmentSeed = i; + getHandle().enchantmentSeed = i; } @Override public int getExpToLevel() { - return this.getHandle().getXpNeededForNextLevel(); + return getHandle().getXpNeededForNextLevel(); } @Override public float getAttackCooldown() { - return this.getHandle().getAttackStrengthScale(0.5f); + return getHandle().getAttackStrengthScale(0.5f); } @Override @@ -492,7 +494,7 @@ public boolean hasCooldown(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); Preconditions.checkArgument(material.isItem(), "Material %s is not an item", material); - return this.getHandle().getCooldowns().isOnCooldown(CraftItemType.bukkitToMinecraft(material)); + return hasCooldown(new ItemStack(material)); } @Override @@ -500,37 +502,60 @@ public int getCooldown(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); Preconditions.checkArgument(material.isItem(), "Material %s is not an item", material); - ItemCooldowns.CooldownInstance cooldown = this.getHandle().getCooldowns().cooldowns.get(CraftItemType.bukkitToMinecraft(material)); - return (cooldown == null) ? 0 : Math.max(0, cooldown.endTime - this.getHandle().getCooldowns().tickCount); + return getCooldown(new ItemStack(material)); } @Override public void setCooldown(Material material, int ticks) { - Preconditions.checkArgument(material != null, "Material cannot be null"); - Preconditions.checkArgument(material.isItem(), "Material %s is not an item", material); + setCooldown(new ItemStack(material), ticks); + } + + @Override + public boolean hasCooldown(ItemStack item) { + Preconditions.checkArgument(item != null, "Material cannot be null"); + + return getHandle().getCooldowns().isOnCooldown(CraftItemStack.asNMSCopy(item)); + } + + @Override + public int getCooldown(ItemStack item) { + Preconditions.checkArgument(item != null, "Material cannot be null"); + + MinecraftKey group = getHandle().getCooldowns().getCooldownGroup(CraftItemStack.asNMSCopy(item)); + if (group == null) { + return 0; + } + + ItemCooldown.Info cooldown = getHandle().getCooldowns().cooldowns.get(group); + return (cooldown == null) ? 0 : Math.max(0, cooldown.endTime - getHandle().getCooldowns().tickCount); + } + + @Override + public void setCooldown(ItemStack item, int ticks) { + Preconditions.checkArgument(item != null, "Material cannot be null"); Preconditions.checkArgument(ticks >= 0, "Cannot have negative cooldown"); - this.getHandle().getCooldowns().addCooldown(CraftItemType.bukkitToMinecraft(material), ticks); + getHandle().getCooldowns().addCooldown(CraftItemStack.asNMSCopy(item), ticks); } @Override public boolean discoverRecipe(NamespacedKey recipe) { - return this.discoverRecipes(Arrays.asList(recipe)) != 0; + return discoverRecipes(Arrays.asList(recipe)) != 0; } @Override public int discoverRecipes(Collection recipes) { - return this.getHandle().awardRecipes(this.bukkitKeysToMinecraftRecipes(recipes)); + return getHandle().awardRecipes(bukkitKeysToMinecraftRecipes(recipes)); } @Override public boolean undiscoverRecipe(NamespacedKey recipe) { - return this.undiscoverRecipes(Arrays.asList(recipe)) != 0; + return undiscoverRecipes(Arrays.asList(recipe)) != 0; } @Override public int undiscoverRecipes(Collection recipes) { - return this.getHandle().resetRecipes(this.bukkitKeysToMinecraftRecipes(recipes)); + return getHandle().resetRecipes(bukkitKeysToMinecraftRecipes(recipes)); } @Override @@ -545,10 +570,10 @@ public Set getDiscoveredRecipes() { private Collection> bukkitKeysToMinecraftRecipes(Collection recipeKeys) { Collection> recipes = new ArrayList<>(); - RecipeManager manager = this.getHandle().level().getServer().getRecipeManager(); + CraftingManager manager = getHandle().level().getServer().getRecipeManager(); for (NamespacedKey recipeKey : recipeKeys) { - Optional> recipe = manager.byKey(CraftNamespacedKey.toMinecraft(recipeKey)); + Optional> recipe = manager.byKey(CraftRecipe.toMinecraft(recipeKey)); if (!recipe.isPresent()) { continue; } @@ -561,8 +586,8 @@ private Collection> bukkitKeysToMinecraftRecipes(Collection shoulder = EntityType.create(this.getHandle().getShoulderEntityLeft(), this.getHandle().level()); + if (!getHandle().getShoulderEntityLeft().isEmpty()) { + Optional shoulder = EntityTypes.create(getHandle().getShoulderEntityLeft(), getHandle().level(), EntitySpawnReason.LOAD); return (!shoulder.isPresent()) ? null : shoulder.get().getBukkitEntity(); } @@ -572,7 +597,7 @@ public org.bukkit.entity.Entity getShoulderEntityLeft() { @Override public void setShoulderEntityLeft(org.bukkit.entity.Entity entity) { - this.getHandle().setShoulderEntityLeft(entity == null ? new CompoundTag() : ((CraftEntity) entity).save()); + getHandle().setShoulderEntityLeft(entity == null ? new NBTTagCompound() : ((CraftEntity) entity).save()); if (entity != null) { entity.remove(); } @@ -580,8 +605,8 @@ public void setShoulderEntityLeft(org.bukkit.entity.Entity entity) { @Override public org.bukkit.entity.Entity getShoulderEntityRight() { - if (!this.getHandle().getShoulderEntityRight().isEmpty()) { - Optional shoulder = EntityType.create(this.getHandle().getShoulderEntityRight(), this.getHandle().level()); + if (!getHandle().getShoulderEntityRight().isEmpty()) { + Optional shoulder = EntityTypes.create(getHandle().getShoulderEntityRight(), getHandle().level(), EntitySpawnReason.LOAD); return (!shoulder.isPresent()) ? null : shoulder.get().getBukkitEntity(); } @@ -591,7 +616,7 @@ public org.bukkit.entity.Entity getShoulderEntityRight() { @Override public void setShoulderEntityRight(org.bukkit.entity.Entity entity) { - this.getHandle().setShoulderEntityRight(entity == null ? new CompoundTag() : ((CraftEntity) entity).save()); + getHandle().setShoulderEntityRight(entity == null ? new NBTTagCompound() : ((CraftEntity) entity).save()); if (entity != null) { entity.remove(); } @@ -599,81 +624,81 @@ public void setShoulderEntityRight(org.bukkit.entity.Entity entity) { @Override public boolean dropItem(boolean dropAll) { - if (!(this.getHandle() instanceof ServerPlayer)) return false; - return ((ServerPlayer) this.getHandle()).drop(dropAll); + if (!(getHandle() instanceof EntityPlayer)) return false; + return ((EntityPlayer) getHandle()).drop(dropAll); } @Override public float getExhaustion() { - return this.getHandle().getFoodData().exhaustionLevel; + return getHandle().getFoodData().exhaustionLevel; } @Override public void setExhaustion(float value) { - this.getHandle().getFoodData().exhaustionLevel = value; + getHandle().getFoodData().exhaustionLevel = value; } @Override public float getSaturation() { - return this.getHandle().getFoodData().saturationLevel; + return getHandle().getFoodData().saturationLevel; } @Override public void setSaturation(float value) { - this.getHandle().getFoodData().saturationLevel = value; + getHandle().getFoodData().saturationLevel = value; } @Override public int getFoodLevel() { - return this.getHandle().getFoodData().foodLevel; + return getHandle().getFoodData().foodLevel; } @Override public void setFoodLevel(int value) { - this.getHandle().getFoodData().foodLevel = value; + getHandle().getFoodData().foodLevel = value; } @Override public int getSaturatedRegenRate() { - return this.getHandle().getFoodData().saturatedRegenRate; + return getHandle().getFoodData().saturatedRegenRate; } @Override public void setSaturatedRegenRate(int i) { - this.getHandle().getFoodData().saturatedRegenRate = i; + getHandle().getFoodData().saturatedRegenRate = i; } @Override public int getUnsaturatedRegenRate() { - return this.getHandle().getFoodData().unsaturatedRegenRate; + return getHandle().getFoodData().unsaturatedRegenRate; } @Override public void setUnsaturatedRegenRate(int i) { - this.getHandle().getFoodData().unsaturatedRegenRate = i; + getHandle().getFoodData().unsaturatedRegenRate = i; } @Override public int getStarvationRate() { - return this.getHandle().getFoodData().starvationRate; + return getHandle().getFoodData().starvationRate; } @Override public void setStarvationRate(int i) { - this.getHandle().getFoodData().starvationRate = i; + getHandle().getFoodData().starvationRate = i; } @Override public Location getLastDeathLocation() { - return this.getHandle().getLastDeathLocation().map(CraftMemoryMapper::fromNms).orElse(null); + return getHandle().getLastDeathLocation().map(CraftMemoryMapper::fromNms).orElse(null); } @Override public void setLastDeathLocation(Location location) { if (location == null) { - this.getHandle().setLastDeathLocation(Optional.empty()); + getHandle().setLastDeathLocation(Optional.empty()); } else { - this.getHandle().setLastDeathLocation(Optional.of(CraftMemoryMapper.toNms(location))); + getHandle().setLastDeathLocation(Optional.of(CraftMemoryMapper.toNms(location))); } } @@ -682,8 +707,8 @@ public Firework fireworkBoost(ItemStack fireworkItemStack) { Preconditions.checkArgument(fireworkItemStack != null, "fireworkItemStack must not be null"); Preconditions.checkArgument(fireworkItemStack.getType() == Material.FIREWORK_ROCKET, "fireworkItemStack must be of type %s", Material.FIREWORK_ROCKET); - FireworkRocketEntity fireworks = new FireworkRocketEntity(this.getHandle().level(), CraftItemStack.asNMSCopy(fireworkItemStack), this.getHandle()); - boolean success = this.getHandle().level().addFreshEntity(fireworks, SpawnReason.CUSTOM); + EntityFireworks fireworks = new EntityFireworks(getHandle().level(), CraftItemStack.asNMSCopy(fireworkItemStack), getHandle()); + boolean success = getHandle().level().addFreshEntity(fireworks, SpawnReason.CUSTOM); return success ? (Firework) fireworks.getBukkitEntity() : null; } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java index 4822c744..76f4d809 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java @@ -1,11 +1,12 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityZombieHusk; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Husk; public class CraftHusk extends CraftZombie implements Husk { - public CraftHusk(CraftServer server, net.minecraft.world.entity.monster.Husk entity) { + public CraftHusk(CraftServer server, EntityZombieHusk entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java index fb3c518f..c8be7704 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java @@ -1,18 +1,18 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.monster.AbstractIllager; +import net.minecraft.world.entity.monster.EntityIllagerAbstract; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Illager; public class CraftIllager extends CraftRaider implements Illager { - public CraftIllager(CraftServer server, AbstractIllager entity) { + public CraftIllager(CraftServer server, EntityIllagerAbstract entity) { super(server, entity); } @Override - public AbstractIllager getHandle() { - return (AbstractIllager) super.getHandle(); + public EntityIllagerAbstract getHandle() { + return (EntityIllagerAbstract) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java index 995c77ee..b4116f6b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityIllagerIllusioner; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Illusioner; public class CraftIllusioner extends CraftSpellcaster implements Illusioner { - public CraftIllusioner(CraftServer server, net.minecraft.world.entity.monster.Illusioner entity) { + public CraftIllusioner(CraftServer server, EntityIllagerIllusioner entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Illusioner getHandle() { - return (net.minecraft.world.entity.monster.Illusioner) super.getHandle(); + public EntityIllagerIllusioner getHandle() { + return (EntityIllagerIllusioner) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftInteraction.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftInteraction.java index caa3016b..d60ad117 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftInteraction.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftInteraction.java @@ -24,44 +24,44 @@ public String toString() { @Override public float getInteractionWidth() { - return this.getHandle().getWidth(); + return getHandle().getWidth(); } @Override public void setInteractionWidth(float width) { - this.getHandle().setWidth(width); + getHandle().setWidth(width); } @Override public float getInteractionHeight() { - return this.getHandle().getHeight(); + return getHandle().getHeight(); } @Override public void setInteractionHeight(float height) { - this.getHandle().setHeight(height); + getHandle().setHeight(height); } @Override public boolean isResponsive() { - return this.getHandle().getResponse(); + return getHandle().getResponse(); } @Override public void setResponsive(boolean response) { - this.getHandle().setResponse(response); + getHandle().setResponse(response); } @Override public PreviousInteraction getLastAttack() { - net.minecraft.world.entity.Interaction.PlayerAction last = this.getHandle().attack; + net.minecraft.world.entity.Interaction.PlayerAction last = getHandle().attack; return (last != null) ? new CraftPreviousInteraction(last.player(), last.timestamp()) : null; } @Override public PreviousInteraction getLastInteraction() { - net.minecraft.world.entity.Interaction.PlayerAction last = this.getHandle().interaction; + net.minecraft.world.entity.Interaction.PlayerAction last = getHandle().interaction; return (last != null) ? new CraftPreviousInteraction(last.player(), last.timestamp()) : null; } @@ -78,12 +78,12 @@ public CraftPreviousInteraction(UUID uuid, long timestamp) { @Override public OfflinePlayer getPlayer() { - return Bukkit.getOfflinePlayer(this.uuid); + return Bukkit.getOfflinePlayer(uuid); } @Override public long getTimestamp() { - return this.timestamp; + return timestamp; } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java index 63cae1a2..cb60fe8b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityIronGolem; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.IronGolem; public class CraftIronGolem extends CraftGolem implements IronGolem { - public CraftIronGolem(CraftServer server, net.minecraft.world.entity.animal.IronGolem entity) { + public CraftIronGolem(CraftServer server, EntityIronGolem entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.IronGolem getHandle() { - return (net.minecraft.world.entity.animal.IronGolem) this.entity; + public EntityIronGolem getHandle() { + return (EntityIronGolem) entity; } @Override @@ -20,11 +21,11 @@ public String toString() { @Override public boolean isPlayerCreated() { - return this.getHandle().isPlayerCreated(); + return getHandle().isPlayerCreated(); } @Override public void setPlayerCreated(boolean playerCreated) { - this.getHandle().setPlayerCreated(playerCreated); + getHandle().setPlayerCreated(playerCreated); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java index fb3738f4..29cc100e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.entity; import java.util.UUID; -import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.item.EntityItem; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.entity.Item; @@ -9,48 +9,48 @@ public class CraftItem extends CraftEntity implements Item { - public CraftItem(CraftServer server, ItemEntity entity) { + public CraftItem(CraftServer server, EntityItem entity) { super(server, entity); } @Override - public ItemEntity getHandle() { - return (ItemEntity) this.entity; + public EntityItem getHandle() { + return (EntityItem) entity; } @Override public ItemStack getItemStack() { - return CraftItemStack.asCraftMirror(this.getHandle().getItem()); + return CraftItemStack.asCraftMirror(getHandle().getItem()); } @Override public void setItemStack(ItemStack stack) { - this.getHandle().setItem(CraftItemStack.asNMSCopy(stack)); + getHandle().setItem(CraftItemStack.asNMSCopy(stack)); } @Override public int getPickupDelay() { - return this.getHandle().pickupDelay; + return getHandle().pickupDelay; } @Override public void setPickupDelay(int delay) { - this.getHandle().pickupDelay = Math.min(delay, Short.MAX_VALUE); + getHandle().pickupDelay = Math.min(delay, Short.MAX_VALUE); } @Override public void setUnlimitedLifetime(boolean unlimited) { if (unlimited) { // See EntityItem#INFINITE_LIFETIME - this.getHandle().age = Short.MIN_VALUE; + getHandle().age = Short.MIN_VALUE; } else { - this.getHandle().age = this.getTicksLived(); + getHandle().age = getTicksLived(); } } @Override public boolean isUnlimitedLifetime() { - return this.getHandle().age == Short.MIN_VALUE; + return getHandle().age == Short.MIN_VALUE; } @Override @@ -58,29 +58,29 @@ public void setTicksLived(int value) { super.setTicksLived(value); // Second field for EntityItem (don't set if lifetime is unlimited) - if (!this.isUnlimitedLifetime()) { - this.getHandle().age = value; + if (!isUnlimitedLifetime()) { + getHandle().age = value; } } @Override public void setOwner(UUID uuid) { - this.getHandle().setTarget(uuid); + getHandle().setTarget(uuid); } @Override public UUID getOwner() { - return this.getHandle().target; + return getHandle().target; } @Override public void setThrower(UUID uuid) { - this.getHandle().thrower = uuid; + getHandle().thrower = uuid; } @Override public UUID getThrower() { - return this.getHandle().thrower; + return getHandle().thrower; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftItemDisplay.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftItemDisplay.java index 787f9156..fbfdbe31 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftItemDisplay.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftItemDisplay.java @@ -25,23 +25,23 @@ public String toString() { @Override public ItemStack getItemStack() { - return CraftItemStack.asBukkitCopy(this.getHandle().getItemStack()); + return CraftItemStack.asBukkitCopy(getHandle().getItemStack()); } @Override public void setItemStack(ItemStack item) { - this.getHandle().setItemStack(CraftItemStack.asNMSCopy(item)); + getHandle().setItemStack(CraftItemStack.asNMSCopy(item)); } @Override public ItemDisplayTransform getItemDisplayTransform() { - return ItemDisplayTransform.values()[this.getHandle().getItemTransform().ordinal()]; + return ItemDisplayTransform.values()[getHandle().getItemTransform().ordinal()]; } @Override public void setItemDisplayTransform(ItemDisplayTransform display) { Preconditions.checkArgument(display != null, "Display cannot be null"); - this.getHandle().setItemTransform(ItemDisplayContext.BY_ID.apply(display.ordinal())); + getHandle().setItemTransform(ItemDisplayContext.BY_ID.apply(display.ordinal())); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java index f3a9b338..2097f910 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java @@ -1,8 +1,9 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.core.Direction; -import net.minecraft.world.entity.decoration.HangingEntity; +import net.minecraft.core.EnumDirection; +import net.minecraft.world.entity.decoration.EntityHanging; +import net.minecraft.world.entity.decoration.EntityItemFrame; import net.minecraft.world.level.block.Blocks; import org.bukkit.Rotation; import org.bukkit.block.BlockFace; @@ -12,25 +13,25 @@ import org.bukkit.entity.ItemFrame; public class CraftItemFrame extends CraftHanging implements ItemFrame { - public CraftItemFrame(CraftServer server, net.minecraft.world.entity.decoration.ItemFrame entity) { + public CraftItemFrame(CraftServer server, EntityItemFrame entity) { super(server, entity); } @Override public boolean setFacingDirection(BlockFace face, boolean force) { - HangingEntity hanging = this.getHandle(); - Direction oldDir = hanging.getDirection(); - Direction newDir = CraftBlock.blockFaceToNotch(face); + EntityHanging hanging = getHandle(); + EnumDirection oldDir = hanging.getDirection(); + EnumDirection newDir = CraftBlock.blockFaceToNotch(face); Preconditions.checkArgument(newDir != null, "%s is not a valid facing direction", face); - this.getHandle().setDirection(newDir); - if (!force && !this.getHandle().generation && !hanging.survives()) { + getHandle().setDirection(newDir); + if (!force && !getHandle().generation && !hanging.survives()) { hanging.setDirection(oldDir); return false; } - this.update(); + update(); return true; } @@ -40,45 +41,45 @@ protected void update() { super.update(); // mark dirty, so that the client gets updated with item and rotation - this.getHandle().getEntityData().markDirty(net.minecraft.world.entity.decoration.ItemFrame.DATA_ITEM); - this.getHandle().getEntityData().markDirty(net.minecraft.world.entity.decoration.ItemFrame.DATA_ROTATION); + getHandle().getEntityData().markDirty(EntityItemFrame.DATA_ITEM); + getHandle().getEntityData().markDirty(EntityItemFrame.DATA_ROTATION); // update redstone - if (!this.getHandle().generation) { - this.getHandle().level().updateNeighbourForOutputSignal(this.getHandle().getPos(), Blocks.AIR); + if (!getHandle().generation) { + getHandle().level().updateNeighbourForOutputSignal(getHandle().getPos(), Blocks.AIR); } } @Override public void setItem(org.bukkit.inventory.ItemStack item) { - this.setItem(item, true); + setItem(item, true); } @Override public void setItem(org.bukkit.inventory.ItemStack item, boolean playSound) { // only updated redstone and play sound when it is not in generation - this.getHandle().setItem(CraftItemStack.asNMSCopy(item), !this.getHandle().generation, !this.getHandle().generation && playSound); + getHandle().setItem(CraftItemStack.asNMSCopy(item), !getHandle().generation, !getHandle().generation && playSound); } @Override public org.bukkit.inventory.ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getHandle().getItem()); + return CraftItemStack.asBukkitCopy(getHandle().getItem()); } @Override public float getItemDropChance() { - return this.getHandle().dropChance; + return getHandle().dropChance; } @Override public void setItemDropChance(float chance) { Preconditions.checkArgument(0.0 <= chance && chance <= 1.0, "Chance (%s) outside range [0, 1]", chance); - this.getHandle().dropChance = chance; + getHandle().dropChance = chance; } @Override public Rotation getRotation() { - return this.toBukkitRotation(this.getHandle().getRotation()); + return toBukkitRotation(getHandle().getRotation()); } Rotation toBukkitRotation(int value) { @@ -101,14 +102,14 @@ Rotation toBukkitRotation(int value) { case 7: return Rotation.COUNTER_CLOCKWISE_45; default: - throw new AssertionError("Unknown rotation " + value + " for " + this.getHandle()); + throw new AssertionError("Unknown rotation " + value + " for " + getHandle()); } } @Override public void setRotation(Rotation rotation) { Preconditions.checkArgument(rotation != null, "Rotation cannot be null"); - this.getHandle().setRotation(CraftItemFrame.toInteger(rotation)); + getHandle().setRotation(toInteger(rotation)); } static int toInteger(Rotation rotation) { @@ -137,31 +138,31 @@ static int toInteger(Rotation rotation) { @Override public boolean isVisible() { - return !this.getHandle().isInvisible(); + return !getHandle().isInvisible(); } @Override public void setVisible(boolean visible) { - this.getHandle().setInvisible(!visible); + getHandle().setInvisible(!visible); } @Override public boolean isFixed() { - return this.getHandle().fixed; + return getHandle().fixed; } @Override public void setFixed(boolean fixed) { - this.getHandle().fixed = fixed; + getHandle().fixed = fixed; } @Override - public net.minecraft.world.entity.decoration.ItemFrame getHandle() { - return (net.minecraft.world.entity.decoration.ItemFrame) this.entity; + public EntityItemFrame getHandle() { + return (EntityItemFrame) entity; } @Override public String toString() { - return "CraftItemFrame{item=" + this.getItem() + ", rotation=" + this.getRotation() + "}"; + return "CraftItemFrame{item=" + getItem() + ", rotation=" + getRotation() + "}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java index 0848963e..ffd05382 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java @@ -1,22 +1,23 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntityLargeFireball; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.LargeFireball; public class CraftLargeFireball extends CraftSizedFireball implements LargeFireball { - public CraftLargeFireball(CraftServer server, net.minecraft.world.entity.projectile.LargeFireball entity) { + public CraftLargeFireball(CraftServer server, EntityLargeFireball entity) { super(server, entity); } @Override public void setYield(float yield) { super.setYield(yield); - this.getHandle().explosionPower = (int) yield; + getHandle().explosionPower = (int) yield; } @Override - public net.minecraft.world.entity.projectile.LargeFireball getHandle() { - return (net.minecraft.world.entity.projectile.LargeFireball) this.entity; + public EntityLargeFireball getHandle() { + return (EntityLargeFireball) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java index f9ccd0e0..eed03827 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.decoration.LeashFenceKnotEntity; +import net.minecraft.world.entity.decoration.EntityLeash; import org.bukkit.block.BlockFace; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.LeashHitch; public class CraftLeash extends CraftBlockAttachedEntity implements LeashHitch { - public CraftLeash(CraftServer server, LeashFenceKnotEntity entity) { + public CraftLeash(CraftServer server, EntityLeash entity) { super(server, entity); } @@ -15,7 +15,7 @@ public CraftLeash(CraftServer server, LeashFenceKnotEntity entity) { public boolean setFacingDirection(BlockFace face, boolean force) { Preconditions.checkArgument(face == BlockFace.SELF, "%s is not a valid facing direction", face); - return force || this.getHandle().generation || this.getHandle().survives(); + return force || getHandle().generation || getHandle().survives(); } @Override @@ -23,6 +23,7 @@ public BlockFace getFacing() { // Leash hitch has no facing direction, so we return self return BlockFace.SELF; } + @Override public BlockFace getAttachedFace() { // Leash hitch has no facing direction, so we return self @@ -35,8 +36,8 @@ public void setFacingDirection(BlockFace face) { } @Override - public LeashFenceKnotEntity getHandle() { - return (LeashFenceKnotEntity) this.entity; + public EntityLeash getHandle() { + return (EntityLeash) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java index 0b2ba5c9..3a4fb14b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java @@ -1,69 +1,53 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.LightningBolt; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.entity.EntityLightning; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.LightningStrike; import org.bukkit.entity.Player; public class CraftLightningStrike extends CraftEntity implements LightningStrike { - public CraftLightningStrike(final CraftServer server, final LightningBolt entity) { + public CraftLightningStrike(final CraftServer server, final EntityLightning entity) { super(server, entity); } @Override public boolean isEffect() { - return this.getHandle().visualOnly; + return getHandle().visualOnly; } public int getFlashes() { - return this.getHandle().flashes; + return getHandle().flashes; } public void setFlashes(int flashes) { - this.getHandle().flashes = flashes; + getHandle().flashes = flashes; } public int getLifeTicks() { - return this.getHandle().life; + return getHandle().life; } public void setLifeTicks(int ticks) { - this.getHandle().life = ticks; + getHandle().life = ticks; } public Player getCausingPlayer() { - ServerPlayer player = this.getHandle().getCause(); + EntityPlayer player = getHandle().getCause(); return (player != null) ? player.getBukkitEntity() : null; } public void setCausingPlayer(Player player) { - this.getHandle().setCause((player != null) ? ((CraftPlayer) player).getHandle() : null); + getHandle().setCause((player != null) ? ((CraftPlayer) player).getHandle() : null); } @Override - public LightningBolt getHandle() { - return (LightningBolt) this.entity; + public EntityLightning getHandle() { + return (EntityLightning) entity; } @Override public String toString() { return "CraftLightningStrike"; } - - // Spigot start - private final LightningStrike.Spigot spigot = new LightningStrike.Spigot() { - - @Override - public boolean isSilent() - { - return false; - } - }; - - @Override - public LightningStrike.Spigot spigot() { - return this.spigot; - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java index f0a94b10..6bde0489 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java @@ -8,27 +8,44 @@ import java.util.List; import java.util.Set; import java.util.UUID; +import net.minecraft.core.component.DataComponents; import net.minecraft.network.protocol.game.ClientboundHurtAnimationPacket; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.InteractionHand; +import net.minecraft.server.level.WorldServer; +import net.minecraft.sounds.SoundEffect; +import net.minecraft.sounds.SoundEffects; +import net.minecraft.world.EnumHand; import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.ai.attributes.Attributes; -import net.minecraft.world.entity.boss.wither.WitherBoss; -import net.minecraft.world.entity.decoration.ArmorStand; -import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; -import net.minecraft.world.entity.projectile.FishingHook; -import net.minecraft.world.entity.projectile.LargeFireball; -import net.minecraft.world.entity.projectile.ThrowableProjectile; -import net.minecraft.world.entity.projectile.ThrownEgg; -import net.minecraft.world.entity.projectile.ThrownEnderpearl; -import net.minecraft.world.entity.projectile.ThrownExperienceBottle; -import net.minecraft.world.entity.projectile.ThrownTrident; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.entity.EntityInsentient; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.ai.attributes.GenericAttributes; +import net.minecraft.world.entity.boss.wither.EntityWither; +import net.minecraft.world.entity.decoration.EntityArmorStand; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.entity.projectile.EntityArrow; +import net.minecraft.world.entity.projectile.EntityDragonFireball; +import net.minecraft.world.entity.projectile.EntityEgg; +import net.minecraft.world.entity.projectile.EntityEnderPearl; +import net.minecraft.world.entity.projectile.EntityFireball; +import net.minecraft.world.entity.projectile.EntityFireworks; +import net.minecraft.world.entity.projectile.EntityFishingHook; +import net.minecraft.world.entity.projectile.EntityLargeFireball; +import net.minecraft.world.entity.projectile.EntityLlamaSpit; +import net.minecraft.world.entity.projectile.EntityPotion; +import net.minecraft.world.entity.projectile.EntityProjectile; +import net.minecraft.world.entity.projectile.EntityShulkerBullet; +import net.minecraft.world.entity.projectile.EntitySmallFireball; +import net.minecraft.world.entity.projectile.EntitySnowball; +import net.minecraft.world.entity.projectile.EntitySpectralArrow; +import net.minecraft.world.entity.projectile.EntityThrownExpBottle; +import net.minecraft.world.entity.projectile.EntityThrownTrident; +import net.minecraft.world.entity.projectile.EntityTippedArrow; +import net.minecraft.world.entity.projectile.EntityWitherSkull; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.Consumable; +import net.minecraft.world.phys.Vec3D; import org.bukkit.FluidCollisionMode; import org.bukkit.Location; import org.bukkit.Material; @@ -46,7 +63,9 @@ import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; import org.bukkit.entity.AbstractArrow; +import org.bukkit.entity.AbstractWindCharge; import org.bukkit.entity.Arrow; +import org.bukkit.entity.BreezeWindCharge; import org.bukkit.entity.DragonFireball; import org.bukkit.entity.Egg; import org.bukkit.entity.EnderPearl; @@ -69,7 +88,6 @@ import org.bukkit.entity.ThrownPotion; import org.bukkit.entity.TippedArrow; import org.bukkit.entity.Trident; -import org.bukkit.entity.WindCharge; import org.bukkit.entity.WitherSkull; import org.bukkit.entity.memory.MemoryKey; import org.bukkit.event.entity.EntityPotionEffectEvent; @@ -86,17 +104,17 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity { private CraftEntityEquipment equipment; - public CraftLivingEntity(final CraftServer server, final net.minecraft.world.entity.LivingEntity entity) { + public CraftLivingEntity(final CraftServer server, final EntityLiving entity) { super(server, entity); - if (entity instanceof Mob || entity instanceof ArmorStand) { - this.equipment = new CraftEntityEquipment(this); + if (entity instanceof EntityInsentient || entity instanceof EntityArmorStand) { + equipment = new CraftEntityEquipment(this); } } @Override public double getHealth() { - return Math.min(Math.max(0, this.getHandle().getHealth()), this.getMaxHealth()); + return Math.min(Math.max(0, getHandle().getHealth()), getMaxHealth()); } @Override @@ -105,63 +123,63 @@ public void setHealth(double health) { Preconditions.checkArgument(health >= 0 && health <= this.getMaxHealth(), "Health value (%s) must be between 0 and %s", health, this.getMaxHealth()); // during world generation, we don't want to run logic for dropping items and xp - if (this.getHandle().generation && health == 0) { - this.getHandle().discard(null); // Add Bukkit remove cause + if (getHandle().generation && health == 0) { + getHandle().discard(null); // Add Bukkit remove cause return; } - this.getHandle().setHealth((float) health); + getHandle().setHealth((float) health); if (health == 0) { - this.getHandle().die(this.getHandle().damageSources().generic()); + getHandle().die(getHandle().damageSources().generic()); } } @Override public double getAbsorptionAmount() { - return this.getHandle().getAbsorptionAmount(); + return getHandle().getAbsorptionAmount(); } @Override public void setAbsorptionAmount(double amount) { Preconditions.checkArgument(amount >= 0 && Double.isFinite(amount), "amount < 0 or non-finite"); - this.getHandle().setAbsorptionAmount((float) amount); + getHandle().setAbsorptionAmount((float) amount); } @Override public double getMaxHealth() { - return this.getHandle().getMaxHealth(); + return getHandle().getMaxHealth(); } @Override public void setMaxHealth(double amount) { Preconditions.checkArgument(amount > 0, "Max health amount (%s) must be greater than 0", amount); - this.getHandle().getAttribute(Attributes.MAX_HEALTH).setBaseValue(amount); + getHandle().getAttribute(GenericAttributes.MAX_HEALTH).setBaseValue(amount); - if (this.getHealth() > amount) { - this.setHealth(amount); + if (getHealth() > amount) { + setHealth(amount); } } @Override public void resetMaxHealth() { - this.setMaxHealth(this.getHandle().getAttribute(Attributes.MAX_HEALTH).getAttribute().value().getDefaultValue()); + setMaxHealth(getHandle().getAttribute(GenericAttributes.MAX_HEALTH).getAttribute().value().getDefaultValue()); } @Override public double getEyeHeight() { - return this.getHandle().getEyeHeight(); + return getHandle().getEyeHeight(); } @Override public double getEyeHeight(boolean ignorePose) { - return this.getEyeHeight(); + return getEyeHeight(); } private List getLineOfSight(Set transparent, int maxDistance, int maxLength) { - Preconditions.checkState(!this.getHandle().generation, "Cannot get line of sight during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot get line of sight during world generation"); if (transparent == null) { transparent = Sets.newHashSet(Material.AIR, Material.CAVE_AIR, Material.VOID_AIR); @@ -187,40 +205,18 @@ private List getLineOfSight(Set transparent, int maxDistance, i @Override public List getLineOfSight(Set transparent, int maxDistance) { - return this.getLineOfSight(transparent, maxDistance, 0); + return getLineOfSight(transparent, maxDistance, 0); } @Override public Block getTargetBlock(Set transparent, int maxDistance) { - List blocks = this.getLineOfSight(transparent, maxDistance, 1); + List blocks = getLineOfSight(transparent, maxDistance, 1); return blocks.get(0); } - public Entity getTargetEntity(int maxDistance, boolean ignoreBlocks) { - net.minecraft.world.phys.EntityHitResult rayTrace = rayTraceEntity(maxDistance, ignoreBlocks); - return rayTrace == null ? null : rayTrace.getEntity().getBukkitEntity(); - } - - public net.minecraft.world.phys.EntityHitResult rayTraceEntity(int maxDistance, boolean ignoreBlocks) { - net.minecraft.world.phys.EntityHitResult rayTrace = getHandle().getTargetEntity(maxDistance); - if (rayTrace == null) { - return null; - } - if (!ignoreBlocks) { - net.minecraft.world.phys.HitResult rayTraceBlocks = getHandle().getRayTrace(maxDistance, net.minecraft.world.level.ClipContext.Fluid.NONE); - if (rayTraceBlocks != null) { - net.minecraft.world.phys.Vec3 eye = getHandle().getEyePosition(1.0F); - if (eye.distanceToSqr(rayTraceBlocks.getLocation()) <= eye.distanceToSqr(rayTrace.getLocation())) { - return null; - } - } - } - return rayTrace; - } - @Override public List getLastTwoTargetBlocks(Set transparent, int maxDistance) { - return this.getLineOfSight(transparent, maxDistance, 2); + return getLineOfSight(transparent, maxDistance, 2); } @Override @@ -241,7 +237,7 @@ public RayTraceResult rayTraceBlocks(double maxDistance) { @Override public RayTraceResult rayTraceBlocks(double maxDistance, FluidCollisionMode fluidCollisionMode) { - Preconditions.checkState(!this.getHandle().generation, "Cannot ray tray blocks during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot ray tray blocks during world generation"); Location eyeLocation = this.getEyeLocation(); Vector direction = eyeLocation.getDirection(); @@ -250,168 +246,173 @@ public RayTraceResult rayTraceBlocks(double maxDistance, FluidCollisionMode flui @Override public int getRemainingAir() { - return this.getHandle().getAirSupply(); + return getHandle().getAirSupply(); } @Override public void setRemainingAir(int ticks) { - this.getHandle().setAirSupply(ticks); + getHandle().setAirSupply(ticks); } @Override public int getMaximumAir() { - return this.getHandle().maxAirTicks; + return getHandle().maxAirTicks; } @Override public void setMaximumAir(int ticks) { - this.getHandle().maxAirTicks = ticks; + getHandle().maxAirTicks = ticks; } @Override public ItemStack getItemInUse() { - net.minecraft.world.item.ItemStack item = this.getHandle().getUseItem(); + net.minecraft.world.item.ItemStack item = getHandle().getUseItem(); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } @Override public int getItemInUseTicks() { - return this.getHandle().getUseItemRemainingTicks(); + return getHandle().getUseItemRemainingTicks(); } @Override public void setItemInUseTicks(int ticks) { - this.getHandle().useItemRemaining = ticks; + getHandle().useItemRemaining = ticks; } @Override public int getArrowCooldown() { - return this.getHandle().removeArrowTime; + return getHandle().removeArrowTime; } @Override public void setArrowCooldown(int ticks) { - this.getHandle().removeArrowTime = ticks; + getHandle().removeArrowTime = ticks; } @Override public int getArrowsInBody() { - return this.getHandle().getArrowCount(); + return getHandle().getArrowCount(); } @Override public void setArrowsInBody(int count) { Preconditions.checkArgument(count >= 0, "New arrow amount must be >= 0"); - this.getHandle().getEntityData().set(net.minecraft.world.entity.LivingEntity.DATA_ARROW_COUNT_ID, count); + getHandle().getEntityData().set(EntityLiving.DATA_ARROW_COUNT_ID, count); + } + + @Override + public boolean isInvulnerable() { + return getHandle().isInvulnerableTo((WorldServer) getHandle().level(), getHandle().damageSources().generic()); } @Override public void damage(double amount) { - this.damage(amount, this.getHandle().damageSources().generic()); + damage(amount, getHandle().damageSources().generic()); } @Override public void damage(double amount, org.bukkit.entity.Entity source) { - DamageSource reason = this.getHandle().damageSources().generic(); + DamageSource reason = getHandle().damageSources().generic(); if (source instanceof HumanEntity) { - reason = this.getHandle().damageSources().playerAttack(((CraftHumanEntity) source).getHandle()); + reason = getHandle().damageSources().playerAttack(((CraftHumanEntity) source).getHandle()); } else if (source instanceof LivingEntity) { - reason = this.getHandle().damageSources().mobAttack(((CraftLivingEntity) source).getHandle()); + reason = getHandle().damageSources().mobAttack(((CraftLivingEntity) source).getHandle()); } - this.damage(amount, reason); + damage(amount, reason); } @Override public void damage(double amount, org.bukkit.damage.DamageSource damageSource) { Preconditions.checkArgument(damageSource != null, "damageSource cannot be null"); - this.damage(amount, ((CraftDamageSource) damageSource).getHandle()); + damage(amount, ((CraftDamageSource) damageSource).getHandle()); } private void damage(double amount, DamageSource damageSource) { Preconditions.checkArgument(damageSource != null, "damageSource cannot be null"); - Preconditions.checkState(!this.getHandle().generation, "Cannot damage entity during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot damage entity during world generation"); - this.entity.hurt(damageSource, (float) amount); + entity.hurt(damageSource, (float) amount); } @Override public Location getEyeLocation() { - Location loc = this.getLocation(); - loc.setY(loc.getY() + this.getEyeHeight()); + Location loc = getLocation(); + loc.setY(loc.getY() + getEyeHeight()); return loc; } @Override public int getMaximumNoDamageTicks() { - return this.getHandle().invulnerableDuration; + return getHandle().invulnerableDuration; } @Override public void setMaximumNoDamageTicks(int ticks) { - this.getHandle().invulnerableDuration = ticks; + getHandle().invulnerableDuration = ticks; } @Override public double getLastDamage() { - return this.getHandle().lastHurt; + return getHandle().lastHurt; } @Override public void setLastDamage(double damage) { - this.getHandle().lastHurt = (float) damage; + getHandle().lastHurt = (float) damage; } @Override public int getNoDamageTicks() { - return this.getHandle().invulnerableTime; + return getHandle().invulnerableTime; } @Override public void setNoDamageTicks(int ticks) { - this.getHandle().invulnerableTime = ticks; + getHandle().invulnerableTime = ticks; } @Override public int getNoActionTicks() { - return this.getHandle().getNoActionTime(); + return getHandle().getNoActionTime(); } @Override public void setNoActionTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks must be >= 0"); - this.getHandle().setNoActionTime(ticks); + getHandle().setNoActionTime(ticks); } @Override - public net.minecraft.world.entity.LivingEntity getHandle() { - return (net.minecraft.world.entity.LivingEntity) this.entity; + public EntityLiving getHandle() { + return (EntityLiving) entity; } - public void setHandle(final net.minecraft.world.entity.LivingEntity entity) { + public void setHandle(final EntityLiving entity) { super.setHandle(entity); } @Override public String toString() { - return "CraftLivingEntity{" + "id=" + this.getEntityId() + '}'; + return "CraftLivingEntity{" + "id=" + getEntityId() + '}'; } @Override public Player getKiller() { - return this.getHandle().lastHurtByPlayer == null ? null : (Player) this.getHandle().lastHurtByPlayer.getBukkitEntity(); + return getHandle().lastHurtByPlayer == null ? null : (Player) getHandle().lastHurtByPlayer.getBukkitEntity(); } @Override public boolean addPotionEffect(PotionEffect effect) { - return this.addPotionEffect(effect, false); + return addPotionEffect(effect, false); } @Override public boolean addPotionEffect(PotionEffect effect, boolean force) { - this.getHandle().addEffect(new MobEffectInstance(CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()), EntityPotionEffectEvent.Cause.PLUGIN); + getHandle().addEffect(new MobEffect(CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()), EntityPotionEffectEvent.Cause.PLUGIN); return true; } @@ -419,31 +420,31 @@ public boolean addPotionEffect(PotionEffect effect, boolean force) { public boolean addPotionEffects(Collection effects) { boolean success = true; for (PotionEffect effect : effects) { - success &= this.addPotionEffect(effect); + success &= addPotionEffect(effect); } return success; } @Override public boolean hasPotionEffect(PotionEffectType type) { - return this.getHandle().hasEffect(CraftPotionEffectType.bukkitToMinecraftHolder(type)); + return getHandle().hasEffect(CraftPotionEffectType.bukkitToMinecraftHolder(type)); } @Override public PotionEffect getPotionEffect(PotionEffectType type) { - MobEffectInstance handle = this.getHandle().getEffect(CraftPotionEffectType.bukkitToMinecraftHolder(type)); + MobEffect handle = getHandle().getEffect(CraftPotionEffectType.bukkitToMinecraftHolder(type)); return (handle == null) ? null : new PotionEffect(CraftPotionEffectType.minecraftHolderToBukkit(handle.getEffect()), handle.getDuration(), handle.getAmplifier(), handle.isAmbient(), handle.isVisible()); } @Override public void removePotionEffect(PotionEffectType type) { - this.getHandle().removeEffect(CraftPotionEffectType.bukkitToMinecraftHolder(type), EntityPotionEffectEvent.Cause.PLUGIN); + getHandle().removeEffect(CraftPotionEffectType.bukkitToMinecraftHolder(type), EntityPotionEffectEvent.Cause.PLUGIN); } @Override public Collection getActivePotionEffects() { List effects = new ArrayList(); - for (MobEffectInstance handle : this.getHandle().activeEffects.values()) { + for (MobEffect handle : getHandle().activeEffects.values()) { effects.add(new PotionEffect(CraftPotionEffectType.minecraftHolderToBukkit(handle.getEffect()), handle.getDuration(), handle.getAmplifier(), handle.isAmbient(), handle.isVisible())); } return effects; @@ -451,91 +452,94 @@ public Collection getActivePotionEffects() { @Override public T launchProjectile(Class projectile) { - return this.launchProjectile(projectile, null); + return launchProjectile(projectile, null); } @Override @SuppressWarnings("unchecked") public T launchProjectile(Class projectile, Vector velocity) { - Preconditions.checkState(!this.getHandle().generation, "Cannot launch projectile during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot launch projectile during world generation"); - net.minecraft.world.level.Level world = ((CraftWorld) this.getWorld()).getHandle(); + net.minecraft.world.level.World world = ((CraftWorld) getWorld()).getHandle(); net.minecraft.world.entity.Entity launch = null; if (Snowball.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.Snowball(world, this.getHandle()); - ((ThrowableProjectile) launch).shootFromRotation(this.getHandle(), this.getHandle().getXRot(), this.getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // ItemSnowball + launch = new EntitySnowball(world, getHandle(), new net.minecraft.world.item.ItemStack(Items.SNOWBALL)); + ((EntityProjectile) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // ItemSnowball } else if (Egg.class.isAssignableFrom(projectile)) { - launch = new ThrownEgg(world, this.getHandle()); - ((ThrowableProjectile) launch).shootFromRotation(this.getHandle(), this.getHandle().getXRot(), this.getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // ItemEgg + launch = new EntityEgg(world, getHandle(), new net.minecraft.world.item.ItemStack(Items.EGG)); + ((EntityProjectile) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // ItemEgg } else if (EnderPearl.class.isAssignableFrom(projectile)) { - launch = new ThrownEnderpearl(world, this.getHandle()); - ((ThrowableProjectile) launch).shootFromRotation(this.getHandle(), this.getHandle().getXRot(), this.getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // ItemEnderPearl + launch = new EntityEnderPearl(world, getHandle(), new net.minecraft.world.item.ItemStack(Items.ENDER_PEARL)); + ((EntityProjectile) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // ItemEnderPearl } else if (AbstractArrow.class.isAssignableFrom(projectile)) { if (TippedArrow.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.Arrow(world, this.getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.ARROW), null); + launch = new EntityTippedArrow(world, getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.ARROW), null); ((Arrow) launch.getBukkitEntity()).setBasePotionType(PotionType.WATER); } else if (SpectralArrow.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.SpectralArrow(world, this.getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.SPECTRAL_ARROW), null); + launch = new EntitySpectralArrow(world, getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.SPECTRAL_ARROW), null); } else if (Trident.class.isAssignableFrom(projectile)) { - launch = new ThrownTrident(world, this.getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.TRIDENT)); + launch = new EntityThrownTrident(world, getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.TRIDENT)); } else { - launch = new net.minecraft.world.entity.projectile.Arrow(world, this.getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.ARROW), null); + launch = new EntityTippedArrow(world, getHandle(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.ARROW), null); } - ((net.minecraft.world.entity.projectile.AbstractArrow) launch).shootFromRotation(this.getHandle(), this.getHandle().getXRot(), this.getHandle().getYRot(), 0.0F, 3.0F, 1.0F); // ItemBow + ((EntityArrow) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), 0.0F, 3.0F, 1.0F); // ItemBow } else if (ThrownPotion.class.isAssignableFrom(projectile)) { if (LingeringPotion.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.ThrownPotion(world, this.getHandle()); - ((net.minecraft.world.entity.projectile.ThrownPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); + launch = new EntityPotion(world, getHandle(), new net.minecraft.world.item.ItemStack(Items.LINGERING_POTION)); } else { - launch = new net.minecraft.world.entity.projectile.ThrownPotion(world, this.getHandle()); - ((net.minecraft.world.entity.projectile.ThrownPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.SPLASH_POTION, 1))); + launch = new EntityPotion(world, getHandle(), new net.minecraft.world.item.ItemStack(Items.SPLASH_POTION)); } - ((ThrowableProjectile) launch).shootFromRotation(this.getHandle(), this.getHandle().getXRot(), this.getHandle().getYRot(), -20.0F, 0.5F, 1.0F); // ItemSplashPotion + ((EntityProjectile) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), -20.0F, 0.5F, 1.0F); // ItemSplashPotion } else if (ThrownExpBottle.class.isAssignableFrom(projectile)) { - launch = new ThrownExperienceBottle(world, this.getHandle()); - ((ThrowableProjectile) launch).shootFromRotation(this.getHandle(), this.getHandle().getXRot(), this.getHandle().getYRot(), -20.0F, 0.7F, 1.0F); // ItemExpBottle - } else if (FishHook.class.isAssignableFrom(projectile) && this.getHandle() instanceof net.minecraft.world.entity.player.Player) { - launch = new FishingHook((net.minecraft.world.entity.player.Player) this.getHandle(), world, 0, 0); + launch = new EntityThrownExpBottle(world, getHandle(), new net.minecraft.world.item.ItemStack(Items.EXPERIENCE_BOTTLE)); + ((EntityProjectile) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), -20.0F, 0.7F, 1.0F); // ItemExpBottle + } else if (FishHook.class.isAssignableFrom(projectile) && getHandle() instanceof EntityHuman) { + launch = new EntityFishingHook((EntityHuman) getHandle(), world, 0, 0, new net.minecraft.world.item.ItemStack(Items.FISHING_ROD)); } else if (Fireball.class.isAssignableFrom(projectile)) { - Location location = this.getEyeLocation(); + Location location = getEyeLocation(); Vector direction = location.getDirection().multiply(10); - Vec3 vec = new Vec3(direction.getX(), direction.getY(), direction.getZ()); + Vec3D vec = new Vec3D(direction.getX(), direction.getY(), direction.getZ()); if (SmallFireball.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.SmallFireball(world, this.getHandle(), vec); + launch = new EntitySmallFireball(world, getHandle(), vec); } else if (WitherSkull.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.WitherSkull(world, this.getHandle(), vec); + launch = new EntityWitherSkull(world, getHandle(), vec); } else if (DragonFireball.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.DragonFireball(world, this.getHandle(), vec); - } else if (WindCharge.class.isAssignableFrom(projectile)) { - launch = EntityType.WIND_CHARGE.create(world); - ((net.minecraft.world.entity.projectile.windcharge.WindCharge) launch).setOwner(this.getHandle()); - ((net.minecraft.world.entity.projectile.windcharge.WindCharge) launch).assignDirectionalMovement(vec, 1.0D); + launch = new EntityDragonFireball(world, getHandle(), vec); + } else if (AbstractWindCharge.class.isAssignableFrom(projectile)) { + if (BreezeWindCharge.class.isAssignableFrom(projectile)) { + launch = EntityTypes.BREEZE_WIND_CHARGE.create(world, EntitySpawnReason.TRIGGERED); + } else { + launch = EntityTypes.WIND_CHARGE.create(world, EntitySpawnReason.TRIGGERED); + } + + ((net.minecraft.world.entity.projectile.windcharge.AbstractWindCharge) launch).setOwner(getHandle()); + ((net.minecraft.world.entity.projectile.windcharge.AbstractWindCharge) launch).shootFromRotation(getHandle(), getHandle().getXRot(), getHandle().getYRot(), 0.0F, 1.5F, 1.0F); // WindChargeItem } else { - launch = new LargeFireball(world, this.getHandle(), vec, 1); + launch = new EntityLargeFireball(world, getHandle(), vec, 1); } - ((AbstractHurtingProjectile) launch).projectileSource = this; + ((EntityFireball) launch).projectileSource = this; launch.moveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } else if (LlamaSpit.class.isAssignableFrom(projectile)) { - Location location = this.getEyeLocation(); + Location location = getEyeLocation(); Vector direction = location.getDirection(); - launch = EntityType.LLAMA_SPIT.create(world); + launch = EntityTypes.LLAMA_SPIT.create(world, EntitySpawnReason.TRIGGERED); - ((net.minecraft.world.entity.projectile.LlamaSpit) launch).setOwner(this.getHandle()); - ((net.minecraft.world.entity.projectile.LlamaSpit) launch).shoot(direction.getX(), direction.getY(), direction.getZ(), 1.5F, 10.0F); // EntityLlama + ((EntityLlamaSpit) launch).setOwner(getHandle()); + ((EntityLlamaSpit) launch).shoot(direction.getX(), direction.getY(), direction.getZ(), 1.5F, 10.0F); // EntityLlama launch.moveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } else if (ShulkerBullet.class.isAssignableFrom(projectile)) { - Location location = this.getEyeLocation(); + Location location = getEyeLocation(); - launch = new net.minecraft.world.entity.projectile.ShulkerBullet(world, this.getHandle(), null, null); + launch = new EntityShulkerBullet(world, getHandle(), null, null); launch.moveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } else if (Firework.class.isAssignableFrom(projectile)) { - Location location = this.getEyeLocation(); + Location location = getEyeLocation(); - launch = new FireworkRocketEntity(world, net.minecraft.world.item.ItemStack.EMPTY, this.getHandle()); + launch = new EntityFireworks(world, net.minecraft.world.item.ItemStack.EMPTY, getHandle()); launch.moveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } @@ -551,49 +555,49 @@ public T launchProjectile(Class projectile, @Override public boolean hasLineOfSight(Entity other) { - Preconditions.checkState(!this.getHandle().generation, "Cannot check line of sight during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot check line of sight during world generation"); - return this.getHandle().hasLineOfSight(((CraftEntity) other).getHandle()); + return getHandle().hasLineOfSight(((CraftEntity) other).getHandle()); } @Override public boolean getRemoveWhenFarAway() { - return this.getHandle() instanceof Mob && !((Mob) this.getHandle()).isPersistenceRequired(); + return getHandle() instanceof EntityInsentient && !((EntityInsentient) getHandle()).isPersistenceRequired(); } @Override public void setRemoveWhenFarAway(boolean remove) { - if (this.getHandle() instanceof Mob) { - ((Mob) this.getHandle()).setPersistenceRequired(!remove); + if (getHandle() instanceof EntityInsentient) { + ((EntityInsentient) getHandle()).setPersistenceRequired(!remove); } } @Override public EntityEquipment getEquipment() { - return this.equipment; + return equipment; } @Override public void setCanPickupItems(boolean pickup) { - if (this.getHandle() instanceof Mob) { - ((Mob) this.getHandle()).setCanPickUpLoot(pickup); + if (getHandle() instanceof EntityInsentient) { + ((EntityInsentient) getHandle()).setCanPickUpLoot(pickup); } else { - this.getHandle().bukkitPickUpLoot = pickup; + getHandle().bukkitPickUpLoot = pickup; } } @Override public boolean getCanPickupItems() { - if (this.getHandle() instanceof Mob) { - return ((Mob) this.getHandle()).canPickUpLoot(); + if (getHandle() instanceof EntityInsentient) { + return ((EntityInsentient) getHandle()).canPickUpLoot(); } else { - return this.getHandle().bukkitPickUpLoot; + return getHandle().bukkitPickUpLoot; } } @Override public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) { - if (this.getHealth() == 0) { + if (getHealth() == 0) { return false; } @@ -602,211 +606,223 @@ public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cau @Override public boolean isLeashed() { - if (!(this.getHandle() instanceof Mob)) { + if (!(getHandle() instanceof EntityInsentient)) { return false; } - return ((Mob) this.getHandle()).getLeashHolder() != null; + return ((EntityInsentient) getHandle()).getLeashHolder() != null; } @Override public Entity getLeashHolder() throws IllegalStateException { - Preconditions.checkState(this.isLeashed(), "Entity not leashed"); - return ((Mob) this.getHandle()).getLeashHolder().getBukkitEntity(); + Preconditions.checkState(isLeashed(), "Entity not leashed"); + return ((EntityInsentient) getHandle()).getLeashHolder().getBukkitEntity(); } private boolean unleash() { - if (!this.isLeashed()) { + if (!isLeashed()) { return false; } - ((Mob) this.getHandle()).dropLeash(true, false); + ((EntityInsentient) getHandle()).dropLeash(true, false); return true; } @Override public boolean setLeashHolder(Entity holder) { - if (this.getHandle().generation || (this.getHandle() instanceof WitherBoss) || !(this.getHandle() instanceof Mob)) { + if (getHandle().generation || (getHandle() instanceof EntityWither) || !(getHandle() instanceof EntityInsentient)) { return false; } if (holder == null) { - return this.unleash(); + return unleash(); } if (holder.isDead()) { return false; } - this.unleash(); - ((Mob) this.getHandle()).setLeashedTo(((CraftEntity) holder).getHandle(), true); + unleash(); + ((EntityInsentient) getHandle()).setLeashedTo(((CraftEntity) holder).getHandle(), true); return true; } @Override public boolean isGliding() { - return this.getHandle().getSharedFlag(7); + return getHandle().getSharedFlag(7); } @Override public void setGliding(boolean gliding) { - this.getHandle().setSharedFlag(7, gliding); + getHandle().setSharedFlag(7, gliding); } @Override public boolean isSwimming() { - return this.getHandle().isSwimming(); + return getHandle().isSwimming(); } @Override public void setSwimming(boolean swimming) { - this.getHandle().setSwimming(swimming); + getHandle().setSwimming(swimming); } @Override public boolean isRiptiding() { - return this.getHandle().isAutoSpinAttack(); + return getHandle().isAutoSpinAttack(); } @Override public void setRiptiding(boolean riptiding) { - getHandle().setLivingEntityFlag(net.minecraft.world.entity.LivingEntity.LIVING_ENTITY_FLAG_SPIN_ATTACK, riptiding); + getHandle().setLivingEntityFlag(EntityLiving.LIVING_ENTITY_FLAG_SPIN_ATTACK, riptiding); } @Override public boolean isSleeping() { - return this.getHandle().isSleeping(); + return getHandle().isSleeping(); } @Override public boolean isClimbing() { - Preconditions.checkState(!this.getHandle().generation, "Cannot check if climbing during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot check if climbing during world generation"); - return this.getHandle().onClimbable(); + return getHandle().onClimbable(); } @Override public AttributeInstance getAttribute(Attribute attribute) { - return this.getHandle().craftAttributes.getAttribute(attribute); + return getHandle().craftAttributes.getAttribute(attribute); } @Override public void setAI(boolean ai) { - if (this.getHandle() instanceof Mob) { - ((Mob) this.getHandle()).setNoAi(!ai); + if (this.getHandle() instanceof EntityInsentient) { + ((EntityInsentient) this.getHandle()).setNoAi(!ai); } } @Override public boolean hasAI() { - return (this.getHandle() instanceof Mob) ? !((Mob) this.getHandle()).isNoAi() : false; + return (this.getHandle() instanceof EntityInsentient) ? !((EntityInsentient) this.getHandle()).isNoAi() : false; } @Override public void attack(Entity target) { Preconditions.checkArgument(target != null, "target == null"); - Preconditions.checkState(!this.getHandle().generation, "Cannot attack during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot attack during world generation"); - if (this.getHandle() instanceof net.minecraft.world.entity.player.Player) { - ((net.minecraft.world.entity.player.Player) this.getHandle()).attack(((CraftEntity) target).getHandle()); + if (getHandle() instanceof EntityHuman) { + ((EntityHuman) getHandle()).attack(((CraftEntity) target).getHandle()); } else { - this.getHandle().doHurtTarget(((CraftEntity) target).getHandle()); + getHandle().doHurtTarget((WorldServer) ((CraftEntity) target).getHandle().level(), ((CraftEntity) target).getHandle()); } } @Override public void swingMainHand() { - Preconditions.checkState(!this.getHandle().generation, "Cannot swing hand during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot swing hand during world generation"); - this.getHandle().swing(InteractionHand.MAIN_HAND, true); + getHandle().swing(EnumHand.MAIN_HAND, true); } @Override public void swingOffHand() { - Preconditions.checkState(!this.getHandle().generation, "Cannot swing hand during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot swing hand during world generation"); - this.getHandle().swing(InteractionHand.OFF_HAND, true); + getHandle().swing(EnumHand.OFF_HAND, true); } @Override public void playHurtAnimation(float yaw) { - if (this.getHandle().level() instanceof ServerLevel world) { + if (getHandle().level() instanceof WorldServer world) { /* * Vanilla degrees state that 0 = left, 90 = front, 180 = right, and 270 = behind. * This makes no sense. We'll add 90 to it so that 0 = front, clockwise from there. */ float actualYaw = yaw + 90; - ClientboundHurtAnimationPacket packet = new ClientboundHurtAnimationPacket(this.getEntityId(), actualYaw); + ClientboundHurtAnimationPacket packet = new ClientboundHurtAnimationPacket(getEntityId(), actualYaw); - world.getChunkSource().broadcastAndSend(this.getHandle(), packet); + world.getChunkSource().broadcastAndSend(getHandle(), packet); } } @Override public void setCollidable(boolean collidable) { - this.getHandle().collides = collidable; + getHandle().collides = collidable; } @Override public boolean isCollidable() { - return this.getHandle().collides; + return getHandle().collides; } @Override public Set getCollidableExemptions() { - return this.getHandle().collidableExemptions; + return getHandle().collidableExemptions; } @Override public T getMemory(MemoryKey memoryKey) { - return (T) this.getHandle().getBrain().getMemory(CraftMemoryKey.bukkitToMinecraft(memoryKey)).map(CraftMemoryMapper::fromNms).orElse(null); + return (T) getHandle().getBrain().getMemory(CraftMemoryKey.bukkitToMinecraft(memoryKey)).map(CraftMemoryMapper::fromNms).orElse(null); } @Override public void setMemory(MemoryKey memoryKey, T t) { - this.getHandle().getBrain().setMemory(CraftMemoryKey.bukkitToMinecraft(memoryKey), CraftMemoryMapper.toNms(t)); + getHandle().getBrain().setMemory(CraftMemoryKey.bukkitToMinecraft(memoryKey), CraftMemoryMapper.toNms(t)); } @Override public Sound getHurtSound() { - SoundEvent sound = this.getHandle().getHurtSound0(this.getHandle().damageSources().generic()); + SoundEffect sound = getHandle().getHurtSound0(getHandle().damageSources().generic()); return (sound != null) ? CraftSound.minecraftToBukkit(sound) : null; } @Override public Sound getDeathSound() { - SoundEvent sound = this.getHandle().getDeathSound0(); + SoundEffect sound = getHandle().getDeathSound0(); return (sound != null) ? CraftSound.minecraftToBukkit(sound) : null; } @Override public Sound getFallDamageSound(int fallHeight) { - return CraftSound.minecraftToBukkit(this.getHandle().getFallDamageSound0(fallHeight)); + return CraftSound.minecraftToBukkit(getHandle().getFallDamageSound0(fallHeight)); } @Override public Sound getFallDamageSoundSmall() { - return CraftSound.minecraftToBukkit(this.getHandle().getFallSounds().small()); + return CraftSound.minecraftToBukkit(getHandle().getFallSounds().small()); } @Override public Sound getFallDamageSoundBig() { - return CraftSound.minecraftToBukkit(this.getHandle().getFallSounds().big()); + return CraftSound.minecraftToBukkit(getHandle().getFallSounds().big()); } @Override public Sound getDrinkingSound(ItemStack itemStack) { - Preconditions.checkArgument(itemStack != null, "itemStack must not be null"); - return CraftSound.minecraftToBukkit(this.getHandle().getDrinkingSound0(CraftItemStack.asNMSCopy(itemStack))); + return getEatingSound(itemStack); } @Override public Sound getEatingSound(ItemStack itemStack) { Preconditions.checkArgument(itemStack != null, "itemStack must not be null"); - return CraftSound.minecraftToBukkit(this.getHandle().getEatingSound0(CraftItemStack.asNMSCopy(itemStack))); + + net.minecraft.world.item.ItemStack nms = CraftItemStack.asNMSCopy(itemStack); + Consumable consumable = nms.get(DataComponents.CONSUMABLE); + SoundEffect soundeffect = SoundEffects.GENERIC_DRINK.value(); + + if (consumable != null) { + if (getHandle() instanceof Consumable.b consumable_b) { + soundeffect = consumable_b.getConsumeSound(nms); + } else { + soundeffect = (SoundEffect) consumable.sound().value(); + } + } + + return CraftSound.minecraftToBukkit(soundeffect); } @Override public boolean canBreatheUnderwater() { - return this.getHandle().canBreatheUnderwater(); + return getHandle().canBreatheUnderwater(); } @Override @@ -816,12 +832,12 @@ public EntityCategory getCategory() { @Override public boolean isInvisible() { - return this.getHandle().isInvisible(); + return getHandle().isInvisible(); } @Override public void setInvisible(boolean invisible) { - this.getHandle().persistentInvisibility = invisible; - this.getHandle().setSharedFlag(5, invisible); + getHandle().persistentInvisibility = invisible; + getHandle().setSharedFlag(5, invisible); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java index b910ddd9..9082667b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.animal.horse.EntityLlama; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventoryLlama; import org.bukkit.entity.Horse; @@ -10,43 +11,43 @@ public class CraftLlama extends CraftChestedHorse implements Llama { - public CraftLlama(CraftServer server, net.minecraft.world.entity.animal.horse.Llama entity) { + public CraftLlama(CraftServer server, EntityLlama entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.horse.Llama getHandle() { - return (net.minecraft.world.entity.animal.horse.Llama) super.getHandle(); + public EntityLlama getHandle() { + return (EntityLlama) super.getHandle(); } @Override public Color getColor() { - return Color.values()[this.getHandle().getVariant().ordinal()]; + return Color.values()[getHandle().getVariant().ordinal()]; } @Override public void setColor(Color color) { Preconditions.checkArgument(color != null, "color"); - this.getHandle().setVariant(net.minecraft.world.entity.animal.horse.Llama.Variant.byId(color.ordinal())); + getHandle().setVariant(EntityLlama.Variant.byId(color.ordinal())); } @Override public LlamaInventory getInventory() { - return new CraftInventoryLlama(this.getHandle().inventory, getHandle().getBodyArmorAccess()); + return new CraftInventoryLlama(getHandle().inventory, getHandle().getBodyArmorAccess()); } @Override public int getStrength() { - return this.getHandle().getStrength(); + return getHandle().getStrength(); } @Override public void setStrength(int strength) { Preconditions.checkArgument(1 <= strength && strength <= 5, "strength must be [1,5]"); - if (strength == this.getStrength()) return; - this.getHandle().setStrengthPublic(strength); - this.getHandle().createInventory(); + if (strength == getStrength()) return; + getHandle().setStrengthPublic(strength); + getHandle().createInventory(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java index 70cbc6c6..e128c931 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java @@ -1,18 +1,19 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntityLlamaSpit; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.LlamaSpit; import org.bukkit.projectiles.ProjectileSource; public class CraftLlamaSpit extends AbstractProjectile implements LlamaSpit { - public CraftLlamaSpit(CraftServer server, net.minecraft.world.entity.projectile.LlamaSpit entity) { + public CraftLlamaSpit(CraftServer server, EntityLlamaSpit entity) { super(server, entity); } @Override - public net.minecraft.world.entity.projectile.LlamaSpit getHandle() { - return (net.minecraft.world.entity.projectile.LlamaSpit) super.getHandle(); + public EntityLlamaSpit getHandle() { + return (EntityLlamaSpit) super.getHandle(); } @Override @@ -22,11 +23,11 @@ public String toString() { @Override public ProjectileSource getShooter() { - return (this.getHandle().getOwner() != null) ? (ProjectileSource) this.getHandle().getOwner().getBukkitEntity() : null; + return (getHandle().getOwner() != null) ? (ProjectileSource) getHandle().getOwner().getBukkitEntity() : null; } @Override public void setShooter(ProjectileSource source) { - this.getHandle().setOwner((source != null) ? ((CraftLivingEntity) source).getHandle() : null); + getHandle().setOwner((source != null) ? ((CraftLivingEntity) source).getHandle() : null); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java index 58b638ff..ac38b7b9 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityMagmaCube; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.MagmaCube; public class CraftMagmaCube extends CraftSlime implements MagmaCube { - public CraftMagmaCube(CraftServer server, net.minecraft.world.entity.monster.MagmaCube entity) { + public CraftMagmaCube(CraftServer server, EntityMagmaCube entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.MagmaCube getHandle() { - return (net.minecraft.world.entity.monster.MagmaCube) this.entity; + public EntityMagmaCube getHandle() { + return (EntityMagmaCube) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java index ee010d53..4755140e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.vehicle.AbstractMinecart; +import net.minecraft.world.entity.vehicle.EntityMinecartAbstract; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.block.data.BlockData; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.block.data.CraftBlockData; @@ -12,71 +12,71 @@ import org.bukkit.util.Vector; public abstract class CraftMinecart extends CraftVehicle implements Minecart { - public CraftMinecart(CraftServer server, AbstractMinecart entity) { + public CraftMinecart(CraftServer server, EntityMinecartAbstract entity) { super(server, entity); } @Override public void setDamage(double damage) { - this.getHandle().setDamage((float) damage); + getHandle().setDamage((float) damage); } @Override public double getDamage() { - return this.getHandle().getDamage(); + return getHandle().getDamage(); } @Override public double getMaxSpeed() { - return this.getHandle().maxSpeed; + return getHandle().maxSpeed; } @Override public void setMaxSpeed(double speed) { if (speed >= 0D) { - this.getHandle().maxSpeed = speed; + getHandle().maxSpeed = speed; } } @Override public boolean isSlowWhenEmpty() { - return this.getHandle().slowWhenEmpty; + return getHandle().slowWhenEmpty; } @Override public void setSlowWhenEmpty(boolean slow) { - this.getHandle().slowWhenEmpty = slow; + getHandle().slowWhenEmpty = slow; } @Override public Vector getFlyingVelocityMod() { - return this.getHandle().getFlyingVelocityMod(); + return getHandle().getFlyingVelocityMod(); } @Override public void setFlyingVelocityMod(Vector flying) { - this.getHandle().setFlyingVelocityMod(flying); + getHandle().setFlyingVelocityMod(flying); } @Override public Vector getDerailedVelocityMod() { - return this.getHandle().getDerailedVelocityMod(); + return getHandle().getDerailedVelocityMod(); } @Override public void setDerailedVelocityMod(Vector derailed) { - this.getHandle().setDerailedVelocityMod(derailed); + getHandle().setDerailedVelocityMod(derailed); } @Override - public AbstractMinecart getHandle() { - return (AbstractMinecart) this.entity; + public EntityMinecartAbstract getHandle() { + return (EntityMinecartAbstract) entity; } @Override public void setDisplayBlock(MaterialData material) { if (material != null) { - BlockState block = CraftMagicNumbers.getBlock(material); + IBlockData block = CraftMagicNumbers.getBlock(material); this.getHandle().setDisplayBlockState(block); } else { // Set block to air (default) and set the flag to not have a display block. @@ -88,7 +88,7 @@ public void setDisplayBlock(MaterialData material) { @Override public void setDisplayBlockData(BlockData blockData) { if (blockData != null) { - BlockState block = ((CraftBlockData) blockData).getState(); + IBlockData block = ((CraftBlockData) blockData).getState(); this.getHandle().setDisplayBlockState(block); } else { // Set block to air (default) and set the flag to not have a display block. @@ -99,23 +99,23 @@ public void setDisplayBlockData(BlockData blockData) { @Override public MaterialData getDisplayBlock() { - BlockState blockData = this.getHandle().getDisplayBlockState(); + IBlockData blockData = getHandle().getDisplayBlockState(); return CraftMagicNumbers.getMaterial(blockData); } @Override public BlockData getDisplayBlockData() { - BlockState blockData = this.getHandle().getDisplayBlockState(); + IBlockData blockData = getHandle().getDisplayBlockState(); return CraftBlockData.fromData(blockData); } @Override public void setDisplayBlockOffset(int offset) { - this.getHandle().setDisplayOffset(offset); + getHandle().setDisplayOffset(offset); } @Override public int getDisplayBlockOffset() { - return this.getHandle().getDisplayOffset(); + return getHandle().getDisplayOffset(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java index fd42f0b2..2d2c80cf 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.vehicle.MinecartChest; +import net.minecraft.world.entity.vehicle.EntityMinecartChest; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.entity.minecart.StorageMinecart; @@ -10,18 +10,18 @@ public class CraftMinecartChest extends CraftMinecartContainer implements StorageMinecart { private final CraftInventory inventory; - public CraftMinecartChest(CraftServer server, MinecartChest entity) { + public CraftMinecartChest(CraftServer server, EntityMinecartChest entity) { super(server, entity); - this.inventory = new CraftInventory(entity); + inventory = new CraftInventory(entity); } @Override public Inventory getInventory() { - return this.inventory; + return inventory; } @Override public String toString() { - return "CraftMinecartChest{" + "inventory=" + this.inventory + '}'; + return "CraftMinecartChest{" + "inventory=" + inventory + '}'; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java index 55945b83..dd9b8f18 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.entity; import java.util.Set; -import net.minecraft.world.entity.vehicle.MinecartCommandBlock; +import net.minecraft.world.entity.vehicle.EntityMinecartCommandBlock; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.craftbukkit.CraftServer; @@ -16,29 +16,29 @@ public class CraftMinecartCommand extends CraftMinecart implements CommandMinecart { private final PermissibleBase perm = new PermissibleBase(this); - public CraftMinecartCommand(CraftServer server, MinecartCommandBlock entity) { + public CraftMinecartCommand(CraftServer server, EntityMinecartCommandBlock entity) { super(server, entity); } @Override - public MinecartCommandBlock getHandle() { - return (MinecartCommandBlock) this.entity; + public EntityMinecartCommandBlock getHandle() { + return (EntityMinecartCommandBlock) entity; } @Override public String getCommand() { - return this.getHandle().getCommandBlock().getCommand(); + return getHandle().getCommandBlock().getCommand(); } @Override public void setCommand(String command) { - this.getHandle().getCommandBlock().setCommand(command != null ? command : ""); - this.getHandle().getEntityData().set(MinecartCommandBlock.DATA_ID_COMMAND_NAME, this.getHandle().getCommandBlock().getCommand()); + getHandle().getCommandBlock().setCommand(command != null ? command : ""); + getHandle().getEntityData().set(EntityMinecartCommandBlock.DATA_ID_COMMAND_NAME, getHandle().getCommandBlock().getCommand()); } @Override public void setName(String name) { - this.getHandle().getCommandBlock().setCustomName(CraftChatMessage.fromStringOrNull(name)); + getHandle().getCommandBlock().setCustomName(CraftChatMessage.fromStringOrNull(name)); } @Override @@ -56,7 +56,7 @@ public void sendMessage(String... messages) { @Override public String getName() { - return CraftChatMessage.fromComponent(this.getHandle().getCommandBlock().getName()); + return CraftChatMessage.fromComponent(getHandle().getCommandBlock().getName()); } @Override @@ -71,7 +71,7 @@ public void setOp(boolean value) { @Override public boolean isPermissionSet(String name) { - return this.perm.isPermissionSet(name); + return perm.isPermissionSet(name); } @Override @@ -81,7 +81,7 @@ public boolean isPermissionSet(Permission perm) { @Override public boolean hasPermission(String name) { - return this.perm.hasPermission(name); + return perm.hasPermission(name); } @Override @@ -91,37 +91,37 @@ public boolean hasPermission(Permission perm) { @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return this.perm.addAttachment(plugin, name, value); + return perm.addAttachment(plugin, name, value); } @Override public PermissionAttachment addAttachment(Plugin plugin) { - return this.perm.addAttachment(plugin); + return perm.addAttachment(plugin); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return this.perm.addAttachment(plugin, name, value, ticks); + return perm.addAttachment(plugin, name, value, ticks); } @Override public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return this.perm.addAttachment(plugin, ticks); + return perm.addAttachment(plugin, ticks); } @Override public void removeAttachment(PermissionAttachment attachment) { - this.perm.removeAttachment(attachment); + perm.removeAttachment(attachment); } @Override public void recalculatePermissions() { - this.perm.recalculatePermissions(); + perm.recalculatePermissions(); } @Override public Set getEffectivePermissions() { - return this.perm.getEffectivePermissions(); + return perm.getEffectivePermissions(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java index 3db34cfa..420341ca 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.vehicle.AbstractMinecart; -import net.minecraft.world.entity.vehicle.AbstractMinecartContainer; +import net.minecraft.world.entity.vehicle.EntityMinecartAbstract; +import net.minecraft.world.entity.vehicle.EntityMinecartContainer; import org.bukkit.craftbukkit.CraftLootTable; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.loot.LootTable; @@ -9,36 +9,36 @@ public abstract class CraftMinecartContainer extends CraftMinecart implements Lootable { - public CraftMinecartContainer(CraftServer server, AbstractMinecart entity) { + public CraftMinecartContainer(CraftServer server, EntityMinecartAbstract entity) { super(server, entity); } @Override - public AbstractMinecartContainer getHandle() { - return (AbstractMinecartContainer) this.entity; + public EntityMinecartContainer getHandle() { + return (EntityMinecartContainer) entity; } @Override public void setLootTable(LootTable table) { - this.setLootTable(table, this.getSeed()); + setLootTable(table, getSeed()); } @Override public LootTable getLootTable() { - return CraftLootTable.minecraftToBukkit(this.getHandle().getLootTable()); + return CraftLootTable.minecraftToBukkit(getHandle().lootTable); } @Override public void setSeed(long seed) { - this.setLootTable(this.getLootTable(), seed); + setLootTable(getLootTable(), seed); } @Override public long getSeed() { - return this.getHandle().getLootTableSeed(); + return getHandle().lootTableSeed; } private void setLootTable(LootTable table, long seed) { - this.getHandle().setLootTable(CraftLootTable.bukkitToMinecraft(table), seed); + getHandle().setLootTable(CraftLootTable.bukkitToMinecraft(table), seed); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java index 53042b75..a810eb05 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java @@ -1,30 +1,30 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.vehicle.MinecartFurnace; +import net.minecraft.world.entity.vehicle.EntityMinecartFurnace; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.minecart.PoweredMinecart; @SuppressWarnings("deprecation") public class CraftMinecartFurnace extends CraftMinecart implements PoweredMinecart { - public CraftMinecartFurnace(CraftServer server, MinecartFurnace entity) { + public CraftMinecartFurnace(CraftServer server, EntityMinecartFurnace entity) { super(server, entity); } @Override - public MinecartFurnace getHandle() { - return (MinecartFurnace) this.entity; + public EntityMinecartFurnace getHandle() { + return (EntityMinecartFurnace) entity; } @Override public int getFuel() { - return this.getHandle().fuel; + return getHandle().fuel; } @Override public void setFuel(int fuel) { Preconditions.checkArgument(fuel >= 0, "ticks cannot be negative"); - this.getHandle().fuel = fuel; + getHandle().fuel = fuel; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java index 39427b4f..3bceeac6 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.vehicle.MinecartHopper; +import net.minecraft.world.entity.vehicle.EntityMinecartHopper; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.entity.minecart.HopperMinecart; @@ -9,28 +9,28 @@ public final class CraftMinecartHopper extends CraftMinecartContainer implements HopperMinecart { private final CraftInventory inventory; - public CraftMinecartHopper(CraftServer server, MinecartHopper entity) { + public CraftMinecartHopper(CraftServer server, EntityMinecartHopper entity) { super(server, entity); - this.inventory = new CraftInventory(entity); + inventory = new CraftInventory(entity); } @Override public String toString() { - return "CraftMinecartHopper{" + "inventory=" + this.inventory + '}'; + return "CraftMinecartHopper{" + "inventory=" + inventory + '}'; } @Override public Inventory getInventory() { - return this.inventory; + return inventory; } @Override public boolean isEnabled() { - return ((MinecartHopper) this.getHandle()).isEnabled(); + return ((EntityMinecartHopper) getHandle()).isEnabled(); } @Override public void setEnabled(boolean enabled) { - ((MinecartHopper) this.getHandle()).setEnabled(enabled); + ((EntityMinecartHopper) getHandle()).setEnabled(enabled); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java index cc1e7f8e..546472fd 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java @@ -6,8 +6,9 @@ import java.util.Optional; import net.minecraft.util.RandomSource; import net.minecraft.util.random.SimpleWeightedRandomList; -import net.minecraft.world.entity.vehicle.MinecartSpawner; -import net.minecraft.world.level.SpawnData; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.vehicle.EntityMinecartMobSpawner; +import net.minecraft.world.level.MobSpawnerData; import org.bukkit.block.spawner.SpawnRule; import org.bukkit.block.spawner.SpawnerEntry; import org.bukkit.craftbukkit.CraftServer; @@ -17,19 +18,18 @@ import org.bukkit.entity.minecart.SpawnerMinecart; final class CraftMinecartMobSpawner extends CraftMinecart implements SpawnerMinecart { - CraftMinecartMobSpawner(CraftServer server, MinecartSpawner entity) { + CraftMinecartMobSpawner(CraftServer server, EntityMinecartMobSpawner entity) { super(server, entity); } - @Override public EntityType getSpawnedType() { - SpawnData spawnData = getHandle().getSpawner().nextSpawnData; + MobSpawnerData spawnData = getHandle().getSpawner().nextSpawnData; if (spawnData == null) { return null; } - Optional> type = net.minecraft.world.entity.EntityType.by(spawnData.getEntityToSpawn()); + Optional> type = EntityTypes.by(spawnData.getEntityToSpawn()); return type.map(CraftEntityType::minecraftToBukkit).orElse(null); } @@ -37,7 +37,7 @@ public EntityType getSpawnedType() { public void setSpawnedType(EntityType entityType) { if (entityType == null) { getHandle().getSpawner().spawnPotentials = SimpleWeightedRandomList.empty(); // need clear the spawnPotentials to avoid nextSpawnData being replaced later - getHandle().getSpawner().nextSpawnData = new SpawnData(); + getHandle().getSpawner().nextSpawnData = new MobSpawnerData(); return; } Preconditions.checkArgument(entityType != EntityType.UNKNOWN, "Can't spawn EntityType %s from mob spawners!", entityType); @@ -48,7 +48,7 @@ public void setSpawnedType(EntityType entityType) { @Override public EntitySnapshot getSpawnedEntity() { - SpawnData spawnData = getHandle().getSpawner().nextSpawnData; + MobSpawnerData spawnData = getHandle().getSpawner().nextSpawnData; if (spawnData == null) { return null; } @@ -164,8 +164,8 @@ public void setSpawnRange(int spawnRange) { } @Override - public MinecartSpawner getHandle() { - return (MinecartSpawner) entity; + public EntityMinecartMobSpawner getHandle() { + return (EntityMinecartMobSpawner) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java index 2f8c3f90..b6181134 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.vehicle.AbstractMinecart; +import net.minecraft.world.entity.vehicle.EntityMinecartAbstract; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.minecart.RideableMinecart; public class CraftMinecartRideable extends CraftMinecart implements RideableMinecart { - public CraftMinecartRideable(CraftServer server, AbstractMinecart entity) { + public CraftMinecartRideable(CraftServer server, EntityMinecartAbstract entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java index 79b608e8..c7f3da5e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java @@ -1,50 +1,70 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.vehicle.MinecartTNT; +import net.minecraft.world.entity.vehicle.EntityMinecartTNT; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.minecart.ExplosiveMinecart; public final class CraftMinecartTNT extends CraftMinecart implements ExplosiveMinecart { - CraftMinecartTNT(CraftServer server, MinecartTNT entity) { + CraftMinecartTNT(CraftServer server, EntityMinecartTNT entity) { super(server, entity); } + @Override + public float getYield() { + return getHandle().explosionPowerBase; + } + + @Override + public boolean isIncendiary() { + return getHandle().isIncendiary; + } + + @Override + public void setIsIncendiary(boolean isIncendiary) { + getHandle().isIncendiary = isIncendiary; + } + + @Override + public void setYield(float yield) { + getHandle().explosionPowerBase = yield; + } + @Override public void setFuseTicks(int ticks) { - this.getHandle().fuse = ticks; + getHandle().fuse = ticks; } @Override public int getFuseTicks() { - return this.getHandle().getFuse(); + return getHandle().getFuse(); } @Override public void ignite() { - this.getHandle().primeFuse(); + getHandle().primeFuse(); } @Override public boolean isIgnited() { - return this.getHandle().isPrimed(); + return getHandle().isPrimed(); } @Override public void explode() { - this.getHandle().explode(this.getHandle().getDeltaMovement().horizontalDistanceSqr()); + getHandle().explode(getHandle().getDeltaMovement().horizontalDistanceSqr()); } @Override public void explode(double power) { Preconditions.checkArgument(0 <= power && power <= 5, "Power must be in range [0, 5] (got %s)", power); - this.getHandle().explode(power); + getHandle().explode(power); } @Override - public MinecartTNT getHandle() { - return (MinecartTNT) super.getHandle(); + public EntityMinecartTNT getHandle() { + return (EntityMinecartTNT) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java index 58e690a9..4a52c56f 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java @@ -1,7 +1,9 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.sounds.SoundEvent; +import java.util.Optional; +import net.minecraft.sounds.SoundEffect; +import net.minecraft.world.entity.EntityInsentient; import org.bukkit.Sound; import org.bukkit.craftbukkit.CraftLootTable; import org.bukkit.craftbukkit.CraftServer; @@ -11,15 +13,15 @@ import org.bukkit.loot.LootTable; public abstract class CraftMob extends CraftLivingEntity implements Mob { - public CraftMob(CraftServer server, net.minecraft.world.entity.Mob entity) { + public CraftMob(CraftServer server, EntityInsentient entity) { super(server, entity); } @Override public void setTarget(LivingEntity target) { - Preconditions.checkState(!this.getHandle().generation, "Cannot set target during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot set target during world generation"); - net.minecraft.world.entity.Mob entity = this.getHandle(); + EntityInsentient entity = getHandle(); if (target == null) { entity.setTarget(null, null, false); } else if (target instanceof CraftLivingEntity) { @@ -29,30 +31,30 @@ public void setTarget(LivingEntity target) { @Override public CraftLivingEntity getTarget() { - if (this.getHandle().getTarget() == null) return null; + if (getHandle().getTarget() == null) return null; - return (CraftLivingEntity) this.getHandle().getTarget().getBukkitEntity(); + return (CraftLivingEntity) getHandle().getTarget().getBukkitEntity(); } @Override public void setAware(boolean aware) { - this.getHandle().aware = aware; + getHandle().aware = aware; } @Override public boolean isAware() { - return this.getHandle().aware; + return getHandle().aware; } @Override public Sound getAmbientSound() { - SoundEvent sound = this.getHandle().getAmbientSound0(); + SoundEffect sound = getHandle().getAmbientSound0(); return (sound != null) ? CraftSound.minecraftToBukkit(sound) : null; } @Override - public net.minecraft.world.entity.Mob getHandle() { - return (net.minecraft.world.entity.Mob) this.entity; + public EntityInsentient getHandle() { + return (EntityInsentient) entity; } @Override @@ -62,21 +64,21 @@ public String toString() { @Override public void setLootTable(LootTable table) { - this.getHandle().lootTable = CraftLootTable.bukkitToMinecraft(table); + getHandle().lootTable = Optional.ofNullable(CraftLootTable.bukkitToMinecraft(table)); } @Override public LootTable getLootTable() { - return CraftLootTable.minecraftToBukkit(this.getHandle().getLootTable()); + return CraftLootTable.minecraftToBukkit(getHandle().getLootTable().orElse(null)); } @Override public void setSeed(long seed) { - this.getHandle().lootTableSeed = seed; + getHandle().lootTableSeed = seed; } @Override public long getSeed() { - return this.getHandle().lootTableSeed; + return getHandle().lootTableSeed; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java index 706c74c8..dd3ef689 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityMonster; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Monster; public class CraftMonster extends CraftCreature implements Monster, CraftEnemy { - public CraftMonster(CraftServer server, net.minecraft.world.entity.monster.Monster entity) { + public CraftMonster(CraftServer server, EntityMonster entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Monster getHandle() { - return (net.minecraft.world.entity.monster.Monster) this.entity; + public EntityMonster getHandle() { + return (EntityMonster) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java index 97820a5d..18cfc80f 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.horse.EntityHorseMule; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Horse.Variant; import org.bukkit.entity.Mule; public class CraftMule extends CraftChestedHorse implements Mule { - public CraftMule(CraftServer server, net.minecraft.world.entity.animal.horse.Mule entity) { + public CraftMule(CraftServer server, EntityHorseMule entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java index 986f7b18..2dff4228 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java @@ -5,7 +5,8 @@ import java.util.List; import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffectList; +import net.minecraft.world.entity.animal.EntityMushroomCow; import net.minecraft.world.item.component.SuspiciousStewEffects; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; @@ -15,7 +16,7 @@ import org.bukkit.potion.PotionEffectType; public class CraftMushroomCow extends CraftCow implements MushroomCow { - public CraftMushroomCow(CraftServer server, net.minecraft.world.entity.animal.MushroomCow entity) { + public CraftMushroomCow(CraftServer server, EntityMushroomCow entity) { super(server, entity); } @@ -37,7 +38,7 @@ public List getEffectsForNextStew() { @Override public boolean addEffectToNextStew(PotionEffect potionEffect, boolean overwrite) { Preconditions.checkArgument(potionEffect != null, "PotionEffect cannot be null"); - MobEffectInstance minecraftPotionEffect = CraftPotionUtil.fromBukkit(potionEffect); + MobEffect minecraftPotionEffect = CraftPotionUtil.fromBukkit(potionEffect); if (!overwrite && this.hasEffectForNextStew(potionEffect.getType())) { return false; } @@ -45,16 +46,16 @@ public boolean addEffectToNextStew(PotionEffect potionEffect, boolean overwrite) if (stewEffects == null) { stewEffects = SuspiciousStewEffects.EMPTY; } - SuspiciousStewEffects.Entry recordSuspiciousEffect = new SuspiciousStewEffects.Entry(minecraftPotionEffect.getEffect(), minecraftPotionEffect.getDuration()); + SuspiciousStewEffects.a recordSuspiciousEffect = new SuspiciousStewEffects.a(minecraftPotionEffect.getEffect(), minecraftPotionEffect.getDuration()); this.removeEffectFromNextStew(potionEffect.getType()); // Avoid duplicates of effects - this.getHandle().stewEffects = stewEffects.withEffectAdded(recordSuspiciousEffect); + getHandle().stewEffects = stewEffects.withEffectAdded(recordSuspiciousEffect); return true; } @Override public boolean removeEffectFromNextStew(PotionEffectType potionEffectType) { Preconditions.checkArgument(potionEffectType != null, "potionEffectType cannot be null"); - if (!this.hasEffectForNextStew(potionEffectType)) { + if (!hasEffectForNextStew(potionEffectType)) { return false; } @@ -63,8 +64,8 @@ public boolean removeEffectFromNextStew(PotionEffectType potionEffectType) { return false; } - Holder minecraftPotionEffectType = CraftPotionEffectType.bukkitToMinecraftHolder(potionEffectType); - this.getHandle().stewEffects = new SuspiciousStewEffects(stewEffects.effects().stream().filter((effect) -> !effect.effect().equals(minecraftPotionEffectType)).toList()); + Holder minecraftPotionEffectType = CraftPotionEffectType.bukkitToMinecraftHolder(potionEffectType); + getHandle().stewEffects = new SuspiciousStewEffects(stewEffects.effects().stream().filter((effect) -> !effect.effect().equals(minecraftPotionEffectType)).toList()); return true; } @@ -75,7 +76,7 @@ public boolean hasEffectForNextStew(PotionEffectType potionEffectType) { if (stewEffects == null) { return false; } - Holder minecraftPotionEffectType = CraftPotionEffectType.bukkitToMinecraftHolder(potionEffectType); + Holder minecraftPotionEffectType = CraftPotionEffectType.bukkitToMinecraftHolder(potionEffectType); return stewEffects.effects().stream().anyMatch(recordSuspiciousEffect -> recordSuspiciousEffect.effect().equals(minecraftPotionEffectType)); } @@ -85,20 +86,20 @@ public void clearEffectsForNextStew() { } @Override - public net.minecraft.world.entity.animal.MushroomCow getHandle() { - return (net.minecraft.world.entity.animal.MushroomCow) this.entity; + public EntityMushroomCow getHandle() { + return (EntityMushroomCow) entity; } @Override public Variant getVariant() { - return Variant.values()[this.getHandle().getVariant().ordinal()]; + return Variant.values()[getHandle().getVariant().ordinal()]; } @Override public void setVariant(Variant variant) { Preconditions.checkArgument(variant != null, "Variant cannot be null"); - this.getHandle().setVariant(net.minecraft.world.entity.animal.MushroomCow.MushroomType.values()[variant.ordinal()]); + getHandle().setVariant(EntityMushroomCow.Type.values()[variant.ordinal()]); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java index 5c60a30e..38807f0e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java @@ -1,27 +1,28 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityOcelot; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Ocelot.Type; public class CraftOcelot extends CraftAnimals implements Ocelot { - public CraftOcelot(CraftServer server, net.minecraft.world.entity.animal.Ocelot ocelot) { + public CraftOcelot(CraftServer server, EntityOcelot ocelot) { super(server, ocelot); } @Override - public net.minecraft.world.entity.animal.Ocelot getHandle() { - return (net.minecraft.world.entity.animal.Ocelot) this.entity; + public EntityOcelot getHandle() { + return (EntityOcelot) entity; } @Override public boolean isTrusting() { - return this.getHandle().isTrusting(); + return getHandle().isTrusting(); } @Override public void setTrusting(boolean trust) { - this.getHandle().setTrusting(trust); + getHandle().setTrusting(trust); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftOminousItemSpawner.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftOminousItemSpawner.java index ecdac2cf..4aa00b24 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftOminousItemSpawner.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftOminousItemSpawner.java @@ -13,7 +13,7 @@ public CraftOminousItemSpawner(CraftServer server, net.minecraft.world.entity.Om @Override public net.minecraft.world.entity.OminousItemSpawner getHandle() { - return (net.minecraft.world.entity.OminousItemSpawner) this.entity; + return (net.minecraft.world.entity.OminousItemSpawner) entity; } @Override @@ -23,21 +23,21 @@ public String toString() { @Override public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getHandle().getItem()); + return CraftItemStack.asBukkitCopy(getHandle().getItem()); } @Override public void setItem(ItemStack item) { - this.getHandle().setItem(CraftItemStack.asNMSCopy(item)); + getHandle().setItem(CraftItemStack.asNMSCopy(item)); } @Override public long getSpawnItemAfterTicks() { - return this.getHandle().spawnItemAfterTicks; + return getHandle().spawnItemAfterTicks; } @Override public void setSpawnItemAfterTicks(long ticks) { - this.getHandle().spawnItemAfterTicks = ticks; + getHandle().spawnItemAfterTicks = ticks; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java index dd02cec9..c8f74b33 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import net.minecraft.core.Holder; +import net.minecraft.world.entity.decoration.EntityPainting; import net.minecraft.world.entity.decoration.PaintingVariant; import org.bukkit.Art; import org.bukkit.block.BlockFace; @@ -10,27 +11,27 @@ public class CraftPainting extends CraftHanging implements Painting { - public CraftPainting(CraftServer server, net.minecraft.world.entity.decoration.Painting entity) { + public CraftPainting(CraftServer server, EntityPainting entity) { super(server, entity); } @Override public Art getArt() { - return CraftArt.minecraftHolderToBukkit(this.getHandle().getVariant()); + return CraftArt.minecraftHolderToBukkit(getHandle().getVariant()); } @Override public boolean setArt(Art art) { - return this.setArt(art, false); + return setArt(art, false); } @Override public boolean setArt(Art art, boolean force) { - net.minecraft.world.entity.decoration.Painting painting = this.getHandle(); + EntityPainting painting = this.getHandle(); Holder oldArt = painting.getVariant(); painting.setVariant(CraftArt.bukkitToMinecraftHolder(art)); painting.setDirection(painting.getDirection()); - if (!force && !this.getHandle().generation && !painting.survives()) { + if (!force && !getHandle().generation && !painting.survives()) { // Revert painting since it doesn't fit painting.setVariant(oldArt); painting.setDirection(painting.getDirection()); @@ -43,7 +44,7 @@ public boolean setArt(Art art, boolean force) { @Override public boolean setFacingDirection(BlockFace face, boolean force) { if (super.setFacingDirection(face, force)) { - this.update(); + update(); return true; } @@ -51,12 +52,12 @@ public boolean setFacingDirection(BlockFace face, boolean force) { } @Override - public net.minecraft.world.entity.decoration.Painting getHandle() { - return (net.minecraft.world.entity.decoration.Painting) this.entity; + public EntityPainting getHandle() { + return (EntityPainting) entity; } @Override public String toString() { - return "CraftPainting{art=" + this.getArt() + "}"; + return "CraftPainting{art=" + getArt() + "}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java index 5467e4a7..514af4e3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java @@ -1,19 +1,20 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.animal.EntityPanda; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Panda; import org.bukkit.entity.Panda.Gene; public class CraftPanda extends CraftAnimals implements Panda { - public CraftPanda(CraftServer server, net.minecraft.world.entity.animal.Panda entity) { + public CraftPanda(CraftServer server, EntityPanda entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Panda getHandle() { - return (net.minecraft.world.entity.animal.Panda) super.getHandle(); + public EntityPanda getHandle() { + return (EntityPanda) super.getHandle(); } @Override @@ -23,93 +24,93 @@ public String toString() { @Override public Gene getMainGene() { - return CraftPanda.fromNms(this.getHandle().getMainGene()); + return fromNms(getHandle().getMainGene()); } @Override public void setMainGene(Gene gene) { - this.getHandle().setMainGene(CraftPanda.toNms(gene)); + getHandle().setMainGene(toNms(gene)); } @Override public Gene getHiddenGene() { - return CraftPanda.fromNms(this.getHandle().getHiddenGene()); + return fromNms(getHandle().getHiddenGene()); } @Override public void setHiddenGene(Gene gene) { - this.getHandle().setHiddenGene(CraftPanda.toNms(gene)); + getHandle().setHiddenGene(toNms(gene)); } @Override public boolean isRolling() { - return this.getHandle().isRolling(); + return getHandle().isRolling(); } @Override public void setRolling(boolean flag) { - this.getHandle().roll(flag); + getHandle().roll(flag); } @Override public boolean isSneezing() { - return this.getHandle().isSneezing(); + return getHandle().isSneezing(); } @Override public void setSneezing(boolean flag) { - this.getHandle().sneeze(flag); + getHandle().sneeze(flag); } @Override public boolean isSitting() { - return this.getHandle().isSitting(); + return getHandle().isSitting(); } @Override public void setSitting(boolean flag) { - this.getHandle().sit(flag); + getHandle().sit(flag); } @Override public boolean isOnBack() { - return this.getHandle().isOnBack(); + return getHandle().isOnBack(); } @Override public void setOnBack(boolean flag) { - this.getHandle().setOnBack(flag); + getHandle().setOnBack(flag); } @Override public boolean isEating() { - return this.getHandle().isEating(); + return getHandle().isEating(); } @Override public void setEating(boolean flag) { - this.getHandle().eat(flag); + getHandle().eat(flag); } @Override public boolean isScared() { - return this.getHandle().isScared(); + return getHandle().isScared(); } @Override public int getUnhappyTicks() { - return this.getHandle().getUnhappyCounter(); + return getHandle().getUnhappyCounter(); } - public static Gene fromNms(net.minecraft.world.entity.animal.Panda.Gene gene) { + public static Gene fromNms(EntityPanda.Gene gene) { Preconditions.checkArgument(gene != null, "Gene may not be null"); return Gene.values()[gene.ordinal()]; } - public static net.minecraft.world.entity.animal.Panda.Gene toNms(Gene gene) { + public static EntityPanda.Gene toNms(Gene gene) { Preconditions.checkArgument(gene != null, "Gene may not be null"); - return net.minecraft.world.entity.animal.Panda.Gene.values()[gene.ordinal()]; + return EntityPanda.Gene.values()[gene.ordinal()]; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java index 04d6cf6a..16c2afba 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java @@ -1,31 +1,32 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.animal.EntityParrot; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Parrot; import org.bukkit.entity.Parrot.Variant; public class CraftParrot extends CraftTameableAnimal implements Parrot { - public CraftParrot(CraftServer server, net.minecraft.world.entity.animal.Parrot parrot) { + public CraftParrot(CraftServer server, EntityParrot parrot) { super(server, parrot); } @Override - public net.minecraft.world.entity.animal.Parrot getHandle() { - return (net.minecraft.world.entity.animal.Parrot) this.entity; + public EntityParrot getHandle() { + return (EntityParrot) entity; } @Override public Variant getVariant() { - return Variant.values()[this.getHandle().getVariant().ordinal()]; + return Variant.values()[getHandle().getVariant().ordinal()]; } @Override public void setVariant(Variant variant) { Preconditions.checkArgument(variant != null, "variant"); - this.getHandle().setVariant(net.minecraft.world.entity.animal.Parrot.Variant.byId(variant.ordinal())); + getHandle().setVariant(EntityParrot.Variant.byId(variant.ordinal())); } @Override @@ -35,6 +36,6 @@ public String toString() { @Override public boolean isDancing() { - return this.getHandle().isPartyParrot(); + return getHandle().isPartyParrot(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java index 0359c161..877429f1 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java @@ -1,27 +1,28 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityPhantom; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Phantom; public class CraftPhantom extends CraftFlying implements Phantom, CraftEnemy { - public CraftPhantom(CraftServer server, net.minecraft.world.entity.monster.Phantom entity) { + public CraftPhantom(CraftServer server, EntityPhantom entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Phantom getHandle() { - return (net.minecraft.world.entity.monster.Phantom) super.getHandle(); + public EntityPhantom getHandle() { + return (EntityPhantom) super.getHandle(); } @Override public int getSize() { - return this.getHandle().getPhantomSize(); + return getHandle().getPhantomSize(); } @Override public void setSize(int sz) { - this.getHandle().setPhantomSize(sz); + getHandle().setPhantomSize(sz); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java index 8016c810..e1844580 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java @@ -1,50 +1,51 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.animal.EntityPig; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Pig; public class CraftPig extends CraftAnimals implements Pig { - public CraftPig(CraftServer server, net.minecraft.world.entity.animal.Pig entity) { + public CraftPig(CraftServer server, EntityPig entity) { super(server, entity); } @Override public boolean hasSaddle() { - return this.getHandle().isSaddled(); + return getHandle().isSaddled(); } @Override public void setSaddle(boolean saddled) { - this.getHandle().steering.setSaddle(saddled); + getHandle().steering.setSaddle(saddled); } @Override public int getBoostTicks() { - return this.getHandle().steering.boosting ? this.getHandle().steering.boostTimeTotal() : 0; + return getHandle().steering.boosting ? getHandle().steering.boostTimeTotal() : 0; } @Override public void setBoostTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks must be >= 0"); - this.getHandle().steering.setBoostTicks(ticks); + getHandle().steering.setBoostTicks(ticks); } @Override public int getCurrentBoostTicks() { - return this.getHandle().steering.boosting ? this.getHandle().steering.boostTime : 0; + return getHandle().steering.boosting ? getHandle().steering.boostTime : 0; } @Override public void setCurrentBoostTicks(int ticks) { - if (!this.getHandle().steering.boosting) { + if (!getHandle().steering.boosting) { return; } - int max = this.getHandle().steering.boostTimeTotal(); + int max = getHandle().steering.boostTimeTotal(); Preconditions.checkArgument(ticks >= 0 && ticks <= max, "boost ticks must not exceed 0 or %d (inclusive)", max); this.getHandle().steering.boostTime = ticks; @@ -56,8 +57,8 @@ public Material getSteerMaterial() { } @Override - public net.minecraft.world.entity.animal.Pig getHandle() { - return (net.minecraft.world.entity.animal.Pig) this.entity; + public EntityPig getHandle() { + return (EntityPig) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java index 49beb836..fcd97b82 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java @@ -1,38 +1,38 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.monster.ZombifiedPiglin; +import net.minecraft.world.entity.monster.EntityPigZombie; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.PigZombie; public class CraftPigZombie extends CraftZombie implements PigZombie { - public CraftPigZombie(CraftServer server, ZombifiedPiglin entity) { + public CraftPigZombie(CraftServer server, EntityPigZombie entity) { super(server, entity); } @Override public int getAnger() { - return this.getHandle().getRemainingPersistentAngerTime(); + return getHandle().getRemainingPersistentAngerTime(); } @Override public void setAnger(int level) { - this.getHandle().setRemainingPersistentAngerTime(level); + getHandle().setRemainingPersistentAngerTime(level); } @Override public void setAngry(boolean angry) { - this.setAnger(angry ? 400 : 0); + setAnger(angry ? 400 : 0); } @Override public boolean isAngry() { - return this.getAnger() > 0; + return getAnger() > 0; } @Override - public ZombifiedPiglin getHandle() { - return (ZombifiedPiglin) this.entity; + public EntityPigZombie getHandle() { + return (EntityPigZombie) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglin.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglin.java index 9426395c..f7d443de 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglin.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglin.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; +import net.minecraft.world.entity.monster.piglin.EntityPiglin; import net.minecraft.world.item.Item; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; @@ -14,18 +15,18 @@ public class CraftPiglin extends CraftPiglinAbstract implements Piglin { - public CraftPiglin(CraftServer server, net.minecraft.world.entity.monster.piglin.Piglin entity) { + public CraftPiglin(CraftServer server, EntityPiglin entity) { super(server, entity); } @Override public boolean isAbleToHunt() { - return this.getHandle().cannotHunt; + return getHandle().cannotHunt; } @Override public void setIsAbleToHunt(boolean flag) { - this.getHandle().cannotHunt = flag; + getHandle().cannotHunt = flag; } @Override @@ -33,7 +34,7 @@ public boolean addBarterMaterial(Material material) { Preconditions.checkArgument(material != null, "material cannot be null"); Item item = CraftItemType.bukkitToMinecraft(material); - return this.getHandle().allowedBarterItems.add(item); + return getHandle().allowedBarterItems.add(item); } @Override @@ -41,7 +42,7 @@ public boolean removeBarterMaterial(Material material) { Preconditions.checkArgument(material != null, "material cannot be null"); Item item = CraftItemType.bukkitToMinecraft(material); - return this.getHandle().allowedBarterItems.remove(item); + return getHandle().allowedBarterItems.remove(item); } @Override @@ -49,7 +50,7 @@ public boolean addMaterialOfInterest(Material material) { Preconditions.checkArgument(material != null, "material cannot be null"); Item item = CraftItemType.bukkitToMinecraft(material); - return this.getHandle().interestItems.add(item); + return getHandle().interestItems.add(item); } @Override @@ -57,27 +58,27 @@ public boolean removeMaterialOfInterest(Material material) { Preconditions.checkArgument(material != null, "material cannot be null"); Item item = CraftItemType.bukkitToMinecraft(material); - return this.getHandle().interestItems.remove(item); + return getHandle().interestItems.remove(item); } @Override public Set getInterestList() { - return Collections.unmodifiableSet(this.getHandle().interestItems.stream().map(CraftItemType::minecraftToBukkit).collect(Collectors.toSet())); + return Collections.unmodifiableSet(getHandle().interestItems.stream().map(CraftItemType::minecraftToBukkit).collect(Collectors.toSet())); } @Override public Set getBarterList() { - return Collections.unmodifiableSet(this.getHandle().allowedBarterItems.stream().map(CraftItemType::minecraftToBukkit).collect(Collectors.toSet())); + return Collections.unmodifiableSet(getHandle().allowedBarterItems.stream().map(CraftItemType::minecraftToBukkit).collect(Collectors.toSet())); } @Override public Inventory getInventory() { - return new CraftInventory(this.getHandle().inventory); + return new CraftInventory(getHandle().inventory); } @Override - public net.minecraft.world.entity.monster.piglin.Piglin getHandle() { - return (net.minecraft.world.entity.monster.piglin.Piglin) super.getHandle(); + public EntityPiglin getHandle() { + return (EntityPiglin) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinAbstract.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinAbstract.java index e7957d60..ca64b9f4 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinAbstract.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinAbstract.java @@ -1,65 +1,65 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.monster.piglin.AbstractPiglin; +import net.minecraft.world.entity.monster.piglin.EntityPiglinAbstract; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.PiglinAbstract; public class CraftPiglinAbstract extends CraftMonster implements PiglinAbstract { - public CraftPiglinAbstract(CraftServer server, AbstractPiglin entity) { + public CraftPiglinAbstract(CraftServer server, EntityPiglinAbstract entity) { super(server, entity); } @Override public boolean isImmuneToZombification() { - return this.getHandle().isImmuneToZombification(); + return getHandle().isImmuneToZombification(); } @Override public void setImmuneToZombification(boolean flag) { - this.getHandle().setImmuneToZombification(flag); + getHandle().setImmuneToZombification(flag); } @Override public int getConversionTime() { - Preconditions.checkState(this.isConverting(), "Entity not converting"); - return this.getHandle().timeInOverworld; + Preconditions.checkState(isConverting(), "Entity not converting"); + return getHandle().timeInOverworld; } @Override public void setConversionTime(int time) { if (time < 0) { - this.getHandle().timeInOverworld = -1; - this.getHandle().setImmuneToZombification(false); + getHandle().timeInOverworld = -1; + getHandle().setImmuneToZombification(false); } else { - this.getHandle().timeInOverworld = time; + getHandle().timeInOverworld = time; } } @Override public boolean isConverting() { - return this.getHandle().isConverting(); + return getHandle().isConverting(); } @Override public boolean isBaby() { - return this.getHandle().isBaby(); + return getHandle().isBaby(); } @Override public void setBaby(boolean flag) { - this.getHandle().setBaby(flag); + getHandle().setBaby(flag); } @Override public int getAge() { - return this.getHandle().isBaby() ? -1 : 0; + return getHandle().isBaby() ? -1 : 0; } @Override public void setAge(int i) { - this.getHandle().setBaby(i < 0); + getHandle().setBaby(i < 0); } @Override @@ -73,17 +73,17 @@ public boolean getAgeLock() { @Override public void setBaby() { - this.getHandle().setBaby(true); + getHandle().setBaby(true); } @Override public void setAdult() { - this.getHandle().setBaby(false); + getHandle().setBaby(false); } @Override public boolean isAdult() { - return !this.getHandle().isBaby(); + return !getHandle().isBaby(); } @Override @@ -96,7 +96,7 @@ public void setBreed(boolean b) { } @Override - public AbstractPiglin getHandle() { - return (AbstractPiglin) super.getHandle(); + public EntityPiglinAbstract getHandle() { + return (EntityPiglinAbstract) super.getHandle(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinBrute.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinBrute.java index be874dc9..db41b100 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinBrute.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPiglinBrute.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.piglin.EntityPiglinBrute; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.PiglinBrute; public class CraftPiglinBrute extends CraftPiglinAbstract implements PiglinBrute { - public CraftPiglinBrute(CraftServer server, net.minecraft.world.entity.monster.piglin.PiglinBrute entity) { + public CraftPiglinBrute(CraftServer server, EntityPiglinBrute entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.piglin.PiglinBrute getHandle() { - return (net.minecraft.world.entity.monster.piglin.PiglinBrute) super.getHandle(); + public EntityPiglinBrute getHandle() { + return (EntityPiglinBrute) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java index 441a0740..be108be9 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityPillager; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.entity.Pillager; @@ -7,13 +8,13 @@ public class CraftPillager extends CraftIllager implements Pillager { - public CraftPillager(CraftServer server, net.minecraft.world.entity.monster.Pillager entity) { + public CraftPillager(CraftServer server, EntityPillager entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Pillager getHandle() { - return (net.minecraft.world.entity.monster.Pillager) super.getHandle(); + public EntityPillager getHandle() { + return (EntityPillager) super.getHandle(); } @Override @@ -23,6 +24,6 @@ public String toString() { @Override public Inventory getInventory() { - return new CraftInventory(this.getHandle().getInventory()); + return new CraftInventory(getHandle().inventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java index 3f5c8326..f1ffe7bb 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java @@ -3,7 +3,6 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.io.BaseEncoding; -import com.mohistmc.youer.api.color.ColorsAPI; import com.mojang.authlib.GameProfile; import com.mojang.datafixers.util.Pair; import io.netty.buffer.Unpooled; @@ -35,14 +34,15 @@ import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.stream.Collectors; import javax.annotation.Nullable; import net.minecraft.advancements.AdvancementProgress; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; -import net.minecraft.core.SectionPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.ConnectionProtocol; -import net.minecraft.network.chat.Component; +import net.minecraft.core.SectionPosition; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.EnumProtocol; +import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.network.chat.PlayerChatMessage; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; @@ -54,68 +54,71 @@ import net.minecraft.network.protocol.common.custom.DiscardedPayload; import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; import net.minecraft.network.protocol.cookie.ServerboundCookieResponsePacket; -import net.minecraft.network.protocol.game.ClientboundBlockDestructionPacket; -import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; -import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket; import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket; -import net.minecraft.network.protocol.game.ClientboundGameEventPacket; import net.minecraft.network.protocol.game.ClientboundHurtAnimationPacket; -import net.minecraft.network.protocol.game.ClientboundLevelEventPacket; -import net.minecraft.network.protocol.game.ClientboundLevelParticlesPacket; -import net.minecraft.network.protocol.game.ClientboundMapItemDataPacket; import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket; import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; -import net.minecraft.network.protocol.game.ClientboundSectionBlocksUpdatePacket; import net.minecraft.network.protocol.game.ClientboundSetBorderCenterPacket; import net.minecraft.network.protocol.game.ClientboundSetBorderLerpSizePacket; import net.minecraft.network.protocol.game.ClientboundSetBorderSizePacket; import net.minecraft.network.protocol.game.ClientboundSetBorderWarningDelayPacket; import net.minecraft.network.protocol.game.ClientboundSetBorderWarningDistancePacket; -import net.minecraft.network.protocol.game.ClientboundSetDefaultSpawnPositionPacket; -import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; -import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket; -import net.minecraft.network.protocol.game.ClientboundSetHealthPacket; import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket; import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket; import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket; -import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; -import net.minecraft.network.protocol.game.ClientboundSoundPacket; -import net.minecraft.network.protocol.game.ClientboundStopSoundPacket; -import net.minecraft.network.protocol.game.ClientboundTabListPacket; -import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; -import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.PlayerAdvancements; -import net.minecraft.server.level.ChunkMap; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.server.players.UserWhiteListEntry; -import net.minecraft.sounds.SoundEvent; +import net.minecraft.network.protocol.game.PacketPlayOutBlockBreakAnimation; +import net.minecraft.network.protocol.game.PacketPlayOutBlockChange; +import net.minecraft.network.protocol.game.PacketPlayOutEntityEffect; +import net.minecraft.network.protocol.game.PacketPlayOutEntityEquipment; +import net.minecraft.network.protocol.game.PacketPlayOutEntitySound; +import net.minecraft.network.protocol.game.PacketPlayOutExperience; +import net.minecraft.network.protocol.game.PacketPlayOutGameStateChange; +import net.minecraft.network.protocol.game.PacketPlayOutMap; +import net.minecraft.network.protocol.game.PacketPlayOutMultiBlockChange; +import net.minecraft.network.protocol.game.PacketPlayOutNamedSoundEffect; +import net.minecraft.network.protocol.game.PacketPlayOutPlayerListHeaderFooter; +import net.minecraft.network.protocol.game.PacketPlayOutRemoveEntityEffect; +import net.minecraft.network.protocol.game.PacketPlayOutSpawnPosition; +import net.minecraft.network.protocol.game.PacketPlayOutStopSound; +import net.minecraft.network.protocol.game.PacketPlayOutTileEntityData; +import net.minecraft.network.protocol.game.PacketPlayOutUpdateAttributes; +import net.minecraft.network.protocol.game.PacketPlayOutUpdateHealth; +import net.minecraft.network.protocol.game.PacketPlayOutWorldEvent; +import net.minecraft.network.protocol.game.PacketPlayOutWorldParticles; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.server.AdvancementDataPlayer; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.server.level.PlayerChunkMap; +import net.minecraft.server.level.WorldServer; +import net.minecraft.server.network.PlayerConnection; +import net.minecraft.server.players.WhiteListEntry; +import net.minecraft.sounds.SoundEffect; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.ai.attributes.AttributeInstance; -import net.minecraft.world.entity.ai.attributes.AttributeMap; -import net.minecraft.world.entity.ai.attributes.Attributes; -import net.minecraft.world.food.FoodData; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.level.GameType; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.EnumItemSlot; +import net.minecraft.world.entity.ai.attributes.AttributeMapBase; +import net.minecraft.world.entity.ai.attributes.AttributeModifiable; +import net.minecraft.world.entity.ai.attributes.GenericAttributes; +import net.minecraft.world.food.FoodMetaData; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.item.EnumColor; +import net.minecraft.world.level.EnumGamemode; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.SignBlockEntity; import net.minecraft.world.level.block.entity.SignText; -import net.minecraft.world.level.border.BorderChangeListener; -import net.minecraft.world.level.saveddata.maps.MapDecoration; +import net.minecraft.world.level.block.entity.TileEntitySign; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.border.IWorldBorderListener; +import net.minecraft.world.level.saveddata.maps.MapIcon; import net.minecraft.world.level.saveddata.maps.MapId; -import net.minecraft.world.level.saveddata.maps.MapItemSavedData; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.level.saveddata.maps.WorldMap; import org.bukkit.BanEntry; import org.bukkit.BanList; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.Effect; import org.bukkit.GameMode; +import org.bukkit.Input; import org.bukkit.Instrument; import org.bukkit.Location; import org.bukkit.Material; @@ -123,7 +126,6 @@ import org.bukkit.Note; import org.bukkit.OfflinePlayer; import org.bukkit.Particle; -import org.bukkit.Server; import org.bukkit.ServerLinks; import org.bukkit.Sound; import org.bukkit.Statistic; @@ -143,6 +145,7 @@ import org.bukkit.conversations.ManuallyAbandonedConversationCanceller; import org.bukkit.craftbukkit.CraftEffect; import org.bukkit.craftbukkit.CraftEquipmentSlot; +import org.bukkit.craftbukkit.CraftInput; import org.bukkit.craftbukkit.CraftOfflinePlayer; import org.bukkit.craftbukkit.CraftParticle; import org.bukkit.craftbukkit.CraftServer; @@ -160,6 +163,7 @@ import org.bukkit.craftbukkit.conversations.ConversationTracker; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.inventory.CraftRecipe; import org.bukkit.craftbukkit.map.CraftMapCursor; import org.bukkit.craftbukkit.map.CraftMapView; import org.bukkit.craftbukkit.map.RenderData; @@ -171,6 +175,7 @@ import org.bukkit.craftbukkit.util.CraftLocation; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.craftbukkit.util.CraftNamespacedKey; +import org.bukkit.entity.EnderPearl; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; @@ -195,8 +200,6 @@ import org.bukkit.scoreboard.Scoreboard; import org.jetbrains.annotations.NotNull; -import net.md_5.bungee.api.chat.BaseComponent; // Spigot - @DelegateDeserialization(CraftOfflinePlayer.class) public class CraftPlayer extends CraftHumanEntity implements Player { private long firstPlayed = 0; @@ -211,57 +214,57 @@ public class CraftPlayer extends CraftHumanEntity implements Player { private boolean scaledHealth = false; private double healthScale = 20; private CraftWorldBorder clientWorldBorder = null; - private BorderChangeListener clientWorldBorderListener = this.createWorldBorderListener(); + private IWorldBorderListener clientWorldBorderListener = createWorldBorderListener(); - public CraftPlayer(CraftServer server, ServerPlayer entity) { + public CraftPlayer(CraftServer server, EntityPlayer entity) { super(server, entity); - this.firstPlayed = System.currentTimeMillis(); + firstPlayed = System.currentTimeMillis(); } public GameProfile getProfile() { - return this.getHandle().getGameProfile(); + return getHandle().getGameProfile(); } @Override public void remove() { // Will lead to an inconsistent player state if we remove the player as any other entity. - throw new UnsupportedOperationException(String.format("Cannot remove player %s, use Player#kickPlayer(String) instead.", this.getName())); + throw new UnsupportedOperationException(String.format("Cannot remove player %s, use Player#kickPlayer(String) instead.", getName())); } @Override public boolean isOp() { - return this.server.getHandle().isOp(this.getProfile()); + return server.getHandle().isOp(getProfile()); } @Override public void setOp(boolean value) { - if (value == this.isOp()) return; + if (value == isOp()) return; if (value) { - this.server.getHandle().op(this.getProfile()); + server.getHandle().op(getProfile()); } else { - this.server.getHandle().deop(this.getProfile()); + server.getHandle().deop(getProfile()); } - this.perm.recalculatePermissions(); + perm.recalculatePermissions(); } @Override public boolean isOnline() { - return this.server.getPlayer(this.getUniqueId()) != null; + return server.getPlayer(getUniqueId()) != null; } @Override public PlayerProfile getPlayerProfile() { - return new CraftPlayerProfile(this.getProfile()); + return new CraftPlayerProfile(getProfile()); } @Override public InetSocketAddress getAddress() { - if (this.getHandle().connection.protocol() == null) return null; + if (getHandle().connection.protocol() == null) return null; - SocketAddress addr = this.getHandle().connection.getRemoteAddress(); + SocketAddress addr = getHandle().connection.getRemoteAddress(); if (addr instanceof InetSocketAddress) { return (InetSocketAddress) addr; } else { @@ -273,27 +276,27 @@ public interface TransferCookieConnection { boolean isTransferred(); - ConnectionProtocol getProtocol(); + EnumProtocol getProtocol(); void sendPacket(Packet packet); - void kickPlayer(Component reason); + void kickPlayer(IChatBaseComponent reason); } - public record CookieFuture(ResourceLocation key, CompletableFuture future) { + public record CookieFuture(MinecraftKey key, CompletableFuture future) { } private final Queue requestedCookies = new LinkedList<>(); public boolean isAwaitingCookies() { - return !this.requestedCookies.isEmpty(); + return !requestedCookies.isEmpty(); } public boolean handleCookieResponse(ServerboundCookieResponsePacket response) { - CookieFuture future = this.requestedCookies.peek(); + CookieFuture future = requestedCookies.peek(); if (future != null) { if (future.key.equals(response.key())) { - Preconditions.checkState(future == this.requestedCookies.poll(), "requestedCookies queue mismatch"); + Preconditions.checkState(future == requestedCookies.poll(), "requestedCookies queue mismatch"); future.future().complete(response.payload()); return true; @@ -305,7 +308,7 @@ public boolean handleCookieResponse(ServerboundCookieResponsePacket response) { @Override public boolean isTransferred() { - return this.getHandle().transferCookieConnection.isTransferred(); + return getHandle().transferCookieConnection.isTransferred(); } @Override @@ -313,10 +316,10 @@ public CompletableFuture retrieveCookie(NamespacedKey key) { Preconditions.checkArgument(key != null, "Cookie key cannot be null"); CompletableFuture future = new CompletableFuture<>(); - ResourceLocation nms = CraftNamespacedKey.toMinecraft(key); - this.requestedCookies.add(new CookieFuture(nms, future)); + MinecraftKey nms = CraftNamespacedKey.toMinecraft(key); + requestedCookies.add(new CookieFuture(nms, future)); - this.getHandle().transferCookieConnection.sendPacket(new ClientboundCookieRequestPacket(nms)); + getHandle().transferCookieConnection.sendPacket(new ClientboundCookieRequestPacket(nms)); return future; } @@ -326,17 +329,17 @@ public void storeCookie(NamespacedKey key, byte[] value) { Preconditions.checkArgument(key != null, "Cookie key cannot be null"); Preconditions.checkArgument(value != null, "Cookie value cannot be null"); Preconditions.checkArgument(value.length <= 5120, "Cookie value too large, must be smaller than 5120 bytes"); - Preconditions.checkState(this.getHandle().transferCookieConnection.getProtocol() == ConnectionProtocol.CONFIGURATION || this.getHandle().transferCookieConnection.getProtocol() == ConnectionProtocol.PLAY, "Can only store cookie in CONFIGURATION or PLAY protocol."); + Preconditions.checkState(getHandle().transferCookieConnection.getProtocol() == EnumProtocol.CONFIGURATION || getHandle().transferCookieConnection.getProtocol() == EnumProtocol.PLAY, "Can only store cookie in CONFIGURATION or PLAY protocol."); - this.getHandle().transferCookieConnection.sendPacket(new ClientboundStoreCookiePacket(CraftNamespacedKey.toMinecraft(key), value)); + getHandle().transferCookieConnection.sendPacket(new ClientboundStoreCookiePacket(CraftNamespacedKey.toMinecraft(key), value)); } @Override public void transfer(String host, int port) { Preconditions.checkArgument(host != null, "Host cannot be null"); - Preconditions.checkState(this.getHandle().transferCookieConnection.getProtocol() == ConnectionProtocol.CONFIGURATION || this.getHandle().transferCookieConnection.getProtocol() == ConnectionProtocol.PLAY, "Can only transfer in CONFIGURATION or PLAY protocol."); + Preconditions.checkState(getHandle().transferCookieConnection.getProtocol() == EnumProtocol.CONFIGURATION || getHandle().transferCookieConnection.getProtocol() == EnumProtocol.PLAY, "Can only transfer in CONFIGURATION or PLAY protocol."); - this.getHandle().transferCookieConnection.sendPacket(new ClientboundTransferPacket(host, port)); + getHandle().transferCookieConnection.sendPacket(new ClientboundTransferPacket(host, port)); } @Override @@ -344,7 +347,7 @@ public double getEyeHeight(boolean ignorePose) { if (ignorePose) { return 1.62D; } else { - return this.getEyeHeight(); + return getEyeHeight(); } } @@ -357,16 +360,16 @@ public void sendRawMessage(String message) { public void sendRawMessage(UUID sender, String message) { Preconditions.checkArgument(message != null, "message cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - for (Component component : CraftChatMessage.fromString(ColorsAPI.of(message))) { - this.getHandle().sendSystemMessage(component); + for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { + getHandle().sendSystemMessage(component); } } @Override public void sendMessage(String message) { - if (!this.conversationTracker.isConversingModaly()) { + if (!conversationTracker.isConversingModaly()) { this.sendRawMessage(message); } } @@ -374,13 +377,13 @@ public void sendMessage(String message) { @Override public void sendMessage(String... messages) { for (String message : messages) { - this.sendMessage(message); + sendMessage(message); } } @Override public void sendMessage(UUID sender, String message) { - if (!this.conversationTracker.isConversingModaly()) { + if (!conversationTracker.isConversingModaly()) { this.sendRawMessage(sender, message); } } @@ -388,75 +391,87 @@ public void sendMessage(UUID sender, String message) { @Override public void sendMessage(UUID sender, String... messages) { for (String message : messages) { - this.sendMessage(sender, message); + sendMessage(sender, message); } } @Override public String getDisplayName() { - return this.getHandle().displayName; + return getHandle().displayName; } @Override public void setDisplayName(final String name) { - this.getHandle().displayName = name == null ? this.getName() : name; + getHandle().displayName = name == null ? getName() : name; } @Override public String getPlayerListName() { - return this.getHandle().listName == null ? this.getName() : CraftChatMessage.fromComponent(this.getHandle().listName); + return getHandle().listName == null ? getName() : CraftChatMessage.fromComponent(getHandle().listName); } @Override public void setPlayerListName(String name) { if (name == null) { - name = this.getName(); + name = getName(); } - this.getHandle().listName = name.equals(this.getName()) ? null : CraftChatMessage.fromStringOrNull(name); - for (ServerPlayer player : (List) this.server.getHandle().players) { + getHandle().listName = name.equals(getName()) ? null : CraftChatMessage.fromStringOrNull(name); + for (EntityPlayer player : (List) server.getHandle().players) { if (player.getBukkitEntity().canSee(this)) { - player.connection.send(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, this.getHandle())); + player.connection.send(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.a.UPDATE_DISPLAY_NAME, getHandle())); } } } - private Component playerListHeader; - private Component playerListFooter; + @Override + public int getPlayerListOrder() { + return getHandle().listOrder; + } + + @Override + public void setPlayerListOrder(int order) { + Preconditions.checkArgument(order >= 0, "order cannot be negative"); + + getHandle().listOrder = order; + } + + private IChatBaseComponent playerListHeader; + private IChatBaseComponent playerListFooter; @Override public String getPlayerListHeader() { - return (this.playerListHeader == null) ? null : CraftChatMessage.fromComponent(this.playerListHeader); + return (playerListHeader == null) ? null : CraftChatMessage.fromComponent(playerListHeader); } @Override public String getPlayerListFooter() { - return (this.playerListFooter == null) ? null : CraftChatMessage.fromComponent(this.playerListFooter); + return (playerListFooter == null) ? null : CraftChatMessage.fromComponent(playerListFooter); } @Override public void setPlayerListHeader(String header) { this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true); - this.updatePlayerListHeaderFooter(); + updatePlayerListHeaderFooter(); } @Override public void setPlayerListFooter(String footer) { this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true); - this.updatePlayerListHeaderFooter(); + updatePlayerListHeaderFooter(); } @Override public void setPlayerListHeaderFooter(String header, String footer) { this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true); this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true); - this.updatePlayerListHeaderFooter(); + updatePlayerListHeaderFooter(); } private void updatePlayerListHeaderFooter() { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - ClientboundTabListPacket packet = new ClientboundTabListPacket((this.playerListHeader == null) ? Component.empty() : this.playerListHeader, (this.playerListFooter == null) ? Component.empty() : this.playerListFooter); - this.getHandle().connection.send(packet); + PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter((this.playerListHeader == null) ? IChatBaseComponent.empty() : this.playerListHeader, (this.playerListFooter == null) ? IChatBaseComponent.empty() : this.playerListFooter); + getHandle().connection.send(packet); } @Override @@ -488,35 +503,35 @@ public void kickPlayer(String message) { public void setCompassTarget(Location loc) { Preconditions.checkArgument(loc != null, "Location cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; // Do not directly assign here, from the packethandler we'll assign it. - this.getHandle().connection.send(new ClientboundSetDefaultSpawnPositionPacket(CraftLocation.toBlockPosition(loc), loc.getYaw())); + getHandle().connection.send(new PacketPlayOutSpawnPosition(CraftLocation.toBlockPos(loc), loc.getYaw())); } @Override public Location getCompassTarget() { - return this.getHandle().compassTarget; + return getHandle().compassTarget; } @Override public void chat(String msg) { Preconditions.checkArgument(msg != null, "msg cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().connection.chat(msg, PlayerChatMessage.system(msg), false); + getHandle().connection.chat(msg, PlayerChatMessage.system(msg), false); } @Override public boolean performCommand(String command) { Preconditions.checkArgument(command != null, "command cannot be null"); - return this.server.dispatchCommand(this, command); + return server.dispatchCommand(this, command); } @Override public void playNote(Location loc, byte instrument, byte note) { - this.playNote(loc, Instrument.getByType(instrument), new Note(note)); + playNote(loc, Instrument.getByType(instrument), new Note(note)); } @Override @@ -525,138 +540,138 @@ public void playNote(Location loc, Instrument instrument, Note note) { Preconditions.checkArgument(instrument != null, "Instrument cannot be null"); Preconditions.checkArgument(note != null, "Note cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; Sound instrumentSound = instrument.getSound(); if (instrumentSound == null) return; float pitch = note.getPitch(); - this.getHandle().connection.send(new ClientboundSoundPacket(CraftSound.bukkitToMinecraftHolder(instrumentSound), net.minecraft.sounds.SoundSource.RECORDS, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), 3.0f, pitch, this.getHandle().getRandom().nextLong())); + getHandle().connection.send(new PacketPlayOutNamedSoundEffect(CraftSound.bukkitToMinecraftHolder(instrumentSound), net.minecraft.sounds.SoundCategory.RECORDS, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), 3.0f, pitch, getHandle().getRandom().nextLong())); } @Override public void playSound(Location loc, Sound sound, float volume, float pitch) { - this.playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(Location loc, String sound, float volume, float pitch) { - this.playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(loc, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(loc, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(loc, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(loc, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch, long seed) { - if (loc == null || sound == null || category == null || this.getHandle().connection == null) return; + if (loc == null || sound == null || category == null || getHandle().connection == null) return; - this.playSound0(loc, CraftSound.bukkitToMinecraftHolder(sound), net.minecraft.sounds.SoundSource.valueOf(category.name()), volume, pitch, seed); + playSound0(loc, CraftSound.bukkitToMinecraftHolder(sound), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch, seed); } @Override public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch, long seed) { - if (loc == null || sound == null || category == null || this.getHandle().connection == null) return; + if (loc == null || sound == null || category == null || getHandle().connection == null) return; - this.playSound0(loc, Holder.direct(SoundEvent.createVariableRangeEvent(ResourceLocation.parse(sound))), net.minecraft.sounds.SoundSource.valueOf(category.name()), volume, pitch, seed); + playSound0(loc, Holder.direct(SoundEffect.createVariableRangeEvent(MinecraftKey.parse(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch, seed); } - private void playSound0(Location loc, Holder soundEffectHolder, net.minecraft.sounds.SoundSource categoryNMS, float volume, float pitch, long seed) { + private void playSound0(Location loc, Holder soundEffectHolder, net.minecraft.sounds.SoundCategory categoryNMS, float volume, float pitch, long seed) { Preconditions.checkArgument(loc != null, "Location cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - ClientboundSoundPacket packet = new ClientboundSoundPacket(soundEffectHolder, categoryNMS, loc.getX(), loc.getY(), loc.getZ(), volume, pitch, seed); - this.getHandle().connection.send(packet); + PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(soundEffectHolder, categoryNMS, loc.getX(), loc.getY(), loc.getZ(), volume, pitch, seed); + getHandle().connection.send(packet); } @Override public void playSound(org.bukkit.entity.Entity entity, Sound sound, float volume, float pitch) { - this.playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(org.bukkit.entity.Entity entity, String sound, float volume, float pitch) { - this.playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); + playSound(entity, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); } @Override public void playSound(org.bukkit.entity.Entity entity, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(entity, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(entity, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override public void playSound(org.bukkit.entity.Entity entity, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - this.playSound(entity, sound, category, volume, pitch, this.getHandle().random.nextLong()); + playSound(entity, sound, category, volume, pitch, getHandle().random.nextLong()); } @Override public void playSound(org.bukkit.entity.Entity entity, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch, long seed) { - if (!(entity instanceof CraftEntity craftEntity) || sound == null || category == null || this.getHandle().connection == null) return; + if (!(entity instanceof CraftEntity craftEntity) || sound == null || category == null || getHandle().connection == null) return; - this.playSound0(entity, CraftSound.bukkitToMinecraftHolder(sound), net.minecraft.sounds.SoundSource.valueOf(category.name()), volume, pitch, seed); + playSound0(entity, CraftSound.bukkitToMinecraftHolder(sound), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch, seed); } @Override public void playSound(org.bukkit.entity.Entity entity, String sound, org.bukkit.SoundCategory category, float volume, float pitch, long seed) { - if (!(entity instanceof CraftEntity craftEntity) || sound == null || category == null || this.getHandle().connection == null) return; + if (!(entity instanceof CraftEntity craftEntity) || sound == null || category == null || getHandle().connection == null) return; - this.playSound0(entity, Holder.direct(SoundEvent.createVariableRangeEvent(ResourceLocation.parse(sound))), net.minecraft.sounds.SoundSource.valueOf(category.name()), volume, pitch, seed); + playSound0(entity, Holder.direct(SoundEffect.createVariableRangeEvent(MinecraftKey.parse(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch, seed); } - private void playSound0(org.bukkit.entity.Entity entity, Holder soundEffectHolder, net.minecraft.sounds.SoundSource categoryNMS, float volume, float pitch, long seed) { + private void playSound0(org.bukkit.entity.Entity entity, Holder soundEffectHolder, net.minecraft.sounds.SoundCategory categoryNMS, float volume, float pitch, long seed) { Preconditions.checkArgument(entity != null, "Entity cannot be null"); Preconditions.checkArgument(soundEffectHolder != null, "Holder of SoundEffect cannot be null"); Preconditions.checkArgument(categoryNMS != null, "SoundCategory cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; if (!(entity instanceof CraftEntity craftEntity)) return; - ClientboundSoundEntityPacket packet = new ClientboundSoundEntityPacket(soundEffectHolder, categoryNMS, craftEntity.getHandle(), volume, pitch, seed); - this.getHandle().connection.send(packet); + PacketPlayOutEntitySound packet = new PacketPlayOutEntitySound(soundEffectHolder, categoryNMS, craftEntity.getHandle(), volume, pitch, seed); + getHandle().connection.send(packet); } @Override public void stopSound(Sound sound) { - this.stopSound(sound, null); + stopSound(sound, null); } @Override public void stopSound(String sound) { - this.stopSound(sound, null); + stopSound(sound, null); } @Override public void stopSound(Sound sound, org.bukkit.SoundCategory category) { - this.stopSound(sound.getKey().getKey(), category); + stopSound(sound.getKey().getKey(), category); } @Override public void stopSound(String sound, org.bukkit.SoundCategory category) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().connection.send(new ClientboundStopSoundPacket(ResourceLocation.parse(sound), category == null ? net.minecraft.sounds.SoundSource.MASTER : net.minecraft.sounds.SoundSource.valueOf(category.name()))); + getHandle().connection.send(new PacketPlayOutStopSound(MinecraftKey.parse(sound), category == null ? net.minecraft.sounds.SoundCategory.MASTER : net.minecraft.sounds.SoundCategory.valueOf(category.name()))); } @Override public void stopSound(org.bukkit.SoundCategory category) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().connection.send(new ClientboundStopSoundPacket(null, net.minecraft.sounds.SoundSource.valueOf(category.name()))); + getHandle().connection.send(new PacketPlayOutStopSound(null, net.minecraft.sounds.SoundCategory.valueOf(category.name()))); } @Override public void stopAllSounds() { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().connection.send(new ClientboundStopSoundPacket(null, null)); + getHandle().connection.send(new PacketPlayOutStopSound(null, null)); } @Override @@ -664,11 +679,11 @@ public void playEffect(Location loc, Effect effect, int data) { Preconditions.checkArgument(effect != null, "Effect cannot be null"); Preconditions.checkArgument(loc != null, "Location cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; int packetData = effect.getId(); - ClientboundLevelEventPacket packet = new ClientboundLevelEventPacket(packetData, CraftLocation.toBlockPosition(loc), data, false); - this.getHandle().connection.send(packet); + PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, CraftLocation.toBlockPos(loc), data, false); + getHandle().connection.send(packet); } @Override @@ -683,61 +698,61 @@ public void playEffect(Location loc, Effect effect, T data) { } int datavalue = CraftEffect.getDataValue(effect, data); - this.playEffect(loc, effect, datavalue); + playEffect(loc, effect, datavalue); } @Override public boolean breakBlock(Block block) { Preconditions.checkArgument(block != null, "Block cannot be null"); - Preconditions.checkArgument(block.getWorld().equals(this.getWorld()), "Cannot break blocks across worlds"); + Preconditions.checkArgument(block.getWorld().equals(getWorld()), "Cannot break blocks across worlds"); - return this.getHandle().gameMode.destroyBlock(new BlockPos(block.getX(), block.getY(), block.getZ())); + return getHandle().gameMode.destroyBlock(new BlockPos(block.getX(), block.getY(), block.getZ())); } @Override public void sendBlockChange(Location loc, Material material, byte data) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - ClientboundBlockUpdatePacket packet = new ClientboundBlockUpdatePacket(CraftLocation.toBlockPosition(loc), CraftMagicNumbers.getBlock(material, data)); - this.getHandle().connection.send(packet); + PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(CraftLocation.toBlockPos(loc), CraftMagicNumbers.getBlock(material, data)); + getHandle().connection.send(packet); } @Override public void sendBlockChange(Location loc, BlockData block) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - ClientboundBlockUpdatePacket packet = new ClientboundBlockUpdatePacket(CraftLocation.toBlockPosition(loc), ((CraftBlockData) block).getState()); - this.getHandle().connection.send(packet); + PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(CraftLocation.toBlockPos(loc), ((CraftBlockData) block).getState()); + getHandle().connection.send(packet); } @Override public void sendBlockChanges(Collection blocks) { Preconditions.checkArgument(blocks != null, "blocks must not be null"); - if (this.getHandle().connection == null || blocks.isEmpty()) { + if (getHandle().connection == null || blocks.isEmpty()) { return; } - Map changes = new HashMap<>(); + Map changes = new HashMap<>(); for (BlockState state : blocks) { CraftBlockState cstate = (CraftBlockState) state; BlockPos blockPosition = cstate.getPosition(); // The coordinates of the chunk section in which the block is located, aka chunk x, y, and z - SectionPos sectionPosition = SectionPos.of(blockPosition); + SectionPosition sectionPosition = SectionPosition.of(blockPosition); // Push the block change position and block data to the final change map ChunkSectionChanges sectionChanges = changes.computeIfAbsent(sectionPosition, (ignore) -> new ChunkSectionChanges()); - sectionChanges.positions().add(SectionPos.sectionRelativePos(blockPosition)); + sectionChanges.positions().add(SectionPosition.sectionRelativePos(blockPosition)); sectionChanges.blockData().add(cstate.getHandle()); } // Construct the packets using the data allocated above and send then to the players - for (Map.Entry entry : changes.entrySet()) { + for (Map.Entry entry : changes.entrySet()) { ChunkSectionChanges chunkChanges = entry.getValue(); - ClientboundSectionBlocksUpdatePacket packet = new ClientboundSectionBlocksUpdatePacket(entry.getKey(), chunkChanges.positions(), chunkChanges.blockData().toArray(net.minecraft.world.level.block.state.BlockState[]::new)); - this.getHandle().connection.send(packet); + PacketPlayOutMultiBlockChange packet = new PacketPlayOutMultiBlockChange(entry.getKey(), chunkChanges.positions(), chunkChanges.blockData().toArray(IBlockData[]::new)); + getHandle().connection.send(packet); } } @@ -746,7 +761,7 @@ public void sendBlockChanges(Collection blocks, boolean suppressLigh this.sendBlockChanges(blocks); } - private record ChunkSectionChanges(ShortSet positions, List blockData) { + private record ChunkSectionChanges(ShortSet positions, List blockData) { public ChunkSectionChanges() { this(new ShortArraySet(), new ArrayList<>()); @@ -755,7 +770,7 @@ public ChunkSectionChanges() { @Override public void sendBlockDamage(Location loc, float progress) { - this.sendBlockDamage(loc, progress, this.getEntityId()); + this.sendBlockDamage(loc, progress, getEntityId()); } @Override @@ -769,25 +784,25 @@ public void sendBlockDamage(Location loc, float progress, int sourceId) { Preconditions.checkArgument(loc != null, "loc must not be null"); Preconditions.checkArgument(progress >= 0.0 && progress <= 1.0, "progress must be between 0.0 and 1.0 (inclusive)"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; int stage = (int) (9 * progress); // There are 0 - 9 damage states if (progress == 0.0F) { stage = -1; // The protocol states that any other value will reset the damage, which this API promises } - ClientboundBlockDestructionPacket packet = new ClientboundBlockDestructionPacket(sourceId, CraftLocation.toBlockPosition(loc), stage); - this.getHandle().connection.send(packet); + PacketPlayOutBlockBreakAnimation packet = new PacketPlayOutBlockBreakAnimation(sourceId, CraftLocation.toBlockPos(loc), stage); + getHandle().connection.send(packet); } @Override public void sendSignChange(Location loc, String[] lines) { - this.sendSignChange(loc, lines, DyeColor.BLACK); + sendSignChange(loc, lines, DyeColor.BLACK); } @Override public void sendSignChange(Location loc, String[] lines, DyeColor dyeColor) { - this.sendSignChange(loc, lines, dyeColor, false); + sendSignChange(loc, lines, dyeColor, false); } @Override @@ -800,19 +815,19 @@ public void sendSignChange(Location loc, String[] lines, DyeColor dyeColor, bool } Preconditions.checkArgument(lines.length >= 4, "Must have at least 4 lines (%s)", lines.length); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - Component[] components = CraftSign.sanitizeLines(lines); - SignBlockEntity sign = new SignBlockEntity(CraftLocation.toBlockPosition(loc), Blocks.OAK_SIGN.defaultBlockState()); + IChatBaseComponent[] components = CraftSign.sanitizeLines(lines); + TileEntitySign sign = new TileEntitySign(CraftLocation.toBlockPos(loc), Blocks.OAK_SIGN.defaultBlockState()); SignText text = sign.getFrontText(); - text = text.setColor(net.minecraft.world.item.DyeColor.byId(dyeColor.getWoolData())); + text = text.setColor(EnumColor.byId(dyeColor.getWoolData())); text = text.setHasGlowingText(hasGlowingText); for (int i = 0; i < components.length; i++) { text = text.setMessage(i, components[i]); } sign.setText(text, true); - this.getHandle().connection.send(new ClientboundBlockEntityDataPacket(sign.getBlockPos(), sign.getType(), sign.getUpdateTag(this.getHandle().registryAccess()))); + getHandle().connection.send(new PacketPlayOutTileEntityData(sign.getBlockPos(), sign.getType(), sign.getUpdateTag(getHandle().registryAccess()))); } @Override @@ -820,10 +835,10 @@ public void sendBlockUpdate(@NotNull Location location, @NotNull TileState tileS Preconditions.checkArgument(location != null, "Location can not be null"); Preconditions.checkArgument(tileState != null, "TileState can not be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; CraftBlockEntityState craftState = ((CraftBlockEntityState) tileState); - this.getHandle().connection.send(craftState.getUpdatePacket(location)); + getHandle().connection.send(craftState.getUpdatePacket(location)); } @Override @@ -836,11 +851,11 @@ public void sendEquipmentChange(LivingEntity entity, Map> equipment = new ArrayList<>(items.size()); + List> equipment = new ArrayList<>(items.size()); for (Map.Entry entry : items.entrySet()) { EquipmentSlot slot = entry.getKey(); Preconditions.checkArgument(slot != null, "Cannot set null EquipmentSlot"); @@ -848,7 +863,7 @@ public void sendEquipmentChange(LivingEntity entity, Map(CraftEquipmentSlot.getNMS(slot), CraftItemStack.asNMSCopy(entry.getValue()))); } - this.getHandle().connection.send(new ClientboundSetEquipmentPacket(entity.getEntityId(), equipment)); + getHandle().connection.send(new PacketPlayOutEntityEquipment(entity.getEntityId(), equipment)); } @Override @@ -856,11 +871,11 @@ public void sendPotionEffectChange(LivingEntity entity, PotionEffect effect) { Preconditions.checkArgument(entity != null, "Entity cannot be null"); Preconditions.checkArgument(effect != null, "Effect cannot be null"); - if (this.getHandle().connection == null) { + if (getHandle().connection == null) { return; } - this.getHandle().connection.send(new ClientboundUpdateMobEffectPacket(entity.getEntityId(), CraftPotionUtil.fromBukkit(effect), true)); + getHandle().connection.send(new PacketPlayOutEntityEffect(entity.getEntityId(), CraftPotionUtil.fromBukkit(effect), true)); } @Override @@ -868,43 +883,43 @@ public void sendPotionEffectChangeRemove(LivingEntity entity, PotionEffectType t Preconditions.checkArgument(entity != null, "Entity cannot be null"); Preconditions.checkArgument(type != null, "Type cannot be null"); - if (this.getHandle().connection == null) { + if (getHandle().connection == null) { return; } - this.getHandle().connection.send(new ClientboundRemoveMobEffectPacket(entity.getEntityId(), CraftPotionEffectType.bukkitToMinecraftHolder(type))); + getHandle().connection.send(new PacketPlayOutRemoveEntityEffect(entity.getEntityId(), CraftPotionEffectType.bukkitToMinecraftHolder(type))); } @Override public WorldBorder getWorldBorder() { - return this.clientWorldBorder; + return clientWorldBorder; } @Override public void setWorldBorder(WorldBorder border) { CraftWorldBorder craftBorder = (CraftWorldBorder) border; - if (border != null && !craftBorder.isVirtual() && !craftBorder.getWorld().equals(this.getWorld())) { + if (border != null && !craftBorder.isVirtual() && !craftBorder.getWorld().equals(getWorld())) { throw new UnsupportedOperationException("Cannot set player world border to that of another world"); } // Nullify the old client-sided world border listeners so that calls to it will not affect this player - if (this.clientWorldBorder != null) { - this.clientWorldBorder.getHandle().removeListener(this.clientWorldBorderListener); + if (clientWorldBorder != null) { + this.clientWorldBorder.getHandle().removeListener(clientWorldBorderListener); } net.minecraft.world.level.border.WorldBorder newWorldBorder; if (craftBorder == null || !craftBorder.isVirtual()) { this.clientWorldBorder = null; - newWorldBorder = ((CraftWorldBorder) this.getWorld().getWorldBorder()).getHandle(); + newWorldBorder = ((CraftWorldBorder) getWorld().getWorldBorder()).getHandle(); } else { this.clientWorldBorder = craftBorder; - this.clientWorldBorder.getHandle().addListener(this.clientWorldBorderListener); - newWorldBorder = this.clientWorldBorder.getHandle(); + this.clientWorldBorder.getHandle().addListener(clientWorldBorderListener); + newWorldBorder = clientWorldBorder.getHandle(); } // Send all world border update packets to the player - ServerGamePacketListenerImpl connection = this.getHandle().connection; + PlayerConnection connection = getHandle().connection; connection.send(new ClientboundSetBorderSizePacket(newWorldBorder)); connection.send(new ClientboundSetBorderLerpSizePacket(newWorldBorder)); connection.send(new ClientboundSetBorderCenterPacket(newWorldBorder)); @@ -912,64 +927,64 @@ public void setWorldBorder(WorldBorder border) { connection.send(new ClientboundSetBorderWarningDistancePacket(newWorldBorder)); } - private BorderChangeListener createWorldBorderListener() { - return new BorderChangeListener() { + private IWorldBorderListener createWorldBorderListener() { + return new IWorldBorderListener() { @Override public void onBorderSizeSet(net.minecraft.world.level.border.WorldBorder border, double size) { - CraftPlayer.this.getHandle().connection.send(new ClientboundSetBorderSizePacket(border)); + getHandle().connection.send(new ClientboundSetBorderSizePacket(border)); } @Override - public void onBorderSizeLerping(net.minecraft.world.level.border.WorldBorder border, double fromSize, double toSize, long time) { - CraftPlayer.this.getHandle().connection.send(new ClientboundSetBorderLerpSizePacket(border)); + public void onBorderSizeLerping(net.minecraft.world.level.border.WorldBorder border, double size, double newSize, long time) { + getHandle().connection.send(new ClientboundSetBorderLerpSizePacket(border)); } @Override - public void onBorderCenterSet(net.minecraft.world.level.border.WorldBorder border, double centerX, double centerZ) { - CraftPlayer.this.getHandle().connection.send(new ClientboundSetBorderCenterPacket(border)); + public void onBorderCenterSet(net.minecraft.world.level.border.WorldBorder border, double x, double z) { + getHandle().connection.send(new ClientboundSetBorderCenterPacket(border)); } @Override public void onBorderSetWarningTime(net.minecraft.world.level.border.WorldBorder border, int warningTime) { - CraftPlayer.this.getHandle().connection.send(new ClientboundSetBorderWarningDelayPacket(border)); + getHandle().connection.send(new ClientboundSetBorderWarningDelayPacket(border)); } @Override - public void onBorderSetWarningBlocks(net.minecraft.world.level.border.WorldBorder border, int warningBlockDistance) { - CraftPlayer.this.getHandle().connection.send(new ClientboundSetBorderWarningDistancePacket(border)); + public void onBorderSetWarningBlocks(net.minecraft.world.level.border.WorldBorder border, int warningBlocks) { + getHandle().connection.send(new ClientboundSetBorderWarningDistancePacket(border)); } @Override - public void onBorderSetDamagePerBlock(net.minecraft.world.level.border.WorldBorder border, double damagePerBlock) {} // NO OP + public void onBorderSetDamagePerBlock(net.minecraft.world.level.border.WorldBorder border, double damage) {} // NO OP @Override - public void onBorderSetDamageSafeZOne(net.minecraft.world.level.border.WorldBorder border, double safeZoneRadius) {} // NO OP + public void onBorderSetDamageSafeZOne(net.minecraft.world.level.border.WorldBorder border, double blocks) {} // NO OP }; } public boolean hasClientWorldBorder() { - return this.clientWorldBorder != null; + return clientWorldBorder != null; } @Override public void sendMap(MapView map) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; RenderData data = ((CraftMapView) map).render(this); - Collection icons = new ArrayList(); + Collection icons = new ArrayList(); for (MapCursor cursor : data.cursors) { if (cursor.isVisible()) { - icons.add(new MapDecoration(CraftMapCursor.CraftType.bukkitToMinecraftHolder(cursor.getType()), cursor.getX(), cursor.getY(), cursor.getDirection(), CraftChatMessage.fromStringOrOptional(cursor.getCaption()))); + icons.add(new MapIcon(CraftMapCursor.CraftType.bukkitToMinecraftHolder(cursor.getType()), cursor.getX(), cursor.getY(), cursor.getDirection(), CraftChatMessage.fromStringOrOptional(cursor.getCaption()))); } } - ClientboundMapItemDataPacket packet = new ClientboundMapItemDataPacket(new MapId(map.getId()), map.getScale().getValue(), map.isLocked(), icons, new MapItemSavedData.MapPatch(0, 0, 128, 128, data.buffer)); - this.getHandle().connection.send(packet); + PacketPlayOutMap packet = new PacketPlayOutMap(new MapId(map.getId()), map.getScale().getValue(), map.isLocked(), icons, new WorldMap.c(0, 0, 128, 128, data.buffer)); + getHandle().connection.send(packet); } @Override public void sendHurtAnimation(float yaw) { - if (this.getHandle().connection == null) { + if (getHandle().connection == null) { return; } @@ -978,7 +993,7 @@ public void sendHurtAnimation(float yaw) { * This makes no sense. We'll add 90 to it so that 0 = front, clockwise from there. */ float actualYaw = yaw + 90; - this.getHandle().connection.send(new ClientboundHurtAnimationPacket(this.getEntityId(), actualYaw)); + getHandle().connection.send(new ClientboundHurtAnimationPacket(getEntityId(), actualYaw)); } @Override @@ -1008,10 +1023,10 @@ public void setCustomChatCompletions(Collection completions) { } private void sendCustomChatCompletionPacket(Collection completions, ClientboundCustomChatCompletionsPacket.Action action) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; ClientboundCustomChatCompletionsPacket packet = new ClientboundCustomChatCompletionsPacket(action, new ArrayList<>(completions)); - this.getHandle().connection.send(packet); + getHandle().connection.send(packet); } @Override @@ -1025,9 +1040,9 @@ public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cau Preconditions.checkArgument(location.getWorld() != null, "location.world"); location.checkFinite(); - ServerPlayer entity = this.getHandle(); + EntityPlayer entity = getHandle(); - if (this.getHealth() == 0 || entity.isRemoved()) { + if (getHealth() == 0 || entity.isRemoved()) { return false; } @@ -1045,7 +1060,7 @@ public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cau Location to = location; // Create & Call the Teleport Event. PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause); - this.server.getPluginManager().callEvent(event); + server.getPluginManager().callEvent(event); // Return False to inform the Plugin that the Teleport was unsuccessful/cancelled. if (event.isCancelled()) { @@ -1065,12 +1080,12 @@ public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cau // Grab the new To Location dependent on whether the event was cancelled. to = event.getTo(); // Grab the To and From World Handles. - ServerLevel fromWorld = ((CraftWorld) from.getWorld()).getHandle(); - ServerLevel toWorld = ((CraftWorld) to.getWorld()).getHandle(); + WorldServer fromWorld = ((CraftWorld) from.getWorld()).getHandle(); + WorldServer toWorld = ((CraftWorld) to.getWorld()).getHandle(); // Close any foreign inventory - if (this.getHandle().containerMenu != this.getHandle().inventoryMenu) { - this.getHandle().closeContainer(); + if (getHandle().containerMenu != getHandle().inventoryMenu) { + getHandle().closeContainer(); } // Check if the fromWorld and toWorld are the same. @@ -1079,73 +1094,73 @@ public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cau } else { entity.portalProcess = null; // SPIGOT-7785: there is no need to carry this over as it contains the old world/location and we might run into trouble if there is a portal in the same spot in both worlds // The respawn reason should never be used if the passed location is non null. - // this.server.getHandle().respawn(entity, true, Entity.RemovalReason.CHANGED_DIMENSION, null, to); // Mohist TODO + server.getHandle().respawn(entity, true, Entity.RemovalReason.CHANGED_DIMENSION, null, to); } return true; } @Override public void setSneaking(boolean sneak) { - this.getHandle().setShiftKeyDown(sneak); + getHandle().setShiftKeyDown(sneak); } @Override public boolean isSneaking() { - return this.getHandle().isShiftKeyDown(); + return getHandle().isShiftKeyDown(); } @Override public boolean isSprinting() { - return this.getHandle().isSprinting(); + return getHandle().isSprinting(); } @Override public void setSprinting(boolean sprinting) { - this.getHandle().setSprinting(sprinting); + getHandle().setSprinting(sprinting); } @Override public void loadData() { - this.server.getHandle().playerIo.load(this.getHandle()); + server.getHandle().playerIo.load(getHandle()); } @Override public void saveData() { - this.server.getHandle().playerIo.save(this.getHandle()); + server.getHandle().playerIo.save(getHandle()); } @Deprecated @Override public void updateInventory() { - this.getHandle().containerMenu.sendAllDataToRemote(); + getHandle().containerMenu.sendAllDataToRemote(); } @Override public void setSleepingIgnored(boolean isSleeping) { - this.getHandle().fauxSleeping = isSleeping; - ((CraftWorld) this.getWorld()).getHandle().updateSleepingPlayerList(); + getHandle().fauxSleeping = isSleeping; + ((CraftWorld) getWorld()).getHandle().updateSleepingPlayerList(); } @Override public boolean isSleepingIgnored() { - return this.getHandle().fauxSleeping; + return getHandle().fauxSleeping; } @Override public Location getBedSpawnLocation() { - return this.getRespawnLocation(); + return getRespawnLocation(); } @Override public Location getRespawnLocation() { - ServerLevel world = this.getHandle().server.getLevel(this.getHandle().getRespawnDimension()); - BlockPos bed = this.getHandle().getRespawnPosition(); + WorldServer world = getHandle().server.getLevel(getHandle().getRespawnDimension()); + BlockPos bed = getHandle().getRespawnPosition(); if (world != null && bed != null) { - Optional spawnLoc = ServerPlayer.findRespawnAndUseSpawnBlock(world, bed, this.getHandle().getRespawnAngle(), this.getHandle().isRespawnForced(), true); + Optional spawnLoc = EntityPlayer.findRespawnAndUseSpawnBlock(world, bed, getHandle().getRespawnAngle(), getHandle().isRespawnForced(), true); if (spawnLoc.isPresent()) { - ServerPlayer.RespawnPosAngle vec = spawnLoc.get(); - return CraftLocation.toBukkit(vec.position(), world.getWorld(), this.getHandle().getRespawnAngle(), 0); + EntityPlayer.RespawnPosAngle vec = spawnLoc.get(); + return CraftLocation.toBukkit(vec.position(), world.getWorld(), vec.yaw(), 0); } } return null; @@ -1153,193 +1168,203 @@ public Location getRespawnLocation() { @Override public void setBedSpawnLocation(Location location) { - this.setBedSpawnLocation(location, false); + setBedSpawnLocation(location, false); } @Override public void setRespawnLocation(Location location) { - this.setRespawnLocation(location, false); + setRespawnLocation(location, false); } @Override public void setBedSpawnLocation(Location location, boolean override) { - this.setRespawnLocation(location, override); + setRespawnLocation(location, override); } @Override public void setRespawnLocation(Location location, boolean override) { if (location == null) { - this.getHandle().setRespawnPosition(null, null, 0.0F, override, false, PlayerSpawnChangeEvent.Cause.PLUGIN); + getHandle().setRespawnPosition(null, null, 0.0F, override, false, PlayerSpawnChangeEvent.Cause.PLUGIN); } else { - this.getHandle().setRespawnPosition(((CraftWorld) location.getWorld()).getHandle().dimension(), CraftLocation.toBlockPosition(location), location.getYaw(), override, false, PlayerSpawnChangeEvent.Cause.PLUGIN); + getHandle().setRespawnPosition(((CraftWorld) location.getWorld()).getHandle().dimension(), CraftLocation.toBlockPos(location), location.getYaw(), override, false, PlayerSpawnChangeEvent.Cause.PLUGIN); } } + @Override + public Collection getEnderPearls() { + return getHandle().getEnderPearls().stream().map((e) -> (EnderPearl) e.getBukkitEntity()).collect(Collectors.toList()); + } + + @Override + public Input getCurrentInput() { + return new CraftInput(getHandle().getLastClientInput()); + } + @Override public Location getBedLocation() { - Preconditions.checkState(this.isSleeping(), "Not sleeping"); + Preconditions.checkState(isSleeping(), "Not sleeping"); - BlockPos bed = this.getHandle().getRespawnPosition(); - return CraftLocation.toBukkit(bed, this.getWorld()); + BlockPos bed = getHandle().getRespawnPosition(); + return CraftLocation.toBukkit(bed, getWorld()); } @Override public boolean hasDiscoveredRecipe(NamespacedKey recipe) { Preconditions.checkArgument(recipe != null, "recipe cannot be null"); - return this.getHandle().getRecipeBook().contains(CraftNamespacedKey.toMinecraft(recipe)); + return getHandle().getRecipeBook().contains(CraftRecipe.toMinecraft(recipe)); } @Override public Set getDiscoveredRecipes() { ImmutableSet.Builder bukkitRecipeKeys = ImmutableSet.builder(); - this.getHandle().getRecipeBook().known.forEach(key -> bukkitRecipeKeys.add(CraftNamespacedKey.fromMinecraft(key))); + getHandle().getRecipeBook().known.forEach(key -> bukkitRecipeKeys.add(CraftNamespacedKey.fromMinecraft(key.location()))); return bukkitRecipeKeys.build(); } @Override public void incrementStatistic(Statistic statistic) { - CraftStatistic.incrementStatistic(this.getHandle().getStats(), statistic, this.getHandle()); + CraftStatistic.incrementStatistic(getHandle().getStats(), statistic, getHandle()); } @Override public void decrementStatistic(Statistic statistic) { - CraftStatistic.decrementStatistic(this.getHandle().getStats(), statistic, this.getHandle()); + CraftStatistic.decrementStatistic(getHandle().getStats(), statistic, getHandle()); } @Override public int getStatistic(Statistic statistic) { - return CraftStatistic.getStatistic(this.getHandle().getStats(), statistic); + return CraftStatistic.getStatistic(getHandle().getStats(), statistic); } @Override public void incrementStatistic(Statistic statistic, int amount) { - CraftStatistic.incrementStatistic(this.getHandle().getStats(), statistic, amount, this.getHandle()); + CraftStatistic.incrementStatistic(getHandle().getStats(), statistic, amount, getHandle()); } @Override public void decrementStatistic(Statistic statistic, int amount) { - CraftStatistic.decrementStatistic(this.getHandle().getStats(), statistic, amount, this.getHandle()); + CraftStatistic.decrementStatistic(getHandle().getStats(), statistic, amount, getHandle()); } @Override public void setStatistic(Statistic statistic, int newValue) { - CraftStatistic.setStatistic(this.getHandle().getStats(), statistic, newValue, this.getHandle()); + CraftStatistic.setStatistic(getHandle().getStats(), statistic, newValue, getHandle()); } @Override public void incrementStatistic(Statistic statistic, Material material) { - CraftStatistic.incrementStatistic(this.getHandle().getStats(), statistic, material, this.getHandle()); + CraftStatistic.incrementStatistic(getHandle().getStats(), statistic, material, getHandle()); } @Override public void decrementStatistic(Statistic statistic, Material material) { - CraftStatistic.decrementStatistic(this.getHandle().getStats(), statistic, material, this.getHandle()); + CraftStatistic.decrementStatistic(getHandle().getStats(), statistic, material, getHandle()); } @Override public int getStatistic(Statistic statistic, Material material) { - return CraftStatistic.getStatistic(this.getHandle().getStats(), statistic, material); + return CraftStatistic.getStatistic(getHandle().getStats(), statistic, material); } @Override public void incrementStatistic(Statistic statistic, Material material, int amount) { - CraftStatistic.incrementStatistic(this.getHandle().getStats(), statistic, material, amount, this.getHandle()); + CraftStatistic.incrementStatistic(getHandle().getStats(), statistic, material, amount, getHandle()); } @Override public void decrementStatistic(Statistic statistic, Material material, int amount) { - CraftStatistic.decrementStatistic(this.getHandle().getStats(), statistic, material, amount, this.getHandle()); + CraftStatistic.decrementStatistic(getHandle().getStats(), statistic, material, amount, getHandle()); } @Override public void setStatistic(Statistic statistic, Material material, int newValue) { - CraftStatistic.setStatistic(this.getHandle().getStats(), statistic, material, newValue, this.getHandle()); + CraftStatistic.setStatistic(getHandle().getStats(), statistic, material, newValue, getHandle()); } @Override public void incrementStatistic(Statistic statistic, EntityType entityType) { - CraftStatistic.incrementStatistic(this.getHandle().getStats(), statistic, entityType, this.getHandle()); + CraftStatistic.incrementStatistic(getHandle().getStats(), statistic, entityType, getHandle()); } @Override public void decrementStatistic(Statistic statistic, EntityType entityType) { - CraftStatistic.decrementStatistic(this.getHandle().getStats(), statistic, entityType, this.getHandle()); + CraftStatistic.decrementStatistic(getHandle().getStats(), statistic, entityType, getHandle()); } @Override public int getStatistic(Statistic statistic, EntityType entityType) { - return CraftStatistic.getStatistic(this.getHandle().getStats(), statistic, entityType); + return CraftStatistic.getStatistic(getHandle().getStats(), statistic, entityType); } @Override public void incrementStatistic(Statistic statistic, EntityType entityType, int amount) { - CraftStatistic.incrementStatistic(this.getHandle().getStats(), statistic, entityType, amount, this.getHandle()); + CraftStatistic.incrementStatistic(getHandle().getStats(), statistic, entityType, amount, getHandle()); } @Override public void decrementStatistic(Statistic statistic, EntityType entityType, int amount) { - CraftStatistic.decrementStatistic(this.getHandle().getStats(), statistic, entityType, amount, this.getHandle()); + CraftStatistic.decrementStatistic(getHandle().getStats(), statistic, entityType, amount, getHandle()); } @Override public void setStatistic(Statistic statistic, EntityType entityType, int newValue) { - CraftStatistic.setStatistic(this.getHandle().getStats(), statistic, entityType, newValue, this.getHandle()); + CraftStatistic.setStatistic(getHandle().getStats(), statistic, entityType, newValue, getHandle()); } @Override public void setPlayerTime(long time, boolean relative) { - this.getHandle().timeOffset = time; - this.getHandle().relativeTime = relative; + getHandle().timeOffset = time; + getHandle().relativeTime = relative; } @Override public long getPlayerTimeOffset() { - return this.getHandle().timeOffset; + return getHandle().timeOffset; } @Override public long getPlayerTime() { - return this.getHandle().getPlayerTime(); + return getHandle().getPlayerTime(); } @Override public boolean isPlayerTimeRelative() { - return this.getHandle().relativeTime; + return getHandle().relativeTime; } @Override public void resetPlayerTime() { - this.setPlayerTime(0, true); + setPlayerTime(0, true); } @Override public void setPlayerWeather(WeatherType type) { - this.getHandle().setPlayerWeather(type, true); + getHandle().setPlayerWeather(type, true); } @Override public WeatherType getPlayerWeather() { - return this.getHandle().getPlayerWeather(); + return getHandle().getPlayerWeather(); } @Override public int getExpCooldown() { - return this.getHandle().takeXpDelay; + return getHandle().takeXpDelay; } @Override public void setExpCooldown(int ticks) { - this.getHandle().takeXpDelay = CraftEventFactory.callPlayerXpCooldownEvent(this.getHandle(), ticks, PlayerExpCooldownChangeEvent.ChangeReason.PLUGIN).getNewCooldown(); + getHandle().takeXpDelay = CraftEventFactory.callPlayerXpCooldownEvent(this.getHandle(), ticks, PlayerExpCooldownChangeEvent.ChangeReason.PLUGIN).getNewCooldown(); } @Override public void resetPlayerWeather() { - this.getHandle().resetPlayerWeather(); + getHandle().resetPlayerWeather(); } @Override public boolean isBanned() { - return ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).isBanned(this.getPlayerProfile()); + return ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).isBanned(getPlayerProfile()); } @Override @@ -1349,17 +1374,17 @@ public BanEntry ban(String reason, Date expires, String source) { @Override public BanEntry ban(String reason, Instant expires, String source) { - return this.ban(reason, expires != null ? Date.from(expires) : null, source); + return ban(reason, expires != null ? Date.from(expires) : null, source); } @Override public BanEntry ban(String reason, Duration duration, String source) { - return this.ban(reason, duration != null ? Instant.now().plus(duration) : null, source); + return ban(reason, duration != null ? Instant.now().plus(duration) : null, source); } @Override public BanEntry ban(String reason, Date expires, String source, boolean kickPlayer) { - BanEntry banEntry = ((ProfileBanList) this.server.getBanList(BanList.Type.PROFILE)).addBan(this.getPlayerProfile(), reason, expires, source); + BanEntry banEntry = ((ProfileBanList) server.getBanList(BanList.Type.PROFILE)).addBan(getPlayerProfile(), reason, expires, source); if (kickPlayer) { this.kickPlayer(reason); } @@ -1368,18 +1393,18 @@ public BanEntry ban(String reason, Date expires, String source, b @Override public BanEntry ban(String reason, Instant instant, String source, boolean kickPlayer) { - return this.ban(reason, instant != null ? Date.from(instant) : null, source, kickPlayer); + return ban(reason, instant != null ? Date.from(instant) : null, source, kickPlayer); } @Override public BanEntry ban(String reason, Duration duration, String source, boolean kickPlayer) { - return this.ban(reason, duration != null ? Instant.now().plus(duration) : null, source, kickPlayer); + return ban(reason, duration != null ? Instant.now().plus(duration) : null, source, kickPlayer); } @Override public BanEntry banIp(String reason, Date expires, String source, boolean kickPlayer) { - Preconditions.checkArgument(this.getAddress() != null, "The Address of this Player is null"); - BanEntry banEntry = ((IpBanList) this.server.getBanList(BanList.Type.IP)).addBan(this.getAddress().getAddress(), reason, expires, source); + Preconditions.checkArgument(getAddress() != null, "The Address of this Player is null"); + BanEntry banEntry = ((IpBanList) server.getBanList(BanList.Type.IP)).addBan(getAddress().getAddress(), reason, expires, source); if (kickPlayer) { this.kickPlayer(reason); } @@ -1388,96 +1413,96 @@ public BanEntry banIp(String reason, Date expires, String source, b @Override public BanEntry banIp(String reason, Instant instant, String source, boolean kickPlayer) { - return this.banIp(reason, instant != null ? Date.from(instant) : null, source, kickPlayer); + return banIp(reason, instant != null ? Date.from(instant) : null, source, kickPlayer); } @Override public BanEntry banIp(String reason, Duration duration, String source, boolean kickPlayer) { - return this.banIp(reason, duration != null ? Instant.now().plus(duration) : null, source, kickPlayer); + return banIp(reason, duration != null ? Instant.now().plus(duration) : null, source, kickPlayer); } @Override public boolean isWhitelisted() { - return this.server.getHandle().getWhiteList().isWhiteListed(this.getProfile()); + return server.getHandle().getWhiteList().isWhiteListed(getProfile()); } @Override public void setWhitelisted(boolean value) { if (value) { - this.server.getHandle().getWhiteList().add(new UserWhiteListEntry(this.getProfile())); + server.getHandle().getWhiteList().add(new WhiteListEntry(getProfile())); } else { - this.server.getHandle().getWhiteList().remove(this.getProfile()); + server.getHandle().getWhiteList().remove(getProfile()); } } @Override public void setGameMode(GameMode mode) { Preconditions.checkArgument(mode != null, "GameMode cannot be null"); - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().setGameMode(GameType.byId(mode.getValue())); + getHandle().setGameMode(EnumGamemode.byId(mode.getValue())); } @Override public GameMode getGameMode() { - return GameMode.getByValue(this.getHandle().gameMode.getGameModeForPlayer().getId()); + return GameMode.getByValue(getHandle().gameMode.getGameModeForPlayer().getId()); } @Override public GameMode getPreviousGameMode() { - GameType previousGameMode = this.getHandle().gameMode.getPreviousGameModeForPlayer(); + EnumGamemode previousGameMode = getHandle().gameMode.getPreviousGameModeForPlayer(); return (previousGameMode == null) ? null : GameMode.getByValue(previousGameMode.getId()); } @Override public void giveExp(int exp) { - this.getHandle().giveExperiencePoints(exp); + getHandle().giveExperiencePoints(exp); } @Override public void giveExpLevels(int levels) { - this.getHandle().giveExperienceLevels(levels); + getHandle().giveExperienceLevels(levels); } @Override public float getExp() { - return this.getHandle().experienceProgress; + return getHandle().experienceProgress; } @Override public void setExp(float exp) { Preconditions.checkArgument(exp >= 0.0 && exp <= 1.0, "Experience progress must be between 0.0 and 1.0 (%s)", exp); - this.getHandle().experienceProgress = exp; - this.getHandle().lastSentExp = -1; + getHandle().experienceProgress = exp; + getHandle().lastSentExp = -1; } @Override public int getLevel() { - return this.getHandle().experienceLevel; + return getHandle().experienceLevel; } @Override public void setLevel(int level) { Preconditions.checkArgument(level >= 0, "Experience level must not be negative (%s)", level); - this.getHandle().experienceLevel = level; - this.getHandle().lastSentExp = -1; + getHandle().experienceLevel = level; + getHandle().lastSentExp = -1; } @Override public int getTotalExperience() { - return this.getHandle().totalExperience; + return getHandle().totalExperience; } @Override public void setTotalExperience(int exp) { Preconditions.checkArgument(exp >= 0, "Total experience points must not be negative (%s)", exp); - this.getHandle().totalExperience = exp; + getHandle().totalExperience = exp; } @Override public void sendExperienceChange(float progress) { - this.sendExperienceChange(progress, this.getLevel()); + sendExperienceChange(progress, getLevel()); } @Override @@ -1485,28 +1510,28 @@ public void sendExperienceChange(float progress, int level) { Preconditions.checkArgument(progress >= 0.0 && progress <= 1.0, "Experience progress must be between 0.0 and 1.0 (%s)", progress); Preconditions.checkArgument(level >= 0, "Experience level must not be negative (%s)", level); - if (this.getHandle().connection == null) { + if (getHandle().connection == null) { return; } - ClientboundSetExperiencePacket packet = new ClientboundSetExperiencePacket(progress, this.getTotalExperience(), level); - this.getHandle().connection.send(packet); + PacketPlayOutExperience packet = new PacketPlayOutExperience(progress, getTotalExperience(), level); + getHandle().connection.send(packet); } @Nullable private static WeakReference getPluginWeakReference(@Nullable Plugin plugin) { - return (plugin == null) ? null : CraftPlayer.pluginWeakReferences.computeIfAbsent(plugin, WeakReference::new); + return (plugin == null) ? null : pluginWeakReferences.computeIfAbsent(plugin, WeakReference::new); } @Override @Deprecated public void hidePlayer(Player player) { - this.hideEntity0(null, player); + hideEntity0(null, player); } @Override public void hidePlayer(Plugin plugin, Player player) { - this.hideEntity(plugin, player); + hideEntity(plugin, player); } @Override @@ -1514,81 +1539,81 @@ public void hideEntity(Plugin plugin, org.bukkit.entity.Entity entity) { Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); Preconditions.checkArgument(plugin.isEnabled(), "Plugin (%s) cannot be disabled", plugin.getName()); - this.hideEntity0(plugin, entity); + hideEntity0(plugin, entity); } private void hideEntity0(@Nullable Plugin plugin, org.bukkit.entity.Entity entity) { Preconditions.checkArgument(entity != null, "Entity hidden cannot be null"); - if (this.getHandle().connection == null) return; - if (this.equals(entity)) return; + if (getHandle().connection == null) return; + if (equals(entity)) return; boolean shouldHide; if (entity.isVisibleByDefault()) { - shouldHide = this.addInvertedVisibility(plugin, entity); + shouldHide = addInvertedVisibility(plugin, entity); } else { - shouldHide = this.removeInvertedVisibility(plugin, entity); + shouldHide = removeInvertedVisibility(plugin, entity); } if (shouldHide) { - this.untrackAndHideEntity(entity); + untrackAndHideEntity(entity); } } private boolean addInvertedVisibility(@Nullable Plugin plugin, org.bukkit.entity.Entity entity) { - Set> invertedPlugins = this.invertedVisibilityEntities.get(entity.getUniqueId()); + Set> invertedPlugins = invertedVisibilityEntities.get(entity.getUniqueId()); if (invertedPlugins != null) { // Some plugins are already inverting the entity. Just mark that this // plugin wants the entity inverted too and end. - invertedPlugins.add(CraftPlayer.getPluginWeakReference(plugin)); + invertedPlugins.add(getPluginWeakReference(plugin)); return false; } invertedPlugins = new HashSet<>(); - invertedPlugins.add(CraftPlayer.getPluginWeakReference(plugin)); - this.invertedVisibilityEntities.put(entity.getUniqueId(), invertedPlugins); + invertedPlugins.add(getPluginWeakReference(plugin)); + invertedVisibilityEntities.put(entity.getUniqueId(), invertedPlugins); return true; } private void untrackAndHideEntity(org.bukkit.entity.Entity entity) { // Remove this entity from the hidden player's EntityTrackerEntry - ChunkMap tracker = ((ServerLevel) this.getHandle().level()).getChunkSource().chunkMap; + PlayerChunkMap tracker = ((WorldServer) getHandle().level()).getChunkSource().chunkMap; Entity other = ((CraftEntity) entity).getHandle(); - ChunkMap.TrackedEntity entry = tracker.entityMap.get(other.getId()); + PlayerChunkMap.EntityTracker entry = tracker.entityMap.get(other.getId()); if (entry != null) { - entry.removePlayer(this.getHandle()); + entry.removePlayer(getHandle()); } // Remove the hidden entity from this player user list, if they're on it - if (other instanceof ServerPlayer) { - ServerPlayer otherPlayer = (ServerPlayer) other; + if (other instanceof EntityPlayer) { + EntityPlayer otherPlayer = (EntityPlayer) other; if (otherPlayer.sentListPacket) { - this.getHandle().connection.send(new ClientboundPlayerInfoRemovePacket(List.of(otherPlayer.getUUID()))); + getHandle().connection.send(new ClientboundPlayerInfoRemovePacket(List.of(otherPlayer.getUUID()))); } } - this.server.getPluginManager().callEvent(new PlayerHideEntityEvent(this, entity)); + server.getPluginManager().callEvent(new PlayerHideEntityEvent(this, entity)); } void resetAndHideEntity(org.bukkit.entity.Entity entity) { // SPIGOT-7312: Can't show/hide self - if (this.equals(entity)) { + if (equals(entity)) { return; } - if (this.invertedVisibilityEntities.remove(entity.getUniqueId()) == null) { - this.untrackAndHideEntity(entity); + if (invertedVisibilityEntities.remove(entity.getUniqueId()) == null) { + untrackAndHideEntity(entity); } } @Override @Deprecated public void showPlayer(Player player) { - this.showEntity0(null, player); + showEntity0(null, player); } @Override public void showPlayer(Plugin plugin, Player player) { - this.showEntity(plugin, player); + showEntity(plugin, player); } @Override @@ -1596,93 +1621,93 @@ public void showEntity(Plugin plugin, org.bukkit.entity.Entity entity) { Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); // Don't require that plugin be enabled. A plugin must be allowed to call // showPlayer during its onDisable() method. - this.showEntity0(plugin, entity); + showEntity0(plugin, entity); } private void showEntity0(@Nullable Plugin plugin, org.bukkit.entity.Entity entity) { Preconditions.checkArgument(entity != null, "Entity show cannot be null"); - if (this.getHandle().connection == null) return; - if (this.equals(entity)) return; + if (getHandle().connection == null) return; + if (equals(entity)) return; boolean shouldShow; if (entity.isVisibleByDefault()) { - shouldShow = this.removeInvertedVisibility(plugin, entity); + shouldShow = removeInvertedVisibility(plugin, entity); } else { - shouldShow = this.addInvertedVisibility(plugin, entity); + shouldShow = addInvertedVisibility(plugin, entity); } if (shouldShow) { - this.trackAndShowEntity(entity); + trackAndShowEntity(entity); } } private boolean removeInvertedVisibility(@Nullable Plugin plugin, org.bukkit.entity.Entity entity) { - Set> invertedPlugins = this.invertedVisibilityEntities.get(entity.getUniqueId()); + Set> invertedPlugins = invertedVisibilityEntities.get(entity.getUniqueId()); if (invertedPlugins == null) { return false; // Entity isn't inverted } - invertedPlugins.remove(CraftPlayer.getPluginWeakReference(plugin)); + invertedPlugins.remove(getPluginWeakReference(plugin)); if (!invertedPlugins.isEmpty()) { return false; // Some other plugins still want the entity inverted } - this.invertedVisibilityEntities.remove(entity.getUniqueId()); + invertedVisibilityEntities.remove(entity.getUniqueId()); return true; } private void trackAndShowEntity(org.bukkit.entity.Entity entity) { - ChunkMap tracker = ((ServerLevel) this.getHandle().level()).getChunkSource().chunkMap; + PlayerChunkMap tracker = ((WorldServer) getHandle().level()).getChunkSource().chunkMap; Entity other = ((CraftEntity) entity).getHandle(); - if (other instanceof ServerPlayer) { - ServerPlayer otherPlayer = (ServerPlayer) other; - this.getHandle().connection.send(ClientboundPlayerInfoUpdatePacket.createPlayerInitializing(List.of(otherPlayer))); + if (other instanceof EntityPlayer) { + EntityPlayer otherPlayer = (EntityPlayer) other; + getHandle().connection.send(ClientboundPlayerInfoUpdatePacket.createPlayerInitializing(List.of(otherPlayer))); } - ChunkMap.TrackedEntity entry = tracker.entityMap.get(other.getId()); - if (entry != null && !entry.seenBy.contains(this.getHandle().connection)) { - entry.updatePlayer(this.getHandle()); + PlayerChunkMap.EntityTracker entry = tracker.entityMap.get(other.getId()); + if (entry != null && !entry.seenBy.contains(getHandle().connection)) { + entry.updatePlayer(getHandle()); } - this.server.getPluginManager().callEvent(new PlayerShowEntityEvent(this, entity)); + server.getPluginManager().callEvent(new PlayerShowEntityEvent(this, entity)); } void resetAndShowEntity(org.bukkit.entity.Entity entity) { // SPIGOT-7312: Can't show/hide self - if (this.equals(entity)) { + if (equals(entity)) { return; } - if (this.invertedVisibilityEntities.remove(entity.getUniqueId()) == null) { - this.trackAndShowEntity(entity); + if (invertedVisibilityEntities.remove(entity.getUniqueId()) == null) { + trackAndShowEntity(entity); } } public void onEntityRemove(Entity entity) { - this.invertedVisibilityEntities.remove(entity.getUUID()); + invertedVisibilityEntities.remove(entity.getUUID()); } @Override public boolean canSee(Player player) { - return this.canSee((org.bukkit.entity.Entity) player); + return canSee((org.bukkit.entity.Entity) player); } @Override public boolean canSee(org.bukkit.entity.Entity entity) { - return this.equals(entity) || entity.isVisibleByDefault() ^ this.invertedVisibilityEntities.containsKey(entity.getUniqueId()); // SPIGOT-7312: Can always see self + return equals(entity) || entity.isVisibleByDefault() ^ invertedVisibilityEntities.containsKey(entity.getUniqueId()); // SPIGOT-7312: Can always see self } public boolean canSeePlayer(UUID uuid) { - org.bukkit.entity.Entity entity = this.getServer().getPlayer(uuid); + org.bukkit.entity.Entity entity = getServer().getPlayer(uuid); - return (entity != null) ? this.canSee(entity) : false; // If we can't find it, we can't see it + return (entity != null) ? canSee(entity) : false; // If we can't find it, we can't see it } @Override public Map serialize() { Map result = new LinkedHashMap(); - result.put("name", this.getName()); + result.put("name", getName()); return result; } @@ -1693,58 +1718,58 @@ public Player getPlayer() { } @Override - public ServerPlayer getHandle() { - return (ServerPlayer) this.entity; + public EntityPlayer getHandle() { + return (EntityPlayer) entity; } - public void setHandle(final ServerPlayer entity) { + public void setHandle(final EntityPlayer entity) { super.setHandle(entity); } @Override public String toString() { - return "CraftPlayer{" + "name=" + this.getName() + '}'; + return "CraftPlayer{" + "name=" + getName() + '}'; } @Override public int hashCode() { - if (this.hash == 0 || this.hash == 485) { - this.hash = 97 * 5 + (this.getUniqueId() != null ? this.getUniqueId().hashCode() : 0); + if (hash == 0 || hash == 485) { + hash = 97 * 5 + (this.getUniqueId() != null ? this.getUniqueId().hashCode() : 0); } - return this.hash; + return hash; } @Override public long getFirstPlayed() { - return this.firstPlayed; + return firstPlayed; } @Override public long getLastPlayed() { - return this.lastPlayed; + return lastPlayed; } @Override public boolean hasPlayedBefore() { - return this.hasPlayedBefore; + return hasPlayedBefore; } public void setFirstPlayed(long firstPlayed) { this.firstPlayed = firstPlayed; } - public void readExtraData(CompoundTag nbttagcompound) { - this.hasPlayedBefore = true; + public void readExtraData(NBTTagCompound nbttagcompound) { + hasPlayedBefore = true; if (nbttagcompound.contains("bukkit")) { - CompoundTag data = nbttagcompound.getCompound("bukkit"); + NBTTagCompound data = nbttagcompound.getCompound("bukkit"); if (data.contains("firstPlayed")) { - this.firstPlayed = data.getLong("firstPlayed"); - this.lastPlayed = data.getLong("lastPlayed"); + firstPlayed = data.getLong("firstPlayed"); + lastPlayed = data.getLong("lastPlayed"); } if (data.contains("newExp")) { - ServerPlayer handle = this.getHandle(); + EntityPlayer handle = getHandle(); handle.newExp = data.getInt("newExp"); handle.newTotalExp = data.getInt("newTotalExp"); handle.newLevel = data.getInt("newLevel"); @@ -1754,94 +1779,94 @@ public void readExtraData(CompoundTag nbttagcompound) { } } - public void setExtraData(CompoundTag nbttagcompound) { + public void setExtraData(NBTTagCompound nbttagcompound) { if (!nbttagcompound.contains("bukkit")) { - nbttagcompound.put("bukkit", new CompoundTag()); + nbttagcompound.put("bukkit", new NBTTagCompound()); } - CompoundTag data = nbttagcompound.getCompound("bukkit"); - ServerPlayer handle = this.getHandle(); + NBTTagCompound data = nbttagcompound.getCompound("bukkit"); + EntityPlayer handle = getHandle(); data.putInt("newExp", handle.newExp); data.putInt("newTotalExp", handle.newTotalExp); data.putInt("newLevel", handle.newLevel); data.putInt("expToDrop", handle.expToDrop); data.putBoolean("keepLevel", handle.keepLevel); - data.putLong("firstPlayed", this.getFirstPlayed()); + data.putLong("firstPlayed", getFirstPlayed()); data.putLong("lastPlayed", System.currentTimeMillis()); data.putString("lastKnownName", handle.getScoreboardName()); } @Override public boolean beginConversation(Conversation conversation) { - return this.conversationTracker.beginConversation(conversation); + return conversationTracker.beginConversation(conversation); } @Override public void abandonConversation(Conversation conversation) { - this.conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); + conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); } @Override public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { - this.conversationTracker.abandonConversation(conversation, details); + conversationTracker.abandonConversation(conversation, details); } @Override public void acceptConversationInput(String input) { - this.conversationTracker.acceptConversationInput(input); + conversationTracker.acceptConversationInput(input); } @Override public boolean isConversing() { - return this.conversationTracker.isConversing(); + return conversationTracker.isConversing(); } @Override public void sendPluginMessage(Plugin source, String channel, byte[] message) { - StandardMessenger.validatePluginMessage(this.server.getMessenger(), source, channel, message); - if (this.getHandle().connection == null) return; + StandardMessenger.validatePluginMessage(server.getMessenger(), source, channel, message); + if (getHandle().connection == null) return; - if (this.channels.contains(channel)) { - ResourceLocation id = ResourceLocation.parse(StandardMessenger.validateAndCorrectChannel(channel)); - this.sendCustomPayload(id, message); + if (channels.contains(channel)) { + MinecraftKey id = MinecraftKey.parse(StandardMessenger.validateAndCorrectChannel(channel)); + sendCustomPayload(id, message); } } - private void sendCustomPayload(ResourceLocation id, byte[] message) { + private void sendCustomPayload(MinecraftKey id, byte[] message) { ClientboundCustomPayloadPacket packet = new ClientboundCustomPayloadPacket(new DiscardedPayload(id, Unpooled.wrappedBuffer(message))); - this.getHandle().connection.send(packet); + getHandle().connection.send(packet); } @Override public void setTexturePack(String url) { - this.setResourcePack(url); + setResourcePack(url); } @Override public void setResourcePack(String url) { - this.setResourcePack(url, null); + setResourcePack(url, null); } @Override public void setResourcePack(String url, byte[] hash) { - this.setResourcePack(url, hash, false); + setResourcePack(url, hash, false); } @Override public void setResourcePack(String url, byte[] hash, String prompt) { - this.setResourcePack(url, hash, prompt, false); + setResourcePack(url, hash, prompt, false); } @Override public void setResourcePack(String url, byte[] hash, boolean force) { - this.setResourcePack(url, hash, null, force); + setResourcePack(url, hash, null, force); } @Override public void setResourcePack(String url, byte[] hash, String prompt, boolean force) { Preconditions.checkArgument(url != null, "Resource pack URL cannot be null"); - this.setResourcePack(UUID.nameUUIDFromBytes(url.getBytes(StandardCharsets.UTF_8)), url, hash, prompt, force); + setResourcePack(UUID.nameUUIDFromBytes(url.getBytes(StandardCharsets.UTF_8)), url, hash, prompt, force); } @Override @@ -1874,48 +1899,48 @@ public void addResourcePack(UUID id, String url, byte[] hash, String prompt, boo @Override public void removeResourcePack(UUID id) { Preconditions.checkArgument(id != null, "Resource pack id cannot be null"); - if (this.getHandle().connection == null) return; - this.getHandle().connection.send(new ClientboundResourcePackPopPacket(Optional.of(id))); + if (getHandle().connection == null) return; + getHandle().connection.send(new ClientboundResourcePackPopPacket(Optional.of(id))); } @Override public void removeResourcePacks() { - if (this.getHandle().connection == null) return; - this.getHandle().connection.send(new ClientboundResourcePackPopPacket(Optional.empty())); + if (getHandle().connection == null) return; + getHandle().connection.send(new ClientboundResourcePackPopPacket(Optional.empty())); } private void handlePushResourcePack(ClientboundResourcePackPushPacket resourcePackPushPacket, boolean resetBeforePush) { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; if (resetBeforePush) { this.removeResourcePacks(); } - this.getHandle().connection.send(resourcePackPushPacket); + getHandle().connection.send(resourcePackPushPacket); } public void addChannel(String channel) { - Preconditions.checkState(this.channels.size() < 128, "Cannot register channel '%s'. Too many channels registered!", channel); + Preconditions.checkState(channels.size() < 128, "Cannot register channel '%s'. Too many channels registered!", channel); channel = StandardMessenger.validateAndCorrectChannel(channel); - if (this.channels.add(channel)) { - this.server.getPluginManager().callEvent(new PlayerRegisterChannelEvent(this, channel)); + if (channels.add(channel)) { + server.getPluginManager().callEvent(new PlayerRegisterChannelEvent(this, channel)); } } public void removeChannel(String channel) { channel = StandardMessenger.validateAndCorrectChannel(channel); - if (this.channels.remove(channel)) { - this.server.getPluginManager().callEvent(new PlayerUnregisterChannelEvent(this, channel)); + if (channels.remove(channel)) { + server.getPluginManager().callEvent(new PlayerUnregisterChannelEvent(this, channel)); } } @Override public Set getListeningPluginChannels() { - return ImmutableSet.copyOf(this.channels); + return ImmutableSet.copyOf(channels); } public void sendSupportedChannels() { - if (this.getHandle().connection == null) return; - Set listening = this.server.getMessenger().getIncomingChannels(); + if (getHandle().connection == null) return; + Set listening = server.getMessenger().getIncomingChannels(); if (!listening.isEmpty()) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); @@ -1925,37 +1950,37 @@ public void sendSupportedChannels() { stream.write(channel.getBytes("UTF8")); stream.write((byte) 0); } catch (IOException ex) { - Logger.getLogger(CraftPlayer.class.getName()).log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + this.getName(), ex); + Logger.getLogger(CraftPlayer.class.getName()).log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex); } } - this.sendCustomPayload(ResourceLocation.withDefaultNamespace("register"), stream.toByteArray()); + sendCustomPayload(MinecraftKey.withDefaultNamespace("register"), stream.toByteArray()); } } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - this.server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); + server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List getMetadata(String metadataKey) { - return this.server.getPlayerMetadata().getMetadata(this, metadataKey); + return server.getPlayerMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { - return this.server.getPlayerMetadata().hasMetadata(this, metadataKey); + return server.getPlayerMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { - this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); + server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override public boolean setWindowProperty(Property prop, int value) { - AbstractContainerMenu container = this.getHandle().containerMenu; + Container container = getHandle().containerMenu; if (container.getBukkitView().getType() != prop.getType()) { return false; } @@ -1964,59 +1989,59 @@ public boolean setWindowProperty(Property prop, int value) { } public void disconnect(String reason) { - this.conversationTracker.abandonAllConversations(); - this.perm.clearPermissions(); + conversationTracker.abandonAllConversations(); + perm.clearPermissions(); } @Override public boolean isFlying() { - return this.getHandle().getAbilities().flying; + return getHandle().getAbilities().flying; } @Override public void setFlying(boolean value) { - if (!this.getAllowFlight()) { + if (!getAllowFlight()) { Preconditions.checkArgument(!value, "Player is not allowed to fly (check #getAllowFlight())"); } - this.getHandle().getAbilities().flying = value; - this.getHandle().onUpdateAbilities(); + getHandle().getAbilities().flying = value; + getHandle().onUpdateAbilities(); } @Override public boolean getAllowFlight() { - return this.getHandle().getAbilities().mayfly; + return getHandle().getAbilities().mayfly; } @Override public void setAllowFlight(boolean value) { - if (this.isFlying() && !value) { - this.getHandle().getAbilities().flying = false; + if (isFlying() && !value) { + getHandle().getAbilities().flying = false; } - this.getHandle().getAbilities().mayfly = value; - this.getHandle().onUpdateAbilities(); + getHandle().getAbilities().mayfly = value; + getHandle().onUpdateAbilities(); } @Override public int getNoDamageTicks() { - if (this.getHandle().spawnInvulnerableTime > 0) { - return Math.max(this.getHandle().spawnInvulnerableTime, this.getHandle().invulnerableTime); + if (getHandle().spawnInvulnerableTime > 0) { + return Math.max(getHandle().spawnInvulnerableTime, getHandle().invulnerableTime); } else { - return this.getHandle().invulnerableTime; + return getHandle().invulnerableTime; } } @Override public void setNoDamageTicks(int ticks) { super.setNoDamageTicks(ticks); - this.getHandle().spawnInvulnerableTime = ticks; // SPIGOT-5921: Update both for players, like the getter above + getHandle().spawnInvulnerableTime = ticks; // SPIGOT-5921: Update both for players, like the getter above } @Override public void setFlySpeed(float value) { - this.validateSpeed(value); - ServerPlayer player = this.getHandle(); + validateSpeed(value); + EntityPlayer player = getHandle(); player.getAbilities().flyingSpeed = value / 2f; player.onUpdateAbilities(); @@ -2024,21 +2049,21 @@ public void setFlySpeed(float value) { @Override public void setWalkSpeed(float value) { - this.validateSpeed(value); - ServerPlayer player = this.getHandle(); + validateSpeed(value); + EntityPlayer player = getHandle(); player.getAbilities().walkingSpeed = value / 2f; player.onUpdateAbilities(); - this.getHandle().getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(player.getAbilities().walkingSpeed); // SPIGOT-5833: combination of the two in 1.16+ + getHandle().getAttribute(GenericAttributes.MOVEMENT_SPEED).setBaseValue(player.getAbilities().walkingSpeed); // SPIGOT-5833: combination of the two in 1.16+ } @Override public float getFlySpeed() { - return (float) this.getHandle().getAbilities().flyingSpeed * 2f; + return (float) getHandle().getAbilities().flyingSpeed * 2f; } @Override public float getWalkSpeed() { - return this.getHandle().getAbilities().walkingSpeed * 2f; + return getHandle().getAbilities().walkingSpeed * 2f; } private void validateSpeed(float value) { @@ -2049,13 +2074,13 @@ private void validateSpeed(float value) { public void setMaxHealth(double amount) { super.setMaxHealth(amount); this.health = Math.min(this.health, amount); - this.getHandle().resetSentInfo(); + getHandle().resetSentInfo(); } @Override public void resetMaxHealth() { super.resetMaxHealth(); - this.getHandle().resetSentInfo(); + getHandle().resetSentInfo(); } @Override @@ -2066,7 +2091,7 @@ public CraftScoreboard getScoreboard() { @Override public void setScoreboard(Scoreboard scoreboard) { Preconditions.checkArgument(scoreboard != null, "Scoreboard cannot be null"); - Preconditions.checkState(this.getHandle().connection != null, "Cannot set scoreboard yet (invalid player connection)"); + Preconditions.checkState(getHandle().connection != null, "Cannot set scoreboard yet (invalid player connection)"); this.server.getScoreboardManager().setPlayerBoard(this, scoreboard); } @@ -2074,35 +2099,35 @@ public void setScoreboard(Scoreboard scoreboard) { @Override public void setHealthScale(double value) { Preconditions.checkArgument(value > 0F, "Health value (%s) must be greater than 0", value); - this.healthScale = value; - this.scaledHealth = true; - this.updateScaledHealth(); + healthScale = value; + scaledHealth = true; + updateScaledHealth(); } @Override public double getHealthScale() { - return this.healthScale; + return healthScale; } @Override public void setHealthScaled(boolean scale) { - if (this.scaledHealth != (this.scaledHealth = scale)) { - this.updateScaledHealth(); + if (scaledHealth != (scaledHealth = scale)) { + updateScaledHealth(); } } @Override public boolean isHealthScaled() { - return this.scaledHealth; + return scaledHealth; } public float getScaledHealth() { - return (float) (this.isHealthScaled() ? this.getHealth() * this.getHealthScale() / this.getMaxHealth() : this.getHealth()); + return (float) (isHealthScaled() ? getHealth() * getHealthScale() / getMaxHealth() : getHealth()); } @Override public double getHealth() { - return this.health; + return health; } public void setRealHealth(double health) { @@ -2110,158 +2135,145 @@ public void setRealHealth(double health) { } public void updateScaledHealth() { - this.updateScaledHealth(true); + updateScaledHealth(true); } public void updateScaledHealth(boolean sendHealth) { - AttributeMap attributemapserver = this.getHandle().getAttributes(); - Collection set = attributemapserver.getSyncableAttributes(); + AttributeMapBase attributemapserver = getHandle().getAttributes(); + Collection set = attributemapserver.getSyncableAttributes(); - this.injectScaledMaxHealth(set, true); + injectScaledMaxHealth(set, true); // SPIGOT-3813: Attributes before health - if (this.getHandle().connection != null) { - this.getHandle().connection.send(new ClientboundUpdateAttributesPacket(this.getHandle().getId(), set)); + if (getHandle().connection != null) { + getHandle().connection.send(new PacketPlayOutUpdateAttributes(getHandle().getId(), set)); if (sendHealth) { - this.sendHealthUpdate(); + sendHealthUpdate(); } } - this.getHandle().getEntityData().set(net.minecraft.world.entity.LivingEntity.DATA_HEALTH_ID, (float) this.getScaledHealth()); + getHandle().getEntityData().set(EntityLiving.DATA_HEALTH_ID, (float) getScaledHealth()); - this.getHandle().maxHealthCache = this.getMaxHealth(); + getHandle().maxHealthCache = getMaxHealth(); } @Override public void sendHealthUpdate(double health, int foodLevel, float saturation) { - this.getHandle().connection.send(new ClientboundSetHealthPacket((float) health, foodLevel, saturation)); + getHandle().connection.send(new PacketPlayOutUpdateHealth((float) health, foodLevel, saturation)); } @Override public void sendHealthUpdate() { - FoodData foodData = this.getHandle().getFoodData(); - this.sendHealthUpdate(this.getScaledHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel()); + FoodMetaData foodData = getHandle().getFoodData(); + sendHealthUpdate(getScaledHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel()); } - public void injectScaledMaxHealth(Collection collection, boolean force) { - if (!this.scaledHealth && !force) { + public void injectScaledMaxHealth(Collection collection, boolean force) { + if (!scaledHealth && !force) { return; } - for (AttributeInstance genericInstance : collection) { - if (genericInstance.getAttribute() == Attributes.MAX_HEALTH) { + for (AttributeModifiable genericInstance : collection) { + if (genericInstance.getAttribute() == GenericAttributes.MAX_HEALTH) { collection.remove(genericInstance); break; } } - AttributeInstance dummy = new AttributeInstance(Attributes.MAX_HEALTH, (attribute) -> { }); - // Spigot start - double healthMod = this.scaledHealth ? this.healthScale : this.getMaxHealth(); - if ( healthMod >= Float.MAX_VALUE || healthMod <= 0 ) - { - healthMod = 20; // Reset health - this.getServer().getLogger().warning( this.getName() + " tried to crash the server with a large health attribute" ); - } - dummy.setBaseValue(healthMod); - // Spigot end + AttributeModifiable dummy = new AttributeModifiable(GenericAttributes.MAX_HEALTH, (attribute) -> { }); + dummy.setBaseValue(scaledHealth ? healthScale : getMaxHealth()); collection.add(dummy); } @Override public org.bukkit.entity.Entity getSpectatorTarget() { - Entity followed = this.getHandle().getCamera(); - return followed == this.getHandle() ? null : followed.getBukkitEntity(); + Entity followed = getHandle().getCamera(); + return followed == getHandle() ? null : followed.getBukkitEntity(); } @Override public void setSpectatorTarget(org.bukkit.entity.Entity entity) { - Preconditions.checkArgument(this.getGameMode() == GameMode.SPECTATOR, "Player must be in spectator mode"); - this.getHandle().setCamera((entity == null) ? null : ((CraftEntity) entity).getHandle()); + Preconditions.checkArgument(getGameMode() == GameMode.SPECTATOR, "Player must be in spectator mode"); + getHandle().setCamera((entity == null) ? null : ((CraftEntity) entity).getHandle()); } @Override public void sendTitle(String title, String subtitle) { - this.sendTitle(title, subtitle, 10, 70, 20); + sendTitle(title, subtitle, 10, 70, 20); } @Override public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) { ClientboundSetTitlesAnimationPacket times = new ClientboundSetTitlesAnimationPacket(fadeIn, stay, fadeOut); - this.getHandle().connection.send(times); + getHandle().connection.send(times); if (title != null) { ClientboundSetTitleTextPacket packetTitle = new ClientboundSetTitleTextPacket(CraftChatMessage.fromString(title)[0]); - this.getHandle().connection.send(packetTitle); + getHandle().connection.send(packetTitle); } if (subtitle != null) { ClientboundSetSubtitleTextPacket packetSubtitle = new ClientboundSetSubtitleTextPacket(CraftChatMessage.fromString(subtitle)[0]); - this.getHandle().connection.send(packetSubtitle); + getHandle().connection.send(packetSubtitle); } } @Override public void resetTitle() { ClientboundClearTitlesPacket packetReset = new ClientboundClearTitlesPacket(true); - this.getHandle().connection.send(packetReset); - } - - public void restore(CraftPlayer player) { - setDisplayName(player.getDisplayName()); - player.setHandle(getHandle()); + getHandle().connection.send(packetReset); } @Override public void spawnParticle(Particle particle, Location location, int count) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count) { - this.spawnParticle(particle, x, y, z, count, null); + spawnParticle(particle, x, y, z, count, null); } @Override public void spawnParticle(Particle particle, Location location, int count, T data) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, data); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, data); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { - this.spawnParticle(particle, x, y, z, count, 0, 0, 0, data); + spawnParticle(particle, x, y, z, count, 0, 0, 0, data); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, null); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, null); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, 1, data); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, 1, data); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); } @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { - this.spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); + spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); } @Override public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - this.spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); + spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); } @Override @@ -2276,7 +2288,7 @@ public void spawnParticle(Particle particle, Location location, int count, d @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - ClientboundLevelParticlesPacket packetplayoutworldparticles = new ClientboundLevelParticlesPacket(CraftParticle.createParticleParam(particle, data), force, (float) x, (float) y, (float) z, (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count); + PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(CraftParticle.createParticleParam(particle, data), force, (float) x, (float) y, (float) z, (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count); getHandle().connection.send(packetplayoutworldparticles); } @@ -2285,7 +2297,7 @@ public org.bukkit.advancement.AdvancementProgress getAdvancementProgress(org.buk Preconditions.checkArgument(advancement != null, "advancement"); CraftAdvancement craft = (CraftAdvancement) advancement; - PlayerAdvancements data = this.getHandle().getAdvancements(); + AdvancementDataPlayer data = getHandle().getAdvancements(); AdvancementProgress progress = data.getOrStartProgress(craft.getHandle()); return new CraftAdvancementProgress(craft, data, progress); @@ -2293,24 +2305,24 @@ public org.bukkit.advancement.AdvancementProgress getAdvancementProgress(org.buk @Override public int getClientViewDistance() { - return (this.getHandle().requestedViewDistance() == 0) ? Bukkit.getViewDistance() : this.getHandle().requestedViewDistance(); + return (getHandle().requestedViewDistance() == 0) ? Bukkit.getViewDistance() : getHandle().requestedViewDistance(); } @Override public int getPing() { - return this.getHandle().connection.latency(); + return getHandle().connection.latency(); } @Override public String getLocale() { - return this.getHandle().language; + return getHandle().language; } @Override public void updateCommands() { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().server.getCommands().sendCommands(this.getHandle()); + getHandle().server.getCommands().sendCommands(getHandle()); } @Override @@ -2318,15 +2330,15 @@ public void openBook(ItemStack book) { Preconditions.checkArgument(book != null, "ItemStack cannot be null"); Preconditions.checkArgument(book.getType() == Material.WRITTEN_BOOK, "ItemStack Material (%s) must be Material.WRITTEN_BOOK", book.getType()); - ItemStack hand = this.getInventory().getItemInMainHand(); - this.getInventory().setItemInMainHand(book); - this.getHandle().openItemGui(org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(book), net.minecraft.world.InteractionHand.MAIN_HAND); - this.getInventory().setItemInMainHand(hand); + ItemStack hand = getInventory().getItemInMainHand(); + getInventory().setItemInMainHand(book); + getHandle().openItemGui(org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(book), net.minecraft.world.EnumHand.MAIN_HAND); + getInventory().setItemInMainHand(hand); } @Override public void openSign(Sign sign) { - this.openSign(sign, Side.FRONT); + openSign(sign, Side.FRONT); } @Override @@ -2336,96 +2348,13 @@ public void openSign(@NotNull Sign sign, @NotNull Side side) { @Override public void showDemoScreen() { - if (this.getHandle().connection == null) return; + if (getHandle().connection == null) return; - this.getHandle().connection.send(new ClientboundGameEventPacket(ClientboundGameEventPacket.DEMO_EVENT, ClientboundGameEventPacket.DEMO_PARAM_INTRO)); + getHandle().connection.send(new PacketPlayOutGameStateChange(PacketPlayOutGameStateChange.DEMO_EVENT, PacketPlayOutGameStateChange.DEMO_PARAM_INTRO)); } @Override public boolean isAllowingServerListings() { - return this.getHandle().allowsListing(); - } - - // Spigot start - private final Player.Spigot spigot = new Player.Spigot() - { - - @Override - public InetSocketAddress getRawAddress() - { - return (InetSocketAddress) CraftPlayer.this.getHandle().connection.getRawAddress(); - } - - @Override - public void respawn() - { - if ( CraftPlayer.this.getHealth() <= 0 && CraftPlayer.this.isOnline() ) - { - // CraftPlayer.this.server.getServer().getPlayerList().respawn( CraftPlayer.this.getHandle(), false, org.bukkit.event.player.PlayerRespawnEvent.RespawnReason.PLUGIN ); Mohist TODO - } - } - - @Override - public Set getHiddenPlayers() - { - Set ret = new HashSet<>(); - for ( Player p : CraftPlayer.this.getServer().getOnlinePlayers() ) - { - if ( !CraftPlayer.this.canSee(p) ) - { - ret.add( p ); - } - } - - return java.util.Collections.unmodifiableSet( ret ); - } - - @Override - public void sendMessage(BaseComponent component) { - this.sendMessage( new BaseComponent[] { component } ); - } - - @Override - public void sendMessage(BaseComponent... components) { - this.sendMessage(net.md_5.bungee.api.ChatMessageType.SYSTEM, components); - } - - @Override - public void sendMessage(UUID sender, BaseComponent component) { - this.sendMessage(net.md_5.bungee.api.ChatMessageType.CHAT, sender, component); - } - - @Override - public void sendMessage(UUID sender, BaseComponent... components) { - this.sendMessage(net.md_5.bungee.api.ChatMessageType.CHAT, sender, components); - } - - @Override - public void sendMessage(net.md_5.bungee.api.ChatMessageType position, BaseComponent component) { - this.sendMessage( position, new BaseComponent[] { component } ); - } - - @Override - public void sendMessage(net.md_5.bungee.api.ChatMessageType position, BaseComponent... components) { - this.sendMessage(position, null, components); - } - - @Override - public void sendMessage(net.md_5.bungee.api.ChatMessageType position, UUID sender, BaseComponent component) { - this.sendMessage( position, sender, new BaseComponent[] { component } ); - } - - @Override - public void sendMessage(net.md_5.bungee.api.ChatMessageType position, UUID sender, BaseComponent... components) { - if ( CraftPlayer.this.getHandle().connection == null ) return; - - CraftPlayer.this.getHandle().connection.send(new net.minecraft.network.protocol.game.ClientboundSystemChatPacket(components, position == net.md_5.bungee.api.ChatMessageType.ACTION_BAR)); - } - }; - - public Player.Spigot spigot() - { - return this.spigot; + return getHandle().allowsListing(); } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java index c7aec6f2..89478ab0 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityPolarBear; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.PolarBear; public class CraftPolarBear extends CraftAnimals implements PolarBear { - public CraftPolarBear(CraftServer server, net.minecraft.world.entity.animal.PolarBear entity) { + public CraftPolarBear(CraftServer server, EntityPolarBear entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.PolarBear getHandle() { - return (net.minecraft.world.entity.animal.PolarBear) this.entity; + public EntityPolarBear getHandle() { + return (EntityPolarBear) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java index 696fdfa7..339fcfe7 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java @@ -1,33 +1,34 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.projectile.IProjectile; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Projectile; import org.bukkit.projectiles.ProjectileSource; public abstract class CraftProjectile extends AbstractProjectile implements Projectile { - public CraftProjectile(CraftServer server, net.minecraft.world.entity.projectile.Projectile entity) { + public CraftProjectile(CraftServer server, net.minecraft.world.entity.projectile.IProjectile entity) { super(server, entity); } @Override public ProjectileSource getShooter() { - return this.getHandle().projectileSource; + return getHandle().projectileSource; } @Override public void setShooter(ProjectileSource shooter) { if (shooter instanceof CraftLivingEntity) { - this.getHandle().setOwner((LivingEntity) ((CraftLivingEntity) shooter).entity); + getHandle().setOwner((EntityLiving) ((CraftLivingEntity) shooter).entity); } else { - this.getHandle().setOwner(null); + getHandle().setOwner(null); } - this.getHandle().projectileSource = shooter; + getHandle().projectileSource = shooter; } @Override - public net.minecraft.world.entity.projectile.Projectile getHandle() { - return (net.minecraft.world.entity.projectile.Projectile) this.entity; + public IProjectile getHandle() { + return (IProjectile) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java index 35a82197..6468400b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java @@ -1,28 +1,28 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.animal.Pufferfish; +import net.minecraft.world.entity.animal.EntityPufferFish; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.PufferFish; public class CraftPufferFish extends CraftFish implements PufferFish { - public CraftPufferFish(CraftServer server, Pufferfish entity) { + public CraftPufferFish(CraftServer server, EntityPufferFish entity) { super(server, entity); } @Override - public Pufferfish getHandle() { - return (Pufferfish) super.getHandle(); + public EntityPufferFish getHandle() { + return (EntityPufferFish) super.getHandle(); } @Override public int getPuffState() { - return this.getHandle().getPuffState(); + return getHandle().getPuffState(); } @Override public void setPuffState(int state) { - this.getHandle().setPuffState(state); + getHandle().setPuffState(state); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java index 6b48b117..5009cc7f 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java @@ -1,32 +1,33 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityRabbit; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Rabbit; import org.bukkit.entity.Rabbit.Type; public class CraftRabbit extends CraftAnimals implements Rabbit { - public CraftRabbit(CraftServer server, net.minecraft.world.entity.animal.Rabbit entity) { + public CraftRabbit(CraftServer server, EntityRabbit entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Rabbit getHandle() { - return (net.minecraft.world.entity.animal.Rabbit) this.entity; + public EntityRabbit getHandle() { + return (EntityRabbit) entity; } @Override public String toString() { - return "CraftRabbit{RabbitType=" + this.getRabbitType() + "}"; + return "CraftRabbit{RabbitType=" + getRabbitType() + "}"; } @Override public Type getRabbitType() { - return Type.values()[this.getHandle().getVariant().ordinal()]; + return Type.values()[getHandle().getVariant().ordinal()]; } @Override public void setRabbitType(Type type) { - this.getHandle().setVariant(net.minecraft.world.entity.animal.Rabbit.Variant.values()[type.ordinal()]); + getHandle().setVariant(EntityRabbit.Variant.values()[type.ordinal()]); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java index 763c368e..2deb3c1e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.raid.EntityRaider; import org.bukkit.Raid; import org.bukkit.Sound; import org.bukkit.block.Block; @@ -12,13 +13,13 @@ public abstract class CraftRaider extends CraftMonster implements Raider { - public CraftRaider(CraftServer server, net.minecraft.world.entity.raid.Raider entity) { + public CraftRaider(CraftServer server, EntityRaider entity) { super(server, entity); } @Override - public net.minecraft.world.entity.raid.Raider getHandle() { - return (net.minecraft.world.entity.raid.Raider) super.getHandle(); + public EntityRaider getHandle() { + return (EntityRaider) super.getHandle(); } @Override @@ -28,83 +29,83 @@ public String toString() { @Override public void setRaid(Raid raid) { - this.getHandle().setCurrentRaid(raid != null ? ((CraftRaid) raid).getHandle() : null); + getHandle().setCurrentRaid(raid != null ? ((CraftRaid) raid).getHandle() : null); } @Override public Raid getRaid() { - return this.getHandle().getCurrentRaid() == null ? null : new CraftRaid(this.getHandle().getCurrentRaid()); + return getHandle().getCurrentRaid() == null ? null : new CraftRaid(getHandle().getCurrentRaid()); } @Override public void setWave(int wave) { Preconditions.checkArgument(wave >= 0, "wave must be >= 0"); - this.getHandle().setWave(wave); + getHandle().setWave(wave); } @Override public int getWave() { - return this.getHandle().getWave(); + return getHandle().getWave(); } @Override public Block getPatrolTarget() { - return this.getHandle().getPatrolTarget() == null ? null : CraftBlock.at(this.getHandle().level(), this.getHandle().getPatrolTarget()); + return getHandle().getPatrolTarget() == null ? null : CraftBlock.at(getHandle().level(), getHandle().getPatrolTarget()); } @Override public void setPatrolTarget(Block block) { if (block == null) { - this.getHandle().setPatrolTarget(null); + getHandle().setPatrolTarget(null); } else { Preconditions.checkArgument(block.getWorld().equals(this.getWorld()), "Block must be in same world"); - this.getHandle().setPatrolTarget(((CraftBlock) block).getPosition()); + getHandle().setPatrolTarget(((CraftBlock) block).getPosition()); } } @Override public boolean isPatrolLeader() { - return this.getHandle().isPatrolLeader(); + return getHandle().isPatrolLeader(); } @Override public void setPatrolLeader(boolean leader) { - this.getHandle().setPatrolLeader(leader); + getHandle().setPatrolLeader(leader); } @Override public boolean isCanJoinRaid() { - return this.getHandle().canJoinRaid(); + return getHandle().canJoinRaid(); } @Override public void setCanJoinRaid(boolean join) { - this.getHandle().setCanJoinRaid(join); + getHandle().setCanJoinRaid(join); } @Override public boolean isCelebrating() { - return this.getHandle().isCelebrating(); + return getHandle().isCelebrating(); } @Override public void setCelebrating(boolean celebrating) { - this.getHandle().setCelebrating(celebrating); + getHandle().setCelebrating(celebrating); } @Override public int getTicksOutsideRaid() { - return this.getHandle().getTicksOutsideRaid(); + return getHandle().getTicksOutsideRaid(); } @Override public void setTicksOutsideRaid(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks must be >= 0"); - this.getHandle().setTicksOutsideRaid(ticks); + getHandle().setTicksOutsideRaid(ticks); } @Override public Sound getCelebrationSound() { - return CraftSound.minecraftToBukkit(this.getHandle().getCelebrateSound()); + return CraftSound.minecraftToBukkit(getHandle().getCelebrateSound()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java index cae59f77..f17f0884 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityRavager; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Ravager; public class CraftRavager extends CraftRaider implements Ravager { - public CraftRavager(CraftServer server, net.minecraft.world.entity.monster.Ravager entity) { + public CraftRavager(CraftServer server, EntityRavager entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Ravager getHandle() { - return (net.minecraft.world.entity.monster.Ravager) super.getHandle(); + public EntityRavager getHandle() { + return (EntityRavager) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java index b8140aa2..171691e1 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java @@ -1,21 +1,35 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; +import net.minecraft.world.entity.animal.EntitySalmon; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Salmon; public class CraftSalmon extends CraftFish implements Salmon { - public CraftSalmon(CraftServer server, net.minecraft.world.entity.animal.Salmon entity) { + public CraftSalmon(CraftServer server, EntitySalmon entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Salmon getHandle() { - return (net.minecraft.world.entity.animal.Salmon) super.getHandle(); + public EntitySalmon getHandle() { + return (EntitySalmon) super.getHandle(); } @Override public String toString() { return "CraftSalmon"; } + + @Override + public Variant getVariant() { + return Variant.values()[getHandle().getVariant().ordinal()]; + } + + @Override + public void setVariant(Variant variant) { + Preconditions.checkArgument(variant != null, "variant"); + + getHandle().setVariant(EntitySalmon.a.values()[variant.ordinal()]); + } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java index 030bf7b6..a498b9c6 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java @@ -1,37 +1,39 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntitySheep; +import net.minecraft.world.item.EnumColor; import org.bukkit.DyeColor; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Sheep; public class CraftSheep extends CraftAnimals implements Sheep { - public CraftSheep(CraftServer server, net.minecraft.world.entity.animal.Sheep entity) { + public CraftSheep(CraftServer server, EntitySheep entity) { super(server, entity); } @Override public DyeColor getColor() { - return DyeColor.getByWoolData((byte) this.getHandle().getColor().getId()); + return DyeColor.getByWoolData((byte) getHandle().getColor().getId()); } @Override public void setColor(DyeColor color) { - this.getHandle().setColor(net.minecraft.world.item.DyeColor.byId(color.getWoolData())); + getHandle().setColor(EnumColor.byId(color.getWoolData())); } @Override public boolean isSheared() { - return this.getHandle().isSheared(); + return getHandle().isSheared(); } @Override public void setSheared(boolean flag) { - this.getHandle().setSheared(flag); + getHandle().setSheared(flag); } @Override - public net.minecraft.world.entity.animal.Sheep getHandle() { - return (net.minecraft.world.entity.animal.Sheep) this.entity; + public EntitySheep getHandle() { + return (EntitySheep) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java index 05ec06b7..7c89d088 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.monster.EntityShulker; import org.bukkit.DyeColor; import org.bukkit.block.BlockFace; import org.bukkit.craftbukkit.CraftServer; @@ -9,7 +10,7 @@ public class CraftShulker extends CraftGolem implements Shulker, CraftEnemy { - public CraftShulker(CraftServer server, net.minecraft.world.entity.monster.Shulker entity) { + public CraftShulker(CraftServer server, EntityShulker entity) { super(server, entity); } @@ -19,40 +20,40 @@ public String toString() { } @Override - public net.minecraft.world.entity.monster.Shulker getHandle() { - return (net.minecraft.world.entity.monster.Shulker) this.entity; + public EntityShulker getHandle() { + return (EntityShulker) entity; } @Override public DyeColor getColor() { - return DyeColor.getByWoolData(this.getHandle().getEntityData().get(net.minecraft.world.entity.monster.Shulker.DATA_COLOR_ID)); + return DyeColor.getByWoolData(getHandle().getEntityData().get(EntityShulker.DATA_COLOR_ID)); } @Override public void setColor(DyeColor color) { - this.getHandle().getEntityData().set(net.minecraft.world.entity.monster.Shulker.DATA_COLOR_ID, (color == null) ? 16 : color.getWoolData()); + getHandle().getEntityData().set(EntityShulker.DATA_COLOR_ID, (color == null) ? 16 : color.getWoolData()); } @Override public float getPeek() { - return (float) this.getHandle().getRawPeekAmount() / 100; + return (float) getHandle().getRawPeekAmount() / 100; } @Override public void setPeek(float value) { Preconditions.checkArgument(value >= 0 && value <= 1, "value needs to be in between or equal to 0 and 1"); - this.getHandle().setRawPeekAmount((int) (value * 100)); + getHandle().setRawPeekAmount((int) (value * 100)); } @Override public BlockFace getAttachedFace() { - return CraftBlock.notchToBlockFace(this.getHandle().getAttachFace()); + return CraftBlock.notchToBlockFace(getHandle().getAttachFace()); } @Override public void setAttachedFace(BlockFace face) { Preconditions.checkNotNull(face, "face cannot be null"); Preconditions.checkArgument(face.isCartesian(), "%s is not a valid block face to attach a shulker to, a cartesian block face is expected", face); - this.getHandle().setAttachFace(CraftBlock.blockFaceToNotch(face)); + getHandle().setAttachFace(CraftBlock.blockFaceToNotch(face)); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java index d685d09c..ab21af41 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.projectile.EntityShulkerBullet; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Entity; import org.bukkit.entity.ShulkerBullet; @@ -8,35 +9,35 @@ public class CraftShulkerBullet extends AbstractProjectile implements ShulkerBullet { - public CraftShulkerBullet(CraftServer server, net.minecraft.world.entity.projectile.ShulkerBullet entity) { + public CraftShulkerBullet(CraftServer server, EntityShulkerBullet entity) { super(server, entity); } @Override public ProjectileSource getShooter() { - return this.getHandle().projectileSource; + return getHandle().projectileSource; } @Override public void setShooter(ProjectileSource shooter) { if (shooter instanceof Entity) { - this.getHandle().setOwner(((CraftEntity) shooter).getHandle()); + getHandle().setOwner(((CraftEntity) shooter).getHandle()); } else { - this.getHandle().setOwner(null); + getHandle().setOwner(null); } - this.getHandle().projectileSource = shooter; + getHandle().projectileSource = shooter; } @Override public org.bukkit.entity.Entity getTarget() { - return this.getHandle().getTarget() != null ? this.getHandle().getTarget().getBukkitEntity() : null; + return getHandle().getTarget() != null ? getHandle().getTarget().getBukkitEntity() : null; } @Override public void setTarget(org.bukkit.entity.Entity target) { - Preconditions.checkState(!this.getHandle().generation, "Cannot set target during world generation"); + Preconditions.checkState(!getHandle().generation, "Cannot set target during world generation"); - this.getHandle().setTarget(target == null ? null : ((CraftEntity) target).getHandle()); + getHandle().setTarget(target == null ? null : ((CraftEntity) target).getHandle()); } @Override @@ -45,7 +46,7 @@ public String toString() { } @Override - public net.minecraft.world.entity.projectile.ShulkerBullet getHandle() { - return (net.minecraft.world.entity.projectile.ShulkerBullet) this.entity; + public EntityShulkerBullet getHandle() { + return (EntityShulkerBullet) entity; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java index 7c75d78e..aaed9aa2 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntitySilverfish; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Silverfish; public class CraftSilverfish extends CraftMonster implements Silverfish { - public CraftSilverfish(CraftServer server, net.minecraft.world.entity.monster.Silverfish entity) { + public CraftSilverfish(CraftServer server, EntitySilverfish entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Silverfish getHandle() { - return (net.minecraft.world.entity.monster.Silverfish) this.entity; + public EntitySilverfish getHandle() { + return (EntitySilverfish) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSizedFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSizedFireball.java index de332781..4c7627b1 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSizedFireball.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSizedFireball.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.projectile.Fireball; +import net.minecraft.world.entity.projectile.EntityFireballFireball; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; @@ -9,26 +9,26 @@ public class CraftSizedFireball extends CraftFireball implements SizedFireball { - public CraftSizedFireball(CraftServer server, Fireball entity) { + public CraftSizedFireball(CraftServer server, EntityFireballFireball entity) { super(server, entity); } @Override public ItemStack getDisplayItem() { - if (this.getHandle().getItem().isEmpty()) { + if (getHandle().getItem().isEmpty()) { return new ItemStack(Material.FIRE_CHARGE); } else { - return CraftItemStack.asBukkitCopy(this.getHandle().getItem()); + return CraftItemStack.asBukkitCopy(getHandle().getItem()); } } @Override public void setDisplayItem(ItemStack item) { - this.getHandle().setItem(CraftItemStack.asNMSCopy(item)); + getHandle().setItem(CraftItemStack.asNMSCopy(item)); } @Override - public Fireball getHandle() { - return (Fireball) this.entity; + public EntityFireballFireball getHandle() { + return (EntityFireballFireball) entity; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java index a0ea5418..09de7114 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.monster.EntitySkeleton; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Skeleton; public class CraftSkeleton extends CraftAbstractSkeleton implements Skeleton { - public CraftSkeleton(CraftServer server, net.minecraft.world.entity.monster.Skeleton entity) { + public CraftSkeleton(CraftServer server, EntitySkeleton entity) { super(server, entity); } @@ -25,15 +26,15 @@ public int getConversionTime() { public void setConversionTime(int time) { if (time < 0) { this.getHandle().conversionTime = -1; - this.getHandle().getEntityData().set(net.minecraft.world.entity.monster.Skeleton.DATA_STRAY_CONVERSION_ID, false); + this.getHandle().getEntityData().set(EntitySkeleton.DATA_STRAY_CONVERSION_ID, false); } else { this.getHandle().startFreezeConversion(time); } } @Override - public net.minecraft.world.entity.monster.Skeleton getHandle() { - return (net.minecraft.world.entity.monster.Skeleton) this.entity; + public EntitySkeleton getHandle() { + return (EntitySkeleton) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java index 248e4feb..b24e24b4 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.horse.EntityHorseSkeleton; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Horse.Variant; import org.bukkit.entity.SkeletonHorse; public class CraftSkeletonHorse extends CraftAbstractHorse implements SkeletonHorse { - public CraftSkeletonHorse(CraftServer server, net.minecraft.world.entity.animal.horse.SkeletonHorse entity) { + public CraftSkeletonHorse(CraftServer server, EntityHorseSkeleton entity) { super(server, entity); } @@ -21,27 +22,27 @@ public Variant getVariant() { } @Override - public net.minecraft.world.entity.animal.horse.SkeletonHorse getHandle() { - return (net.minecraft.world.entity.animal.horse.SkeletonHorse) this.entity; + public EntityHorseSkeleton getHandle() { + return (EntityHorseSkeleton) entity; } @Override public boolean isTrapped() { - return this.getHandle().isTrap(); + return getHandle().isTrap(); } @Override public void setTrapped(boolean trapped) { - this.getHandle().setTrap(trapped); + getHandle().setTrap(trapped); } @Override public int getTrapTime() { - return this.getHandle().trapTime; + return getHandle().trapTime; } @Override public void setTrapTime(int trapTime) { - this.getHandle().trapTime = trapTime; + getHandle().trapTime = trapTime; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java index 3d991d9d..75097983 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java @@ -1,27 +1,28 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntitySlime; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Slime; public class CraftSlime extends CraftMob implements Slime, CraftEnemy { - public CraftSlime(CraftServer server, net.minecraft.world.entity.monster.Slime entity) { + public CraftSlime(CraftServer server, EntitySlime entity) { super(server, entity); } @Override public int getSize() { - return this.getHandle().getSize(); + return getHandle().getSize(); } @Override public void setSize(int size) { - this.getHandle().setSize(size, true); + getHandle().setSize(size, true); } @Override - public net.minecraft.world.entity.monster.Slime getHandle() { - return (net.minecraft.world.entity.monster.Slime) this.entity; + public EntitySlime getHandle() { + return (EntitySlime) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java index 072df206..24083c8b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntitySmallFireball; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.SmallFireball; public class CraftSmallFireball extends CraftSizedFireball implements SmallFireball { - public CraftSmallFireball(CraftServer server, net.minecraft.world.entity.projectile.SmallFireball entity) { + public CraftSmallFireball(CraftServer server, EntitySmallFireball entity) { super(server, entity); } @Override - public net.minecraft.world.entity.projectile.SmallFireball getHandle() { - return (net.minecraft.world.entity.projectile.SmallFireball) this.entity; + public EntitySmallFireball getHandle() { + return (EntitySmallFireball) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSniffer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSniffer.java index 60251107..3f544e9a 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSniffer.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSniffer.java @@ -34,22 +34,22 @@ public Collection getExploredLocations() { @Override public void removeExploredLocation(Location location) { Preconditions.checkArgument(location != null, "location cannot be null"); - if (location.getWorld() != this.getWorld()) { + if (location.getWorld() != getWorld()) { return; } - BlockPos blockPosition = CraftLocation.toBlockPosition(location); + BlockPos blockPosition = CraftLocation.toBlockPos(location); this.getHandle().getBrain().setMemory(MemoryModuleType.SNIFFER_EXPLORED_POSITIONS, this.getHandle().getExploredPositions().filter(blockPositionExplored -> !blockPositionExplored.equals(blockPosition)).collect(Collectors.toList())); } @Override public void addExploredLocation(Location location) { Preconditions.checkArgument(location != null, "location cannot be null"); - if (location.getWorld() != this.getWorld()) { + if (location.getWorld() != getWorld()) { return; } - this.getHandle().storeExploredPosition(CraftLocation.toBlockPosition(location)); + this.getHandle().storeExploredPosition(CraftLocation.toBlockPos(location)); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java index d959825f..32447e2e 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntitySnowball; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Snowball; public class CraftSnowball extends CraftThrowableProjectile implements Snowball { - public CraftSnowball(CraftServer server, net.minecraft.world.entity.projectile.Snowball entity) { + public CraftSnowball(CraftServer server, EntitySnowball entity) { super(server, entity); } @Override - public net.minecraft.world.entity.projectile.Snowball getHandle() { - return (net.minecraft.world.entity.projectile.Snowball) this.entity; + public EntitySnowball getHandle() { + return (EntitySnowball) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java index 1f373896..b00b0a72 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java @@ -1,27 +1,27 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.animal.SnowGolem; +import net.minecraft.world.entity.animal.EntitySnowman; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Snowman; public class CraftSnowman extends CraftGolem implements Snowman { - public CraftSnowman(CraftServer server, SnowGolem entity) { + public CraftSnowman(CraftServer server, EntitySnowman entity) { super(server, entity); } @Override public boolean isDerp() { - return !this.getHandle().hasPumpkin(); + return !getHandle().hasPumpkin(); } @Override public void setDerp(boolean derpMode) { - this.getHandle().setPumpkin(!derpMode); + getHandle().setPumpkin(!derpMode); } @Override - public SnowGolem getHandle() { - return (SnowGolem) this.entity; + public EntitySnowman getHandle() { + return (EntitySnowman) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java index 70f1f874..d30553b6 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntitySpectralArrow; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.SpectralArrow; public class CraftSpectralArrow extends CraftAbstractArrow implements SpectralArrow { - public CraftSpectralArrow(CraftServer server, net.minecraft.world.entity.projectile.SpectralArrow entity) { + public CraftSpectralArrow(CraftServer server, EntitySpectralArrow entity) { super(server, entity); } @Override - public net.minecraft.world.entity.projectile.SpectralArrow getHandle() { - return (net.minecraft.world.entity.projectile.SpectralArrow) this.entity; + public EntitySpectralArrow getHandle() { + return (EntitySpectralArrow) entity; } @Override @@ -21,11 +22,11 @@ public String toString() { @Override public int getGlowingTicks() { - return this.getHandle().duration; + return getHandle().duration; } @Override public void setGlowingTicks(int duration) { - this.getHandle().duration = duration; + getHandle().duration = duration; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java index 525827f1..83eb3ff0 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java @@ -1,20 +1,20 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.monster.SpellcasterIllager; +import net.minecraft.world.entity.monster.EntityIllagerWizard; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Spellcaster; import org.bukkit.entity.Spellcaster.Spell; public class CraftSpellcaster extends CraftIllager implements Spellcaster { - public CraftSpellcaster(CraftServer server, SpellcasterIllager entity) { + public CraftSpellcaster(CraftServer server, EntityIllagerWizard entity) { super(server, entity); } @Override - public SpellcasterIllager getHandle() { - return (SpellcasterIllager) super.getHandle(); + public EntityIllagerWizard getHandle() { + return (EntityIllagerWizard) super.getHandle(); } @Override @@ -24,21 +24,21 @@ public String toString() { @Override public Spell getSpell() { - return CraftSpellcaster.toBukkitSpell(this.getHandle().getCurrentSpell()); + return toBukkitSpell(getHandle().getCurrentSpell()); } @Override public void setSpell(Spell spell) { Preconditions.checkArgument(spell != null, "Use Spell.NONE"); - this.getHandle().setIsCastingSpell(CraftSpellcaster.toNMSSpell(spell)); + getHandle().setIsCastingSpell(toNMSSpell(spell)); } - public static Spell toBukkitSpell(SpellcasterIllager.IllagerSpell spell) { + public static Spell toBukkitSpell(EntityIllagerWizard.Spell spell) { return Spell.valueOf(spell.name()); } - public static SpellcasterIllager.IllagerSpell toNMSSpell(Spell spell) { - return SpellcasterIllager.IllagerSpell.byId(spell.ordinal()); + public static EntityIllagerWizard.Spell toNMSSpell(Spell spell) { + return EntityIllagerWizard.Spell.byId(spell.ordinal()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java index b4afc37c..6e1876e9 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntitySpider; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Spider; public class CraftSpider extends CraftMonster implements Spider { - public CraftSpider(CraftServer server, net.minecraft.world.entity.monster.Spider entity) { + public CraftSpider(CraftServer server, EntitySpider entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Spider getHandle() { - return (net.minecraft.world.entity.monster.Spider) this.entity; + public EntitySpider getHandle() { + return (EntitySpider) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java index a6e3b61c..25df325d 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntitySquid; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Squid; -public class CraftSquid extends CraftWaterMob implements Squid { +public class CraftSquid extends CraftAgeable implements Squid { - public CraftSquid(CraftServer server, net.minecraft.world.entity.animal.Squid entity) { + public CraftSquid(CraftServer server, EntitySquid entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Squid getHandle() { - return (net.minecraft.world.entity.animal.Squid) this.entity; + public EntitySquid getHandle() { + return (EntitySquid) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java index 83329052..335f3f10 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntitySkeletonStray; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.entity.Stray; public class CraftStray extends CraftAbstractSkeleton implements Stray { - public CraftStray(CraftServer server, net.minecraft.world.entity.monster.Stray entity) { + public CraftStray(CraftServer server, EntitySkeletonStray entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftStrider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftStrider.java index 9472a6f9..d57b6a97 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftStrider.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftStrider.java @@ -1,19 +1,20 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; +import net.minecraft.world.entity.monster.EntityStrider; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Strider; public class CraftStrider extends CraftAnimals implements Strider { - public CraftStrider(CraftServer server, net.minecraft.world.entity.monster.Strider entity) { + public CraftStrider(CraftServer server, EntityStrider entity) { super(server, entity); } @Override public boolean isShivering() { - return this.getHandle().isSuffocating(); + return getHandle().isSuffocating(); } @Override @@ -23,38 +24,38 @@ public void setShivering(boolean shivering) { @Override public boolean hasSaddle() { - return this.getHandle().isSaddled(); + return getHandle().isSaddled(); } @Override public void setSaddle(boolean saddled) { - this.getHandle().steering.setSaddle(saddled); + getHandle().steering.setSaddle(saddled); } @Override public int getBoostTicks() { - return this.getHandle().steering.boosting ? this.getHandle().steering.boostTimeTotal() : 0; + return getHandle().steering.boosting ? getHandle().steering.boostTimeTotal() : 0; } @Override public void setBoostTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks must be >= 0"); - this.getHandle().steering.setBoostTicks(ticks); + getHandle().steering.setBoostTicks(ticks); } @Override public int getCurrentBoostTicks() { - return this.getHandle().steering.boosting ? this.getHandle().steering.boostTime : 0; + return getHandle().steering.boosting ? getHandle().steering.boostTime : 0; } @Override public void setCurrentBoostTicks(int ticks) { - if (!this.getHandle().steering.boosting) { + if (!getHandle().steering.boosting) { return; } - int max = this.getHandle().steering.boostTimeTotal(); + int max = getHandle().steering.boostTimeTotal(); Preconditions.checkArgument(ticks >= 0 && ticks <= max, "boost ticks must not exceed 0 or %d (inclusive)", max); this.getHandle().steering.boostTime = ticks; @@ -66,8 +67,8 @@ public Material getSteerMaterial() { } @Override - public net.minecraft.world.entity.monster.Strider getHandle() { - return (net.minecraft.world.entity.monster.Strider) this.entity; + public EntityStrider getHandle() { + return (EntityStrider) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java index 3f32c683..872642b2 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java @@ -1,6 +1,7 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.item.EntityTNTPrimed; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -8,43 +9,43 @@ public class CraftTNTPrimed extends CraftEntity implements TNTPrimed { - public CraftTNTPrimed(CraftServer server, PrimedTnt entity) { + public CraftTNTPrimed(CraftServer server, EntityTNTPrimed entity) { super(server, entity); } @Override public float getYield() { - return this.getHandle().yield; + return getHandle().explosionPower; } @Override public boolean isIncendiary() { - return this.getHandle().isIncendiary; + return getHandle().isIncendiary; } @Override public void setIsIncendiary(boolean isIncendiary) { - this.getHandle().isIncendiary = isIncendiary; + getHandle().isIncendiary = isIncendiary; } @Override public void setYield(float yield) { - this.getHandle().yield = yield; + getHandle().explosionPower = yield; } @Override public int getFuseTicks() { - return this.getHandle().getFuse(); + return getHandle().getFuse(); } @Override public void setFuseTicks(int fuseTicks) { - this.getHandle().setFuse(fuseTicks); + getHandle().setFuse(fuseTicks); } @Override - public PrimedTnt getHandle() { - return (PrimedTnt) this.entity; + public EntityTNTPrimed getHandle() { + return (EntityTNTPrimed) entity; } @Override @@ -54,7 +55,7 @@ public String toString() { @Override public Entity getSource() { - net.minecraft.world.entity.LivingEntity source = this.getHandle().getOwner(); + EntityLiving source = getHandle().getOwner(); return (source != null) ? source.getBukkitEntity() : null; } @@ -62,9 +63,9 @@ public Entity getSource() { @Override public void setSource(Entity source) { if (source instanceof LivingEntity) { - this.getHandle().owner = ((CraftLivingEntity) source).getHandle(); + getHandle().owner = ((CraftLivingEntity) source).getHandle(); } else { - this.getHandle().owner = null; + getHandle().owner = null; } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTadpole.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTadpole.java index 451a9bfd..c4f11770 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTadpole.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTadpole.java @@ -11,7 +11,7 @@ public CraftTadpole(CraftServer server, Tadpole entity) { @Override public Tadpole getHandle() { - return (Tadpole) this.entity; + return (Tadpole) entity; } @Override @@ -21,11 +21,11 @@ public String toString() { @Override public int getAge() { - return this.getHandle().age; + return getHandle().age; } @Override public void setAge(int age) { - this.getHandle().age = age; + getHandle().age = age; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java index 3d19a077..dc4466f3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java @@ -1,43 +1,43 @@ package org.bukkit.craftbukkit.entity; import java.util.UUID; -import net.minecraft.world.entity.TamableAnimal; +import net.minecraft.world.entity.EntityTameableAnimal; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Creature; import org.bukkit.entity.Tameable; public class CraftTameableAnimal extends CraftAnimals implements Tameable, Creature { - public CraftTameableAnimal(CraftServer server, TamableAnimal entity) { + public CraftTameableAnimal(CraftServer server, EntityTameableAnimal entity) { super(server, entity); } @Override - public TamableAnimal getHandle() { - return (TamableAnimal) super.getHandle(); + public EntityTameableAnimal getHandle() { + return (EntityTameableAnimal) super.getHandle(); } public UUID getOwnerUUID() { try { - return this.getHandle().getOwnerUUID(); + return getHandle().getOwnerUUID(); } catch (IllegalArgumentException ex) { return null; } } public void setOwnerUUID(UUID uuid) { - this.getHandle().setOwnerUUID(uuid); + getHandle().setOwnerUUID(uuid); } @Override public AnimalTamer getOwner() { - if (this.getOwnerUUID() == null) { + if (getOwnerUUID() == null) { return null; } - AnimalTamer owner = this.getServer().getPlayer(this.getOwnerUUID()); + AnimalTamer owner = getServer().getPlayer(getOwnerUUID()); if (owner == null) { - owner = this.getServer().getOfflinePlayer(this.getOwnerUUID()); + owner = getServer().getOfflinePlayer(getOwnerUUID()); } return owner; @@ -45,40 +45,40 @@ public AnimalTamer getOwner() { @Override public boolean isTamed() { - return this.getHandle().isTame(); + return getHandle().isTame(); } @Override public void setOwner(AnimalTamer tamer) { if (tamer != null) { - this.setTamed(true); - this.getHandle().setTarget(null, null, false); - this.setOwnerUUID(tamer.getUniqueId()); + setTamed(true); + getHandle().setTarget(null, null, false); + setOwnerUUID(tamer.getUniqueId()); } else { - this.setTamed(false); - this.setOwnerUUID(null); + setTamed(false); + setOwnerUUID(null); } } @Override public void setTamed(boolean tame) { - this.getHandle().setTame(tame, true); + getHandle().setTame(tame, true); if (!tame) { - this.setOwnerUUID(null); + setOwnerUUID(null); } } public boolean isSitting() { - return this.getHandle().isInSittingPose(); + return getHandle().isInSittingPose(); } public void setSitting(boolean sitting) { - this.getHandle().setInSittingPose(sitting); - this.getHandle().setOrderedToSit(sitting); + getHandle().setInSittingPose(sitting); + getHandle().setOrderedToSit(sitting); } @Override public String toString() { - return this.getClass().getSimpleName() + "{owner=" + this.getOwner() + ",tamed=" + this.isTamed() + "}"; + return getClass().getSimpleName() + "{owner=" + getOwner() + ",tamed=" + isTamed() + "}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java index 5725b028..a1d8c2c5 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java @@ -25,27 +25,27 @@ public String toString() { @Override public String getText() { - return CraftChatMessage.fromComponent(this.getHandle().getText()); + return CraftChatMessage.fromComponent(getHandle().getText()); } @Override public void setText(String text) { - this.getHandle().setText(CraftChatMessage.fromString(text, true)[0]); + getHandle().setText(CraftChatMessage.fromString(text, true)[0]); } @Override public int getLineWidth() { - return this.getHandle().getLineWidth(); + return getHandle().getLineWidth(); } @Override public void setLineWidth(int width) { - this.getHandle().getEntityData().set(Display.TextDisplay.DATA_LINE_WIDTH_ID, width); + getHandle().getEntityData().set(Display.TextDisplay.DATA_LINE_WIDTH_ID, width); } @Override public Color getBackgroundColor() { - int color = this.getHandle().getBackgroundColor(); + int color = getHandle().getBackgroundColor(); return (color == -1) ? null : Color.fromARGB(color); } @@ -53,55 +53,55 @@ public Color getBackgroundColor() { @Override public void setBackgroundColor(Color color) { if (color == null) { - this.getHandle().getEntityData().set(Display.TextDisplay.DATA_BACKGROUND_COLOR_ID, -1); + getHandle().getEntityData().set(Display.TextDisplay.DATA_BACKGROUND_COLOR_ID, -1); } else { - this.getHandle().getEntityData().set(Display.TextDisplay.DATA_BACKGROUND_COLOR_ID, color.asARGB()); + getHandle().getEntityData().set(Display.TextDisplay.DATA_BACKGROUND_COLOR_ID, color.asARGB()); } } @Override public byte getTextOpacity() { - return this.getHandle().getTextOpacity(); + return getHandle().getTextOpacity(); } @Override public void setTextOpacity(byte opacity) { - this.getHandle().setTextOpacity(opacity); + getHandle().setTextOpacity(opacity); } @Override public boolean isShadowed() { - return this.getFlag(Display.TextDisplay.FLAG_SHADOW); + return getFlag(Display.TextDisplay.FLAG_SHADOW); } @Override public void setShadowed(boolean shadow) { - this.setFlag(Display.TextDisplay.FLAG_SHADOW, shadow); + setFlag(Display.TextDisplay.FLAG_SHADOW, shadow); } @Override public boolean isSeeThrough() { - return this.getFlag(Display.TextDisplay.FLAG_SEE_THROUGH); + return getFlag(Display.TextDisplay.FLAG_SEE_THROUGH); } @Override public void setSeeThrough(boolean seeThrough) { - this.setFlag(Display.TextDisplay.FLAG_SEE_THROUGH, seeThrough); + setFlag(Display.TextDisplay.FLAG_SEE_THROUGH, seeThrough); } @Override public boolean isDefaultBackground() { - return this.getFlag(Display.TextDisplay.FLAG_USE_DEFAULT_BACKGROUND); + return getFlag(Display.TextDisplay.FLAG_USE_DEFAULT_BACKGROUND); } @Override public void setDefaultBackground(boolean defaultBackground) { - this.setFlag(Display.TextDisplay.FLAG_USE_DEFAULT_BACKGROUND, defaultBackground); + setFlag(Display.TextDisplay.FLAG_USE_DEFAULT_BACKGROUND, defaultBackground); } @Override public TextAlignment getAlignment() { - Display.TextDisplay.Align nms = Display.TextDisplay.getAlign(this.getHandle().getFlags()); + Display.TextDisplay.Align nms = Display.TextDisplay.getAlign(getHandle().getFlags()); return TextAlignment.valueOf(nms.name()); } @@ -111,16 +111,16 @@ public void setAlignment(TextAlignment alignment) { switch (alignment) { case LEFT: - this.setFlag(Display.TextDisplay.FLAG_ALIGN_LEFT, true); - this.setFlag(Display.TextDisplay.FLAG_ALIGN_RIGHT, false); + setFlag(Display.TextDisplay.FLAG_ALIGN_LEFT, true); + setFlag(Display.TextDisplay.FLAG_ALIGN_RIGHT, false); break; case RIGHT: - this.setFlag(Display.TextDisplay.FLAG_ALIGN_LEFT, false); - this.setFlag(Display.TextDisplay.FLAG_ALIGN_RIGHT, true); + setFlag(Display.TextDisplay.FLAG_ALIGN_LEFT, false); + setFlag(Display.TextDisplay.FLAG_ALIGN_RIGHT, true); break; case CENTER: - this.setFlag(Display.TextDisplay.FLAG_ALIGN_LEFT, false); - this.setFlag(Display.TextDisplay.FLAG_ALIGN_RIGHT, false); + setFlag(Display.TextDisplay.FLAG_ALIGN_LEFT, false); + setFlag(Display.TextDisplay.FLAG_ALIGN_RIGHT, false); break; default: throw new IllegalArgumentException("Unknown alignment " + alignment); @@ -128,11 +128,11 @@ public void setAlignment(TextAlignment alignment) { } private boolean getFlag(int flag) { - return (this.getHandle().getFlags() & flag) != 0; + return (getHandle().getFlags() & flag) != 0; } private void setFlag(int flag, boolean set) { - byte flagBits = this.getHandle().getFlags(); + byte flagBits = getHandle().getFlags(); if (set) { flagBits |= flag; @@ -140,6 +140,6 @@ private void setFlag(int flag, boolean set) { flagBits &= ~flag; } - this.getHandle().setFlags(flagBits); + getHandle().setFlags(flagBits); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrowableProjectile.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrowableProjectile.java index bf7b111a..e56754a3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrowableProjectile.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrowableProjectile.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.projectile.ThrowableItemProjectile; +import net.minecraft.world.entity.projectile.EntityProjectileThrowable; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.entity.ThrowableProjectile; @@ -8,26 +8,26 @@ public abstract class CraftThrowableProjectile extends CraftProjectile implements ThrowableProjectile { - public CraftThrowableProjectile(CraftServer server, ThrowableItemProjectile entity) { + public CraftThrowableProjectile(CraftServer server, EntityProjectileThrowable entity) { super(server, entity); } @Override public ItemStack getItem() { - if (this.getHandle().getItem().isEmpty()) { - return CraftItemStack.asBukkitCopy(new net.minecraft.world.item.ItemStack(this.getHandle().getDefaultItemPublic())); + if (getHandle().getItem().isEmpty()) { + return CraftItemStack.asBukkitCopy(new net.minecraft.world.item.ItemStack(getHandle().getDefaultItemPublic())); } else { - return CraftItemStack.asBukkitCopy(this.getHandle().getItem()); + return CraftItemStack.asBukkitCopy(getHandle().getItem()); } } @Override public void setItem(ItemStack item) { - this.getHandle().setItem(CraftItemStack.asNMSCopy(item)); + getHandle().setItem(CraftItemStack.asNMSCopy(item)); } @Override - public ThrowableItemProjectile getHandle() { - return (ThrowableItemProjectile) this.entity; + public EntityProjectileThrowable getHandle() { + return (EntityProjectileThrowable) entity; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java index 5e7fef66..884ca109 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java @@ -1,17 +1,17 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.projectile.ThrownExperienceBottle; +import net.minecraft.world.entity.projectile.EntityThrownExpBottle; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.ThrownExpBottle; public class CraftThrownExpBottle extends CraftThrowableProjectile implements ThrownExpBottle { - public CraftThrownExpBottle(CraftServer server, ThrownExperienceBottle entity) { + public CraftThrownExpBottle(CraftServer server, EntityThrownExpBottle entity) { super(server, entity); } @Override - public ThrownExperienceBottle getHandle() { - return (ThrownExperienceBottle) this.entity; + public EntityThrownExpBottle getHandle() { + return (EntityThrownExpBottle) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java index d67a8016..868b3de9 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java @@ -4,7 +4,8 @@ import com.google.common.collect.ImmutableList; import java.util.Collection; import net.minecraft.core.component.DataComponents; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.entity.projectile.EntityPotion; import net.minecraft.world.item.alchemy.PotionContents; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; @@ -15,14 +16,14 @@ import org.bukkit.potion.PotionEffect; public class CraftThrownPotion extends CraftThrowableProjectile implements ThrownPotion { - public CraftThrownPotion(CraftServer server, net.minecraft.world.entity.projectile.ThrownPotion entity) { + public CraftThrownPotion(CraftServer server, EntityPotion entity) { super(server, entity); } @Override public Collection getEffects() { ImmutableList.Builder builder = ImmutableList.builder(); - for (MobEffectInstance effect : this.getHandle().getItem().getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).getAllEffects()) { + for (MobEffect effect : getHandle().getItem().getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).getAllEffects()) { builder.add(CraftPotionUtil.toBukkit(effect)); } return builder.build(); @@ -30,7 +31,7 @@ public Collection getEffects() { @Override public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getHandle().getItem()); + return CraftItemStack.asBukkitCopy(getHandle().getItem()); } @Override @@ -38,11 +39,11 @@ public void setItem(ItemStack item) { Preconditions.checkArgument(item != null, "ItemStack cannot be null"); Preconditions.checkArgument(item.getType() == Material.LINGERING_POTION || item.getType() == Material.SPLASH_POTION, "ItemStack material must be Material.LINGERING_POTION or Material.SPLASH_POTION but was Material.%s", item.getType()); - this.getHandle().setItem(CraftItemStack.asNMSCopy(item)); + getHandle().setItem(CraftItemStack.asNMSCopy(item)); } @Override - public net.minecraft.world.entity.projectile.ThrownPotion getHandle() { - return (net.minecraft.world.entity.projectile.ThrownPotion) this.entity; + public EntityPotion getHandle() { + return (EntityPotion) entity; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java index 4b3a7641..129d6318 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.horse.EntityLlamaTrader; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.TraderLlama; public class CraftTraderLlama extends CraftLlama implements TraderLlama { - public CraftTraderLlama(CraftServer server, net.minecraft.world.entity.animal.horse.TraderLlama entity) { + public CraftTraderLlama(CraftServer server, EntityLlamaTrader entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.horse.TraderLlama getHandle() { - return (net.minecraft.world.entity.animal.horse.TraderLlama) super.getHandle(); + public EntityLlamaTrader getHandle() { + return (EntityLlamaTrader) super.getHandle(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java index 33d6e812..dd0c3f76 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.projectile.ThrownTrident; +import net.minecraft.world.entity.projectile.EntityThrownTrident; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.entity.Trident; @@ -8,23 +8,23 @@ public class CraftTrident extends CraftAbstractArrow implements Trident { - public CraftTrident(CraftServer server, ThrownTrident entity) { + public CraftTrident(CraftServer server, EntityThrownTrident entity) { super(server, entity); } @Override - public ThrownTrident getHandle() { - return (ThrownTrident) super.getHandle(); + public EntityThrownTrident getHandle() { + return (EntityThrownTrident) super.getHandle(); } @Override public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(this.getHandle().pickupItemStack); + return CraftItemStack.asBukkitCopy(getHandle().pickupItemStack); } @Override public void setItem(ItemStack itemStack) { - this.getHandle().pickupItemStack = CraftItemStack.asNMSCopy(itemStack); + getHandle().pickupItemStack = CraftItemStack.asNMSCopy(itemStack); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java index e3bde6d1..60b16c5a 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java @@ -2,6 +2,7 @@ import java.util.HashMap; import java.util.Map; +import net.minecraft.world.entity.animal.EntityTropicalFish; import org.bukkit.DyeColor; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.TropicalFish; @@ -9,13 +10,13 @@ public class CraftTropicalFish extends CraftFish implements TropicalFish { - public CraftTropicalFish(CraftServer server, net.minecraft.world.entity.animal.TropicalFish entity) { + public CraftTropicalFish(CraftServer server, EntityTropicalFish entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.TropicalFish getHandle() { - return (net.minecraft.world.entity.animal.TropicalFish) this.entity; + public EntityTropicalFish getHandle() { + return (EntityTropicalFish) entity; } @Override @@ -25,32 +26,32 @@ public String toString() { @Override public DyeColor getPatternColor() { - return CraftTropicalFish.getPatternColor(this.getHandle().getPackedVariant()); + return getPatternColor(getHandle().getPackedVariant()); } @Override public void setPatternColor(DyeColor color) { - this.getHandle().setPackedVariant(CraftTropicalFish.getData(color, this.getBodyColor(), this.getPattern())); + getHandle().setPackedVariant(getData(color, getBodyColor(), getPattern())); } @Override public DyeColor getBodyColor() { - return CraftTropicalFish.getBodyColor(this.getHandle().getPackedVariant()); + return getBodyColor(getHandle().getPackedVariant()); } @Override public void setBodyColor(DyeColor color) { - this.getHandle().setPackedVariant(CraftTropicalFish.getData(this.getPatternColor(), color, this.getPattern())); + getHandle().setPackedVariant(getData(getPatternColor(), color, getPattern())); } @Override public Pattern getPattern() { - return CraftTropicalFish.getPattern(this.getHandle().getPackedVariant()); + return getPattern(getHandle().getPackedVariant()); } @Override public void setPattern(Pattern pattern) { - this.getHandle().setPackedVariant(CraftTropicalFish.getData(this.getPatternColor(), this.getBodyColor(), pattern)); + getHandle().setPackedVariant(getData(getPatternColor(), getBodyColor(), pattern)); } public static enum CraftPattern { @@ -89,7 +90,7 @@ private CraftPattern(int variant, boolean large) { } public int getDataValue() { - return this.variant << 8 | ((this.large) ? 1 : 0); + return variant << 8 | ((large) ? 1 : 0); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java index fac0317f..789e83db 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.EntityTurtle; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Turtle; public class CraftTurtle extends CraftAnimals implements Turtle { - public CraftTurtle(CraftServer server, net.minecraft.world.entity.animal.Turtle entity) { + public CraftTurtle(CraftServer server, EntityTurtle entity) { super(server, entity); } @Override - public net.minecraft.world.entity.animal.Turtle getHandle() { - return (net.minecraft.world.entity.animal.Turtle) super.getHandle(); + public EntityTurtle getHandle() { + return (EntityTurtle) super.getHandle(); } @Override @@ -21,11 +22,11 @@ public String toString() { @Override public boolean hasEgg() { - return this.getHandle().hasEgg(); + return getHandle().hasEgg(); } @Override public boolean isLayingEgg() { - return this.getHandle().isLayingEgg(); + return getHandle().isLayingEgg(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java index 59e5b417..2a3ae470 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java @@ -10,6 +10,6 @@ public CraftVehicle(CraftServer server, net.minecraft.world.entity.Entity entity @Override public String toString() { - return "CraftVehicle{passenger=" + this.getPassenger() + '}'; + return "CraftVehicle{passenger=" + getPassenger() + '}'; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java index f816e30e..1e8329a7 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.monster.EntityVex; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftLocation; @@ -9,13 +10,13 @@ public class CraftVex extends CraftMonster implements Vex { - public CraftVex(CraftServer server, net.minecraft.world.entity.monster.Vex entity) { + public CraftVex(CraftServer server, EntityVex entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Vex getHandle() { - return (net.minecraft.world.entity.monster.Vex) super.getHandle(); + public EntityVex getHandle() { + return (EntityVex) super.getHandle(); } @Override @@ -25,45 +26,45 @@ public String toString() { @Override public boolean isCharging() { - return this.getHandle().isCharging(); + return getHandle().isCharging(); } @Override public void setCharging(boolean charging) { - this.getHandle().setIsCharging(charging); + getHandle().setIsCharging(charging); } @Override public Location getBound() { - BlockPos blockPosition = this.getHandle().getBoundOrigin(); - return (blockPosition == null) ? null : CraftLocation.toBukkit(blockPosition, this.getWorld()); + BlockPos blockPosition = getHandle().getBoundOrigin(); + return (blockPosition == null) ? null : CraftLocation.toBukkit(blockPosition, getWorld()); } @Override public void setBound(Location location) { if (location == null) { - this.getHandle().setBoundOrigin(null); + getHandle().setBoundOrigin(null); } else { - Preconditions.checkArgument(this.getWorld().equals(location.getWorld()), "The bound world cannot be different to the entity's world."); - this.getHandle().setBoundOrigin(CraftLocation.toBlockPosition(location)); + Preconditions.checkArgument(getWorld().equals(location.getWorld()), "The bound world cannot be different to the entity's world."); + getHandle().setBoundOrigin(CraftLocation.toBlockPos(location)); } } @Override public int getLifeTicks() { - return this.getHandle().limitedLifeTicks; + return getHandle().limitedLifeTicks; } @Override public void setLifeTicks(int lifeTicks) { - this.getHandle().setLimitedLife(lifeTicks); + getHandle().setLimitedLife(lifeTicks); if (lifeTicks < 0) { - this.getHandle().hasLimitedLife = false; + getHandle().hasLimitedLife = false; } } @Override public boolean hasLimitedLife() { - return this.getHandle().hasLimitedLife; + return getHandle().hasLimitedLife; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java index 4cfdb963..d354b374 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java @@ -4,32 +4,34 @@ import java.util.Locale; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; -import net.minecraft.world.entity.monster.Zombie; +import net.minecraft.world.entity.monster.EntityZombie; +import net.minecraft.world.entity.monster.EntityZombieVillager; +import net.minecraft.world.entity.npc.EntityVillager; import net.minecraft.world.entity.npc.VillagerProfession; import net.minecraft.world.entity.npc.VillagerType; -import net.minecraft.world.level.block.BedBlock; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.BlockBed; +import net.minecraft.world.level.block.state.IBlockData; import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.craftbukkit.CraftRegistry; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftLocation; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.craftbukkit.util.Handleable; import org.bukkit.entity.Villager; import org.bukkit.entity.ZombieVillager; import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityTransformEvent; public class CraftVillager extends CraftAbstractVillager implements Villager { - public CraftVillager(CraftServer server, net.minecraft.world.entity.npc.Villager entity) { + public CraftVillager(CraftServer server, EntityVillager entity) { super(server, entity); } @Override - public net.minecraft.world.entity.npc.Villager getHandle() { - return (net.minecraft.world.entity.npc.Villager) this.entity; + public EntityVillager getHandle() { + return (EntityVillager) entity; } @Override @@ -39,90 +41,90 @@ public String toString() { @Override public void remove() { - this.getHandle().releaseAllPois(); + getHandle().releaseAllPois(); super.remove(); } @Override public Profession getProfession() { - return CraftProfession.minecraftToBukkit(this.getHandle().getVillagerData().getProfession()); + return CraftProfession.minecraftToBukkit(getHandle().getVillagerData().getProfession()); } @Override public void setProfession(Profession profession) { Preconditions.checkArgument(profession != null, "Profession cannot be null"); - this.getHandle().setVillagerData(this.getHandle().getVillagerData().setProfession(CraftProfession.bukkitToMinecraft(profession))); + getHandle().setVillagerData(getHandle().getVillagerData().setProfession(CraftProfession.bukkitToMinecraft(profession))); } @Override public Type getVillagerType() { - return CraftType.minecraftToBukkit(this.getHandle().getVillagerData().getType()); + return CraftType.minecraftToBukkit(getHandle().getVillagerData().getType()); } @Override public void setVillagerType(Type type) { Preconditions.checkArgument(type != null, "Type cannot be null"); - this.getHandle().setVillagerData(this.getHandle().getVillagerData().setType(CraftType.bukkitToMinecraft(type))); + getHandle().setVillagerData(getHandle().getVillagerData().setType(CraftType.bukkitToMinecraft(type))); } @Override public int getVillagerLevel() { - return this.getHandle().getVillagerData().getLevel(); + return getHandle().getVillagerData().getLevel(); } @Override public void setVillagerLevel(int level) { Preconditions.checkArgument(1 <= level && level <= 5, "level (%s) must be between [1, 5]", level); - this.getHandle().setVillagerData(this.getHandle().getVillagerData().setLevel(level)); + getHandle().setVillagerData(getHandle().getVillagerData().setLevel(level)); } @Override public int getVillagerExperience() { - return this.getHandle().getVillagerXp(); + return getHandle().getVillagerXp(); } @Override public void setVillagerExperience(int experience) { Preconditions.checkArgument(experience >= 0, "Experience (%s) must be positive", experience); - this.getHandle().setVillagerXp(experience); + getHandle().setVillagerXp(experience); } @Override public boolean sleep(Location location) { Preconditions.checkArgument(location != null, "Location cannot be null"); Preconditions.checkArgument(location.getWorld() != null, "Location needs to be in a world"); - Preconditions.checkArgument(location.getWorld().equals(this.getWorld()), "Cannot sleep across worlds"); - Preconditions.checkState(!this.getHandle().generation, "Cannot sleep during world generation"); + Preconditions.checkArgument(location.getWorld().equals(getWorld()), "Cannot sleep across worlds"); + Preconditions.checkState(!getHandle().generation, "Cannot sleep during world generation"); - BlockPos position = CraftLocation.toBlockPosition(location); - BlockState iblockdata = this.getHandle().level().getBlockState(position); - if (!(iblockdata.getBlock() instanceof BedBlock)) { + BlockPos position = CraftLocation.toBlockPos(location); + IBlockData iblockdata = getHandle().level().getBlockState(position); + if (!(iblockdata.getBlock() instanceof BlockBed)) { return false; } - this.getHandle().startSleeping(position); + getHandle().startSleeping(position); return true; } @Override public void wakeup() { - Preconditions.checkState(this.isSleeping(), "Cannot wakeup if not sleeping"); - Preconditions.checkState(!this.getHandle().generation, "Cannot wakeup during world generation"); + Preconditions.checkState(isSleeping(), "Cannot wakeup if not sleeping"); + Preconditions.checkState(!getHandle().generation, "Cannot wakeup during world generation"); - this.getHandle().stopSleeping(); + getHandle().stopSleeping(); } @Override public void shakeHead() { - this.getHandle().setUnhappy(); + getHandle().setUnhappy(); } @Override public ZombieVillager zombify() { - net.minecraft.world.entity.monster.ZombieVillager entityzombievillager = Zombie.zombifyVillager(this.getHandle().level().getMinecraftWorld(), this.getHandle(), this.getHandle().blockPosition(), this.isSilent(), CreatureSpawnEvent.SpawnReason.CUSTOM); + EntityZombieVillager entityzombievillager = EntityZombie.convertVillagerToZombieVillager(getHandle().level().getMinecraftWorld(), getHandle(), getHandle().blockPosition(), isSilent(), EntityTransformEvent.TransformReason.INFECTION, CreatureSpawnEvent.SpawnReason.CUSTOM); return (entityzombievillager != null) ? (ZombieVillager) entityzombievillager.getBukkitEntity() : null; } @@ -154,38 +156,38 @@ public CraftType(NamespacedKey key, VillagerType villagerType) { } else { this.name = key.toString(); } - this.ordinal = CraftType.count++; + this.ordinal = count++; } @Override public VillagerType getHandle() { - return this.villagerType; + return villagerType; } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public int compareTo(Type type) { - return this.ordinal - type.ordinal(); + return ordinal - type.ordinal(); } @Override public String name() { - return this.name; + return name; } @Override public int ordinal() { - return this.ordinal; + return ordinal; } @Override public String toString() { // For backwards compatibility - return this.name(); + return name(); } @Override @@ -198,12 +200,12 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((Type) other).getKey()); + return getKey().equals(((Type) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } } @@ -235,38 +237,38 @@ public CraftProfession(NamespacedKey key, VillagerProfession villagerProfession) } else { this.name = key.toString(); } - this.ordinal = CraftProfession.count++; + this.ordinal = count++; } @Override public VillagerProfession getHandle() { - return this.villagerProfession; + return villagerProfession; } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public int compareTo(Profession profession) { - return this.ordinal - profession.ordinal(); + return ordinal - profession.ordinal(); } @Override public String name() { - return this.name; + return name; } @Override public int ordinal() { - return this.ordinal; + return ordinal; } @Override public String toString() { // For backwards compatibility - return this.name(); + return name(); } @Override @@ -279,12 +281,12 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((Profession) other).getKey()); + return getKey().equals(((Profession) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java index e2a0c118..ccdd0fd8 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.monster.EntityZombieVillager; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.CraftServer; @@ -10,13 +11,13 @@ public class CraftVillagerZombie extends CraftZombie implements ZombieVillager { - public CraftVillagerZombie(CraftServer server, net.minecraft.world.entity.monster.ZombieVillager entity) { + public CraftVillagerZombie(CraftServer server, EntityZombieVillager entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.ZombieVillager getHandle() { - return (net.minecraft.world.entity.monster.ZombieVillager) super.getHandle(); + public EntityZombieVillager getHandle() { + return (EntityZombieVillager) super.getHandle(); } @Override @@ -26,58 +27,58 @@ public String toString() { @Override public Villager.Profession getVillagerProfession() { - return CraftVillager.CraftProfession.minecraftToBukkit(this.getHandle().getVillagerData().getProfession()); + return CraftVillager.CraftProfession.minecraftToBukkit(getHandle().getVillagerData().getProfession()); } @Override public void setVillagerProfession(Villager.Profession profession) { Preconditions.checkArgument(profession != null, "Villager.Profession cannot be null"); - this.getHandle().setVillagerData(this.getHandle().getVillagerData().setProfession(CraftVillager.CraftProfession.bukkitToMinecraft(profession))); + getHandle().setVillagerData(getHandle().getVillagerData().setProfession(CraftVillager.CraftProfession.bukkitToMinecraft(profession))); } @Override public Villager.Type getVillagerType() { - return CraftVillager.CraftType.minecraftToBukkit(this.getHandle().getVillagerData().getType()); + return CraftVillager.CraftType.minecraftToBukkit(getHandle().getVillagerData().getType()); } @Override public void setVillagerType(Villager.Type type) { Preconditions.checkArgument(type != null, "Villager.Type cannot be null"); - this.getHandle().setVillagerData(this.getHandle().getVillagerData().setType(CraftVillager.CraftType.bukkitToMinecraft(type))); + getHandle().setVillagerData(getHandle().getVillagerData().setType(CraftVillager.CraftType.bukkitToMinecraft(type))); } @Override public boolean isConverting() { - return this.getHandle().isConverting(); + return getHandle().isConverting(); } @Override public int getConversionTime() { - Preconditions.checkState(this.isConverting(), "Entity not converting"); + Preconditions.checkState(isConverting(), "Entity not converting"); - return this.getHandle().villagerConversionTime; + return getHandle().villagerConversionTime; } @Override public void setConversionTime(int time) { if (time < 0) { - this.getHandle().villagerConversionTime = -1; - this.getHandle().getEntityData().set(net.minecraft.world.entity.monster.ZombieVillager.DATA_CONVERTING_ID, false); - this.getHandle().conversionStarter = null; - this.getHandle().removeEffect(MobEffects.DAMAGE_BOOST, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); + getHandle().villagerConversionTime = -1; + getHandle().getEntityData().set(EntityZombieVillager.DATA_CONVERTING_ID, false); + getHandle().conversionStarter = null; + getHandle().removeEffect(MobEffects.DAMAGE_BOOST, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); } else { - this.getHandle().startConverting(null, time); + getHandle().startConverting(null, time); } } @Override public OfflinePlayer getConversionPlayer() { - return (this.getHandle().conversionStarter == null) ? null : Bukkit.getOfflinePlayer(this.getHandle().conversionStarter); + return (getHandle().conversionStarter == null) ? null : Bukkit.getOfflinePlayer(getHandle().conversionStarter); } @Override public void setConversionPlayer(OfflinePlayer conversionPlayer) { if (!this.isConverting()) return; - this.getHandle().conversionStarter = (conversionPlayer == null) ? null : conversionPlayer.getUniqueId(); + getHandle().conversionStarter = (conversionPlayer == null) ? null : conversionPlayer.getUniqueId(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java index bcd3370b..c5f739c1 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityVindicator; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Vindicator; public class CraftVindicator extends CraftIllager implements Vindicator { - public CraftVindicator(CraftServer server, net.minecraft.world.entity.monster.Vindicator entity) { + public CraftVindicator(CraftServer server, EntityVindicator entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Vindicator getHandle() { - return (net.minecraft.world.entity.monster.Vindicator) super.getHandle(); + public EntityVindicator getHandle() { + return (EntityVindicator) super.getHandle(); } @Override @@ -21,11 +22,11 @@ public String toString() { @Override public boolean isJohnny() { - return this.getHandle().isJohnny; + return getHandle().isJohnny; } @Override public void setJohnny(boolean johnny) { - this.getHandle().isJohnny = johnny; + getHandle().isJohnny = johnny; } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java index 08194a78..71bae8b3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java @@ -1,17 +1,18 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.npc.EntityVillagerTrader; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.WanderingTrader; public class CraftWanderingTrader extends CraftAbstractVillager implements WanderingTrader { - public CraftWanderingTrader(CraftServer server, net.minecraft.world.entity.npc.WanderingTrader entity) { + public CraftWanderingTrader(CraftServer server, EntityVillagerTrader entity) { super(server, entity); } @Override - public net.minecraft.world.entity.npc.WanderingTrader getHandle() { - return (net.minecraft.world.entity.npc.WanderingTrader) this.entity; + public EntityVillagerTrader getHandle() { + return (EntityVillagerTrader) entity; } @Override @@ -21,11 +22,11 @@ public String toString() { @Override public int getDespawnDelay() { - return this.getHandle().getDespawnDelay(); + return getHandle().getDespawnDelay(); } @Override public void setDespawnDelay(int despawnDelay) { - this.getHandle().setDespawnDelay(despawnDelay); + getHandle().setDespawnDelay(despawnDelay); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWarden.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWarden.java index 794e4fe0..34cba9c2 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWarden.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWarden.java @@ -17,7 +17,7 @@ public CraftWarden(CraftServer server, Warden entity) { @Override public Warden getHandle() { - return (Warden) this.entity; + return (Warden) entity; } @Override @@ -27,53 +27,53 @@ public String toString() { @Override public int getAnger() { - return this.getHandle().getAngerManagement().getActiveAnger(this.getHandle().getTarget()); + return getHandle().getAngerManagement().getActiveAnger(getHandle().getTarget()); } @Override public int getAnger(Entity entity) { Preconditions.checkArgument(entity != null, "Entity cannot be null"); - return this.getHandle().getAngerManagement().getActiveAnger(((CraftEntity) entity).getHandle()); + return getHandle().getAngerManagement().getActiveAnger(((CraftEntity) entity).getHandle()); } @Override public void increaseAnger(Entity entity, int increase) { Preconditions.checkArgument(entity != null, "Entity cannot be null"); - this.getHandle().getAngerManagement().increaseAnger(((CraftEntity) entity).getHandle(), increase); + getHandle().getAngerManagement().increaseAnger(((CraftEntity) entity).getHandle(), increase); } @Override public void setAnger(Entity entity, int anger) { Preconditions.checkArgument(entity != null, "Entity cannot be null"); - this.getHandle().clearAnger(((CraftEntity) entity).getHandle()); - this.getHandle().getAngerManagement().increaseAnger(((CraftEntity) entity).getHandle(), anger); + getHandle().clearAnger(((CraftEntity) entity).getHandle()); + getHandle().getAngerManagement().increaseAnger(((CraftEntity) entity).getHandle(), anger); } @Override public void clearAnger(Entity entity) { Preconditions.checkArgument(entity != null, "Entity cannot be null"); - this.getHandle().clearAnger(((CraftEntity) entity).getHandle()); + getHandle().clearAnger(((CraftEntity) entity).getHandle()); } @Override public LivingEntity getEntityAngryAt() { - return (LivingEntity) this.getHandle().getEntityAngryAt().map(net.minecraft.world.entity.Entity::getBukkitEntity).orElse(null); + return (LivingEntity) getHandle().getEntityAngryAt().map(net.minecraft.world.entity.Entity::getBukkitEntity).orElse(null); } @Override public void setDisturbanceLocation(Location location) { Preconditions.checkArgument(location != null, "Location cannot be null"); - WardenAi.setDisturbanceLocation(this.getHandle(), BlockPos.containing(location.getX(), location.getY(), location.getZ())); + WardenAi.setDisturbanceLocation(getHandle(), BlockPos.containing(location.getX(), location.getY(), location.getZ())); } @Override public AngerLevel getAngerLevel() { - return switch (this.getHandle().getAngerLevel()) { + return switch (getHandle().getAngerLevel()) { case CALM -> AngerLevel.CALM; case AGITATED -> AngerLevel.AGITATED; case ANGRY -> AngerLevel.ANGRY; diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java index 1b347deb..4860475c 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java @@ -1,18 +1,18 @@ package org.bukkit.craftbukkit.entity; -import net.minecraft.world.entity.animal.WaterAnimal; +import net.minecraft.world.entity.animal.EntityWaterAnimal; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.WaterMob; public class CraftWaterMob extends CraftCreature implements WaterMob { - public CraftWaterMob(CraftServer server, WaterAnimal entity) { + public CraftWaterMob(CraftServer server, EntityWaterAnimal entity) { super(server, entity); } @Override - public WaterAnimal getHandle() { - return (WaterAnimal) this.entity; + public EntityWaterAnimal getHandle() { + return (EntityWaterAnimal) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java index bf6acf78..e5cb9e20 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java @@ -1,16 +1,17 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityWitch; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Witch; public class CraftWitch extends CraftRaider implements Witch { - public CraftWitch(CraftServer server, net.minecraft.world.entity.monster.Witch entity) { + public CraftWitch(CraftServer server, EntityWitch entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Witch getHandle() { - return (net.minecraft.world.entity.monster.Witch) this.entity; + public EntityWitch getHandle() { + return (EntityWitch) entity; } @Override @@ -20,6 +21,6 @@ public String toString() { @Override public boolean isDrinkingPotion() { - return this.getHandle().isDrinkingPotion(); + return getHandle().isDrinkingPotion(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java index 59bdb36c..38db21cd 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java @@ -2,7 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.boss.wither.WitherBoss; +import net.minecraft.world.entity.boss.wither.EntityWither; import org.bukkit.boss.BossBar; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.boss.CraftBossBar; @@ -13,7 +13,7 @@ public class CraftWither extends CraftMonster implements Wither { private BossBar bossBar; - public CraftWither(CraftServer server, WitherBoss entity) { + public CraftWither(CraftServer server, EntityWither entity) { super(server, entity); if (entity.bossEvent != null) { @@ -22,8 +22,8 @@ public CraftWither(CraftServer server, WitherBoss entity) { } @Override - public WitherBoss getHandle() { - return (WitherBoss) this.entity; + public EntityWither getHandle() { + return (EntityWither) entity; } @Override @@ -33,7 +33,7 @@ public String toString() { @Override public BossBar getBossBar() { - return this.bossBar; + return bossBar; } @Override @@ -41,30 +41,30 @@ public void setTarget(Head head, LivingEntity livingEntity) { Preconditions.checkArgument(head != null, "head cannot be null"); int entityId = (livingEntity != null) ? livingEntity.getEntityId() : 0; - this.getHandle().setAlternativeTarget(head.ordinal(), entityId); + getHandle().setAlternativeTarget(head.ordinal(), entityId); } @Override public LivingEntity getTarget(Head head) { Preconditions.checkArgument(head != null, "head cannot be null"); - int entityId = this.getHandle().getAlternativeTarget(head.ordinal()); + int entityId = getHandle().getAlternativeTarget(head.ordinal()); if (entityId == 0) { return null; } - Entity target = this.getHandle().level().getEntity(entityId); + Entity target = getHandle().level().getEntity(entityId); return (target != null) ? (LivingEntity) target.getBukkitEntity() : null; } @Override public int getInvulnerabilityTicks() { - return this.getHandle().getInvulnerableTicks(); + return getHandle().getInvulnerableTicks(); } @Override public void setInvulnerabilityTicks(int ticks) { Preconditions.checkArgument(ticks >= 0, "ticks must be >=0"); - this.getHandle().setInvulnerableTicks(ticks); + getHandle().setInvulnerableTicks(ticks); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java index ffee517b..6f96b750 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntitySkeletonWither; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.entity.WitherSkeleton; public class CraftWitherSkeleton extends CraftAbstractSkeleton implements WitherSkeleton { - public CraftWitherSkeleton(CraftServer server, net.minecraft.world.entity.monster.WitherSkeleton entity) { + public CraftWitherSkeleton(CraftServer server, EntitySkeletonWither entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java index bc978391..5c09ceb7 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java @@ -1,26 +1,27 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.projectile.EntityWitherSkull; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.WitherSkull; public class CraftWitherSkull extends CraftFireball implements WitherSkull { - public CraftWitherSkull(CraftServer server, net.minecraft.world.entity.projectile.WitherSkull entity) { + public CraftWitherSkull(CraftServer server, EntityWitherSkull entity) { super(server, entity); } @Override public void setCharged(boolean charged) { - this.getHandle().setDangerous(charged); + getHandle().setDangerous(charged); } @Override public boolean isCharged() { - return this.getHandle().isDangerous(); + return getHandle().isDangerous(); } @Override - public net.minecraft.world.entity.projectile.WitherSkull getHandle() { - return (net.minecraft.world.entity.projectile.WitherSkull) this.entity; + public EntityWitherSkull getHandle() { + return (EntityWitherSkull) entity; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java index 86574da2..90129132 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java @@ -2,8 +2,11 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; +import net.minecraft.world.entity.animal.EntityWolf; import net.minecraft.world.entity.animal.WolfVariant; +import net.minecraft.world.item.EnumColor; import org.bukkit.DyeColor; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -13,69 +16,69 @@ import org.bukkit.entity.Wolf; public class CraftWolf extends CraftTameableAnimal implements Wolf { - public CraftWolf(CraftServer server, net.minecraft.world.entity.animal.Wolf wolf) { + public CraftWolf(CraftServer server, EntityWolf wolf) { super(server, wolf); } @Override public boolean isAngry() { - return this.getHandle().isAngry(); + return getHandle().isAngry(); } @Override public void setAngry(boolean angry) { if (angry) { - this.getHandle().startPersistentAngerTimer(); + getHandle().startPersistentAngerTimer(); } else { - this.getHandle().stopBeingAngry(); + getHandle().stopBeingAngry(); } } @Override - public net.minecraft.world.entity.animal.Wolf getHandle() { - return (net.minecraft.world.entity.animal.Wolf) this.entity; + public EntityWolf getHandle() { + return (EntityWolf) entity; } @Override public DyeColor getCollarColor() { - return DyeColor.getByWoolData((byte) this.getHandle().getCollarColor().getId()); + return DyeColor.getByWoolData((byte) getHandle().getCollarColor().getId()); } @Override public void setCollarColor(DyeColor color) { - this.getHandle().setCollarColor(net.minecraft.world.item.DyeColor.byId(color.getWoolData())); + getHandle().setCollarColor(EnumColor.byId(color.getWoolData())); } @Override public boolean isWet() { - return this.getHandle().isWet(); + return getHandle().isWet; } @Override public float getTailAngle() { - return this.getHandle().getTailAngle(); + return getHandle().getTailAngle(); } @Override public boolean isInterested() { - return this.getHandle().isInterested(); + return getHandle().isInterested(); } @Override public void setInterested(boolean flag) { - this.getHandle().setIsInterested(flag); + getHandle().setIsInterested(flag); } @Override public Variant getVariant() { - return CraftVariant.minecraftHolderToBukkit(this.getHandle().getVariant()); + return CraftVariant.minecraftHolderToBukkit(getHandle().getVariant()); } @Override public void setVariant(Variant variant) { Preconditions.checkArgument(variant != null, "variant"); - this.getHandle().setVariant(CraftVariant.bukkitToMinecraftHolder(variant)); + getHandle().setVariant(CraftVariant.bukkitToMinecraftHolder(variant)); } public static class CraftVariant implements Variant, Handleable { @@ -85,7 +88,7 @@ public static Variant minecraftToBukkit(WolfVariant minecraft) { } public static Variant minecraftHolderToBukkit(Holder minecraft) { - return CraftVariant.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static WolfVariant bukkitToMinecraft(Variant bukkit) { @@ -95,9 +98,9 @@ public static WolfVariant bukkitToMinecraft(Variant bukkit) { public static Holder bukkitToMinecraftHolder(Variant bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.WOLF_VARIANT); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.WOLF_VARIANT); - if (registry.wrapAsHolder(CraftVariant.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -115,17 +118,17 @@ public CraftVariant(NamespacedKey key, WolfVariant variant) { @Override public WolfVariant getHandle() { - return this.variant; + return variant; } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public String toString() { - return this.key.toString(); + return key.toString(); } @Override @@ -138,12 +141,12 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(otherVariant.getKey()); + return getKey().equals(otherVariant.getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftZoglin.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftZoglin.java index c134c4bb..6b4907a3 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftZoglin.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftZoglin.java @@ -1,27 +1,28 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.monster.EntityZoglin; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Zoglin; public class CraftZoglin extends CraftMonster implements Zoglin { - public CraftZoglin(CraftServer server, net.minecraft.world.entity.monster.Zoglin entity) { + public CraftZoglin(CraftServer server, EntityZoglin entity) { super(server, entity); } @Override public boolean isBaby() { - return this.getHandle().isBaby(); + return getHandle().isBaby(); } @Override public void setBaby(boolean flag) { - this.getHandle().setBaby(flag); + getHandle().setBaby(flag); } @Override - public net.minecraft.world.entity.monster.Zoglin getHandle() { - return (net.minecraft.world.entity.monster.Zoglin) this.entity; + public EntityZoglin getHandle() { + return (EntityZoglin) entity; } @Override @@ -31,12 +32,12 @@ public String toString() { @Override public int getAge() { - return this.getHandle().isBaby() ? -1 : 0; + return getHandle().isBaby() ? -1 : 0; } @Override public void setAge(int i) { - this.getHandle().setBaby(i < 0); + getHandle().setBaby(i < 0); } @Override @@ -50,17 +51,17 @@ public boolean getAgeLock() { @Override public void setBaby() { - this.getHandle().setBaby(true); + getHandle().setBaby(true); } @Override public void setAdult() { - this.getHandle().setBaby(false); + getHandle().setBaby(false); } @Override public boolean isAdult() { - return !this.getHandle().isBaby(); + return !getHandle().isBaby(); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java index 99dcaa82..100d3aa1 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java @@ -1,20 +1,21 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.monster.ZombieVillager; +import net.minecraft.world.entity.monster.EntityZombie; +import net.minecraft.world.entity.monster.EntityZombieVillager; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Villager; import org.bukkit.entity.Zombie; public class CraftZombie extends CraftMonster implements Zombie { - public CraftZombie(CraftServer server, net.minecraft.world.entity.monster.Zombie entity) { + public CraftZombie(CraftServer server, EntityZombie entity) { super(server, entity); } @Override - public net.minecraft.world.entity.monster.Zombie getHandle() { - return (net.minecraft.world.entity.monster.Zombie) this.entity; + public EntityZombie getHandle() { + return (EntityZombie) entity; } @Override @@ -24,17 +25,17 @@ public String toString() { @Override public boolean isBaby() { - return this.getHandle().isBaby(); + return getHandle().isBaby(); } @Override public void setBaby(boolean flag) { - this.getHandle().setBaby(flag); + getHandle().setBaby(flag); } @Override public boolean isVillager() { - return this.getHandle() instanceof ZombieVillager; + return getHandle() instanceof EntityZombieVillager; } @Override @@ -54,34 +55,34 @@ public Villager.Profession getVillagerProfession() { @Override public boolean isConverting() { - return this.getHandle().isUnderWaterConverting(); + return getHandle().isUnderWaterConverting(); } @Override public int getConversionTime() { - Preconditions.checkState(this.isConverting(), "Entity not converting"); + Preconditions.checkState(isConverting(), "Entity not converting"); - return this.getHandle().conversionTime; + return getHandle().conversionTime; } @Override public void setConversionTime(int time) { if (time < 0) { - this.getHandle().conversionTime = -1; - this.getHandle().getEntityData().set(net.minecraft.world.entity.monster.Zombie.DATA_DROWNED_CONVERSION_ID, false); + getHandle().conversionTime = -1; + getHandle().getEntityData().set(EntityZombie.DATA_DROWNED_CONVERSION_ID, false); } else { - this.getHandle().startUnderWaterConversion(time); + getHandle().startUnderWaterConversion(time); } } @Override public int getAge() { - return this.getHandle().isBaby() ? -1 : 0; + return getHandle().isBaby() ? -1 : 0; } @Override public void setAge(int i) { - this.getHandle().setBaby(i < 0); + getHandle().setBaby(i < 0); } @Override @@ -95,17 +96,17 @@ public boolean getAgeLock() { @Override public void setBaby() { - this.getHandle().setBaby(true); + getHandle().setBaby(true); } @Override public void setAdult() { - this.getHandle().setBaby(false); + getHandle().setBaby(false); } @Override public boolean isAdult() { - return !this.getHandle().isBaby(); + return !getHandle().isBaby(); } @Override @@ -119,11 +120,11 @@ public void setBreed(boolean b) { @Override public boolean canBreakDoors() { - return this.getHandle().canBreakDoors(); + return getHandle().canBreakDoors(); } @Override public void setCanBreakDoors(boolean flag) { - this.getHandle().setCanBreakDoors(flag); + getHandle().setCanBreakDoors(flag); } } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java index 2c47ea42..4a69d07c 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java @@ -1,12 +1,13 @@ package org.bukkit.craftbukkit.entity; +import net.minecraft.world.entity.animal.horse.EntityHorseZombie; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Horse.Variant; import org.bukkit.entity.ZombieHorse; public class CraftZombieHorse extends CraftAbstractHorse implements ZombieHorse { - public CraftZombieHorse(CraftServer server, net.minecraft.world.entity.animal.horse.ZombieHorse entity) { + public CraftZombieHorse(CraftServer server, EntityHorseZombie entity) { super(server, entity); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftAcaciaBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftAcaciaBoat.java new file mode 100644 index 00000000..0ffa2e8e --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftAcaciaBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.AcaciaBoat; + +public class CraftAcaciaBoat extends CraftBoat implements AcaciaBoat { + + public CraftAcaciaBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftAcaciaChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftAcaciaChestBoat.java new file mode 100644 index 00000000..29bb5460 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftAcaciaChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.AcaciaChestBoat; + +public class CraftAcaciaChestBoat extends CraftChestBoat implements AcaciaChestBoat { + + public CraftAcaciaChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBambooChestRaft.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBambooChestRaft.java new file mode 100644 index 00000000..eea57635 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBambooChestRaft.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.BambooChestRaft; + +public class CraftBambooChestRaft extends CraftChestBoat implements BambooChestRaft { + + public CraftBambooChestRaft(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBambooRaft.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBambooRaft.java new file mode 100644 index 00000000..05952dd6 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBambooRaft.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.BambooRaft; + +public class CraftBambooRaft extends CraftBoat implements BambooRaft { + + public CraftBambooRaft(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBirchBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBirchBoat.java new file mode 100644 index 00000000..1d629bf9 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBirchBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.BirchBoat; + +public class CraftBirchBoat extends CraftBoat implements BirchBoat { + + public CraftBirchBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBirchChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBirchChestBoat.java new file mode 100644 index 00000000..24734c47 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftBirchChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.BirchChestBoat; + +public class CraftBirchChestBoat extends CraftChestBoat implements BirchChestBoat { + + public CraftBirchChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftCherryBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftCherryBoat.java new file mode 100644 index 00000000..3f55982c --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftCherryBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.CherryBoat; + +public class CraftCherryBoat extends CraftBoat implements CherryBoat { + + public CraftCherryBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftCherryChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftCherryChestBoat.java new file mode 100644 index 00000000..a983236c --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftCherryChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.CherryChestBoat; + +public class CraftCherryChestBoat extends CraftChestBoat implements CherryChestBoat { + + public CraftCherryChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftDarkOakBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftDarkOakBoat.java new file mode 100644 index 00000000..06c64e92 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftDarkOakBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.DarkOakBoat; + +public class CraftDarkOakBoat extends CraftBoat implements DarkOakBoat { + + public CraftDarkOakBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftDarkOakChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftDarkOakChestBoat.java new file mode 100644 index 00000000..f49955cf --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftDarkOakChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.DarkOakChestBoat; + +public class CraftDarkOakChestBoat extends CraftChestBoat implements DarkOakChestBoat { + + public CraftDarkOakChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftJungleBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftJungleBoat.java new file mode 100644 index 00000000..400bfe45 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftJungleBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.JungleBoat; + +public class CraftJungleBoat extends CraftBoat implements JungleBoat { + + public CraftJungleBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftJungleChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftJungleChestBoat.java new file mode 100644 index 00000000..e8d6cd4c --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftJungleChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.JungleChestBoat; + +public class CraftJungleChestBoat extends CraftChestBoat implements JungleChestBoat { + + public CraftJungleChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftMangroveBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftMangroveBoat.java new file mode 100644 index 00000000..c1f0c3e5 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftMangroveBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.MangroveBoat; + +public class CraftMangroveBoat extends CraftBoat implements MangroveBoat { + + public CraftMangroveBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftMangroveChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftMangroveChestBoat.java new file mode 100644 index 00000000..97eb913b --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftMangroveChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.MangroveChestBoat; + +public class CraftMangroveChestBoat extends CraftChestBoat implements MangroveChestBoat { + + public CraftMangroveChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftOakBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftOakBoat.java new file mode 100644 index 00000000..7e3e8f5f --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftOakBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.OakBoat; + +public class CraftOakBoat extends CraftBoat implements OakBoat { + + public CraftOakBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftOakChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftOakChestBoat.java new file mode 100644 index 00000000..7beb1644 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftOakChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.OakChestBoat; + +public class CraftOakChestBoat extends CraftChestBoat implements OakChestBoat { + + public CraftOakChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftPaleOakBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftPaleOakBoat.java new file mode 100644 index 00000000..e6d65858 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftPaleOakBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.PaleOakBoat; + +public class CraftPaleOakBoat extends CraftBoat implements PaleOakBoat { + + public CraftPaleOakBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftPaleOakChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftPaleOakChestBoat.java new file mode 100644 index 00000000..bcc91c83 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftPaleOakChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.PaleOakChestBoat; + +public class CraftPaleOakChestBoat extends CraftChestBoat implements PaleOakChestBoat { + + public CraftPaleOakChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftSpruceBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftSpruceBoat.java new file mode 100644 index 00000000..92eb7ea2 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftSpruceBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftBoat; +import org.bukkit.entity.boat.SpruceBoat; + +public class CraftSpruceBoat extends CraftBoat implements SpruceBoat { + + public CraftSpruceBoat(CraftServer server, AbstractBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftSpruceChestBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftSpruceChestBoat.java new file mode 100644 index 00000000..64cc4dc3 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/entity/boat/CraftSpruceChestBoat.java @@ -0,0 +1,13 @@ +package org.bukkit.craftbukkit.entity.boat; + +import net.minecraft.world.entity.vehicle.AbstractChestBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftChestBoat; +import org.bukkit.entity.boat.SpruceChestBoat; + +public class CraftSpruceChestBoat extends CraftChestBoat implements SpruceChestBoat { + + public CraftSpruceChestBoat(CraftServer server, AbstractChestBoat entity) { + super(server, entity); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java b/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java index 43cd5ef2..b6ebc876 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.entity.memory; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.ai.memory.MemoryModuleType; import org.bukkit.Registry; @@ -16,7 +17,7 @@ public static MemoryKey minecraftToBukkit(MemoryModuleType minecraf return null; } - net.minecraft.core.Registry> registry = CraftRegistry.getMinecraftRegistry(Registries.MEMORY_MODULE_TYPE); + IRegistry> registry = CraftRegistry.getMinecraftRegistry(Registries.MEMORY_MODULE_TYPE); MemoryKey bukkit = Registry.MEMORY_MODULE_TYPE.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); return bukkit; diff --git a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java b/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java index ad42f2bf..c8632ec9 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java @@ -14,7 +14,7 @@ private CraftMemoryMapper() {} public static Object fromNms(Object object) { if (object instanceof GlobalPos) { - return CraftMemoryMapper.fromNms((GlobalPos) object); + return fromNms((GlobalPos) object); } else if (object instanceof Long) { return (Long) object; } else if (object instanceof UUID) { @@ -32,7 +32,7 @@ public static Object toNms(Object object) { if (object == null) { return null; } else if (object instanceof Location) { - return CraftMemoryMapper.toNms((Location) object); + return toNms((Location) object); } else if (object instanceof Long) { return (Long) object; } else if (object instanceof UUID) { diff --git a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java index 76331ab3..95abea69 100644 --- a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java +++ b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java @@ -16,59 +16,70 @@ import java.util.stream.Stream; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.network.protocol.game.ServerboundContainerClosePacket; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.core.EnumDirection; +import net.minecraft.network.protocol.game.PacketPlayInCloseWindow; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.server.level.WorldServer; import net.minecraft.tags.DamageTypeTags; import net.minecraft.util.Unit; -import net.minecraft.world.Container; -import net.minecraft.world.InteractionHand; +import net.minecraft.world.EnumHand; +import net.minecraft.world.IInventory; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageTypes; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.animal.AbstractFish; -import net.minecraft.world.entity.animal.AbstractGolem; -import net.minecraft.world.entity.animal.Animal; -import net.minecraft.world.entity.animal.WaterAnimal; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.monster.Ghast; -import net.minecraft.world.entity.monster.Monster; -import net.minecraft.world.entity.monster.Slime; -import net.minecraft.world.entity.monster.SpellcasterIllager; -import net.minecraft.world.entity.npc.Npc; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; +import net.minecraft.world.entity.EntityAreaEffectCloud; +import net.minecraft.world.entity.EntityExperienceOrb; +import net.minecraft.world.entity.EntityInsentient; +import net.minecraft.world.entity.EntityLiving; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EnumItemSlot; +import net.minecraft.world.entity.animal.EntityAnimal; +import net.minecraft.world.entity.animal.EntityFish; +import net.minecraft.world.entity.animal.EntityGolem; +import net.minecraft.world.entity.animal.EntityWaterAnimal; +import net.minecraft.world.entity.item.EntityItem; +import net.minecraft.world.entity.monster.EntityGhast; +import net.minecraft.world.entity.monster.EntityIllagerWizard; +import net.minecraft.world.entity.monster.EntityMonster; +import net.minecraft.world.entity.monster.EntitySlime; +import net.minecraft.world.entity.monster.EntityStrider; +import net.minecraft.world.entity.monster.piglin.EntityPiglin; +import net.minecraft.world.entity.npc.EntityVillager; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.entity.projectile.EntityFireworks; +import net.minecraft.world.entity.projectile.EntityPotion; +import net.minecraft.world.entity.projectile.IProjectile; +import net.minecraft.world.entity.raid.EntityRaider; import net.minecraft.world.entity.raid.Raid; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.inventory.MerchantMenu; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.ContainerMerchant; +import net.minecraft.world.inventory.InventoryCrafting; import net.minecraft.world.inventory.RecipeBookType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.context.ItemActionContext; +import net.minecraft.world.item.crafting.RecipeCrafting; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.ChunkCoordIntPair; import net.minecraft.world.level.Explosion; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.entity.SignBlockEntity; -import net.minecraft.world.level.block.state.properties.NoteBlockInstrument; -import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.GeneratorAccess; +import net.minecraft.world.level.World; +import net.minecraft.world.level.block.entity.TileEntitySign; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.block.state.properties.BlockPropertyInstrument; import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.EntityHitResult; -import net.minecraft.world.phys.HitResult; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.level.storage.loot.LootTableInfo; +import net.minecraft.world.level.storage.loot.parameters.LootContextParameters; +import net.minecraft.world.phys.MovingObjectPosition; +import net.minecraft.world.phys.MovingObjectPositionBlock; +import net.minecraft.world.phys.MovingObjectPositionEntity; +import net.minecraft.world.phys.Vec3D; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Statistic.Type; -import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; @@ -249,6 +260,7 @@ import org.bukkit.event.world.EntitiesLoadEvent; import org.bukkit.event.world.EntitiesUnloadEvent; import org.bukkit.event.world.LootGenerateEvent; +import org.bukkit.inventory.CraftingRecipe; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.Recipe; @@ -260,10 +272,10 @@ public class CraftEventFactory { // helper methods - private static boolean canBuild(ServerLevel world, Player player, int x, int z) { + private static boolean canBuild(WorldServer world, Player player, int x, int z) { int spawnSize = Bukkit.getServer().getSpawnRadius(); - if (world.dimension() != Level.OVERWORLD) return true; + if (world.dimension() != World.OVERWORLD) return true; if (spawnSize <= 0) return true; if (((CraftServer) Bukkit.getServer()).getHandle().getOps().isEmpty()) return true; if (player.isOp()) return true; @@ -282,11 +294,11 @@ public static T callEvent(T event) { /** * PlayerSignOpenEvent */ - public static boolean callPlayerSignOpenEvent(net.minecraft.world.entity.player.Player player, SignBlockEntity tileEntitySign, boolean front, PlayerSignOpenEvent.Cause cause) { + public static boolean callPlayerSignOpenEvent(EntityHuman player, TileEntitySign tileEntitySign, boolean front, PlayerSignOpenEvent.Cause cause) { final Block block = CraftBlock.at(tileEntitySign.getLevel(), tileEntitySign.getBlockPos()); final Sign sign = (Sign) CraftBlockStates.getBlockState(block); final Side side = (front) ? Side.FRONT : Side.BACK; - return CraftEventFactory.callPlayerSignOpenEvent((Player) player.getBukkitEntity(), sign, side, cause); + return callPlayerSignOpenEvent((Player) player.getBukkitEntity(), sign, side, cause); } /** @@ -301,10 +313,10 @@ public static boolean callPlayerSignOpenEvent(Player player, Sign sign, Side sid /** * PlayerBedEnterEvent */ - public static Either callPlayerBedEnterEvent(net.minecraft.world.entity.player.Player player, BlockPos bed, Either nmsBedResult) { - BedEnterResult bedEnterResult = nmsBedResult.mapBoth(new Function() { + public static Either callPlayerBedEnterEvent(EntityHuman player, BlockPos bed, Either nmsBedResult) { + BedEnterResult bedEnterResult = nmsBedResult.mapBoth(new Function() { @Override - public BedEnterResult apply(net.minecraft.world.entity.player.Player.BedSleepingProblem t) { + public BedEnterResult apply(EntityHuman.EnumBedResult t) { switch (t) { case NOT_POSSIBLE_HERE: return BedEnterResult.NOT_POSSIBLE_HERE; @@ -327,7 +339,7 @@ public BedEnterResult apply(net.minecraft.world.entity.player.Player.BedSleeping if (result == Result.ALLOW) { return Either.right(Unit.INSTANCE); } else if (result == Result.DENY) { - return Either.left(net.minecraft.world.entity.player.Player.BedSleepingProblem.OTHER_PROBLEM); + return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM); } return nmsBedResult; @@ -336,7 +348,7 @@ public BedEnterResult apply(net.minecraft.world.entity.player.Player.BedSleeping /** * Entity Enter Love Mode Event */ - public static EntityEnterLoveModeEvent callEntityEnterLoveModeEvent(net.minecraft.world.entity.player.Player entityHuman, Animal entityAnimal, int loveTicks) { + public static EntityEnterLoveModeEvent callEntityEnterLoveModeEvent(EntityHuman entityHuman, EntityAnimal entityAnimal, int loveTicks) { EntityEnterLoveModeEvent entityEnterLoveModeEvent = new EntityEnterLoveModeEvent((Animals) entityAnimal.getBukkitEntity(), entityHuman != null ? (HumanEntity) entityHuman.getBukkitEntity() : null, loveTicks); Bukkit.getPluginManager().callEvent(entityEnterLoveModeEvent); return entityEnterLoveModeEvent; @@ -345,7 +357,7 @@ public static EntityEnterLoveModeEvent callEntityEnterLoveModeEvent(net.minecraf /** * Player Harvest Block Event */ - public static PlayerHarvestBlockEvent callPlayerHarvestBlockEvent(Level world, BlockPos blockposition, net.minecraft.world.entity.player.Player who, InteractionHand enumhand, List itemsToHarvest) { + public static PlayerHarvestBlockEvent callPlayerHarvestBlockEvent(World world, BlockPos blockposition, EntityHuman who, EnumHand enumhand, List itemsToHarvest) { List bukkitItemsToHarvest = new ArrayList<>(itemsToHarvest.stream().map(CraftItemStack::asBukkitCopy).collect(Collectors.toList())); Player player = (Player) who.getBukkitEntity(); PlayerHarvestBlockEvent playerHarvestBlockEvent = new PlayerHarvestBlockEvent(player, CraftBlock.at(world, blockposition), CraftEquipmentSlot.getHand(enumhand), bukkitItemsToHarvest); @@ -356,12 +368,12 @@ public static PlayerHarvestBlockEvent callPlayerHarvestBlockEvent(Level world, B /** * Player Fish Bucket Event */ - public static PlayerBucketEntityEvent callPlayerFishBucketEvent(net.minecraft.world.entity.LivingEntity fish, net.minecraft.world.entity.player.Player entityHuman, ItemStack originalBucket, ItemStack entityBucket, InteractionHand enumhand) { + public static PlayerBucketEntityEvent callPlayerFishBucketEvent(EntityLiving fish, EntityHuman entityHuman, ItemStack originalBucket, ItemStack entityBucket, EnumHand enumhand) { Player player = (Player) entityHuman.getBukkitEntity(); EquipmentSlot hand = CraftEquipmentSlot.getHand(enumhand); PlayerBucketEntityEvent event; - if (fish instanceof AbstractFish) { + if (fish instanceof EntityFish) { event = new PlayerBucketFishEvent(player, (Fish) fish.getBukkitEntity(), CraftItemStack.asBukkitCopy(originalBucket), CraftItemStack.asBukkitCopy(entityBucket), hand); } else { event = new PlayerBucketEntityEvent(player, fish.getBukkitEntity(), CraftItemStack.asBukkitCopy(originalBucket), CraftItemStack.asBukkitCopy(entityBucket), hand); @@ -373,13 +385,13 @@ public static PlayerBucketEntityEvent callPlayerFishBucketEvent(net.minecraft.wo /** * Trade Index Change Event */ - public static TradeSelectEvent callTradeSelectEvent(ServerPlayer player, int newIndex, MerchantMenu merchant) { + public static TradeSelectEvent callTradeSelectEvent(EntityPlayer player, int newIndex, ContainerMerchant merchant) { TradeSelectEvent tradeSelectEvent = new TradeSelectEvent(merchant.getBukkitView(), newIndex); Bukkit.getPluginManager().callEvent(tradeSelectEvent); return tradeSelectEvent; } - public static boolean handleBellRingEvent(Level world, BlockPos position, Direction direction, Entity entity) { + public static boolean handleBellRingEvent(World world, BlockPos position, EnumDirection direction, Entity entity) { Block block = CraftBlock.at(world, position); BlockFace bukkitDirection = CraftBlock.notchToBlockFace(direction); BellRingEvent event = new BellRingEvent(block, bukkitDirection, (entity != null) ? entity.getBukkitEntity() : null); @@ -387,7 +399,7 @@ public static boolean handleBellRingEvent(Level world, BlockPos position, Direct return !event.isCancelled(); } - public static Stream handleBellResonateEvent(Level world, BlockPos position, List bukkitEntities) { + public static Stream handleBellResonateEvent(World world, BlockPos position, List bukkitEntities) { Block block = CraftBlock.at(world, position); BellResonateEvent event = new BellResonateEvent(block, bukkitEntities); Bukkit.getPluginManager().callEvent(event); @@ -397,7 +409,7 @@ public static Stream handleBellResonate /** * Block place methods */ - public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(ServerLevel world, net.minecraft.world.entity.player.Player who, InteractionHand hand, List blockStates, int clickedX, int clickedY, int clickedZ) { + public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(WorldServer world, EntityHuman who, EnumHand hand, List blockStates, int clickedX, int clickedY, int clickedZ) { CraftWorld craftWorld = world.getWorld(); CraftServer craftServer = world.getCraftServer(); Player player = (Player) who.getBukkitEntity(); @@ -406,14 +418,14 @@ public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(ServerLevel world, n boolean canBuild = true; for (int i = 0; i < blockStates.size(); i++) { - if (!CraftEventFactory.canBuild(world, player, blockStates.get(i).getX(), blockStates.get(i).getZ())) { + if (!canBuild(world, player, blockStates.get(i).getX(), blockStates.get(i).getZ())) { canBuild = false; break; } } org.bukkit.inventory.ItemStack item; - if (hand == InteractionHand.MAIN_HAND) { + if (hand == EnumHand.MAIN_HAND) { item = player.getInventory().getItemInMainHand(); } else { item = player.getInventory().getItemInOffHand(); @@ -425,7 +437,7 @@ public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(ServerLevel world, n return event; } - public static BlockPlaceEvent callBlockPlaceEvent(ServerLevel world, net.minecraft.world.entity.player.Player who, InteractionHand hand, BlockState replacedBlockState, int clickedX, int clickedY, int clickedZ) { + public static BlockPlaceEvent callBlockPlaceEvent(WorldServer world, EntityHuman who, EnumHand hand, BlockState replacedBlockState, int clickedX, int clickedY, int clickedZ) { CraftWorld craftWorld = world.getWorld(); CraftServer craftServer = world.getCraftServer(); @@ -434,11 +446,11 @@ public static BlockPlaceEvent callBlockPlaceEvent(ServerLevel world, net.minecra Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ); Block placedBlock = replacedBlockState.getBlock(); - boolean canBuild = CraftEventFactory.canBuild(world, player, placedBlock.getX(), placedBlock.getZ()); + boolean canBuild = canBuild(world, player, placedBlock.getX(), placedBlock.getZ()); org.bukkit.inventory.ItemStack item; EquipmentSlot equipmentSlot; - if (hand == InteractionHand.MAIN_HAND) { + if (hand == EnumHand.MAIN_HAND) { item = player.getInventory().getItemInMainHand(); equipmentSlot = EquipmentSlot.HAND; } else { @@ -452,22 +464,22 @@ public static BlockPlaceEvent callBlockPlaceEvent(ServerLevel world, net.minecra return event; } - public static void handleBlockDropItemEvent(Block block, BlockState state, ServerPlayer player, List items) { + public static void handleBlockDropItemEvent(Block block, BlockState state, EntityPlayer player, List items) { BlockDropItemEvent event = new BlockDropItemEvent(block, state, player.getBukkitEntity(), Lists.transform(items, (item) -> (org.bukkit.entity.Item) item.getBukkitEntity())); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { - for (ItemEntity item : items) { + for (EntityItem item : items) { item.level().addFreshEntity(item); } } } - public static EntityPlaceEvent callEntityPlaceEvent(UseOnContext itemactioncontext, Entity entity) { - return CraftEventFactory.callEntityPlaceEvent(itemactioncontext.getLevel(), itemactioncontext.getClickedPos(), itemactioncontext.getClickedFace(), itemactioncontext.getPlayer(), entity, itemactioncontext.getHand()); + public static EntityPlaceEvent callEntityPlaceEvent(ItemActionContext itemactioncontext, Entity entity) { + return callEntityPlaceEvent(itemactioncontext.getLevel(), itemactioncontext.getClickedPos(), itemactioncontext.getClickedFace(), itemactioncontext.getPlayer(), entity, itemactioncontext.getHand()); } - public static EntityPlaceEvent callEntityPlaceEvent(Level world, BlockPos clickPosition, Direction clickedFace, net.minecraft.world.entity.player.Player human, Entity entity, InteractionHand enumhand) { + public static EntityPlaceEvent callEntityPlaceEvent(World world, BlockPos clickPosition, EnumDirection clickedFace, EntityHuman human, Entity entity, EnumHand enumhand) { Player who = (human == null) ? null : (Player) human.getBukkitEntity(); org.bukkit.block.Block blockClicked = CraftBlock.at(world, clickPosition); org.bukkit.block.BlockFace blockFace = org.bukkit.craftbukkit.block.CraftBlock.notchToBlockFace(clickedFace); @@ -481,15 +493,15 @@ public static EntityPlaceEvent callEntityPlaceEvent(Level world, BlockPos clickP /** * Bucket methods */ - public static PlayerBucketEmptyEvent callPlayerBucketEmptyEvent(ServerLevel world, net.minecraft.world.entity.player.Player who, BlockPos changed, BlockPos clicked, Direction clickedFace, ItemStack itemInHand, InteractionHand enumhand) { - return (PlayerBucketEmptyEvent) CraftEventFactory.getPlayerBucketEvent(false, world, who, changed, clicked, clickedFace, itemInHand, Items.BUCKET, enumhand); + public static PlayerBucketEmptyEvent callPlayerBucketEmptyEvent(WorldServer world, EntityHuman who, BlockPos changed, BlockPos clicked, EnumDirection clickedFace, ItemStack itemInHand, EnumHand enumhand) { + return (PlayerBucketEmptyEvent) getPlayerBucketEvent(false, world, who, changed, clicked, clickedFace, itemInHand, Items.BUCKET, enumhand); } - public static PlayerBucketFillEvent callPlayerBucketFillEvent(ServerLevel world, net.minecraft.world.entity.player.Player who, BlockPos changed, BlockPos clicked, Direction clickedFace, ItemStack itemInHand, net.minecraft.world.item.Item bucket, InteractionHand enumhand) { - return (PlayerBucketFillEvent) CraftEventFactory.getPlayerBucketEvent(true, world, who, clicked, changed, clickedFace, itemInHand, bucket, enumhand); + public static PlayerBucketFillEvent callPlayerBucketFillEvent(WorldServer world, EntityHuman who, BlockPos changed, BlockPos clicked, EnumDirection clickedFace, ItemStack itemInHand, net.minecraft.world.item.Item bucket, EnumHand enumhand) { + return (PlayerBucketFillEvent) getPlayerBucketEvent(true, world, who, clicked, changed, clickedFace, itemInHand, bucket, enumhand); } - private static PlayerEvent getPlayerBucketEvent(boolean isFilling, ServerLevel world, net.minecraft.world.entity.player.Player who, BlockPos changed, BlockPos clicked, Direction clickedFace, ItemStack itemstack, net.minecraft.world.item.Item item, InteractionHand enumhand) { + private static PlayerEvent getPlayerBucketEvent(boolean isFilling, WorldServer world, EntityHuman who, BlockPos changed, BlockPos clicked, EnumDirection clickedFace, ItemStack itemstack, net.minecraft.world.item.Item item, EnumHand enumhand) { Player player = (Player) who.getBukkitEntity(); CraftItemStack itemInHand = CraftItemStack.asNewCraftStack(item); Material bucket = CraftItemType.minecraftToBukkit(itemstack.getItem()); @@ -504,10 +516,10 @@ private static PlayerEvent getPlayerBucketEvent(boolean isFilling, ServerLevel w PlayerEvent event; if (isFilling) { event = new PlayerBucketFillEvent(player, block, blockClicked, blockFace, bucket, itemInHand, hand); - ((PlayerBucketFillEvent) event).setCancelled(!CraftEventFactory.canBuild(world, player, changed.getX(), changed.getZ())); + ((PlayerBucketFillEvent) event).setCancelled(!canBuild(world, player, changed.getX(), changed.getZ())); } else { event = new PlayerBucketEmptyEvent(player, block, blockClicked, blockFace, bucket, itemInHand, hand); - ((PlayerBucketEmptyEvent) event).setCancelled(!CraftEventFactory.canBuild(world, player, changed.getX(), changed.getZ())); + ((PlayerBucketEmptyEvent) event).setCancelled(!canBuild(world, player, changed.getX(), changed.getZ())); } craftServer.getPluginManager().callEvent(event); @@ -518,24 +530,24 @@ private static PlayerEvent getPlayerBucketEvent(boolean isFilling, ServerLevel w /** * Player Interact event */ - public static PlayerInteractEvent callPlayerInteractEvent(net.minecraft.world.entity.player.Player who, Action action, ItemStack itemstack, InteractionHand hand) { + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, ItemStack itemstack, EnumHand hand) { if (action != Action.LEFT_CLICK_AIR && action != Action.RIGHT_CLICK_AIR) { throw new AssertionError(String.format("%s performing %s with %s", who, action, itemstack)); } - return CraftEventFactory.callPlayerInteractEvent(who, action, null, Direction.SOUTH, itemstack, hand); + return callPlayerInteractEvent(who, action, null, EnumDirection.SOUTH, itemstack, hand); } - public static PlayerInteractEvent callPlayerInteractEvent(net.minecraft.world.entity.player.Player who, Action action, BlockPos position, Direction direction, ItemStack itemstack, InteractionHand hand) { - return CraftEventFactory.callPlayerInteractEvent(who, action, position, direction, itemstack, false, hand, null); + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, BlockPos position, EnumDirection direction, ItemStack itemstack, EnumHand hand) { + return callPlayerInteractEvent(who, action, position, direction, itemstack, false, hand, null); } - public static PlayerInteractEvent callPlayerInteractEvent(net.minecraft.world.entity.player.Player who, Action action, BlockPos position, Direction direction, ItemStack itemstack, boolean cancelledBlock, InteractionHand hand, Vec3 targetPos) { + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, BlockPos position, EnumDirection direction, ItemStack itemstack, boolean cancelledBlock, EnumHand hand, Vec3D targetPos) { Player player = (who == null) ? null : (Player) who.getBukkitEntity(); CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); Vector clickedPos = null; if (position != null && targetPos != null) { - clickedPos = CraftVector.toBukkit(targetPos.subtract(Vec3.atLowerCornerOf(position))); + clickedPos = CraftVector.toBukkit(targetPos.subtract(Vec3D.atLowerCornerOf(position))); } CraftWorld craftWorld = (CraftWorld) player.getWorld(); @@ -560,7 +572,7 @@ public static PlayerInteractEvent callPlayerInteractEvent(net.minecraft.world.en itemInHand = null; } - PlayerInteractEvent event = new PlayerInteractEvent(player, action, itemInHand, blockClicked, blockFace, (hand == null) ? null : ((hand == InteractionHand.OFF_HAND) ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND), clickedPos); + PlayerInteractEvent event = new PlayerInteractEvent(player, action, itemInHand, blockClicked, blockFace, (hand == null) ? null : ((hand == EnumHand.OFF_HAND) ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND), clickedPos); if (cancelledBlock) { event.setUseInteractedBlock(Event.Result.DENY); } @@ -572,16 +584,16 @@ public static PlayerInteractEvent callPlayerInteractEvent(net.minecraft.world.en /** * EntityTransformEvent */ - public static EntityTransformEvent callEntityTransformEvent(net.minecraft.world.entity.LivingEntity original, net.minecraft.world.entity.LivingEntity coverted, EntityTransformEvent.TransformReason transformReason) { - return CraftEventFactory.callEntityTransformEvent(original, Collections.singletonList(coverted), transformReason); + public static EntityTransformEvent callEntityTransformEvent(EntityLiving original, EntityLiving coverted, EntityTransformEvent.TransformReason transformReason) { + return callEntityTransformEvent(original, Collections.singletonList(coverted), transformReason); } /** * EntityTransformEvent */ - public static EntityTransformEvent callEntityTransformEvent(net.minecraft.world.entity.LivingEntity original, List convertedList, EntityTransformEvent.TransformReason convertType) { + public static EntityTransformEvent callEntityTransformEvent(EntityLiving original, List convertedList, EntityTransformEvent.TransformReason convertType) { List list = new ArrayList<>(); - for (net.minecraft.world.entity.LivingEntity entityLiving : convertedList) { + for (EntityLiving entityLiving : convertedList) { list.add(entityLiving.getBukkitEntity()); } @@ -594,12 +606,12 @@ public static EntityTransformEvent callEntityTransformEvent(net.minecraft.world. /** * EntityShootBowEvent */ - public static EntityShootBowEvent callEntityShootBowEvent(net.minecraft.world.entity.LivingEntity who, ItemStack bow, ItemStack consumableItem, Entity entityArrow, InteractionHand hand, float force, boolean consumeItem) { + public static EntityShootBowEvent callEntityShootBowEvent(EntityLiving who, ItemStack bow, ItemStack consumableItem, Entity entityArrow, EnumHand hand, float force, boolean consumeItem) { LivingEntity shooter = (LivingEntity) who.getBukkitEntity(); CraftItemStack itemInHand = CraftItemStack.asCraftMirror(bow); CraftItemStack itemConsumable = CraftItemStack.asCraftMirror(consumableItem); org.bukkit.entity.Entity arrow = entityArrow.getBukkitEntity(); - EquipmentSlot handSlot = (hand == InteractionHand.MAIN_HAND) ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND; + EquipmentSlot handSlot = (hand == EnumHand.MAIN_HAND) ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND; if (itemInHand != null && (itemInHand.getType() == Material.AIR || itemInHand.getAmount() == 0)) { itemInHand = null; @@ -614,7 +626,7 @@ public static EntityShootBowEvent callEntityShootBowEvent(net.minecraft.world.en /** * VillagerCareerChangeEvent */ - public static VillagerCareerChangeEvent callVillagerCareerChangeEvent(net.minecraft.world.entity.npc.Villager vilager, Profession future, VillagerCareerChangeEvent.ChangeReason reason) { + public static VillagerCareerChangeEvent callVillagerCareerChangeEvent(EntityVillager vilager, Profession future, VillagerCareerChangeEvent.ChangeReason reason) { VillagerCareerChangeEvent event = new VillagerCareerChangeEvent((Villager) vilager.getBukkitEntity(), future, reason); Bukkit.getPluginManager().callEvent(event); @@ -624,7 +636,7 @@ public static VillagerCareerChangeEvent callVillagerCareerChangeEvent(net.minecr /** * BlockDamageEvent */ - public static BlockDamageEvent callBlockDamageEvent(ServerPlayer who, BlockPos pos, ItemStack itemstack, boolean instaBreak) { + public static BlockDamageEvent callBlockDamageEvent(EntityPlayer who, BlockPos pos, ItemStack itemstack, boolean instaBreak) { Player player = who.getBukkitEntity(); CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); @@ -636,7 +648,7 @@ public static BlockDamageEvent callBlockDamageEvent(ServerPlayer who, BlockPos p return event; } - public static BlockDamageAbortEvent callBlockDamageAbortEvent(ServerPlayer who, BlockPos pos, ItemStack itemstack) { + public static BlockDamageAbortEvent callBlockDamageAbortEvent(EntityPlayer who, BlockPos pos, ItemStack itemstack) { Player player = who.getBukkitEntity(); CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); @@ -648,25 +660,24 @@ public static BlockDamageAbortEvent callBlockDamageAbortEvent(ServerPlayer who, return event; } - public static boolean doEntityAddEventCalling(Level world, Entity entity, SpawnReason spawnReason) { + public static boolean doEntityAddEventCalling(World world, Entity entity, SpawnReason spawnReason) { if (entity == null) return false; org.bukkit.event.Cancellable event = null; - if (entity instanceof net.minecraft.world.entity.LivingEntity && !(entity instanceof ServerPlayer)) { - boolean isAnimal = entity instanceof Animal || entity instanceof WaterAnimal || entity instanceof AbstractGolem; - boolean isMonster = entity instanceof Monster || entity instanceof Ghast || entity instanceof Slime; - boolean isNpc = entity instanceof Npc; + if (entity instanceof EntityLiving && !(entity instanceof EntityPlayer)) { + boolean isAnimal = entity instanceof EntityAnimal || entity instanceof EntityWaterAnimal || entity instanceof EntityGolem; + boolean isMonster = entity instanceof EntityMonster || entity instanceof EntityGhast || entity instanceof EntitySlime; if (spawnReason != SpawnReason.CUSTOM) { - if (isAnimal && !world.getWorld().getAllowAnimals() || isMonster && !world.getWorld().getAllowMonsters() || isNpc && !world.getCraftServer().getServer().areNpcsEnabled()) { + if (isAnimal && !world.getWorld().getAllowAnimals() || isMonster && !world.getWorld().getAllowMonsters()) { entity.discard(null); // Add Bukkit remove cause return false; } } - event = CraftEventFactory.callCreatureSpawnEvent((net.minecraft.world.entity.LivingEntity) entity, spawnReason); - } else if (entity instanceof ItemEntity) { - event = CraftEventFactory.callItemSpawnEvent((ItemEntity) entity); + event = CraftEventFactory.callCreatureSpawnEvent((EntityLiving) entity, spawnReason); + } else if (entity instanceof EntityItem) { + event = CraftEventFactory.callItemSpawnEvent((EntityItem) entity); } else if (entity.getBukkitEntity() instanceof org.bukkit.entity.Projectile) { // Not all projectiles extend EntityProjectile, so check for Bukkit interface instead event = CraftEventFactory.callProjectileLaunchEvent(entity); @@ -690,7 +701,7 @@ public static boolean doEntityAddEventCalling(Level world, Entity entity, SpawnR return true; } event = CraftEventFactory.callLightningStrikeEvent((LightningStrike) entity.getBukkitEntity(), cause); - } else if (!(entity instanceof ServerPlayer)) { + } else if (!(entity instanceof EntityPlayer)) { event = CraftEventFactory.callEntitySpawnEvent(entity); } @@ -706,23 +717,6 @@ public static boolean doEntityAddEventCalling(Level world, Entity entity, SpawnR return false; } - // Spigot start - SPIGOT-7523: Merge after spawn event and only merge if the event was not cancelled (gets checked above) - if (entity instanceof net.minecraft.world.entity.ExperienceOrb xp) { - double radius = world.spigotConfig.expMerge; - if (radius > 0) { - List entities = world.getEntities(entity, entity.getBoundingBox().inflate(radius, radius, radius)); - for (Entity e : entities) { - if (e instanceof net.minecraft.world.entity.ExperienceOrb loopItem) { - if (!loopItem.isRemoved()) { - xp.value += loopItem.value; - loopItem.discard(null); // Add Bukkit remove cause - } - } - } - } - } - // Spigot end - return true; } @@ -740,7 +734,7 @@ public static EntitySpawnEvent callEntitySpawnEvent(Entity entity) { /** * CreatureSpawnEvent */ - public static CreatureSpawnEvent callCreatureSpawnEvent(net.minecraft.world.entity.LivingEntity entityliving, SpawnReason spawnReason) { + public static CreatureSpawnEvent callCreatureSpawnEvent(EntityLiving entityliving, SpawnReason spawnReason) { LivingEntity entity = (LivingEntity) entityliving.getBukkitEntity(); CraftServer craftServer = (CraftServer) entity.getServer(); @@ -752,7 +746,7 @@ public static CreatureSpawnEvent callCreatureSpawnEvent(net.minecraft.world.enti /** * EntityTameEvent */ - public static EntityTameEvent callEntityTameEvent(Mob entity, net.minecraft.world.entity.player.Player tamer) { + public static EntityTameEvent callEntityTameEvent(EntityInsentient entity, EntityHuman tamer) { org.bukkit.entity.Entity bukkitEntity = entity.getBukkitEntity(); org.bukkit.entity.AnimalTamer bukkitTamer = (tamer != null ? tamer.getBukkitEntity() : null); CraftServer craftServer = (CraftServer) bukkitEntity.getServer(); @@ -765,7 +759,7 @@ public static EntityTameEvent callEntityTameEvent(Mob entity, net.minecraft.worl /** * ItemSpawnEvent */ - public static ItemSpawnEvent callItemSpawnEvent(ItemEntity entityitem) { + public static ItemSpawnEvent callItemSpawnEvent(EntityItem entityitem) { org.bukkit.entity.Item entity = (org.bukkit.entity.Item) entityitem.getBukkitEntity(); CraftServer craftServer = (CraftServer) entity.getServer(); @@ -778,7 +772,7 @@ public static ItemSpawnEvent callItemSpawnEvent(ItemEntity entityitem) { /** * ItemDespawnEvent */ - public static ItemDespawnEvent callItemDespawnEvent(ItemEntity entityitem) { + public static ItemDespawnEvent callItemDespawnEvent(EntityItem entityitem) { org.bukkit.entity.Item entity = (org.bukkit.entity.Item) entityitem.getBukkitEntity(); ItemDespawnEvent event = new ItemDespawnEvent(entity, entity.getLocation()); @@ -790,7 +784,7 @@ public static ItemDespawnEvent callItemDespawnEvent(ItemEntity entityitem) { /** * ItemMergeEvent */ - public static boolean callItemMergeEvent(ItemEntity merging, ItemEntity mergingWith) { + public static boolean callItemMergeEvent(EntityItem merging, EntityItem mergingWith) { org.bukkit.entity.Item entityMerging = (org.bukkit.entity.Item) merging.getBukkitEntity(); org.bukkit.entity.Item entityMergingWith = (org.bukkit.entity.Item) mergingWith.getBukkitEntity(); @@ -803,20 +797,20 @@ public static boolean callItemMergeEvent(ItemEntity merging, ItemEntity mergingW /** * PotionSplashEvent */ - public static PotionSplashEvent callPotionSplashEvent(net.minecraft.world.entity.projectile.ThrownPotion potion, HitResult position, Map affectedEntities) { + public static PotionSplashEvent callPotionSplashEvent(EntityPotion potion, MovingObjectPosition position, Map affectedEntities) { ThrownPotion thrownPotion = (ThrownPotion) potion.getBukkitEntity(); Block hitBlock = null; BlockFace hitFace = null; - if (position.getType() == HitResult.Type.BLOCK) { - BlockHitResult positionBlock = (BlockHitResult) position; + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + MovingObjectPositionBlock positionBlock = (MovingObjectPositionBlock) position; hitBlock = CraftBlock.at(potion.level(), positionBlock.getBlockPos()); hitFace = CraftBlock.notchToBlockFace(positionBlock.getDirection()); } org.bukkit.entity.Entity hitEntity = null; - if (position.getType() == HitResult.Type.ENTITY) { - hitEntity = ((EntityHitResult) position).getEntity().getBukkitEntity(); + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { + hitEntity = ((MovingObjectPositionEntity) position).getEntity().getBukkitEntity(); } PotionSplashEvent event = new PotionSplashEvent(thrownPotion, hitEntity, hitBlock, hitFace, affectedEntities); @@ -824,21 +818,21 @@ public static PotionSplashEvent callPotionSplashEvent(net.minecraft.world.entity return event; } - public static LingeringPotionSplashEvent callLingeringPotionSplashEvent(net.minecraft.world.entity.projectile.ThrownPotion potion, HitResult position, net.minecraft.world.entity.AreaEffectCloud cloud) { + public static LingeringPotionSplashEvent callLingeringPotionSplashEvent(EntityPotion potion, MovingObjectPosition position, EntityAreaEffectCloud cloud) { ThrownPotion thrownPotion = (ThrownPotion) potion.getBukkitEntity(); AreaEffectCloud effectCloud = (AreaEffectCloud) cloud.getBukkitEntity(); Block hitBlock = null; BlockFace hitFace = null; - if (position.getType() == HitResult.Type.BLOCK) { - BlockHitResult positionBlock = (BlockHitResult) position; + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + MovingObjectPositionBlock positionBlock = (MovingObjectPositionBlock) position; hitBlock = CraftBlock.at(potion.level(), positionBlock.getBlockPos()); hitFace = CraftBlock.notchToBlockFace(positionBlock.getDirection()); } org.bukkit.entity.Entity hitEntity = null; - if (position.getType() == HitResult.Type.ENTITY) { - hitEntity = ((EntityHitResult) position).getEntity().getBukkitEntity(); + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { + hitEntity = ((MovingObjectPositionEntity) position).getEntity().getBukkitEntity(); } LingeringPotionSplashEvent event = new LingeringPotionSplashEvent(thrownPotion, hitEntity, hitBlock, hitFace, effectCloud); @@ -849,7 +843,7 @@ public static LingeringPotionSplashEvent callLingeringPotionSplashEvent(net.mine /** * BlockFadeEvent */ - public static BlockFadeEvent callBlockFadeEvent(LevelAccessor world, BlockPos pos, net.minecraft.world.level.block.state.BlockState newBlock) { + public static BlockFadeEvent callBlockFadeEvent(GeneratorAccess world, BlockPos pos, IBlockData newBlock) { CraftBlockState state = CraftBlockStates.getBlockState(world, pos); state.setData(newBlock); @@ -858,7 +852,7 @@ public static BlockFadeEvent callBlockFadeEvent(LevelAccessor world, BlockPos po return event; } - public static boolean handleMoistureChangeEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState newBlock, int flag) { + public static boolean handleMoistureChangeEvent(World world, BlockPos pos, IBlockData newBlock, int flag) { CraftBlockState state = CraftBlockStates.getBlockState(world, pos, flag); state.setData(newBlock); @@ -871,15 +865,15 @@ public static boolean handleMoistureChangeEvent(Level world, BlockPos pos, net.m return !event.isCancelled(); } - public static boolean handleBlockSpreadEvent(Level world, BlockPos source, BlockPos target, net.minecraft.world.level.block.state.BlockState block) { - return CraftEventFactory.handleBlockSpreadEvent(world, source, target, block, 2); + public static boolean handleBlockSpreadEvent(World world, BlockPos source, BlockPos target, IBlockData block) { + return handleBlockSpreadEvent(world, source, target, block, 2); } - public static BlockPos sourceBlockOverride = null; // SPIGOT-7068: Add source block override, not the most elegant way but better than passing down a BlockPosition up to five methods deep. + public static BlockPos sourceBlockOverride = null; // SPIGOT-7068: Add source block override, not the most elegant way but better than passing down a BlockPos up to five methods deep. - public static boolean handleBlockSpreadEvent(LevelAccessor world, BlockPos source, BlockPos target, net.minecraft.world.level.block.state.BlockState block, int flag) { + public static boolean handleBlockSpreadEvent(GeneratorAccess world, BlockPos source, BlockPos target, IBlockData block, int flag) { // Suppress during worldgen - if (!(world instanceof Level)) { + if (!(world instanceof World)) { world.setBlock(target, block, flag); return true; } @@ -887,7 +881,7 @@ public static boolean handleBlockSpreadEvent(LevelAccessor world, BlockPos sourc CraftBlockState state = CraftBlockStates.getBlockState(world, target, flag); state.setData(block); - BlockSpreadEvent event = new BlockSpreadEvent(state.getBlock(), CraftBlock.at(world, CraftEventFactory.sourceBlockOverride != null ? CraftEventFactory.sourceBlockOverride : source), state); + BlockSpreadEvent event = new BlockSpreadEvent(state.getBlock(), CraftBlock.at(world, sourceBlockOverride != null ? sourceBlockOverride : source), state); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { @@ -896,15 +890,15 @@ public static boolean handleBlockSpreadEvent(LevelAccessor world, BlockPos sourc return !event.isCancelled(); } - public static EntityDeathEvent callEntityDeathEvent(net.minecraft.world.entity.LivingEntity victim, DamageSource damageSource) { - return CraftEventFactory.callEntityDeathEvent(victim, damageSource, new ArrayList(0)); + public static EntityDeathEvent callEntityDeathEvent(EntityLiving victim, DamageSource damageSource) { + return callEntityDeathEvent(victim, damageSource, new ArrayList(0)); } - public static EntityDeathEvent callEntityDeathEvent(net.minecraft.world.entity.LivingEntity victim, DamageSource damageSource, List drops) { + public static EntityDeathEvent callEntityDeathEvent(EntityLiving victim, DamageSource damageSource, List drops) { CraftLivingEntity entity = (CraftLivingEntity) victim.getBukkitEntity(); CraftDamageSource bukkitDamageSource = new CraftDamageSource(damageSource); - EntityDeathEvent event = new EntityDeathEvent(entity, bukkitDamageSource, drops, victim.getExpReward(damageSource.getEntity())); CraftWorld world = (CraftWorld) entity.getWorld(); + EntityDeathEvent event = new EntityDeathEvent(entity, bukkitDamageSource, drops, victim.getExpReward(world.getHandle(), damageSource.getEntity())); Bukkit.getServer().getPluginManager().callEvent(event); victim.expToDrop = event.getDroppedExp(); @@ -918,10 +912,10 @@ public static EntityDeathEvent callEntityDeathEvent(net.minecraft.world.entity.L return event; } - public static PlayerDeathEvent callPlayerDeathEvent(ServerPlayer victim, DamageSource damageSource, List drops, String deathMessage, boolean keepInventory) { + public static PlayerDeathEvent callPlayerDeathEvent(EntityPlayer victim, DamageSource damageSource, List drops, String deathMessage, boolean keepInventory) { CraftPlayer entity = victim.getBukkitEntity(); CraftDamageSource bukkitDamageSource = new CraftDamageSource(damageSource); - PlayerDeathEvent event = new PlayerDeathEvent(entity, bukkitDamageSource, drops, victim.getExpReward(damageSource.getEntity()), 0, deathMessage); + PlayerDeathEvent event = new PlayerDeathEvent(entity, bukkitDamageSource, drops, victim.getExpReward(victim.serverLevel(), damageSource.getEntity()), 0, deathMessage); event.setKeepInventory(keepInventory); event.setKeepLevel(victim.keepLevel); // SPIGOT-2222: pre-set keepLevel Bukkit.getServer().getPluginManager().callEvent(event); @@ -935,7 +929,13 @@ public static PlayerDeathEvent callPlayerDeathEvent(ServerPlayer victim, DamageS for (org.bukkit.inventory.ItemStack stack : event.getDrops()) { if (stack == null || stack.getType() == Material.AIR) continue; - victim.drop(CraftItemStack.asNMSCopy(stack), true, false, false); // SPIGOT-7800, SPIGOT-7801: Vanilla Behaviour for dropped items + if (stack instanceof CraftItemStack craftItemStack && craftItemStack.isForInventoryDrop()) { + victim.drop(CraftItemStack.asNMSCopy(stack), true, false, false); // SPIGOT-7800, SPIGOT-7801: Vanilla Behaviour for Player Inventory dropped items + } else { + victim.forceDrops = true; + victim.spawnAtLocation(victim.serverLevel(), CraftItemStack.asNMSCopy(stack)); // SPIGOT-7806: Vanilla Behaviour for items not related to Player Inventory dropped items + victim.forceDrops = false; + } } return event; @@ -951,7 +951,7 @@ public static ServerListPingEvent callServerListPingEvent(SocketAddress address, } private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSource source, Map modifiers, Map> modifierFunctions) { - return CraftEventFactory.handleEntityDamageEvent(entity, source, modifiers, modifierFunctions, false); + return handleEntityDamageEvent(entity, source, modifiers, modifierFunctions, false); } private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSource source, Map modifiers, Map> modifierFunctions, boolean cancelled) { @@ -959,14 +959,14 @@ private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSo Entity damager = (source.getDamager() != null) ? source.getDamager() : source.getEntity(); if (source.is(DamageTypeTags.IS_EXPLOSION)) { if (damager == null) { - return CraftEventFactory.callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, DamageCause.BLOCK_EXPLOSION, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, DamageCause.BLOCK_EXPLOSION, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } DamageCause damageCause = (damager.getBukkitEntity() instanceof org.bukkit.entity.TNTPrimed) ? DamageCause.BLOCK_EXPLOSION : DamageCause.ENTITY_EXPLOSION; - return CraftEventFactory.callEntityDamageEvent(damager, entity, damageCause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent(damager, entity, damageCause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } else if (damager != null || source.getDirectEntity() != null) { DamageCause cause = (source.isSweep()) ? DamageCause.ENTITY_SWEEP_ATTACK : DamageCause.ENTITY_ATTACK; - if (damager instanceof net.minecraft.world.entity.projectile.Projectile) { + if (damager instanceof IProjectile) { if (damager.getBukkitEntity() instanceof ThrownPotion) { cause = DamageCause.MAGIC; } else if (damager.getBukkitEntity() instanceof Projectile) { @@ -988,11 +988,11 @@ private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSo cause = DamageCause.MAGIC; } - return CraftEventFactory.callEntityDamageEvent(damager, entity, cause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent(damager, entity, cause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } else if (source.is(DamageTypes.FELL_OUT_OF_WORLD)) { - return CraftEventFactory.callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, DamageCause.VOID, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, DamageCause.VOID, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } else if (source.is(DamageTypes.LAVA)) { - return CraftEventFactory.callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, DamageCause.LAVA, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, DamageCause.LAVA, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } else if (source.getDirectBlock() != null) { DamageCause cause; if (source.is(DamageTypes.CACTUS) || source.is(DamageTypes.SWEET_BERRY_BUSH) || source.is(DamageTypes.STALAGMITE) || source.is(DamageTypes.FALLING_STALACTITE) || source.is(DamageTypes.FALLING_ANVIL)) { @@ -1008,7 +1008,7 @@ private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSo } else { throw new IllegalStateException(String.format("Unhandled damage of %s by %s from %s [%s]", entity, source.getDirectBlock(), source.getMsgId(), source.typeHolder().getRegisteredName())); } - return CraftEventFactory.callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, cause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent(source.getDirectBlock(), source.getDirectBlockState(), entity, cause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } DamageCause cause; @@ -1048,7 +1048,7 @@ private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSo cause = DamageCause.CUSTOM; } - return CraftEventFactory.callEntityDamageEvent((Entity) null, entity, cause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); + return callEntityDamageEvent((Entity) null, entity, cause, bukkitDamageSource, modifiers, modifierFunctions, cancelled); } private static EntityDamageEvent callEntityDamageEvent(Entity damager, Entity damagee, DamageCause cause, org.bukkit.damage.DamageSource bukkitDamageSource, Map modifiers, Map> modifierFunctions, boolean cancelled) { @@ -1058,7 +1058,7 @@ private static EntityDamageEvent callEntityDamageEvent(Entity damager, Entity da } else { event = new EntityDamageEvent(damagee.getBukkitEntity(), cause, bukkitDamageSource, modifiers, modifierFunctions); } - return CraftEventFactory.callEntityDamageEvent(event, damagee, cancelled); + return callEntityDamageEvent(event, damagee, cancelled); } private static EntityDamageEvent callEntityDamageEvent(Block damager, BlockState damagerState, Entity damagee, DamageCause cause, org.bukkit.damage.DamageSource bukkitDamageSource, Map modifiers, Map> modifierFunctions, boolean cancelled) { @@ -1068,7 +1068,7 @@ private static EntityDamageEvent callEntityDamageEvent(Block damager, BlockState private static EntityDamageEvent callEntityDamageEvent(EntityDamageEvent event, Entity damagee, boolean cancelled) { event.setCancelled(cancelled); - CraftEventFactory.callEvent(event); + callEvent(event); if (!event.isCancelled()) { event.getEntity().setLastDamageCause(event); @@ -1085,7 +1085,7 @@ public static EntityDamageEvent handleLivingEntityDamageEvent(Entity damagee, Da Map modifiers = new EnumMap<>(DamageModifier.class); Map> modifierFunctions = new EnumMap<>(DamageModifier.class); modifiers.put(DamageModifier.BASE, rawDamage); - modifierFunctions.put(DamageModifier.BASE, CraftEventFactory.ZERO); + modifierFunctions.put(DamageModifier.BASE, ZERO); if (source.is(DamageTypes.FREEZE)) { modifiers.put(DamageModifier.FREEZING, freezingModifier); modifierFunctions.put(DamageModifier.FREEZING, freezing); @@ -1094,7 +1094,7 @@ public static EntityDamageEvent handleLivingEntityDamageEvent(Entity damagee, Da modifiers.put(DamageModifier.HARD_HAT, hardHatModifier); modifierFunctions.put(DamageModifier.HARD_HAT, hardHat); } - if (damagee instanceof net.minecraft.world.entity.player.Player) { + if (damagee instanceof EntityHuman) { modifiers.put(DamageModifier.BLOCKING, blockingModifier); modifierFunctions.put(DamageModifier.BLOCKING, blocking); } @@ -1106,16 +1106,16 @@ public static EntityDamageEvent handleLivingEntityDamageEvent(Entity damagee, Da modifierFunctions.put(DamageModifier.MAGIC, magic); modifiers.put(DamageModifier.ABSORPTION, absorptionModifier); modifierFunctions.put(DamageModifier.ABSORPTION, absorption); - return CraftEventFactory.handleEntityDamageEvent(damagee, source, modifiers, modifierFunctions); + return handleEntityDamageEvent(damagee, source, modifiers, modifierFunctions); } // Non-Living Entities such as EntityEnderCrystal and EntityFireball need to call this public static boolean handleNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage) { - return CraftEventFactory.handleNonLivingEntityDamageEvent(entity, source, damage, true); + return handleNonLivingEntityDamageEvent(entity, source, damage, true); } public static boolean handleNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage, boolean cancelOnZeroDamage) { - return CraftEventFactory.handleNonLivingEntityDamageEvent(entity, source, damage, cancelOnZeroDamage, false); + return handleNonLivingEntityDamageEvent(entity, source, damage, cancelOnZeroDamage, false); } public static EntityDamageEvent callNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage, boolean cancelled) { @@ -1123,13 +1123,13 @@ public static EntityDamageEvent callNonLivingEntityDamageEvent(Entity entity, Da final EnumMap> functions = new EnumMap(DamageModifier.class); modifiers.put(DamageModifier.BASE, damage); - functions.put(DamageModifier.BASE, CraftEventFactory.ZERO); + functions.put(DamageModifier.BASE, ZERO); - return CraftEventFactory.handleEntityDamageEvent(entity, source, modifiers, functions, cancelled); + return handleEntityDamageEvent(entity, source, modifiers, functions, cancelled); } public static boolean handleNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage, boolean cancelOnZeroDamage, boolean cancelled) { - final EntityDamageEvent event = CraftEventFactory.callNonLivingEntityDamageEvent(entity, source, damage, cancelled); + final EntityDamageEvent event = callNonLivingEntityDamageEvent(entity, source, damage, cancelled); if (event == null) { return false; @@ -1143,21 +1143,21 @@ public static PlayerLevelChangeEvent callPlayerLevelChangeEvent(Player player, i return event; } - public static PlayerExpChangeEvent callPlayerExpChangeEvent(net.minecraft.world.entity.player.Player entity, int expAmount) { + public static PlayerExpChangeEvent callPlayerExpChangeEvent(EntityHuman entity, int expAmount) { Player player = (Player) entity.getBukkitEntity(); PlayerExpChangeEvent event = new PlayerExpChangeEvent(player, expAmount); Bukkit.getPluginManager().callEvent(event); return event; } - public static PlayerExpCooldownChangeEvent callPlayerXpCooldownEvent(net.minecraft.world.entity.player.Player entity, int newCooldown, PlayerExpCooldownChangeEvent.ChangeReason changeReason) { + public static PlayerExpCooldownChangeEvent callPlayerXpCooldownEvent(EntityHuman entity, int newCooldown, PlayerExpCooldownChangeEvent.ChangeReason changeReason) { Player player = (Player) entity.getBukkitEntity(); PlayerExpCooldownChangeEvent event = new PlayerExpCooldownChangeEvent(player, newCooldown, changeReason); Bukkit.getPluginManager().callEvent(event); return event; } - public static PlayerItemMendEvent callPlayerItemMendEvent(net.minecraft.world.entity.player.Player entity, net.minecraft.world.entity.ExperienceOrb orb, net.minecraft.world.item.ItemStack nmsMendedItem, net.minecraft.world.entity.EquipmentSlot slot, int repairAmount) { + public static PlayerItemMendEvent callPlayerItemMendEvent(EntityHuman entity, EntityExperienceOrb orb, net.minecraft.world.item.ItemStack nmsMendedItem, EnumItemSlot slot, int repairAmount) { Player player = (Player) entity.getBukkitEntity(); org.bukkit.inventory.ItemStack bukkitStack = CraftItemStack.asCraftMirror(nmsMendedItem); PlayerItemMendEvent event = new PlayerItemMendEvent(player, bukkitStack, CraftEquipmentSlot.getSlot(slot), (ExperienceOrb) orb.getBukkitEntity(), repairAmount); @@ -1165,11 +1165,11 @@ public static PlayerItemMendEvent callPlayerItemMendEvent(net.minecraft.world.en return event; } - public static boolean handleBlockGrowEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState block) { - return CraftEventFactory.handleBlockGrowEvent(world, pos, block, 3); + public static boolean handleBlockGrowEvent(World world, BlockPos pos, IBlockData block) { + return handleBlockGrowEvent(world, pos, block, 3); } - public static boolean handleBlockGrowEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState newData, int flag) { + public static boolean handleBlockGrowEvent(World world, BlockPos pos, IBlockData newData, int flag) { Block block = world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); CraftBlockState state = (CraftBlockState) block.getState(); state.setData(newData); @@ -1184,17 +1184,17 @@ public static boolean handleBlockGrowEvent(Level world, BlockPos pos, net.minecr return !event.isCancelled(); } - public static FluidLevelChangeEvent callFluidLevelChangeEvent(Level world, BlockPos block, net.minecraft.world.level.block.state.BlockState newData) { + public static FluidLevelChangeEvent callFluidLevelChangeEvent(World world, BlockPos block, IBlockData newData) { FluidLevelChangeEvent event = new FluidLevelChangeEvent(CraftBlock.at(world, block), CraftBlockData.fromData(newData)); world.getCraftServer().getPluginManager().callEvent(event); return event; } - public static FoodLevelChangeEvent callFoodLevelChangeEvent(net.minecraft.world.entity.player.Player entity, int level) { - return CraftEventFactory.callFoodLevelChangeEvent(entity, level, null); + public static FoodLevelChangeEvent callFoodLevelChangeEvent(EntityHuman entity, int level) { + return callFoodLevelChangeEvent(entity, level, null); } - public static FoodLevelChangeEvent callFoodLevelChangeEvent(net.minecraft.world.entity.player.Player entity, int level, ItemStack item) { + public static FoodLevelChangeEvent callFoodLevelChangeEvent(EntityHuman entity, int level, ItemStack item) { FoodLevelChangeEvent event = new FoodLevelChangeEvent(entity.getBukkitEntity(), level, (item == null) ? null : CraftItemStack.asBukkitCopy(item)); entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); return event; @@ -1212,11 +1212,11 @@ public static boolean callHorseJumpEvent(Entity horse, float power) { return !event.isCancelled(); } - public static boolean callEntityChangeBlockEvent(Entity entity, BlockPos position, net.minecraft.world.level.block.state.BlockState newBlock) { - return CraftEventFactory.callEntityChangeBlockEvent(entity, position, newBlock, false); + public static boolean callEntityChangeBlockEvent(Entity entity, BlockPos position, IBlockData newBlock) { + return callEntityChangeBlockEvent(entity, position, newBlock, false); } - public static boolean callEntityChangeBlockEvent(Entity entity, BlockPos position, net.minecraft.world.level.block.state.BlockState newBlock, boolean cancelled) { + public static boolean callEntityChangeBlockEvent(Entity entity, BlockPos position, IBlockData newBlock, boolean cancelled) { Block block = entity.level().getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()); EntityChangeBlockEvent event = new EntityChangeBlockEvent(entity.getBukkitEntity(), block, CraftBlockData.fromData(newBlock)); @@ -1237,7 +1237,7 @@ public static EntityTargetEvent callEntityTargetEvent(Entity entity, Entity targ return event; } - public static EntityTargetLivingEntityEvent callEntityTargetLivingEvent(Entity entity, net.minecraft.world.entity.LivingEntity target, EntityTargetEvent.TargetReason reason) { + public static EntityTargetLivingEntityEvent callEntityTargetLivingEvent(Entity entity, EntityLiving target, EntityTargetEvent.TargetReason reason) { EntityTargetLivingEntityEvent event = new EntityTargetLivingEntityEvent(entity.getBukkitEntity(), (target == null) ? null : (LivingEntity) target.getBukkitEntity(), reason); entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); return event; @@ -1253,13 +1253,13 @@ public static EntityBreakDoorEvent callEntityBreakDoorEvent(Entity entity, Block return event; } - public static AbstractContainerMenu callInventoryOpenEvent(ServerPlayer player, AbstractContainerMenu container) { - return CraftEventFactory.callInventoryOpenEvent(player, container, false); + public static Container callInventoryOpenEvent(EntityPlayer player, Container container) { + return callInventoryOpenEvent(player, container, false); } - public static AbstractContainerMenu callInventoryOpenEvent(ServerPlayer player, AbstractContainerMenu container, boolean cancelled) { + public static Container callInventoryOpenEvent(EntityPlayer player, Container container, boolean cancelled) { if (player.containerMenu != player.inventoryMenu) { // fire INVENTORY_CLOSE if one already open - player.connection.handleContainerClose(new ServerboundContainerClosePacket(player.containerMenu.containerId)); + player.connection.handleContainerClose(new PacketPlayInCloseWindow(player.containerMenu.containerId)); } CraftServer server = player.level().getCraftServer(); @@ -1278,7 +1278,7 @@ public static AbstractContainerMenu callInventoryOpenEvent(ServerPlayer player, return container; } - public static ItemStack callPreCraftEvent(CraftingContainer matrix, Container resultInventory, ItemStack result, InventoryView lastCraftView, boolean isRepair) { + public static ItemStack callPreCraftEvent(InventoryCrafting matrix, IInventory resultInventory, ItemStack result, InventoryView lastCraftView, boolean isRepair) { CraftInventoryCrafting inventory = new CraftInventoryCrafting(matrix, resultInventory); inventory.setResult(CraftItemStack.asCraftMirror(result)); @@ -1290,10 +1290,10 @@ public static ItemStack callPreCraftEvent(CraftingContainer matrix, Container re return CraftItemStack.asNMSCopy(bitem); } - public static CrafterCraftEvent callCrafterCraftEvent(BlockPos pos, Level world, CraftingContainer inventoryCrafting, ItemStack result, RecipeHolder holder) { + public static CrafterCraftEvent callCrafterCraftEvent(BlockPos pos, World world, InventoryCrafting inventoryCrafting, ItemStack result, RecipeHolder holder) { CraftBlock block = CraftBlock.at(world, pos); CraftItemStack itemStack = CraftItemStack.asCraftMirror(result); - org.bukkit.inventory.CraftingRecipe craftingRecipe = (org.bukkit.inventory.CraftingRecipe) holder.toBukkitRecipe(); + CraftingRecipe craftingRecipe = (CraftingRecipe) holder.toBukkitRecipe(); CrafterCraftEvent crafterCraftEvent = new CrafterCraftEvent(block, craftingRecipe, itemStack); Bukkit.getPluginManager().callEvent(crafterCraftEvent); @@ -1307,22 +1307,22 @@ public static ProjectileLaunchEvent callProjectileLaunchEvent(Entity entity) { return event; } - public static ProjectileHitEvent callProjectileHitEvent(Entity entity, HitResult position) { - if (position.getType() == HitResult.Type.MISS) { + public static ProjectileHitEvent callProjectileHitEvent(Entity entity, MovingObjectPosition position) { + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { return null; } Block hitBlock = null; BlockFace hitFace = null; - if (position.getType() == HitResult.Type.BLOCK) { - BlockHitResult positionBlock = (BlockHitResult) position; + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + MovingObjectPositionBlock positionBlock = (MovingObjectPositionBlock) position; hitBlock = CraftBlock.at(entity.level(), positionBlock.getBlockPos()); hitFace = CraftBlock.notchToBlockFace(positionBlock.getDirection()); } org.bukkit.entity.Entity hitEntity = null; - if (position.getType() == HitResult.Type.ENTITY) { - hitEntity = ((EntityHitResult) position).getEntity().getBukkitEntity(); + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { + hitEntity = ((MovingObjectPositionEntity) position).getEntity().getBukkitEntity(); } ProjectileHitEvent event = new ProjectileHitEvent((Projectile) entity.getBukkitEntity(), hitEntity, hitBlock, hitFace); @@ -1330,20 +1330,20 @@ public static ProjectileHitEvent callProjectileHitEvent(Entity entity, HitResult return event; } - public static ExpBottleEvent callExpBottleEvent(Entity entity, HitResult position, int exp) { + public static ExpBottleEvent callExpBottleEvent(Entity entity, MovingObjectPosition position, int exp) { ThrownExpBottle bottle = (ThrownExpBottle) entity.getBukkitEntity(); Block hitBlock = null; BlockFace hitFace = null; - if (position.getType() == HitResult.Type.BLOCK) { - BlockHitResult positionBlock = (BlockHitResult) position; + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + MovingObjectPositionBlock positionBlock = (MovingObjectPositionBlock) position; hitBlock = CraftBlock.at(entity.level(), positionBlock.getBlockPos()); hitFace = CraftBlock.notchToBlockFace(positionBlock.getDirection()); } org.bukkit.entity.Entity hitEntity = null; - if (position.getType() == HitResult.Type.ENTITY) { - hitEntity = ((EntityHitResult) position).getEntity().getBukkitEntity(); + if (position.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { + hitEntity = ((MovingObjectPositionEntity) position).getEntity().getBukkitEntity(); } ExpBottleEvent event = new ExpBottleEvent(bottle, hitEntity, hitBlock, hitFace, exp); @@ -1351,25 +1351,25 @@ public static ExpBottleEvent callExpBottleEvent(Entity entity, HitResult positio return event; } - public static BlockRedstoneEvent callRedstoneChange(Level world, BlockPos pos, int oldCurrent, int newCurrent) { + public static BlockRedstoneEvent callRedstoneChange(World world, BlockPos pos, int oldCurrent, int newCurrent) { BlockRedstoneEvent event = new BlockRedstoneEvent(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), oldCurrent, newCurrent); world.getCraftServer().getPluginManager().callEvent(event); return event; } - public static NotePlayEvent callNotePlayEvent(Level world, BlockPos pos, NoteBlockInstrument instrument, int note) { + public static NotePlayEvent callNotePlayEvent(World world, BlockPos pos, BlockPropertyInstrument instrument, int note) { NotePlayEvent event = new NotePlayEvent(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), org.bukkit.Instrument.getByType((byte) instrument.ordinal()), new org.bukkit.Note(note)); world.getCraftServer().getPluginManager().callEvent(event); return event; } - public static void callPlayerItemBreakEvent(ServerPlayer human, ItemStack brokenItem) { + public static void callPlayerItemBreakEvent(EntityPlayer human, ItemStack brokenItem) { CraftItemStack item = CraftItemStack.asCraftMirror(brokenItem); PlayerItemBreakEvent event = new PlayerItemBreakEvent(human.getBukkitEntity(), item); Bukkit.getPluginManager().callEvent(event); } - public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos block, BlockPos source) { + public static BlockIgniteEvent callBlockIgniteEvent(World world, BlockPos block, BlockPos source) { org.bukkit.World bukkitWorld = world.getWorld(); Block igniter = bukkitWorld.getBlockAt(source.getX(), source.getY(), source.getZ()); IgniteCause cause; @@ -1390,7 +1390,7 @@ public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos block, return event; } - public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos pos, Entity igniter) { + public static BlockIgniteEvent callBlockIgniteEvent(World world, BlockPos pos, Entity igniter) { org.bukkit.World bukkitWorld = world.getWorld(); org.bukkit.entity.Entity bukkitIgniter = igniter.getBukkitEntity(); IgniteCause cause; @@ -1412,8 +1412,8 @@ public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos pos, E cause = IgniteCause.FLINT_AND_STEEL; } - if (igniter instanceof net.minecraft.world.entity.projectile.Projectile) { - Entity shooter = ((net.minecraft.world.entity.projectile.Projectile) igniter).getOwner(); + if (igniter instanceof IProjectile) { + Entity shooter = ((IProjectile) igniter).getOwner(); if (shooter != null) { bukkitIgniter = shooter.getBukkitEntity(); } @@ -1424,27 +1424,27 @@ public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos pos, E return event; } - public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos blockposition, Explosion explosion) { - org.bukkit.entity.Entity igniter = explosion.source == null ? null : explosion.source.getBukkitEntity(); + public static BlockIgniteEvent callBlockIgniteEvent(World world, BlockPos blockposition, Explosion explosion) { + org.bukkit.entity.Entity igniter = explosion.getDirectSourceEntity() == null ? null : explosion.getDirectSourceEntity().getBukkitEntity(); BlockIgniteEvent event = new BlockIgniteEvent(CraftBlock.at(world, blockposition), IgniteCause.EXPLOSION, igniter); world.getCraftServer().getPluginManager().callEvent(event); return event; } - public static BlockIgniteEvent callBlockIgniteEvent(Level world, BlockPos pos, IgniteCause cause, Entity igniter) { + public static BlockIgniteEvent callBlockIgniteEvent(World world, BlockPos pos, IgniteCause cause, Entity igniter) { BlockIgniteEvent event = new BlockIgniteEvent(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), cause, igniter.getBukkitEntity()); world.getCraftServer().getPluginManager().callEvent(event); return event; } - public static void handleInventoryCloseEvent(net.minecraft.world.entity.player.Player human) { + public static void handleInventoryCloseEvent(EntityHuman human) { InventoryCloseEvent event = new InventoryCloseEvent(human.containerMenu.getBukkitView()); human.level().getCraftServer().getPluginManager().callEvent(event); human.containerMenu.transferTo(human.inventoryMenu, human.getBukkitEntity()); } - public static ItemStack handleEditBookEvent(ServerPlayer player, int itemInHandIndex, ItemStack itemInHand, ItemStack newBookItem) { + public static ItemStack handleEditBookEvent(EntityPlayer player, int itemInHandIndex, ItemStack itemInHand, ItemStack newBookItem) { PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(player.getBukkitEntity(), (itemInHandIndex >= 0 && itemInHandIndex <= 8) ? itemInHandIndex : -1, (BookMeta) CraftItemStack.getItemMeta(itemInHand), (BookMeta) CraftItemStack.getItemMeta(newBookItem), newBookItem.getItem() == Items.WRITTEN_BOOK); player.level().getCraftServer().getPluginManager().callEvent(editBookEvent); @@ -1464,24 +1464,24 @@ public static ItemStack handleEditBookEvent(ServerPlayer player, int itemInHandI return itemInHand; } - public static void callRecipeBookSettingsEvent(ServerPlayer player, RecipeBookType type, boolean open, boolean filter) { + public static void callRecipeBookSettingsEvent(EntityPlayer player, RecipeBookType type, boolean open, boolean filter) { PlayerRecipeBookSettingsChangeEvent.RecipeBookType bukkitType = PlayerRecipeBookSettingsChangeEvent.RecipeBookType.values()[type.ordinal()]; Bukkit.getPluginManager().callEvent(new PlayerRecipeBookSettingsChangeEvent(player.getBukkitEntity(), bukkitType, open, filter)); } - public static PlayerUnleashEntityEvent callPlayerUnleashEntityEvent(Entity entity, net.minecraft.world.entity.player.Player player, InteractionHand enumhand) { + public static PlayerUnleashEntityEvent callPlayerUnleashEntityEvent(Entity entity, EntityHuman player, EnumHand enumhand) { PlayerUnleashEntityEvent event = new PlayerUnleashEntityEvent(entity.getBukkitEntity(), (Player) player.getBukkitEntity(), CraftEquipmentSlot.getHand(enumhand)); entity.level().getCraftServer().getPluginManager().callEvent(event); return event; } - public static PlayerLeashEntityEvent callPlayerLeashEntityEvent(Entity entity, Entity leashHolder, net.minecraft.world.entity.player.Player player, InteractionHand enumhand) { + public static PlayerLeashEntityEvent callPlayerLeashEntityEvent(Entity entity, Entity leashHolder, EntityHuman player, EnumHand enumhand) { PlayerLeashEntityEvent event = new PlayerLeashEntityEvent(entity.getBukkitEntity(), leashHolder.getBukkitEntity(), (Player) player.getBukkitEntity(), CraftEquipmentSlot.getHand(enumhand)); entity.level().getCraftServer().getPluginManager().callEvent(event); return event; } - public static void callPlayerRiptideEvent(net.minecraft.world.entity.player.Player player, ItemStack tridentItemStack, float velocityX, float velocityY, float velocityZ) { + public static void callPlayerRiptideEvent(EntityHuman player, ItemStack tridentItemStack, float velocityX, float velocityY, float velocityZ) { PlayerRiptideEvent event = new PlayerRiptideEvent((Player) player.getBukkitEntity(), CraftItemStack.asCraftMirror(tridentItemStack), new Vector(velocityX, velocityY, velocityZ)); player.level().getCraftServer().getPluginManager().callEvent(event); } @@ -1492,18 +1492,18 @@ public static BlockShearEntityEvent callBlockShearEntityEvent(Entity animal, org return bse; } - public static boolean handlePlayerShearEntityEvent(net.minecraft.world.entity.player.Player player, Entity sheared, ItemStack shears, InteractionHand hand) { - if (!(player instanceof ServerPlayer)) { + public static boolean handlePlayerShearEntityEvent(EntityHuman player, Entity sheared, ItemStack shears, EnumHand hand) { + if (!(player instanceof EntityPlayer)) { return true; } - PlayerShearEntityEvent event = new PlayerShearEntityEvent((Player) player.getBukkitEntity(), sheared.getBukkitEntity(), CraftItemStack.asCraftMirror(shears), (hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND)); + PlayerShearEntityEvent event = new PlayerShearEntityEvent((Player) player.getBukkitEntity(), sheared.getBukkitEntity(), CraftItemStack.asCraftMirror(shears), (hand == EnumHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND)); Bukkit.getPluginManager().callEvent(event); return !event.isCancelled(); } - public static Cancellable handleStatisticsIncrease(net.minecraft.world.entity.player.Player entityHuman, net.minecraft.stats.Stat statistic, int current, int newValue) { - Player player = ((ServerPlayer) entityHuman).getBukkitEntity(); + public static Cancellable handleStatisticsIncrease(EntityHuman entityHuman, net.minecraft.stats.Statistic statistic, int current, int newValue) { + Player player = ((EntityPlayer) entityHuman).getBukkitEntity(); Event event; if (true) { org.bukkit.Statistic stat = CraftStatistic.getBukkitStatistic(statistic); @@ -1539,7 +1539,7 @@ public static Cancellable handleStatisticsIncrease(net.minecraft.world.entity.pl if (stat.getType() == Type.UNTYPED) { event = new PlayerStatisticIncrementEvent(player, stat, current, newValue); } else if (stat.getType() == Type.ENTITY) { - EntityType entityType = CraftStatistic.getEntityTypeFromStatistic((net.minecraft.stats.Stat>) statistic); + EntityType entityType = CraftStatistic.getEntityTypeFromStatistic((net.minecraft.stats.Statistic>) statistic); event = new PlayerStatisticIncrementEvent(player, stat, current, newValue, entityType); } else { Material material = CraftStatistic.getMaterialFromStatistic(statistic); @@ -1550,7 +1550,7 @@ public static Cancellable handleStatisticsIncrease(net.minecraft.world.entity.pl return (Cancellable) event; } - public static FireworkExplodeEvent callFireworkExplodeEvent(FireworkRocketEntity firework) { + public static FireworkExplodeEvent callFireworkExplodeEvent(EntityFireworks firework) { FireworkExplodeEvent event = new FireworkExplodeEvent((Firework) firework.getBukkitEntity()); firework.level().getCraftServer().getPluginManager().callEvent(event); return event; @@ -1607,7 +1607,7 @@ public static TrialSpawnerSpawnEvent callTrialSpawnerSpawnEvent(Entity spawnee, return event; } - public static BlockDispenseLootEvent callBlockDispenseLootEvent(ServerLevel worldServer, BlockPos blockPosition, net.minecraft.world.entity.player.Player player, List rewardLoot) { + public static BlockDispenseLootEvent callBlockDispenseLootEvent(WorldServer worldServer, BlockPos blockPosition, EntityHuman player, List rewardLoot) { List craftItemStacks = rewardLoot.stream().map(CraftItemStack::asBukkitCopy).collect(Collectors.toList()); BlockDispenseLootEvent event = new BlockDispenseLootEvent((player == null) ? null : (Player) player.getBukkitEntity(), CraftBlock.at(worldServer, blockPosition), craftItemStacks); @@ -1615,25 +1615,25 @@ public static BlockDispenseLootEvent callBlockDispenseLootEvent(ServerLevel worl return event; } - public static VaultDisplayItemEvent callVaultDisplayItemEvent(ServerLevel worldServer, BlockPos blockPosition, ItemStack displayitemStack) { + public static VaultDisplayItemEvent callVaultDisplayItemEvent(WorldServer worldServer, BlockPos blockPosition, ItemStack displayitemStack) { VaultDisplayItemEvent event = new VaultDisplayItemEvent(CraftBlock.at(worldServer, blockPosition), CraftItemStack.asBukkitCopy(displayitemStack)); Bukkit.getPluginManager().callEvent(event); return event; } - public static EntityToggleGlideEvent callToggleGlideEvent(net.minecraft.world.entity.LivingEntity entity, boolean gliding) { + public static EntityToggleGlideEvent callToggleGlideEvent(EntityLiving entity, boolean gliding) { EntityToggleGlideEvent event = new EntityToggleGlideEvent((LivingEntity) entity.getBukkitEntity(), gliding); entity.level().getCraftServer().getPluginManager().callEvent(event); return event; } - public static EntityToggleSwimEvent callToggleSwimEvent(net.minecraft.world.entity.LivingEntity entity, boolean swimming) { + public static EntityToggleSwimEvent callToggleSwimEvent(EntityLiving entity, boolean swimming) { EntityToggleSwimEvent event = new EntityToggleSwimEvent((LivingEntity) entity.getBukkitEntity(), swimming); entity.level().getCraftServer().getPluginManager().callEvent(event); return event; } - public static AreaEffectCloudApplyEvent callAreaEffectCloudApplyEvent(net.minecraft.world.entity.AreaEffectCloud cloud, List entities) { + public static AreaEffectCloudApplyEvent callAreaEffectCloudApplyEvent(EntityAreaEffectCloud cloud, List entities) { AreaEffectCloudApplyEvent event = new AreaEffectCloudApplyEvent((AreaEffectCloud) cloud.getBukkitEntity(), entities); cloud.level().getCraftServer().getPluginManager().callEvent(event); return event; @@ -1646,7 +1646,7 @@ public static VehicleCreateEvent callVehicleCreateEvent(Entity entity) { return event; } - public static EntityBreedEvent callEntityBreedEvent(net.minecraft.world.entity.LivingEntity child, net.minecraft.world.entity.LivingEntity mother, net.minecraft.world.entity.LivingEntity father, net.minecraft.world.entity.LivingEntity breeder, ItemStack bredWith, int experience) { + public static EntityBreedEvent callEntityBreedEvent(EntityLiving child, EntityLiving mother, EntityLiving father, EntityLiving breeder, ItemStack bredWith, int experience) { org.bukkit.entity.LivingEntity breederEntity = (LivingEntity) (breeder == null ? null : breeder.getBukkitEntity()); CraftItemStack bredWithStack = bredWith == null ? null : CraftItemStack.asCraftMirror(bredWith).clone(); @@ -1655,29 +1655,29 @@ public static EntityBreedEvent callEntityBreedEvent(net.minecraft.world.entity.L return event; } - public static BlockPhysicsEvent callBlockPhysicsEvent(LevelAccessor world, BlockPos blockposition) { + public static BlockPhysicsEvent callBlockPhysicsEvent(GeneratorAccess world, BlockPos blockposition) { org.bukkit.block.Block block = CraftBlock.at(world, blockposition); BlockPhysicsEvent event = new BlockPhysicsEvent(block, block.getBlockData()); // Suppress during worldgen - if (world instanceof Level) { - ((Level) world).getServer().server.getPluginManager().callEvent(event); + if (world instanceof World) { + ((World) world).getServer().server.getPluginManager().callEvent(event); } return event; } - public static boolean handleBlockFormEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState block) { - return CraftEventFactory.handleBlockFormEvent(world, pos, block, 3); + public static boolean handleBlockFormEvent(World world, BlockPos pos, IBlockData block) { + return handleBlockFormEvent(world, pos, block, 3); } - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(net.minecraft.world.entity.LivingEntity entity, @Nullable MobEffectInstance oldEffect, @Nullable MobEffectInstance newEffect, EntityPotionEffectEvent.Cause cause) { - return CraftEventFactory.callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, true); + public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause) { + return callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, true); } - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(net.minecraft.world.entity.LivingEntity entity, @Nullable MobEffectInstance oldEffect, @Nullable MobEffectInstance newEffect, EntityPotionEffectEvent.Cause cause, EntityPotionEffectEvent.Action action) { - return CraftEventFactory.callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, action, true); + public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause, EntityPotionEffectEvent.Action action) { + return callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, action, true); } - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(net.minecraft.world.entity.LivingEntity entity, @Nullable MobEffectInstance oldEffect, @Nullable MobEffectInstance newEffect, EntityPotionEffectEvent.Cause cause, boolean willOverride) { + public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause, boolean willOverride) { EntityPotionEffectEvent.Action action = EntityPotionEffectEvent.Action.CHANGED; if (oldEffect == null) { action = EntityPotionEffectEvent.Action.ADDED; @@ -1685,10 +1685,10 @@ public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(net.mine action = EntityPotionEffectEvent.Action.REMOVED; } - return CraftEventFactory.callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, action, willOverride); + return callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, action, willOverride); } - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(net.minecraft.world.entity.LivingEntity entity, @Nullable MobEffectInstance oldEffect, @Nullable MobEffectInstance newEffect, EntityPotionEffectEvent.Cause cause, EntityPotionEffectEvent.Action action, boolean willOverride) { + public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause, EntityPotionEffectEvent.Action action, boolean willOverride) { PotionEffect bukkitOldEffect = (oldEffect == null) ? null : CraftPotionUtil.toBukkit(oldEffect); PotionEffect bukkitNewEffect = (newEffect == null) ? null : CraftPotionUtil.toBukkit(newEffect); @@ -1700,15 +1700,15 @@ public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(net.mine return event; } - public static boolean handleBlockFormEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState block, @Nullable Entity entity) { - return CraftEventFactory.handleBlockFormEvent(world, pos, block, 3, entity); + public static boolean handleBlockFormEvent(World world, BlockPos pos, IBlockData block, @Nullable Entity entity) { + return handleBlockFormEvent(world, pos, block, 3, entity); } - public static boolean handleBlockFormEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState block, int flag) { - return CraftEventFactory.handleBlockFormEvent(world, pos, block, flag, null); + public static boolean handleBlockFormEvent(World world, BlockPos pos, IBlockData block, int flag) { + return handleBlockFormEvent(world, pos, block, flag, null); } - public static boolean handleBlockFormEvent(Level world, BlockPos pos, net.minecraft.world.level.block.state.BlockState block, int flag, @Nullable Entity entity) { + public static boolean handleBlockFormEvent(World world, BlockPos pos, IBlockData block, int flag, @Nullable Entity entity) { CraftBlockState blockState = CraftBlockStates.getBlockState(world, pos, flag); blockState.setData(block); @@ -1728,13 +1728,13 @@ public static boolean handleBatToggleSleepEvent(Entity bat, boolean awake) { return !event.isCancelled(); } - public static boolean handlePlayerRecipeListUpdateEvent(net.minecraft.world.entity.player.Player who, ResourceLocation recipe) { + public static boolean handlePlayerRecipeListUpdateEvent(EntityHuman who, MinecraftKey recipe) { PlayerRecipeDiscoverEvent event = new PlayerRecipeDiscoverEvent((Player) who.getBukkitEntity(), CraftNamespacedKey.fromMinecraft(recipe)); Bukkit.getPluginManager().callEvent(event); return !event.isCancelled(); } - public static EntityPickupItemEvent callEntityPickupItemEvent(Entity who, ItemEntity item, int remaining, boolean cancelled) { + public static EntityPickupItemEvent callEntityPickupItemEvent(Entity who, EntityItem item, int remaining, boolean cancelled) { EntityPickupItemEvent event = new EntityPickupItemEvent((LivingEntity) who.getBukkitEntity(), (Item) item.getBukkitEntity(), remaining); event.setCancelled(cancelled); Bukkit.getPluginManager().callEvent(event); @@ -1750,7 +1750,7 @@ public static LightningStrikeEvent callLightningStrikeEvent(LightningStrike enti /** * Raid events */ - public static boolean callRaidTriggerEvent(Raid raid, ServerPlayer player) { + public static boolean callRaidTriggerEvent(Raid raid, EntityPlayer player) { RaidTriggerEvent event = new RaidTriggerEvent(new CraftRaid(raid), raid.getLevel().getWorld(), player.getBukkitEntity()); Bukkit.getPluginManager().callEvent(event); return !event.isCancelled(); @@ -1766,19 +1766,19 @@ public static void callRaidStopEvent(Raid raid, RaidStopEvent.Reason reason) { Bukkit.getPluginManager().callEvent(event); } - public static void callRaidSpawnWaveEvent(Raid raid, net.minecraft.world.entity.raid.Raider leader, List raiders) { + public static void callRaidSpawnWaveEvent(Raid raid, EntityRaider leader, List raiders) { Raider craftLeader = (CraftRaider) leader.getBukkitEntity(); List craftRaiders = new ArrayList<>(); - for (net.minecraft.world.entity.raid.Raider entityRaider : raiders) { + for (EntityRaider entityRaider : raiders) { craftRaiders.add((Raider) entityRaider.getBukkitEntity()); } RaidSpawnWaveEvent event = new RaidSpawnWaveEvent(new CraftRaid(raid), raid.getLevel().getWorld(), craftLeader, craftRaiders); Bukkit.getPluginManager().callEvent(event); } - public static LootGenerateEvent callLootGenerateEvent(Container inventory, LootTable lootTable, LootContext lootInfo, List loot, boolean plugin) { + public static LootGenerateEvent callLootGenerateEvent(IInventory inventory, LootTable lootTable, LootTableInfo lootInfo, List loot, boolean plugin) { CraftWorld world = lootInfo.getLevel().getWorld(); - Entity entity = lootInfo.getParamOrNull(LootContextParams.THIS_ENTITY); + Entity entity = lootInfo.getOptionalParameter(LootContextParameters.THIS_ENTITY); List bukkitLoot = loot.stream().map(CraftItemStack::asCraftMirror).collect(Collectors.toCollection(ArrayList::new)); LootGenerateEvent event = new LootGenerateEvent(world, (entity != null ? entity.getBukkitEntity() : null), inventory.getOwner(), lootTable.craftLootTable, CraftLootTable.convertContext(lootInfo), bukkitLoot, plugin); @@ -1786,13 +1786,13 @@ public static LootGenerateEvent callLootGenerateEvent(Container inventory, LootT return event; } - public static boolean callStriderTemperatureChangeEvent(net.minecraft.world.entity.monster.Strider strider, boolean shivering) { + public static boolean callStriderTemperatureChangeEvent(EntityStrider strider, boolean shivering) { StriderTemperatureChangeEvent event = new StriderTemperatureChangeEvent((Strider) strider.getBukkitEntity(), shivering); Bukkit.getPluginManager().callEvent(event); return !event.isCancelled(); } - public static boolean handleEntitySpellCastEvent(SpellcasterIllager caster, SpellcasterIllager.IllagerSpell spell) { + public static boolean handleEntitySpellCastEvent(EntityIllagerWizard caster, EntityIllagerWizard.Spell spell) { EntitySpellCastEvent event = new EntitySpellCastEvent((Spellcaster) caster.getBukkitEntity(), CraftSpellcaster.toBukkitSpell(spell)); Bukkit.getPluginManager().callEvent(event); return !event.isCancelled(); @@ -1801,7 +1801,7 @@ public static boolean handleEntitySpellCastEvent(SpellcasterIllager caster, Spel /** * ArrowBodyCountChangeEvent */ - public static ArrowBodyCountChangeEvent callArrowBodyCountChangeEvent(net.minecraft.world.entity.LivingEntity entity, int oldAmount, int newAmount, boolean isReset) { + public static ArrowBodyCountChangeEvent callArrowBodyCountChangeEvent(EntityLiving entity, int oldAmount, int newAmount, boolean isReset) { org.bukkit.entity.LivingEntity bukkitEntity = (LivingEntity) entity.getBukkitEntity(); ArrowBodyCountChangeEvent event = new ArrowBodyCountChangeEvent(bukkitEntity, oldAmount, newAmount, isReset); @@ -1810,32 +1810,32 @@ public static ArrowBodyCountChangeEvent callArrowBodyCountChangeEvent(net.minecr return event; } - public static EntityExhaustionEvent callPlayerExhaustionEvent(net.minecraft.world.entity.player.Player humanEntity, EntityExhaustionEvent.ExhaustionReason exhaustionReason, float exhaustion) { + public static EntityExhaustionEvent callPlayerExhaustionEvent(EntityHuman humanEntity, EntityExhaustionEvent.ExhaustionReason exhaustionReason, float exhaustion) { EntityExhaustionEvent event = new EntityExhaustionEvent(humanEntity.getBukkitEntity(), exhaustionReason, exhaustion); Bukkit.getPluginManager().callEvent(event); return event; } - public static PiglinBarterEvent callPiglinBarterEvent(net.minecraft.world.entity.monster.piglin.Piglin piglin, List outcome, ItemStack input) { + public static PiglinBarterEvent callPiglinBarterEvent(EntityPiglin piglin, List outcome, ItemStack input) { PiglinBarterEvent event = new PiglinBarterEvent((Piglin) piglin.getBukkitEntity(), CraftItemStack.asBukkitCopy(input), outcome.stream().map(CraftItemStack::asBukkitCopy).collect(Collectors.toList())); Bukkit.getPluginManager().callEvent(event); return event; } - public static void callEntitiesLoadEvent(Level world, ChunkPos coords, List entities) { + public static void callEntitiesLoadEvent(World world, ChunkCoordIntPair coords, List entities) { List bukkitEntities = Collections.unmodifiableList(entities.stream().map(Entity::getBukkitEntity).collect(Collectors.toList())); - EntitiesLoadEvent event = new EntitiesLoadEvent(new CraftChunk((ServerLevel) world, coords.x, coords.z), bukkitEntities); + EntitiesLoadEvent event = new EntitiesLoadEvent(new CraftChunk((WorldServer) world, coords.x, coords.z), bukkitEntities); Bukkit.getPluginManager().callEvent(event); } - public static void callEntitiesUnloadEvent(Level world, ChunkPos coords, List entities) { + public static void callEntitiesUnloadEvent(World world, ChunkCoordIntPair coords, List entities) { List bukkitEntities = Collections.unmodifiableList(entities.stream().map(Entity::getBukkitEntity).collect(Collectors.toList())); - EntitiesUnloadEvent event = new EntitiesUnloadEvent(new CraftChunk((ServerLevel) world, coords.x, coords.z), bukkitEntities); + EntitiesUnloadEvent event = new EntitiesUnloadEvent(new CraftChunk((WorldServer) world, coords.x, coords.z), bukkitEntities); Bukkit.getPluginManager().callEvent(event); } - public static boolean callTNTPrimeEvent(Level world, BlockPos pos, TNTPrimeEvent.PrimeCause cause, Entity causingEntity, BlockPos causePosition) { + public static boolean callTNTPrimeEvent(World world, BlockPos pos, TNTPrimeEvent.PrimeCause cause, Entity causingEntity, BlockPos causePosition) { org.bukkit.entity.Entity bukkitEntity = (causingEntity == null) ? null : causingEntity.getBukkitEntity(); org.bukkit.block.Block bukkitBlock = (causePosition == null) ? null : CraftBlock.at(world, causePosition); @@ -1845,7 +1845,7 @@ public static boolean callTNTPrimeEvent(Level world, BlockPos pos, TNTPrimeEvent return !event.isCancelled(); } - public static PlayerRecipeBookClickEvent callRecipeBookClickEvent(ServerPlayer player, Recipe recipe, boolean shiftClick) { + public static PlayerRecipeBookClickEvent callRecipeBookClickEvent(EntityPlayer player, Recipe recipe, boolean shiftClick) { PlayerRecipeBookClickEvent event = new PlayerRecipeBookClickEvent(player.getBukkitEntity(), recipe, shiftClick); Bukkit.getPluginManager().callEvent(event); return event; @@ -1873,13 +1873,13 @@ public static boolean callEntityInteractEvent(Entity nmsEntity, Block block) { return !event.isCancelled(); } - public static EntityExplodeEvent callEntityExplodeEvent(Entity entity, List blocks, float yield, Explosion.BlockInteraction effect) { + public static EntityExplodeEvent callEntityExplodeEvent(Entity entity, List blocks, float yield, Explosion.Effect effect) { EntityExplodeEvent event = new EntityExplodeEvent(entity.getBukkitEntity(), entity.getBukkitEntity().getLocation(), blocks, yield, CraftExplosionResult.toBukkit(effect)); Bukkit.getPluginManager().callEvent(event); return event; } - public static BlockExplodeEvent callBlockExplodeEvent(Block block, BlockState state, List blocks, float yield, Explosion.BlockInteraction effect) { + public static BlockExplodeEvent callBlockExplodeEvent(Block block, BlockState state, List blocks, float yield, Explosion.Effect effect) { BlockExplodeEvent event = new BlockExplodeEvent(block, state, blocks, yield, CraftExplosionResult.toBukkit(effect)); Bukkit.getPluginManager().callEvent(event); return event; @@ -1897,7 +1897,7 @@ public static ExplosionPrimeEvent callExplosionPrimeEvent(Entity nmsEntity, floa return event; } - public static EntityKnockbackEvent callEntityKnockbackEvent(CraftLivingEntity entity, Entity attacker, EntityKnockbackEvent.KnockbackCause cause, double force, Vec3 raw, double x, double y, double z) { + public static EntityKnockbackEvent callEntityKnockbackEvent(CraftLivingEntity entity, Entity attacker, EntityKnockbackEvent.KnockbackCause cause, double force, Vec3D raw, double x, double y, double z) { Vector bukkitRaw = new Vector(-raw.x, raw.y, -raw.z); // Due to how the knockback calculation works, we need to invert x and z. EntityKnockbackEvent event; @@ -1912,7 +1912,7 @@ public static EntityKnockbackEvent callEntityKnockbackEvent(CraftLivingEntity en } public static void callEntityRemoveEvent(Entity entity, EntityRemoveEvent.Cause cause) { - if (entity instanceof ServerPlayer) { + if (entity instanceof EntityPlayer) { return; // Don't call for player } diff --git a/src/main/java/org/bukkit/craftbukkit/event/CraftPortalEvent.java b/src/main/java/org/bukkit/craftbukkit/event/CraftPortalEvent.java index 4b6e4504..07712e75 100644 --- a/src/main/java/org/bukkit/craftbukkit/event/CraftPortalEvent.java +++ b/src/main/java/org/bukkit/craftbukkit/event/CraftPortalEvent.java @@ -16,38 +16,38 @@ public class CraftPortalEvent { private final boolean cancelled; public CraftPortalEvent(EntityPortalEvent portalEvent) { - this.to = portalEvent.getTo(); - this.searchRadius = portalEvent.getSearchRadius(); - this.cancelled = portalEvent.isCancelled(); - this.creationRadius = 0; - this.canCreatePortal = false; + to = portalEvent.getTo(); + searchRadius = portalEvent.getSearchRadius(); + cancelled = portalEvent.isCancelled(); + creationRadius = portalEvent.getCreationRadius(); + canCreatePortal = portalEvent.getCanCreatePortal(); } public CraftPortalEvent(PlayerPortalEvent portalEvent) { - this.to = portalEvent.getTo(); - this.searchRadius = portalEvent.getSearchRadius(); - this.creationRadius = portalEvent.getCreationRadius(); - this.canCreatePortal = portalEvent.getCanCreatePortal(); - this.cancelled = portalEvent.isCancelled(); + to = portalEvent.getTo(); + searchRadius = portalEvent.getSearchRadius(); + creationRadius = portalEvent.getCreationRadius(); + canCreatePortal = portalEvent.getCanCreatePortal(); + cancelled = portalEvent.isCancelled(); } public Location getTo() { - return this.to; + return to; } public int getSearchRadius() { - return this.searchRadius; + return searchRadius; } public int getCreationRadius() { - return this.creationRadius; + return creationRadius; } public boolean getCanCreatePortal() { - return this.canCreatePortal; + return canCreatePortal; } public boolean isCancelled() { - return this.cancelled; + return cancelled; } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CraftBiomeParameterPoint.java b/src/main/java/org/bukkit/craftbukkit/generator/CraftBiomeParameterPoint.java index 3e902694..a6f4e7c5 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/CraftBiomeParameterPoint.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/CraftBiomeParameterPoint.java @@ -13,7 +13,7 @@ public class CraftBiomeParameterPoint implements BiomeParameterPoint { private final double weirdness; private final Climate.Sampler sampler; - public static BiomeParameterPoint createBiomeParameterPoint(Climate.Sampler sampler, Climate.TargetPoint targetPoint) { + public static BiomeParameterPoint createBiomeParameterPoint(Climate.Sampler sampler, Climate.h targetPoint) { return new CraftBiomeParameterPoint(sampler, Climate.unquantizeCoord(targetPoint.temperature()), Climate.unquantizeCoord(targetPoint.humidity()), Climate.unquantizeCoord(targetPoint.continentalness()), Climate.unquantizeCoord(targetPoint.erosion()), Climate.unquantizeCoord(targetPoint.depth()), Climate.unquantizeCoord(targetPoint.weirdness())); } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java b/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java index c96aaa18..d6261d3a 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java @@ -4,10 +4,10 @@ import java.lang.ref.WeakReference; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.EntityBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.block.ITileEntity; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.chunk.IChunkAccess; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; @@ -25,20 +25,20 @@ public final class CraftChunkData implements ChunkGenerator.ChunkData { private final int maxHeight; private final int minHeight; - private final WeakReference weakChunk; + private final WeakReference weakChunk; - public CraftChunkData(World world, ChunkAccess chunkAccess) { + public CraftChunkData(World world, IChunkAccess chunkAccess) { this(world.getMaxHeight(), world.getMinHeight(), chunkAccess); } - CraftChunkData(int maxHeight, int minHeight, ChunkAccess chunkAccess) { + CraftChunkData(int maxHeight, int minHeight, IChunkAccess chunkAccess) { this.maxHeight = maxHeight; this.minHeight = minHeight; this.weakChunk = new WeakReference<>(chunkAccess); } - public ChunkAccess getHandle() { - ChunkAccess access = this.weakChunk.get(); + public IChunkAccess getHandle() { + IChunkAccess access = weakChunk.get(); Preconditions.checkState(access != null, "IChunkAccess no longer present, are you using it in a different tick?"); @@ -46,79 +46,79 @@ public ChunkAccess getHandle() { } public void breakLink() { - this.weakChunk.clear(); + weakChunk.clear(); } @Override public int getMaxHeight() { - return this.maxHeight; + return maxHeight; } @Override public int getMinHeight() { - return this.minHeight; + return minHeight; } @Override public Biome getBiome(int x, int y, int z) { - return CraftBiome.minecraftHolderToBukkit(this.getHandle().getNoiseBiome(x >> 2, y >> 2, z >> 2)); + return CraftBiome.minecraftHolderToBukkit(getHandle().getNoiseBiome(x >> 2, y >> 2, z >> 2)); } @Override public void setBlock(int x, int y, int z, Material material) { - this.setBlock(x, y, z, material.createBlockData()); + setBlock(x, y, z, material.createBlockData()); } @Override public void setBlock(int x, int y, int z, MaterialData material) { - this.setBlock(x, y, z, CraftMagicNumbers.getBlock(material)); + setBlock(x, y, z, CraftMagicNumbers.getBlock(material)); } @Override public void setBlock(int x, int y, int z, BlockData blockData) { - this.setBlock(x, y, z, ((CraftBlockData) blockData).getState()); + setBlock(x, y, z, ((CraftBlockData) blockData).getState()); } @Override public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) { - this.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.createBlockData()); + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.createBlockData()); } @Override public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) { - this.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, CraftMagicNumbers.getBlock(material)); + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, CraftMagicNumbers.getBlock(material)); } @Override public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) { - this.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, ((CraftBlockData) blockData).getState()); + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, ((CraftBlockData) blockData).getState()); } @Override public Material getType(int x, int y, int z) { - return CraftBlockType.minecraftToBukkit(this.getTypeId(x, y, z).getBlock()); + return CraftBlockType.minecraftToBukkit(getTypeId(x, y, z).getBlock()); } @Override public MaterialData getTypeAndData(int x, int y, int z) { - return CraftMagicNumbers.getMaterial(this.getTypeId(x, y, z)); + return CraftMagicNumbers.getMaterial(getTypeId(x, y, z)); } @Override public BlockData getBlockData(int x, int y, int z) { - return CraftBlockData.fromData(this.getTypeId(x, y, z)); + return CraftBlockData.fromData(getTypeId(x, y, z)); } - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockState type) { + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, IBlockData type) { // Clamp to sane values. - if (xMin > 0xf || yMin >= this.maxHeight || zMin > 0xf) { + if (xMin > 0xf || yMin >= maxHeight || zMin > 0xf) { return; } if (xMin < 0) { xMin = 0; } - if (yMin < this.minHeight) { - yMin = this.minHeight; + if (yMin < minHeight) { + yMin = minHeight; } if (zMin < 0) { zMin = 0; @@ -126,8 +126,8 @@ public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax if (xMax > 0x10) { xMax = 0x10; } - if (yMax > this.maxHeight) { - yMax = this.maxHeight; + if (yMax > maxHeight) { + yMax = maxHeight; } if (zMax > 0x10) { zMax = 0x10; @@ -138,37 +138,37 @@ public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax for (int y = yMin; y < yMax; y++) { for (int x = xMin; x < xMax; x++) { for (int z = zMin; z < zMax; z++) { - this.setBlock(x, y, z, type); + setBlock(x, y, z, type); } } } } - public BlockState getTypeId(int x, int y, int z) { - if (x != (x & 0xf) || y < this.minHeight || y >= this.maxHeight || z != (z & 0xf)) { + public IBlockData getTypeId(int x, int y, int z) { + if (x != (x & 0xf) || y < minHeight || y >= maxHeight || z != (z & 0xf)) { return Blocks.AIR.defaultBlockState(); } - ChunkAccess access = this.getHandle(); + IChunkAccess access = getHandle(); return access.getBlockState(new BlockPos(access.getPos().getMinBlockX() + x, y, access.getPos().getMinBlockZ() + z)); } @Override public byte getData(int x, int y, int z) { - return CraftMagicNumbers.toLegacyData(this.getTypeId(x, y, z)); + return CraftMagicNumbers.toLegacyData(getTypeId(x, y, z)); } - private void setBlock(int x, int y, int z, BlockState type) { - if (x != (x & 0xf) || y < this.minHeight || y >= this.maxHeight || z != (z & 0xf)) { + private void setBlock(int x, int y, int z, IBlockData type) { + if (x != (x & 0xf) || y < minHeight || y >= maxHeight || z != (z & 0xf)) { return; } - ChunkAccess access = this.getHandle(); + IChunkAccess access = getHandle(); BlockPos blockPosition = new BlockPos(access.getPos().getMinBlockX() + x, y, access.getPos().getMinBlockZ() + z); - BlockState oldBlockData = access.setBlockState(blockPosition, type, false); + IBlockData oldBlockData = access.setBlockState(blockPosition, type, false); if (type.hasBlockEntity()) { - BlockEntity tileEntity = ((EntityBlock) type.getBlock()).newBlockEntity(blockPosition, type); + TileEntity tileEntity = ((ITileEntity) type.getBlock()).newBlockEntity(blockPosition, type); // createTile can return null, currently only the case with material MOVING_PISTON if (tileEntity == null) { diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java b/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java index e7266835..679ae63b 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java @@ -9,11 +9,13 @@ import java.util.function.Consumer; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.level.ChunkCoordIntPair; +import net.minecraft.world.level.GeneratorAccessSeed; +import net.minecraft.world.level.biome.BiomeBase; +import net.minecraft.world.level.chunk.IChunkAccess; import net.minecraft.world.level.chunk.ProtoChunk; import net.minecraft.world.level.chunk.status.ChunkStatus; import org.bukkit.HeightMap; @@ -32,7 +34,7 @@ public class CraftLimitedRegion extends CraftRegionAccessor implements LimitedRegion { - private final WeakReference weakAccess; + private final WeakReference weakAccess; private final int centerChunkX; private final int centerChunkZ; // Buffer is one chunk (16 blocks), can be seen in ChunkStatus#q @@ -48,24 +50,24 @@ public class CraftLimitedRegion extends CraftRegionAccessor implements LimitedRe // Prevents crash for chunks which are converting from 1.17 to 1.18 private final List outsideEntities = new ArrayList<>(); - public CraftLimitedRegion(WorldGenLevel access, ChunkPos center) { + public CraftLimitedRegion(GeneratorAccessSeed access, ChunkCoordIntPair center) { this.weakAccess = new WeakReference<>(access); - this.centerChunkX = center.x; - this.centerChunkZ = center.z; + centerChunkX = center.x; + centerChunkZ = center.z; World world = access.getMinecraftWorld().getWorld(); - int xCenter = this.centerChunkX << 4; - int zCenter = this.centerChunkZ << 4; - int xMin = xCenter - this.getBuffer(); - int zMin = zCenter - this.getBuffer(); - int xMax = xCenter + this.getBuffer() + 16; - int zMax = zCenter + this.getBuffer() + 16; + int xCenter = centerChunkX << 4; + int zCenter = centerChunkZ << 4; + int xMin = xCenter - getBuffer(); + int zMin = zCenter - getBuffer(); + int xMax = xCenter + getBuffer() + 16; + int zMax = zCenter + getBuffer() + 16; this.region = new BoundingBox(xMin, world.getMinHeight(), zMin, xMax, world.getMaxHeight(), zMax); } - public WorldGenLevel getHandle() { - WorldGenLevel handle = this.weakAccess.get(); + public GeneratorAccessSeed getHandle() { + GeneratorAccessSeed handle = weakAccess.get(); Preconditions.checkState(handle != null, "GeneratorAccessSeed no longer present, are you using it in a different tick?"); @@ -73,22 +75,22 @@ public WorldGenLevel getHandle() { } public void loadEntities() { - if (this.entitiesLoaded) { + if (entitiesLoaded) { return; } - WorldGenLevel access = this.getHandle(); + GeneratorAccessSeed access = getHandle(); // load entities which are already present - for (int x = -(this.buffer >> 4); x <= (this.buffer >> 4); x++) { - for (int z = -(this.buffer >> 4); z <= (this.buffer >> 4); z++) { - ProtoChunk chunk = (ProtoChunk) access.getChunk(this.centerChunkX + x, this.centerChunkZ + z); - for (CompoundTag compound : chunk.getEntities()) { - EntityType.loadEntityRecursive(compound, access.getMinecraftWorld(), (entity) -> { - if (this.region.contains(entity.getX(), entity.getY(), entity.getZ())) { + for (int x = -(buffer >> 4); x <= (buffer >> 4); x++) { + for (int z = -(buffer >> 4); z <= (buffer >> 4); z++) { + ProtoChunk chunk = (ProtoChunk) access.getChunk(centerChunkX + x, centerChunkZ + z); + for (NBTTagCompound compound : chunk.getEntities()) { + EntityTypes.loadEntityRecursive(compound, access.getMinecraftWorld(), EntitySpawnReason.LOAD, (entity) -> { + if (region.contains(entity.getX(), entity.getY(), entity.getZ())) { entity.generation = true; - this.entities.add(entity); + entities.add(entity); } else { - this.outsideEntities.add(entity); + outsideEntities.add(entity); } return entity; }); @@ -96,62 +98,62 @@ public void loadEntities() { } } - this.entitiesLoaded = true; + entitiesLoaded = true; } public void saveEntities() { - WorldGenLevel access = this.getHandle(); + GeneratorAccessSeed access = getHandle(); // We don't clear existing entities when they are not loaded and therefore not modified - if (this.entitiesLoaded) { - for (int x = -(this.buffer >> 4); x <= (this.buffer >> 4); x++) { - for (int z = -(this.buffer >> 4); z <= (this.buffer >> 4); z++) { - ProtoChunk chunk = (ProtoChunk) access.getChunk(this.centerChunkX + x, this.centerChunkZ + z); + if (entitiesLoaded) { + for (int x = -(buffer >> 4); x <= (buffer >> 4); x++) { + for (int z = -(buffer >> 4); z <= (buffer >> 4); z++) { + ProtoChunk chunk = (ProtoChunk) access.getChunk(centerChunkX + x, centerChunkZ + z); chunk.getEntities().clear(); } } } - for (net.minecraft.world.entity.Entity entity : this.entities) { + for (net.minecraft.world.entity.Entity entity : entities) { if (entity.isAlive()) { // check if entity is still in region or if it got teleported outside it - Preconditions.checkState(this.region.contains(entity.getX(), entity.getY(), entity.getZ()), "Entity %s is not in the region", entity); + Preconditions.checkState(region.contains(entity.getX(), entity.getY(), entity.getZ()), "Entity %s is not in the region", entity); access.addFreshEntityWithPassengers(entity); } } - for (net.minecraft.world.entity.Entity entity : this.outsideEntities) { + for (net.minecraft.world.entity.Entity entity : outsideEntities) { access.addFreshEntityWithPassengers(entity); } } public void breakLink() { - this.weakAccess.clear(); + weakAccess.clear(); } @Override public int getBuffer() { - return this.buffer; + return buffer; } @Override public boolean isInRegion(Location location) { - return this.region.contains(location.getX(), location.getY(), location.getZ()); + return region.contains(location.getX(), location.getY(), location.getZ()); } @Override public boolean isInRegion(int x, int y, int z) { - return this.region.contains(x, y, z); + return region.contains(x, y, z); } @Override public List getTileEntities() { List blockStates = new ArrayList<>(); - for (int x = -(this.buffer >> 4); x <= (this.buffer >> 4); x++) { - for (int z = -(this.buffer >> 4); z <= (this.buffer >> 4); z++) { - ProtoChunk chunk = (ProtoChunk) this.getHandle().getChunk(this.centerChunkX + x, this.centerChunkZ + z); + for (int x = -(buffer >> 4); x <= (buffer >> 4); x++) { + for (int z = -(buffer >> 4); z <= (buffer >> 4); z++) { + ProtoChunk chunk = (ProtoChunk) getHandle().getChunk(centerChunkX + x, centerChunkZ + z); for (BlockPos position : chunk.getBlockEntitiesPos()) { - blockStates.add(this.getBlockState(position.getX(), position.getY(), position.getZ())); + blockStates.add(getBlockState(position.getX(), position.getY(), position.getZ())); } } } @@ -161,97 +163,97 @@ public List getTileEntities() { @Override public Biome getBiome(int x, int y, int z) { - Preconditions.checkArgument(this.isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); + Preconditions.checkArgument(isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); return super.getBiome(x, y, z); } @Override - public void setBiome(int x, int y, int z, Holder biomeBase) { - Preconditions.checkArgument(this.isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); - ChunkAccess chunk = this.getHandle().getChunk(x >> 4, z >> 4, ChunkStatus.EMPTY); + public void setBiome(int x, int y, int z, Holder biomeBase) { + Preconditions.checkArgument(isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); + IChunkAccess chunk = getHandle().getChunk(x >> 4, z >> 4, ChunkStatus.EMPTY); chunk.setBiome(x >> 2, y >> 2, z >> 2, biomeBase); } @Override public BlockState getBlockState(int x, int y, int z) { - Preconditions.checkArgument(this.isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); + Preconditions.checkArgument(isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); return super.getBlockState(x, y, z); } @Override public BlockData getBlockData(int x, int y, int z) { - Preconditions.checkArgument(this.isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); + Preconditions.checkArgument(isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); return super.getBlockData(x, y, z); } @Override public Material getType(int x, int y, int z) { - Preconditions.checkArgument(this.isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); + Preconditions.checkArgument(isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); return super.getType(x, y, z); } @Override public void setBlockData(int x, int y, int z, BlockData blockData) { - Preconditions.checkArgument(this.isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); + Preconditions.checkArgument(isInRegion(x, y, z), "Coordinates %s, %s, %s are not in the region", x, y, z); super.setBlockData(x, y, z, blockData); } @Override public int getHighestBlockYAt(int x, int z) { - Preconditions.checkArgument(this.isInRegion(x, this.region.getCenter().getBlockY(), z), "Coordinates %s, %s are not in the region", x, z); + Preconditions.checkArgument(isInRegion(x, region.getCenter().getBlockY(), z), "Coordinates %s, %s are not in the region", x, z); return super.getHighestBlockYAt(x, z); } @Override public int getHighestBlockYAt(Location location) { - Preconditions.checkArgument(this.isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Preconditions.checkArgument(isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); return super.getHighestBlockYAt(location); } @Override public int getHighestBlockYAt(int x, int z, HeightMap heightMap) { - Preconditions.checkArgument(this.isInRegion(x, this.region.getCenter().getBlockY(), z), "Coordinates %s, %s are not in the region", x, z); + Preconditions.checkArgument(isInRegion(x, region.getCenter().getBlockY(), z), "Coordinates %s, %s are not in the region", x, z); return super.getHighestBlockYAt(x, z, heightMap); } @Override public int getHighestBlockYAt(Location location, HeightMap heightMap) { - Preconditions.checkArgument(this.isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Preconditions.checkArgument(isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); return super.getHighestBlockYAt(location, heightMap); } @Override public boolean generateTree(Location location, Random random, TreeType treeType) { - Preconditions.checkArgument(this.isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Preconditions.checkArgument(isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); return super.generateTree(location, random, treeType); } @Override public boolean generateTree(Location location, Random random, TreeType treeType, Consumer consumer) { - Preconditions.checkArgument(this.isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Preconditions.checkArgument(isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); return super.generateTree(location, random, treeType, consumer); } @Override public Collection getNMSEntities() { // Only load entities if we need them - this.loadEntities(); - return new ArrayList<>(this.entities); + loadEntities(); + return new ArrayList<>(entities); } @Override public T spawn(Location location, Class clazz, Consumer function, CreatureSpawnEvent.SpawnReason reason) throws IllegalArgumentException { - Preconditions.checkArgument(this.isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); + Preconditions.checkArgument(isInRegion(location), "Coordinates %s, %s, %s are not in the region", location.getBlockX(), location.getBlockY(), location.getBlockZ()); return super.spawn(location, clazz, function, reason); } @Override public void addEntityToWorld(net.minecraft.world.entity.Entity entity, CreatureSpawnEvent.SpawnReason reason) { - this.entities.add(entity); + entities.add(entity); } @Override public void addEntityWithPassengers(net.minecraft.world.entity.Entity entity, CreatureSpawnEvent.SpawnReason reason) { - this.entities.add(entity); + entities.add(entity); } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CraftWorldInfo.java b/src/main/java/org/bukkit/craftbukkit/generator/CraftWorldInfo.java index 1a802f35..8b7ce81a 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/CraftWorldInfo.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/CraftWorldInfo.java @@ -1,10 +1,10 @@ package org.bukkit.craftbukkit.generator; import java.util.UUID; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.PrimaryLevelData; -import net.minecraft.world.level.storage.ServerLevelData; +import net.minecraft.world.level.dimension.DimensionManager; +import net.minecraft.world.level.storage.Convertable; +import net.minecraft.world.level.storage.IWorldDataServer; +import net.minecraft.world.level.storage.WorldDataServer; import org.bukkit.World; import org.bukkit.craftbukkit.util.WorldUUID; import org.bukkit.generator.WorldInfo; @@ -18,11 +18,11 @@ public class CraftWorldInfo implements WorldInfo { private final int minHeight; private final int maxHeight; - public CraftWorldInfo(ServerLevelData worldDataServer, LevelStorageSource.LevelStorageAccess session, World.Environment environment, DimensionType dimensionManager) { + public CraftWorldInfo(IWorldDataServer worldDataServer, Convertable.ConversionSession session, World.Environment environment, DimensionManager dimensionManager) { this.name = worldDataServer.getLevelName(); - this.uuid = WorldUUID.getUUID(session.getLevelDirectory().path().toFile()); + this.uuid = WorldUUID.getUUID(session.levelDirectory.path().toFile()); this.environment = environment; - this.seed = ((PrimaryLevelData) worldDataServer).worldGenOptions().seed(); + this.seed = ((WorldDataServer) worldDataServer).worldGenOptions().seed(); this.minHeight = dimensionManager.minY(); this.maxHeight = dimensionManager.minY() + dimensionManager.height(); } @@ -38,31 +38,31 @@ public CraftWorldInfo(String name, UUID uuid, World.Environment environment, lon @Override public String getName() { - return this.name; + return name; } @Override public UUID getUID() { - return this.uuid; + return uuid; } @Override public World.Environment getEnvironment() { - return this.environment; + return environment; } @Override public long getSeed() { - return this.seed; + return seed; } @Override public int getMinHeight() { - return this.minHeight; + return minHeight; } @Override public int getMaxHeight() { - return this.maxHeight; + return maxHeight; } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java b/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java index 78a96a0e..a427c635 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java @@ -5,33 +5,32 @@ import java.util.List; import java.util.Random; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; -import net.minecraft.core.RegistryAccess; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.WorldGenRegion; -import net.minecraft.util.Mth; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.server.level.RegionLimitedWorldAccess; +import net.minecraft.server.level.WorldServer; +import net.minecraft.util.MathHelper; import net.minecraft.util.random.WeightedRandomList; -import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.EnumCreatureType; +import net.minecraft.world.level.BlockColumn; +import net.minecraft.world.level.GeneratorAccessSeed; import net.minecraft.world.level.LevelHeightAccessor; -import net.minecraft.world.level.NoiseColumn; import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.BiomeManager; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.MobSpawnSettings; -import net.minecraft.world.level.block.EntityBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.biome.BiomeSettingsMobs; +import net.minecraft.world.level.biome.WorldChunkManager; +import net.minecraft.world.level.block.ITileEntity; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.chunk.ChunkGeneratorStructureState; -import net.minecraft.world.level.chunk.LevelChunkSection; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.chunk.ChunkSection; +import net.minecraft.world.level.chunk.IChunkAccess; +import net.minecraft.world.level.levelgen.HeightMap; import net.minecraft.world.level.levelgen.LegacyRandomSource; import net.minecraft.world.level.levelgen.RandomState; -import net.minecraft.world.level.levelgen.WorldgenRandom; +import net.minecraft.world.level.levelgen.SeededRandom; import net.minecraft.world.level.levelgen.blending.Blender; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.bukkit.block.Biome; @@ -46,7 +45,7 @@ public class CustomChunkGenerator extends InternalChunkGenerator { private final net.minecraft.world.level.chunk.ChunkGenerator delegate; private final ChunkGenerator generator; - private final ServerLevel world; + private final WorldServer world; private final Random random = new Random(); private boolean newApi; private boolean implementBaseHeight = true; @@ -54,37 +53,37 @@ public class CustomChunkGenerator extends InternalChunkGenerator { @Deprecated private class CustomBiomeGrid implements BiomeGrid { - private final ChunkAccess biome; + private final IChunkAccess biome; - public CustomBiomeGrid(ChunkAccess biome) { + public CustomBiomeGrid(IChunkAccess biome) { this.biome = biome; } @Override public Biome getBiome(int x, int z) { - return this.getBiome(x, 0, z); + return getBiome(x, 0, z); } @Override public void setBiome(int x, int z, Biome bio) { - for (int y = CustomChunkGenerator.this.world.getWorld().getMinHeight(); y < CustomChunkGenerator.this.world.getWorld().getMaxHeight(); y += 4) { - this.setBiome(x, y, z, bio); + for (int y = world.getWorld().getMinHeight(); y < world.getWorld().getMaxHeight(); y += 4) { + setBiome(x, y, z, bio); } } @Override public Biome getBiome(int x, int y, int z) { - return CraftBiome.minecraftHolderToBukkit(this.biome.getNoiseBiome(x >> 2, y >> 2, z >> 2)); + return CraftBiome.minecraftHolderToBukkit(biome.getNoiseBiome(x >> 2, y >> 2, z >> 2)); } @Override public void setBiome(int x, int y, int z, Biome bio) { Preconditions.checkArgument(bio != Biome.CUSTOM, "Cannot set the biome to %s", bio); - this.biome.setBiome(x >> 2, y >> 2, z >> 2, CraftBiome.bukkitToMinecraftHolder(bio)); + biome.setBiome(x >> 2, y >> 2, z >> 2, CraftBiome.bukkitToMinecraftHolder(bio)); } } - public CustomChunkGenerator(ServerLevel world, net.minecraft.world.level.chunk.ChunkGenerator delegate, ChunkGenerator generator) { + public CustomChunkGenerator(WorldServer world, net.minecraft.world.level.chunk.ChunkGenerator delegate, ChunkGenerator generator) { super(delegate.getBiomeSource(), delegate.generationSettingsGetter); this.world = world; @@ -93,69 +92,69 @@ public CustomChunkGenerator(ServerLevel world, net.minecraft.world.level.chunk.C } public net.minecraft.world.level.chunk.ChunkGenerator getDelegate() { - return this.delegate; + return delegate; } - private static WorldgenRandom getSeededRandom() { - return new WorldgenRandom(new LegacyRandomSource(0)); + private static SeededRandom getSeededRandom() { + return new SeededRandom(new LegacyRandomSource(0)); } @Override - public BiomeSource getBiomeSource() { - return this.delegate.getBiomeSource(); + public WorldChunkManager getBiomeSource() { + return delegate.getBiomeSource(); } @Override public int getMinY() { - return this.delegate.getMinY(); + return delegate.getMinY(); } @Override public int getSeaLevel() { - return this.delegate.getSeaLevel(); + return delegate.getSeaLevel(); } @Override - public void createStructures(RegistryAccess registryManager, ChunkGeneratorStructureState placementCalculator, StructureManager structureAccessor, ChunkAccess chunk, StructureTemplateManager structureTemplateManager) { - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int x = chunk.getPos().x; - int z = chunk.getPos().z; - - random.setSeed(Mth.getSeed(x, "should-structures".hashCode(), z) ^ this.world.getSeed()); - if (this.generator.shouldGenerateStructures(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { - super.createStructures(registryManager, placementCalculator, structureAccessor, chunk, structureTemplateManager); + public void createStructures(IRegistryCustom iregistrycustom, ChunkGeneratorStructureState chunkgeneratorstructurestate, StructureManager structuremanager, IChunkAccess ichunkaccess, StructureTemplateManager structuretemplatemanager) { + SeededRandom random = getSeededRandom(); + int x = ichunkaccess.getPos().x; + int z = ichunkaccess.getPos().z; + + random.setSeed(MathHelper.getSeed(x, "should-structures".hashCode(), z) ^ world.getSeed()); + if (generator.shouldGenerateStructures(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { + super.createStructures(iregistrycustom, chunkgeneratorstructurestate, structuremanager, ichunkaccess, structuretemplatemanager); } } @Override - public void buildSurface(WorldGenRegion region, StructureManager structures, RandomState noiseConfig, ChunkAccess chunk) { - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int x = chunk.getPos().x; - int z = chunk.getPos().z; - - random.setSeed(Mth.getSeed(x, "should-surface".hashCode(), z) ^ region.getSeed()); - if (this.generator.shouldGenerateSurface(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { - this.delegate.buildSurface(region, structures, noiseConfig, chunk); + public void buildSurface(RegionLimitedWorldAccess regionlimitedworldaccess, StructureManager structuremanager, RandomState randomstate, IChunkAccess ichunkaccess) { + SeededRandom random = getSeededRandom(); + int x = ichunkaccess.getPos().x; + int z = ichunkaccess.getPos().z; + + random.setSeed(MathHelper.getSeed(x, "should-surface".hashCode(), z) ^ regionlimitedworldaccess.getSeed()); + if (generator.shouldGenerateSurface(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { + delegate.buildSurface(regionlimitedworldaccess, structuremanager, randomstate, ichunkaccess); } - CraftChunkData chunkData = new CraftChunkData(this.world.getWorld(), chunk); + CraftChunkData chunkData = new CraftChunkData(this.world.getWorld(), ichunkaccess); random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); - this.generator.generateSurface(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); + generator.generateSurface(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); - if (this.generator.shouldGenerateBedrock()) { - random = CustomChunkGenerator.getSeededRandom(); + if (generator.shouldGenerateBedrock()) { + random = getSeededRandom(); random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); // delegate.buildBedrock(ichunkaccess, random); } - random = CustomChunkGenerator.getSeededRandom(); + random = getSeededRandom(); random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); - this.generator.generateBedrock(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); + generator.generateBedrock(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); chunkData.breakLink(); // return if new api is used - if (this.newApi) { + if (newApi) { return; } @@ -164,27 +163,27 @@ public void buildSurface(WorldGenRegion region, StructureManager structures, Ran this.random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); // Get default biome data for chunk - CustomBiomeGrid biomegrid = new CustomBiomeGrid(chunk); + CustomBiomeGrid biomegrid = new CustomBiomeGrid(ichunkaccess); ChunkData data; try { - if (this.generator.isParallelCapable()) { - data = this.generator.generateChunkData(this.world.getWorld(), this.random, x, z, biomegrid); + if (generator.isParallelCapable()) { + data = generator.generateChunkData(this.world.getWorld(), this.random, x, z, biomegrid); } else { synchronized (this) { - data = this.generator.generateChunkData(this.world.getWorld(), this.random, x, z, biomegrid); + data = generator.generateChunkData(this.world.getWorld(), this.random, x, z, biomegrid); } } } catch (UnsupportedOperationException exception) { - this.newApi = true; + newApi = true; return; } Preconditions.checkArgument(data instanceof OldCraftChunkData, "Plugins must use createChunkData(World) rather than implementing ChunkData: %s", data); OldCraftChunkData craftData = (OldCraftChunkData) data; - LevelChunkSection[] sections = craftData.getRawChunkData(); + ChunkSection[] sections = craftData.getRawChunkData(); - LevelChunkSection[] csect = chunk.getSections(); + ChunkSection[] csect = ichunkaccess.getSections(); int scnt = Math.min(csect.length, sections.length); // Loop through returned sections @@ -192,11 +191,11 @@ public void buildSurface(WorldGenRegion region, StructureManager structures, Ran if (sections[sec] == null) { continue; } - LevelChunkSection section = sections[sec]; + ChunkSection section = sections[sec]; // SPIGOT-6843: Copy biomes over to new section. // Not the most performant way, but has a small footprint and developer should move to the new api anyway - LevelChunkSection oldSection = csect[sec]; + ChunkSection oldSection = csect[sec]; for (int biomeX = 0; biomeX < 4; biomeX++) { for (int biomeY = 0; biomeY < 4; biomeY++) { for (int biomeZ = 0; biomeZ < 4; biomeZ++) { @@ -213,123 +212,123 @@ public void buildSurface(WorldGenRegion region, StructureManager structures, Ran int tx = pos.getX(); int ty = pos.getY(); int tz = pos.getZ(); - BlockState block = craftData.getTypeId(tx, ty, tz); + IBlockData block = craftData.getTypeId(tx, ty, tz); if (block.hasBlockEntity()) { - BlockEntity tile = ((EntityBlock) block.getBlock()).newBlockEntity(new BlockPos((x << 4) + tx, ty, (z << 4) + tz), block); - chunk.setBlockEntity(tile); + TileEntity tile = ((ITileEntity) block.getBlock()).newBlockEntity(new BlockPos((x << 4) + tx, ty, (z << 4) + tz), block); + ichunkaccess.setBlockEntity(tile); } } } } @Override - public void applyCarvers(WorldGenRegion chunkRegion, long seed, RandomState noiseConfig, BiomeManager biomeAccess, StructureManager structureAccessor, ChunkAccess chunk, GenerationStep.Carving carverStep) { - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int x = chunk.getPos().x; - int z = chunk.getPos().z; - - random.setSeed(Mth.getSeed(x, "should-caves".hashCode(), z) ^ chunkRegion.getSeed()); - if (this.generator.shouldGenerateCaves(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { - this.delegate.applyCarvers(chunkRegion, seed, noiseConfig, biomeAccess, structureAccessor, chunk, carverStep); + public void applyCarvers(RegionLimitedWorldAccess regionlimitedworldaccess, long seed, RandomState randomstate, BiomeManager biomemanager, StructureManager structuremanager, IChunkAccess ichunkaccess) { + SeededRandom random = getSeededRandom(); + int x = ichunkaccess.getPos().x; + int z = ichunkaccess.getPos().z; + + random.setSeed(MathHelper.getSeed(x, "should-caves".hashCode(), z) ^ regionlimitedworldaccess.getSeed()); + if (generator.shouldGenerateCaves(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { + delegate.applyCarvers(regionlimitedworldaccess, seed, randomstate, biomemanager, structuremanager, ichunkaccess); } // Minecraft removed the LIQUID_CARVERS stage from world generation, without removing the LIQUID Carving enum. // Meaning this method is only called once for each chunk, so no check is required. - CraftChunkData chunkData = new CraftChunkData(this.world.getWorld(), chunk); + CraftChunkData chunkData = new CraftChunkData(this.world.getWorld(), ichunkaccess); random.setDecorationSeed(seed, 0, 0); - this.generator.generateCaves(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); + generator.generateCaves(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); chunkData.breakLink(); } @Override - public CompletableFuture fillFromNoise(Blender blender, RandomState noiseConfig, StructureManager structureAccessor, ChunkAccess chunk) { - CompletableFuture future = null; - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int x = chunk.getPos().x; - int z = chunk.getPos().z; - - random.setSeed(Mth.getSeed(x, "should-noise".hashCode(), z) ^ this.world.getSeed()); - if (this.generator.shouldGenerateNoise(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { - future = this.delegate.fillFromNoise(blender, noiseConfig, structureAccessor, chunk); + public CompletableFuture fillFromNoise(Blender blender, RandomState randomstate, StructureManager structuremanager, IChunkAccess ichunkaccess) { + CompletableFuture future = null; + SeededRandom random = getSeededRandom(); + int x = ichunkaccess.getPos().x; + int z = ichunkaccess.getPos().z; + + random.setSeed(MathHelper.getSeed(x, "should-noise".hashCode(), z) ^ this.world.getSeed()); + if (generator.shouldGenerateNoise(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { + future = delegate.fillFromNoise(blender, randomstate, structuremanager, ichunkaccess); } - java.util.function.Function function = (ichunkaccess1) -> { + java.util.function.Function function = (ichunkaccess1) -> { CraftChunkData chunkData = new CraftChunkData(this.world.getWorld(), ichunkaccess1); random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); - this.generator.generateNoise(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); + generator.generateNoise(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, chunkData); chunkData.breakLink(); return ichunkaccess1; }; - return future == null ? CompletableFuture.supplyAsync(() -> function.apply(chunk), net.minecraft.Util.backgroundExecutor()) : future.thenApply(function); + return future == null ? CompletableFuture.supplyAsync(() -> function.apply(ichunkaccess), net.minecraft.SystemUtils.backgroundExecutor()) : future.thenApply(function); } @Override - public int getBaseHeight(int x, int z, Heightmap.Types heightmap, LevelHeightAccessor world, RandomState noiseConfig) { - if (this.implementBaseHeight) { + public int getBaseHeight(int i, int j, HeightMap.Type heightmap_type, LevelHeightAccessor levelheightaccessor, RandomState randomstate) { + if (implementBaseHeight) { try { - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int xChunk = x >> 4; - int zChunk = z >> 4; + SeededRandom random = getSeededRandom(); + int xChunk = i >> 4; + int zChunk = j >> 4; random.setSeed((long) xChunk * 341873128712L + (long) zChunk * 132897987541L); - return this.generator.getBaseHeight(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z, CraftHeightMap.fromNMS(heightmap)); + return generator.getBaseHeight(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), i, j, CraftHeightMap.fromNMS(heightmap_type)); } catch (UnsupportedOperationException exception) { - this.implementBaseHeight = false; + implementBaseHeight = false; } } - return this.delegate.getBaseHeight(x, z, heightmap, world, noiseConfig); + return delegate.getBaseHeight(i, j, heightmap_type, levelheightaccessor, randomstate); } @Override - public WeightedRandomList getMobsAt(Holder biome, StructureManager accessor, MobCategory group, BlockPos pos) { - return this.delegate.getMobsAt(biome, accessor, group, pos); + public WeightedRandomList getMobsAt(Holder holder, StructureManager structuremanager, EnumCreatureType enumcreaturetype, BlockPos blockposition) { + return delegate.getMobsAt(holder, structuremanager, enumcreaturetype, blockposition); } @Override - public void applyBiomeDecoration(WorldGenLevel world, ChunkAccess chunk, StructureManager structureAccessor) { - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int x = chunk.getPos().x; - int z = chunk.getPos().z; + public void applyBiomeDecoration(GeneratorAccessSeed generatoraccessseed, IChunkAccess ichunkaccess, StructureManager structuremanager) { + SeededRandom random = getSeededRandom(); + int x = ichunkaccess.getPos().x; + int z = ichunkaccess.getPos().z; - random.setSeed(Mth.getSeed(x, "should-decoration".hashCode(), z) ^ world.getSeed()); - super.applyBiomeDecoration(world, chunk, structureAccessor, this.generator.shouldGenerateDecorations(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)); + random.setSeed(MathHelper.getSeed(x, "should-decoration".hashCode(), z) ^ generatoraccessseed.getSeed()); + super.applyBiomeDecoration(generatoraccessseed, ichunkaccess, structuremanager, generator.shouldGenerateDecorations(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)); } @Override - public void addDebugScreenInfo(List text, RandomState noiseConfig, BlockPos pos) { - this.delegate.addDebugScreenInfo(text, noiseConfig, pos); + public void addDebugScreenInfo(List list, RandomState randomstate, BlockPos blockposition) { + delegate.addDebugScreenInfo(list, randomstate, blockposition); } @Override - public void spawnOriginalMobs(WorldGenRegion region) { - WorldgenRandom random = CustomChunkGenerator.getSeededRandom(); - int x = region.getCenter().x; - int z = region.getCenter().z; - - random.setSeed(Mth.getSeed(x, "should-mobs".hashCode(), z) ^ region.getSeed()); - if (this.generator.shouldGenerateMobs(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { - this.delegate.spawnOriginalMobs(region); + public void spawnOriginalMobs(RegionLimitedWorldAccess regionlimitedworldaccess) { + SeededRandom random = getSeededRandom(); + int x = regionlimitedworldaccess.getCenter().x; + int z = regionlimitedworldaccess.getCenter().z; + + random.setSeed(MathHelper.getSeed(x, "should-mobs".hashCode(), z) ^ regionlimitedworldaccess.getSeed()); + if (generator.shouldGenerateMobs(this.world.getWorld(), new RandomSourceWrapper.RandomWrapper(random), x, z)) { + delegate.spawnOriginalMobs(regionlimitedworldaccess); } } @Override - public int getSpawnHeight(LevelHeightAccessor world) { - return this.delegate.getSpawnHeight(world); + public int getSpawnHeight(LevelHeightAccessor levelheightaccessor) { + return delegate.getSpawnHeight(levelheightaccessor); } @Override public int getGenDepth() { - return this.delegate.getGenDepth(); + return delegate.getGenDepth(); } @Override - public NoiseColumn getBaseColumn(int x, int z, LevelHeightAccessor world, RandomState noiseConfig) { - return this.delegate.getBaseColumn(x, z, world, noiseConfig); + public BlockColumn getBaseColumn(int i, int j, LevelHeightAccessor levelheightaccessor, RandomState randomstate) { + return delegate.getBaseColumn(i, j, levelheightaccessor, randomstate); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CustomWorldChunkManager.java b/src/main/java/org/bukkit/craftbukkit/generator/CustomWorldChunkManager.java index 0063c4c1..c63e645e 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/CustomWorldChunkManager.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/CustomWorldChunkManager.java @@ -6,22 +6,23 @@ import java.util.List; import java.util.stream.Stream; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.core.IRegistry; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.Climate; +import net.minecraft.world.level.biome.WorldChunkManager; import org.bukkit.block.Biome; import org.bukkit.craftbukkit.block.CraftBiome; import org.bukkit.generator.BiomeProvider; import org.bukkit.generator.WorldInfo; -public class CustomWorldChunkManager extends BiomeSource { +public class CustomWorldChunkManager extends WorldChunkManager { private final WorldInfo worldInfo; private final BiomeProvider biomeProvider; - private final Registry registry; + private final IRegistry registry; - private static List> biomeListToBiomeBaseList(List biomes, Registry registry) { - List> biomeBases = new ArrayList<>(); + private static List> biomeListToBiomeBaseList(List biomes, IRegistry registry) { + List> biomeBases = new ArrayList<>(); for (Biome biome : biomes) { Preconditions.checkArgument(biome != Biome.CUSTOM, "Cannot use the biome %s", biome); @@ -31,27 +32,27 @@ private static List> biomeListToBi return biomeBases; } - public CustomWorldChunkManager(WorldInfo worldInfo, BiomeProvider biomeProvider, Registry registry) { + public CustomWorldChunkManager(WorldInfo worldInfo, BiomeProvider biomeProvider, IRegistry registry) { this.worldInfo = worldInfo; this.biomeProvider = biomeProvider; this.registry = registry; } @Override - protected MapCodec codec() { + protected MapCodec codec() { throw new UnsupportedOperationException("Cannot serialize CustomWorldChunkManager"); } @Override - public Holder getNoiseBiome(int x, int y, int z, Climate.Sampler noise) { - Biome biome = this.biomeProvider.getBiome(this.worldInfo, x << 2, y << 2, z << 2, CraftBiomeParameterPoint.createBiomeParameterPoint(noise, noise.sample(x, y, z))); + public Holder getNoiseBiome(int x, int y, int z, Climate.Sampler sampler) { + Biome biome = biomeProvider.getBiome(worldInfo, x << 2, y << 2, z << 2, CraftBiomeParameterPoint.createBiomeParameterPoint(sampler, sampler.sample(x, y, z))); Preconditions.checkArgument(biome != Biome.CUSTOM, "Cannot set the biome to %s", biome); return CraftBiome.bukkitToMinecraftHolder(biome); } @Override - protected Stream> collectPossibleBiomes() { - return CustomWorldChunkManager.biomeListToBiomeBaseList(this.biomeProvider.getBiomes(this.worldInfo), this.registry).stream(); + protected Stream> collectPossibleBiomes() { + return biomeListToBiomeBaseList(biomeProvider.getBiomes(worldInfo), registry).stream(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java b/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java index 7b4bad15..05160224 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java @@ -2,14 +2,14 @@ import java.util.function.Function; import net.minecraft.core.Holder; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.world.level.biome.BiomeBase; +import net.minecraft.world.level.biome.BiomeSettingsGeneration; +import net.minecraft.world.level.biome.WorldChunkManager; // Do not implement functions to this class, add to NormalChunkGenerator public abstract class InternalChunkGenerator extends net.minecraft.world.level.chunk.ChunkGenerator { - public InternalChunkGenerator(BiomeSource biomeSource, Function, BiomeGenerationSettings> generationSettingsGetter) { - super(biomeSource, generationSettingsGetter); + public InternalChunkGenerator(WorldChunkManager worldchunkmanager, Function, BiomeSettingsGeneration> function) { + super(worldchunkmanager, function); } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/OldCraftChunkData.java b/src/main/java/org/bukkit/craftbukkit/generator/OldCraftChunkData.java index e7f7a246..748c0150 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/OldCraftChunkData.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/OldCraftChunkData.java @@ -3,10 +3,11 @@ import java.util.HashSet; import java.util.Set; import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.chunk.ChunkSection; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; @@ -23,26 +24,26 @@ public final class OldCraftChunkData implements ChunkGenerator.ChunkData { private final int minHeight; private final int maxHeight; - private final LevelChunkSection[] sections; - private final Registry biomes; + private final ChunkSection[] sections; + private final IRegistry biomes; private Set tiles; private final Set lights = new HashSet<>(); - public OldCraftChunkData(int minHeight, int maxHeight, Registry biomes) { + public OldCraftChunkData(int minHeight, int maxHeight, IRegistry biomes) { this.minHeight = minHeight; this.maxHeight = maxHeight; this.biomes = biomes; - this.sections = new LevelChunkSection[(((maxHeight - 1) >> 4) + 1) - (minHeight >> 4)]; + this.sections = new ChunkSection[(((maxHeight - 1) >> 4) + 1) - (minHeight >> 4)]; } @Override public int getMinHeight() { - return this.minHeight; + return minHeight; } @Override public int getMaxHeight() { - return this.maxHeight; + return maxHeight; } @Override @@ -52,59 +53,59 @@ public Biome getBiome(int x, int y, int z) { @Override public void setBlock(int x, int y, int z, Material material) { - this.setBlock(x, y, z, material.createBlockData()); + setBlock(x, y, z, material.createBlockData()); } @Override public void setBlock(int x, int y, int z, MaterialData material) { - this.setBlock(x, y, z, CraftMagicNumbers.getBlock(material)); + setBlock(x, y, z, CraftMagicNumbers.getBlock(material)); } @Override public void setBlock(int x, int y, int z, BlockData blockData) { - this.setBlock(x, y, z, ((CraftBlockData) blockData).getState()); + setBlock(x, y, z, ((CraftBlockData) blockData).getState()); } @Override public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) { - this.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.createBlockData()); + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.createBlockData()); } @Override public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) { - this.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, CraftMagicNumbers.getBlock(material)); + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, CraftMagicNumbers.getBlock(material)); } @Override public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) { - this.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, ((CraftBlockData) blockData).getState()); + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, ((CraftBlockData) blockData).getState()); } @Override public Material getType(int x, int y, int z) { - return CraftBlockType.minecraftToBukkit(this.getTypeId(x, y, z).getBlock()); + return CraftBlockType.minecraftToBukkit(getTypeId(x, y, z).getBlock()); } @Override public MaterialData getTypeAndData(int x, int y, int z) { - return CraftMagicNumbers.getMaterial(this.getTypeId(x, y, z)); + return CraftMagicNumbers.getMaterial(getTypeId(x, y, z)); } @Override public BlockData getBlockData(int x, int y, int z) { - return CraftBlockData.fromData(this.getTypeId(x, y, z)); + return CraftBlockData.fromData(getTypeId(x, y, z)); } - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockState type) { + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, IBlockData type) { // Clamp to sane values. - if (xMin > 0xf || yMin >= this.maxHeight || zMin > 0xf) { + if (xMin > 0xf || yMin >= maxHeight || zMin > 0xf) { return; } if (xMin < 0) { xMin = 0; } - if (yMin < this.minHeight) { - yMin = this.minHeight; + if (yMin < minHeight) { + yMin = minHeight; } if (zMin < 0) { zMin = 0; @@ -112,8 +113,8 @@ public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax if (xMax > 0x10) { xMax = 0x10; } - if (yMax > this.maxHeight) { - yMax = this.maxHeight; + if (yMax > maxHeight) { + yMax = maxHeight; } if (zMax > 0x10) { zMax = 0x10; @@ -122,7 +123,7 @@ public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax return; } for (int y = yMin; y < yMax; y++) { - LevelChunkSection section = this.getChunkSection(y, true); + ChunkSection section = getChunkSection(y, true); int offsetBase = y & 0xf; for (int x = xMin; x < xMax; x++) { for (int z = zMin; z < zMax; z++) { @@ -132,11 +133,11 @@ public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax } } - public BlockState getTypeId(int x, int y, int z) { - if (x != (x & 0xf) || y < this.minHeight || y >= this.maxHeight || z != (z & 0xf)) { + public IBlockData getTypeId(int x, int y, int z) { + if (x != (x & 0xf) || y < minHeight || y >= maxHeight || z != (z & 0xf)) { return Blocks.AIR.defaultBlockState(); } - LevelChunkSection section = this.getChunkSection(y, false); + ChunkSection section = getChunkSection(y, false); if (section == null) { return Blocks.AIR.defaultBlockState(); } else { @@ -146,50 +147,50 @@ public BlockState getTypeId(int x, int y, int z) { @Override public byte getData(int x, int y, int z) { - return CraftMagicNumbers.toLegacyData(this.getTypeId(x, y, z)); + return CraftMagicNumbers.toLegacyData(getTypeId(x, y, z)); } - private void setBlock(int x, int y, int z, BlockState type) { - if (x != (x & 0xf) || y < this.minHeight || y >= this.maxHeight || z != (z & 0xf)) { + private void setBlock(int x, int y, int z, IBlockData type) { + if (x != (x & 0xf) || y < minHeight || y >= maxHeight || z != (z & 0xf)) { return; } - LevelChunkSection section = this.getChunkSection(y, true); + ChunkSection section = getChunkSection(y, true); section.setBlockState(x, y & 0xf, z, type); // SPIGOT-1753: Capture light blocks, for light updates if (type.getLightEmission() > 0) { - this.lights.add(new BlockPos(x, y, z)); + lights.add(new BlockPos(x, y, z)); } else { - this.lights.remove(new BlockPos(x, y, z)); + lights.remove(new BlockPos(x, y, z)); } if (type.hasBlockEntity()) { - if (this.tiles == null) { - this.tiles = new HashSet<>(); + if (tiles == null) { + tiles = new HashSet<>(); } - this.tiles.add(new BlockPos(x, y, z)); + tiles.add(new BlockPos(x, y, z)); } } - private LevelChunkSection getChunkSection(int y, boolean create) { - int offset = (y - this.minHeight) >> 4; - LevelChunkSection section = this.sections[offset]; + private ChunkSection getChunkSection(int y, boolean create) { + int offset = (y - minHeight) >> 4; + ChunkSection section = sections[offset]; if (create && section == null) { - this.sections[offset] = section = new LevelChunkSection(this.biomes); + sections[offset] = section = new ChunkSection(biomes); } return section; } - LevelChunkSection[] getRawChunkData() { - return this.sections; + ChunkSection[] getRawChunkData() { + return sections; } Set getTiles() { - return this.tiles; + return tiles; } Set getLights() { - return this.lights; + return lights; } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftGeneratedStructure.java b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftGeneratedStructure.java index f6e36583..99aee229 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftGeneratedStructure.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftGeneratedStructure.java @@ -3,6 +3,7 @@ import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.List; +import net.minecraft.world.level.levelgen.structure.StructureBoundingBox; import net.minecraft.world.level.levelgen.structure.StructureStart; import org.bukkit.generator.structure.GeneratedStructure; import org.bukkit.generator.structure.Structure; @@ -21,24 +22,24 @@ public CraftGeneratedStructure(StructureStart handle) { @Override public BoundingBox getBoundingBox() { - net.minecraft.world.level.levelgen.structure.BoundingBox bb = this.handle.getBoundingBox(); + StructureBoundingBox bb = handle.getBoundingBox(); return new BoundingBox(bb.minX(), bb.minY(), bb.minZ(), bb.maxX(), bb.maxY(), bb.maxZ()); } @Override public Structure getStructure() { - return CraftStructure.minecraftToBukkit(this.handle.getStructure()); + return CraftStructure.minecraftToBukkit(handle.getStructure()); } @Override public Collection getPieces() { - if (this.pieces == null) { // Cache the pieces on first request + if (pieces == null) { // Cache the pieces on first request ImmutableList.Builder builder = new ImmutableList.Builder<>(); - for (net.minecraft.world.level.levelgen.structure.StructurePiece piece : this.handle.getPieces()) { + for (net.minecraft.world.level.levelgen.structure.StructurePiece piece : handle.getPieces()) { builder.add(new CraftStructurePiece(piece)); } - this.pieces = builder.build(); + pieces = builder.build(); } return this.pieces; @@ -46,6 +47,6 @@ public Collection getPieces() { @Override public PersistentDataContainer getPersistentDataContainer() { - return this.handle.persistentDataContainer; + return handle.persistentDataContainer; } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructure.java b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructure.java index bd818f60..342ba3cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructure.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructure.java @@ -1,5 +1,7 @@ package org.bukkit.craftbukkit.generator.structure; +import com.google.common.base.Suppliers; +import java.util.function.Supplier; import net.minecraft.core.registries.Registries; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -20,26 +22,26 @@ public static net.minecraft.world.level.levelgen.structure.Structure bukkitToMin private final NamespacedKey key; private final net.minecraft.world.level.levelgen.structure.Structure structure; - private final StructureType structureType; + private final Supplier structureType; public CraftStructure(NamespacedKey key, net.minecraft.world.level.levelgen.structure.Structure structure) { this.key = key; this.structure = structure; - this.structureType = CraftStructureType.minecraftToBukkit(structure.type()); + this.structureType = Suppliers.memoize(() -> CraftStructureType.minecraftToBukkit(structure.type())); } @Override public net.minecraft.world.level.levelgen.structure.Structure getHandle() { - return this.structure; + return structure; } @Override public StructureType getStructureType() { - return this.structureType; + return structureType.get(); } @Override public NamespacedKey getKey() { - return this.key; + return key; } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructurePiece.java b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructurePiece.java index c15876ea..91cc6dc6 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructurePiece.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructurePiece.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.generator.structure; +import net.minecraft.world.level.levelgen.structure.StructureBoundingBox; import org.bukkit.generator.structure.StructurePiece; import org.bukkit.util.BoundingBox; @@ -13,7 +14,7 @@ public CraftStructurePiece(net.minecraft.world.level.levelgen.structure.Structur @Override public BoundingBox getBoundingBox() { - net.minecraft.world.level.levelgen.structure.BoundingBox bb = this.handle.getBoundingBox(); + StructureBoundingBox bb = handle.getBoundingBox(); return new BoundingBox(bb.minX(), bb.minY(), bb.minZ(), bb.maxX(), bb.maxY(), bb.maxZ()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructureType.java b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructureType.java index 7199847c..af720ad9 100644 --- a/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructureType.java +++ b/src/main/java/org/bukkit/craftbukkit/generator/structure/CraftStructureType.java @@ -27,11 +27,11 @@ public CraftStructureType(NamespacedKey key, net.minecraft.world.level.levelgen. @Override public net.minecraft.world.level.levelgen.structure.StructureType getHandle() { - return this.structureType; + return structureType; } @Override public NamespacedKey getKey() { - return this.key; + return key; } } diff --git a/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java index 7776cc0c..da88fa68 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java +++ b/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java @@ -22,8 +22,8 @@ public CommandAliasHelpTopic(String alias, String aliasFor, HelpMap helpMap) { @Override public String getFullText(CommandSender forWho) { Preconditions.checkArgument(forWho != null, "CommandServer forWho cannot be null"); - StringBuilder sb = new StringBuilder(this.shortText); - HelpTopic aliasForTopic = this.helpMap.getHelpTopic(this.aliasFor); + StringBuilder sb = new StringBuilder(shortText); + HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); if (aliasForTopic != null) { sb.append("\n"); sb.append(aliasForTopic.getFullText(forWho)); @@ -34,15 +34,15 @@ public String getFullText(CommandSender forWho) { @Override public boolean canSee(CommandSender commandSender) { Preconditions.checkArgument(commandSender != null, "CommandServer cannot be null"); - if (this.amendedPermission == null) { - HelpTopic aliasForTopic = this.helpMap.getHelpTopic(this.aliasFor); + if (amendedPermission == null) { + HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); if (aliasForTopic != null) { return aliasForTopic.canSee(commandSender); } else { return false; } } else { - return commandSender.hasPermission(this.amendedPermission); + return commandSender.hasPermission(amendedPermission); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java index a67018fc..78b91bb2 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java +++ b/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java @@ -23,8 +23,8 @@ public boolean canSee(CommandSender sender) { return true; } - if (!this.permissionNode.equals("")) { - return sender.hasPermission(this.permissionNode); + if (!permissionNode.equals("")) { + return sender.hasPermission(permissionNode); } else { return true; } diff --git a/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java index 0e4ce9e9..77134d74 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java +++ b/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java @@ -22,16 +22,16 @@ public CustomIndexHelpTopic(HelpMap helpMap, String name, String shortText, Stri @Override public String getFullText(CommandSender sender) { - if (this.futureTopics != null) { + if (futureTopics != null) { List topics = new LinkedList(); - for (String futureTopic : this.futureTopics) { - HelpTopic topic = this.helpMap.getHelpTopic(futureTopic); + for (String futureTopic : futureTopics) { + HelpTopic topic = helpMap.getHelpTopic(futureTopic); if (topic != null) { topics.add(topic); } } - this.setTopicsCollection(topics); - this.futureTopics = null; + setTopicsCollection(topics); + futureTopics = null; } return super.getFullText(sender); diff --git a/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java b/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java index b9cc1bb4..4f0e00ec 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java +++ b/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java @@ -21,7 +21,7 @@ public HelpTopicAmendment(String topicName, String shortText, String fullText, S * @return the full text */ public String getFullText() { - return this.fullText; + return fullText; } /** @@ -29,7 +29,7 @@ public String getFullText() { * @return the short text */ public String getShortText() { - return this.shortText; + return shortText; } /** @@ -37,7 +37,7 @@ public String getShortText() { * @return the topic name */ public String getTopicName() { - return this.topicName; + return topicName; } /** @@ -45,6 +45,6 @@ public String getTopicName() { * @return the permission */ public String getPermission() { - return this.permission; + return permission; } } diff --git a/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java b/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java index 5923d3c1..d3f17d4c 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java +++ b/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java @@ -26,23 +26,23 @@ public HelpYamlReader(Server server) { this.server = server; File helpYamlFile = new File("help.yml"); - YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("configurations/help.yml"), Charsets.UTF_8)); + YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/help.yml"), Charsets.UTF_8)); try { - this.helpYaml = YamlConfiguration.loadConfiguration(helpYamlFile); - this.helpYaml.options().copyDefaults(true); - this.helpYaml.setDefaults(defaultConfig); + helpYaml = YamlConfiguration.loadConfiguration(helpYamlFile); + helpYaml.options().copyDefaults(true); + helpYaml.setDefaults(defaultConfig); try { if (!helpYamlFile.exists()) { - this.helpYaml.save(helpYamlFile); + helpYaml.save(helpYamlFile); } } catch (IOException ex) { server.getLogger().log(Level.SEVERE, "Could not save " + helpYamlFile, ex); } } catch (Exception ex) { server.getLogger().severe("Failed to load help.yml. Verify the yaml indentation is correct. Reverting to default help.yml."); - this.helpYaml = defaultConfig; + helpYaml = defaultConfig; } } @@ -53,12 +53,12 @@ public HelpYamlReader(Server server) { */ public List getGeneralTopics() { List topics = new LinkedList(); - ConfigurationSection generalTopics = this.helpYaml.getConfigurationSection("general-topics"); + ConfigurationSection generalTopics = helpYaml.getConfigurationSection("general-topics"); if (generalTopics != null) { for (String topicName : generalTopics.getKeys(false)) { ConfigurationSection section = generalTopics.getConfigurationSection(topicName); - String shortText = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("shortText", "")); - String fullText = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("fullText", "")); + String shortText = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("shortText", "")); + String fullText = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("fullText", "")); String permission = section.getString("permission", ""); topics.add(new CustomHelpTopic(topicName, shortText, fullText, permission)); } @@ -73,15 +73,15 @@ public List getGeneralTopics() { */ public List getIndexTopics() { List topics = new LinkedList(); - ConfigurationSection indexTopics = this.helpYaml.getConfigurationSection("index-topics"); + ConfigurationSection indexTopics = helpYaml.getConfigurationSection("index-topics"); if (indexTopics != null) { for (String topicName : indexTopics.getKeys(false)) { ConfigurationSection section = indexTopics.getConfigurationSection(topicName); - String shortText = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("shortText", "")); - String preamble = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("preamble", "")); - String permission = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("permission", "")); + String shortText = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("shortText", "")); + String preamble = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("preamble", "")); + String permission = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("permission", "")); List commands = section.getStringList("commands"); - topics.add(new CustomIndexHelpTopic(this.server.getHelpMap(), topicName, shortText, permission, commands, preamble)); + topics.add(new CustomIndexHelpTopic(server.getHelpMap(), topicName, shortText, permission, commands, preamble)); } } return topics; @@ -94,12 +94,12 @@ public List getIndexTopics() { */ public List getTopicAmendments() { List amendments = new LinkedList(); - ConfigurationSection commandTopics = this.helpYaml.getConfigurationSection("amended-topics"); + ConfigurationSection commandTopics = helpYaml.getConfigurationSection("amended-topics"); if (commandTopics != null) { for (String topicName : commandTopics.getKeys(false)) { ConfigurationSection section = commandTopics.getConfigurationSection(topicName); - String description = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("shortText", "")); - String usage = ChatColor.translateAlternateColorCodes(this.ALT_COLOR_CODE, section.getString("fullText", "")); + String description = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("shortText", "")); + String usage = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("fullText", "")); String permission = section.getString("permission", ""); amendments.add(new HelpTopicAmendment(topicName, description, usage, permission)); } @@ -108,10 +108,10 @@ public List getTopicAmendments() { } public List getIgnoredPlugins() { - return this.helpYaml.getStringList("ignore-plugins"); + return helpYaml.getStringList("ignore-plugins"); } public boolean commandTopicsInMasterIndex() { - return this.helpYaml.getBoolean("command-topics-in-master-index", true); + return helpYaml.getBoolean("command-topics-in-master-index", true); } } diff --git a/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java index 95d791a9..6133235c 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java +++ b/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java @@ -17,7 +17,7 @@ public class MultipleCommandAliasHelpTopic extends HelpTopic { public MultipleCommandAliasHelpTopic(MultipleCommandAlias alias) { this.alias = alias; - this.name = "/" + alias.getLabel(); + name = "/" + alias.getLabel(); // Build short text StringBuilder sb = new StringBuilder(); @@ -28,20 +28,20 @@ public MultipleCommandAliasHelpTopic(MultipleCommandAlias alias) { sb.append("/"); sb.append(alias.getCommands()[i].getLabel()); } - this.shortText = sb.toString(); + shortText = sb.toString(); // Build full text - this.fullText = ChatColor.GOLD + "Alias for: " + ChatColor.WHITE + this.getShortText(); + fullText = ChatColor.GOLD + "Alias for: " + ChatColor.WHITE + getShortText(); } @Override public boolean canSee(CommandSender sender) { - if (this.amendedPermission == null) { + if (amendedPermission == null) { if (sender instanceof ConsoleCommandSender) { return true; } - for (Command command : this.alias.getCommands()) { + for (Command command : alias.getCommands()) { if (!command.testPermissionSilent(sender)) { return false; } @@ -49,7 +49,7 @@ public boolean canSee(CommandSender sender) { return true; } else { - return sender.hasPermission(this.amendedPermission); + return sender.hasPermission(amendedPermission); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java b/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java index 05d3aecd..23bd9f09 100644 --- a/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java +++ b/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java @@ -46,23 +46,23 @@ public SimpleHelpMap(CraftServer server) { this.yaml = new HelpYamlReader(server); Predicate indexFilter = Predicates.not(Predicates.instanceOf(CommandAliasHelpTopic.class)); - if (!this.yaml.commandTopicsInMasterIndex()) { + if (!yaml.commandTopicsInMasterIndex()) { indexFilter = Predicates.and(indexFilter, Predicates.not(new IsCommandTopicPredicate())); } - this.defaultTopic = new IndexHelpTopic("Index", null, null, Collections2.filter(this.helpTopics.values(), indexFilter), "Use /help [n] to get page n of help."); + this.defaultTopic = new IndexHelpTopic("Index", null, null, Collections2.filter(helpTopics.values(), indexFilter), "Use /help [n] to get page n of help."); - this.registerHelpTopicFactory(MultipleCommandAlias.class, new MultipleCommandAliasHelpTopicFactory()); + registerHelpTopicFactory(MultipleCommandAlias.class, new MultipleCommandAliasHelpTopicFactory()); } @Override public synchronized HelpTopic getHelpTopic(String topicName) { if (topicName.equals("")) { - return this.defaultTopic; + return defaultTopic; } - if (this.helpTopics.containsKey(topicName)) { - return this.helpTopics.get(topicName); + if (helpTopics.containsKey(topicName)) { + return helpTopics.get(topicName); } return null; @@ -70,44 +70,44 @@ public synchronized HelpTopic getHelpTopic(String topicName) { @Override public Collection getHelpTopics() { - return this.helpTopics.values(); + return helpTopics.values(); } @Override public synchronized void addTopic(HelpTopic topic) { // Existing topics take priority - if (!this.helpTopics.containsKey(topic.getName())) { - this.helpTopics.put(topic.getName(), topic); + if (!helpTopics.containsKey(topic.getName())) { + helpTopics.put(topic.getName(), topic); } } @Override public synchronized void clear() { - this.helpTopics.clear(); + helpTopics.clear(); } @Override public List getIgnoredPlugins() { - return this.yaml.getIgnoredPlugins(); + return yaml.getIgnoredPlugins(); } /** * Reads the general topics from help.yml and adds them to the help index. */ public synchronized void initializeGeneralTopics() { - this.yaml = new HelpYamlReader(this.server); + yaml = new HelpYamlReader(server); // Initialize general help topics from the help.yml file - for (HelpTopic topic : this.yaml.getGeneralTopics()) { - this.addTopic(topic); + for (HelpTopic topic : yaml.getGeneralTopics()) { + addTopic(topic); } // Initialize index help topics from the help.yml file - for (HelpTopic topic : this.yaml.getIndexTopics()) { + for (HelpTopic topic : yaml.getIndexTopics()) { if (topic.getName().equals("Default")) { - this.defaultTopic = topic; + defaultTopic = topic; } else { - this.addTopic(topic); + addTopic(topic); } } } @@ -117,7 +117,7 @@ public synchronized void initializeGeneralTopics() { */ public synchronized void initializeCommands() { // ** Load topics from highest to lowest priority order ** - Set ignoredPlugins = new HashSet(this.yaml.getIgnoredPlugins()); + Set ignoredPlugins = new HashSet(yaml.getIgnoredPlugins()); // Don't load any automatic help topics if All is ignored if (ignoredPlugins.contains("All")) { @@ -125,60 +125,60 @@ public synchronized void initializeCommands() { } // Initialize help topics from the server's command map - outer: for (Command command : this.server.getCommandMap().getCommands()) { - if (this.commandInIgnoredPlugin(command, ignoredPlugins)) { + outer: for (Command command : server.getCommandMap().getCommands()) { + if (commandInIgnoredPlugin(command, ignoredPlugins)) { continue; } // Register a topic - for (Class c : this.topicFactoryMap.keySet()) { + for (Class c : topicFactoryMap.keySet()) { if (c.isAssignableFrom(command.getClass())) { - HelpTopic t = this.topicFactoryMap.get(c).createTopic(command); - if (t != null) this.addTopic(t); + HelpTopic t = topicFactoryMap.get(c).createTopic(command); + if (t != null) addTopic(t); continue outer; } if (command instanceof PluginCommand && c.isAssignableFrom(((PluginCommand) command).getExecutor().getClass())) { - HelpTopic t = this.topicFactoryMap.get(c).createTopic(command); - if (t != null) this.addTopic(t); + HelpTopic t = topicFactoryMap.get(c).createTopic(command); + if (t != null) addTopic(t); continue outer; } } - this.addTopic(new GenericCommandHelpTopic(command)); + addTopic(new GenericCommandHelpTopic(command)); } // Initialize command alias help topics - for (Command command : this.server.getCommandMap().getCommands()) { - if (this.commandInIgnoredPlugin(command, ignoredPlugins)) { + for (Command command : server.getCommandMap().getCommands()) { + if (commandInIgnoredPlugin(command, ignoredPlugins)) { continue; } for (String alias : command.getAliases()) { // Only register if this command owns the alias - if (this.server.getCommandMap().getCommand(alias) == command) { - this.addTopic(new CommandAliasHelpTopic("/" + alias, "/" + command.getLabel(), this)); + if (server.getCommandMap().getCommand(alias) == command) { + addTopic(new CommandAliasHelpTopic("/" + alias, "/" + command.getLabel(), this)); } } } // Add alias sub-index - Collection filteredTopics = Collections2.filter(this.helpTopics.values(), Predicates.instanceOf(CommandAliasHelpTopic.class)); + Collection filteredTopics = Collections2.filter(helpTopics.values(), Predicates.instanceOf(CommandAliasHelpTopic.class)); if (!filteredTopics.isEmpty()) { - this.addTopic(new IndexHelpTopic("Aliases", "Lists command aliases", null, filteredTopics)); + addTopic(new IndexHelpTopic("Aliases", "Lists command aliases", null, filteredTopics)); } // Initialize plugin-level sub-topics Map> pluginIndexes = new HashMap>(); - this.fillPluginIndexes(pluginIndexes, this.server.getCommandMap().getCommands()); + fillPluginIndexes(pluginIndexes, server.getCommandMap().getCommands()); for (Map.Entry> entry : pluginIndexes.entrySet()) { - this.addTopic(new IndexHelpTopic(entry.getKey(), "All commands for " + entry.getKey(), null, entry.getValue(), "Below is a list of all " + entry.getKey() + " commands:")); + addTopic(new IndexHelpTopic(entry.getKey(), "All commands for " + entry.getKey(), null, entry.getValue(), "Below is a list of all " + entry.getKey() + " commands:")); } // Amend help topics from the help.yml file - for (HelpTopicAmendment amendment : this.yaml.getTopicAmendments()) { - if (this.helpTopics.containsKey(amendment.getTopicName())) { - this.helpTopics.get(amendment.getTopicName()).amendTopic(amendment.getShortText(), amendment.getFullText()); + for (HelpTopicAmendment amendment : yaml.getTopicAmendments()) { + if (helpTopics.containsKey(amendment.getTopicName())) { + helpTopics.get(amendment.getTopicName()).amendTopic(amendment.getShortText(), amendment.getFullText()); if (amendment.getPermission() != null) { - this.helpTopics.get(amendment.getTopicName()).amendCanSee(amendment.getPermission()); + helpTopics.get(amendment.getTopicName()).amendCanSee(amendment.getPermission()); } } } @@ -186,9 +186,9 @@ public synchronized void initializeCommands() { private void fillPluginIndexes(Map> pluginIndexes, Collection commands) { for (Command command : commands) { - String pluginName = this.getCommandPluginName(command); + String pluginName = getCommandPluginName(command); if (pluginName != null) { - HelpTopic topic = this.getHelpTopic("/" + command.getLabel()); + HelpTopic topic = getHelpTopic("/" + command.getLabel()); if (topic != null) { if (!pluginIndexes.containsKey(pluginName)) { pluginIndexes.put(pluginName, new TreeSet(HelpTopicComparator.helpTopicComparatorInstance())); //keep things in topic order @@ -225,7 +225,7 @@ private boolean commandInIgnoredPlugin(Command command, Set ignoredPlugi @Override public void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory) { Preconditions.checkArgument(Command.class.isAssignableFrom(commandClass) || CommandExecutor.class.isAssignableFrom(commandClass), "commandClass (%s) must implement either Command or CommandExecutor", commandClass.getName()); - this.topicFactoryMap.put(commandClass, factory); + topicFactoryMap.put(commandClass, factory); } private class IsCommandTopicPredicate implements Predicate { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java index ac4056e2..ce66f373 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.BlastingRecipe; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; @@ -27,6 +26,6 @@ public static CraftBlastingRecipe fromBukkitRecipe(BlastingRecipe recipe) { public void addToCraftingManager() { ItemStack result = this.getResult(); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.BlastingRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), this.toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), this.getExperience(), this.getCookingTime()))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.RecipeBlasting(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime()))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java index 7ae484b0..ca5d6af7 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.inventory; import net.minecraft.core.BlockPos; -import net.minecraft.world.Container; -import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.IInventory; +import net.minecraft.world.level.GeneratorAccess; import org.bukkit.block.Block; import org.bukkit.craftbukkit.block.CraftBlock; import org.bukkit.inventory.BlockInventoryHolder; @@ -13,18 +13,18 @@ public class CraftBlockInventoryHolder implements BlockInventoryHolder { private final Block block; private final Inventory inventory; - public CraftBlockInventoryHolder(LevelAccessor world, BlockPos pos, Container inv) { + public CraftBlockInventoryHolder(GeneratorAccess world, BlockPos pos, IInventory inv) { this.block = CraftBlock.at(world, pos); this.inventory = new CraftInventory(inv); } @Override public Block getBlock() { - return this.block; + return block; } @Override public Inventory getInventory() { - return this.inventory; + return inventory; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java index be3b081c..ebb9f580 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.CampfireRecipe; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; @@ -27,6 +26,6 @@ public static CraftCampfireRecipe fromBukkitRecipe(CampfireRecipe recipe) { public void addToCraftingManager() { ItemStack result = this.getResult(); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.CampfireCookingRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), this.toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), this.getExperience(), this.getCookingTime()))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.RecipeCampfire(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime()))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftComplexRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftComplexRecipe.java index b46d7ff3..453adee9 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftComplexRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftComplexRecipe.java @@ -1,25 +1,24 @@ package org.bukkit.craftbukkit.inventory; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.IRecipeComplex; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ComplexRecipe; import org.bukkit.inventory.CraftingRecipe; import org.bukkit.inventory.ItemStack; public class CraftComplexRecipe extends CraftingRecipe implements CraftRecipe, ComplexRecipe { - private final CustomRecipe recipe; + private final IRecipeComplex recipe; - public CraftComplexRecipe(NamespacedKey key, ItemStack result, CustomRecipe recipe) { + public CraftComplexRecipe(NamespacedKey key, ItemStack result, IRecipeComplex recipe) { super(key, result); this.recipe = recipe; } @Override public void addToCraftingManager() { - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), this.recipe)); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), recipe)); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java index db44944d..576ed605 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java @@ -1,56 +1,58 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.AnvilMenu; -import net.minecraft.world.inventory.BeaconMenu; -import net.minecraft.world.inventory.BlastFurnaceMenu; -import net.minecraft.world.inventory.BrewingStandMenu; -import net.minecraft.world.inventory.CartographyTableMenu; -import net.minecraft.world.inventory.ChestMenu; +import net.minecraft.world.IInventory; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.entity.player.PlayerInventory; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.ContainerAnvil; +import net.minecraft.world.inventory.ContainerBeacon; +import net.minecraft.world.inventory.ContainerBlastFurnace; +import net.minecraft.world.inventory.ContainerBrewingStand; +import net.minecraft.world.inventory.ContainerCartography; +import net.minecraft.world.inventory.ContainerChest; +import net.minecraft.world.inventory.ContainerDispenser; +import net.minecraft.world.inventory.ContainerEnchantTable; +import net.minecraft.world.inventory.ContainerFurnaceFurnace; +import net.minecraft.world.inventory.ContainerGrindstone; +import net.minecraft.world.inventory.ContainerHopper; +import net.minecraft.world.inventory.ContainerLectern; +import net.minecraft.world.inventory.ContainerLoom; +import net.minecraft.world.inventory.ContainerMerchant; +import net.minecraft.world.inventory.ContainerProperties; +import net.minecraft.world.inventory.ContainerShulkerBox; +import net.minecraft.world.inventory.ContainerSmoker; +import net.minecraft.world.inventory.ContainerWorkbench; +import net.minecraft.world.inventory.Containers; import net.minecraft.world.inventory.CrafterMenu; -import net.minecraft.world.inventory.CraftingMenu; -import net.minecraft.world.inventory.DispenserMenu; -import net.minecraft.world.inventory.EnchantmentMenu; -import net.minecraft.world.inventory.FurnaceMenu; -import net.minecraft.world.inventory.GrindstoneMenu; -import net.minecraft.world.inventory.HopperMenu; -import net.minecraft.world.inventory.LecternMenu; -import net.minecraft.world.inventory.LoomMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.inventory.MerchantMenu; -import net.minecraft.world.inventory.ShulkerBoxMenu; -import net.minecraft.world.inventory.SimpleContainerData; import net.minecraft.world.inventory.Slot; -import net.minecraft.world.inventory.SmokerMenu; import net.minecraft.world.item.ItemStack; import org.bukkit.entity.HumanEntity; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.MenuType; -public class CraftContainer extends AbstractContainerMenu { +public class CraftContainer extends Container { private final InventoryView view; private InventoryType cachedType; - private AbstractContainerMenu delegate; + private Container delegate; - public CraftContainer(InventoryView view, Player player, int id) { - super(CraftContainer.getNotchInventoryType(view.getTopInventory()), id); + public CraftContainer(InventoryView view, EntityHuman player, int id) { + super(getNotchInventoryType(view.getTopInventory()), id); this.view = view; // TODO: Do we need to check that it really is a CraftInventory? - Container top = ((CraftInventory) view.getTopInventory()).getInventory(); - net.minecraft.world.entity.player.Inventory bottom = (net.minecraft.world.entity.player.Inventory) ((CraftInventory) view.getBottomInventory()).getInventory(); - this.cachedType = view.getType(); - this.setupSlots(top, bottom, player); + IInventory top = ((CraftInventory) view.getTopInventory()).getInventory(); + PlayerInventory bottom = (PlayerInventory) ((CraftInventory) view.getBottomInventory()).getInventory(); + cachedType = view.getType(); + setupSlots(top, bottom, player); } - public CraftContainer(final Inventory inventory, final Player player, int id) { + public CraftContainer(final Inventory inventory, final EntityHuman player, int id) { this(new CraftAbstractInventoryView() { private final String originalTitle = (inventory instanceof CraftInventoryCustom) ? ((CraftInventoryCustom.MinecraftInventory) ((CraftInventory) inventory).getInventory()).getTitle() : inventory.getType().getDefaultTitle(); - private String title = this.originalTitle; + private String title = originalTitle; @Override public Inventory getTopInventory() { @@ -59,7 +61,7 @@ public Inventory getTopInventory() { @Override public Inventory getBottomInventory() { - return this.getPlayer().getInventory(); + return getPlayer().getInventory(); } @Override @@ -74,12 +76,12 @@ public InventoryType getType() { @Override public String getTitle() { - return this.title; + return title; } @Override public String getOriginalTitle() { - return this.originalTitle; + return originalTitle; } @Override @@ -93,10 +95,10 @@ public void setTitle(String title) { @Override public InventoryView getBukkitView() { - return this.view; + return view; } - public static MenuType getNotchInventoryType(Inventory inventory) { + public static Containers getNotchInventoryType(Inventory inventory) { final InventoryType type = inventory.getType(); switch (type) { case PLAYER: @@ -105,122 +107,122 @@ public static MenuType getNotchInventoryType(Inventory inventory) { case BARREL: switch (inventory.getSize()) { case 9: - return MenuType.GENERIC_9x1; + return Containers.GENERIC_9x1; case 18: - return MenuType.GENERIC_9x2; + return Containers.GENERIC_9x2; case 27: - return MenuType.GENERIC_9x3; + return Containers.GENERIC_9x3; case 36: case 41: // PLAYER - return MenuType.GENERIC_9x4; + return Containers.GENERIC_9x4; case 45: - return MenuType.GENERIC_9x5; + return Containers.GENERIC_9x5; case 54: - return MenuType.GENERIC_9x6; + return Containers.GENERIC_9x6; default: throw new IllegalArgumentException("Unsupported custom inventory size " + inventory.getSize()); } default: - final org.bukkit.inventory.MenuType menu = type.getMenuType(); + final MenuType menu = type.getMenuType(); if (menu == null) { - return MenuType.GENERIC_9x3; + return Containers.GENERIC_9x3; } else { return ((CraftMenuType) menu).getHandle(); } } } - private void setupSlots(Container top, net.minecraft.world.entity.player.Inventory bottom, Player entityhuman) { + private void setupSlots(IInventory top, PlayerInventory bottom, EntityHuman entityhuman) { int windowId = -1; - switch (this.cachedType) { + switch (cachedType) { case CREATIVE: break; // TODO: This should be an error? case PLAYER: case CHEST: case ENDER_CHEST: case BARREL: - this.delegate = new ChestMenu(MenuType.GENERIC_9x3, windowId, bottom, top, top.getContainerSize() / 9); + delegate = new ContainerChest(Containers.GENERIC_9x3, windowId, bottom, top, top.getContainerSize() / 9); break; case DISPENSER: case DROPPER: - this.delegate = new DispenserMenu(windowId, bottom, top); + delegate = new ContainerDispenser(windowId, bottom, top); break; case FURNACE: - this.delegate = new FurnaceMenu(windowId, bottom, top, new SimpleContainerData(4)); + delegate = new ContainerFurnaceFurnace(windowId, bottom, top, new ContainerProperties(4)); break; case CRAFTING: // TODO: This should be an error? case WORKBENCH: - this.setupWorkbench(top, bottom); // SPIGOT-3812 - manually set up slots so we can use the delegated inventory and not the automatically created one + setupWorkbench(top, bottom); // SPIGOT-3812 - manually set up slots so we can use the delegated inventory and not the automatically created one break; case ENCHANTING: - this.delegate = new EnchantmentMenu(windowId, bottom); + delegate = new ContainerEnchantTable(windowId, bottom); break; case BREWING: - this.delegate = new BrewingStandMenu(windowId, bottom, top, new SimpleContainerData(2)); + delegate = new ContainerBrewingStand(windowId, bottom, top, new ContainerProperties(2)); break; case HOPPER: - this.delegate = new HopperMenu(windowId, bottom, top); + delegate = new ContainerHopper(windowId, bottom, top); break; case ANVIL: - this.setupAnvil(top, bottom); // SPIGOT-6783 - manually set up slots so we can use the delegated inventory and not the automatically created one + setupAnvil(top, bottom); // SPIGOT-6783 - manually set up slots so we can use the delegated inventory and not the automatically created one break; case BEACON: - this.delegate = new BeaconMenu(windowId, bottom); + delegate = new ContainerBeacon(windowId, bottom); break; case SHULKER_BOX: - this.delegate = new ShulkerBoxMenu(windowId, bottom, top); + delegate = new ContainerShulkerBox(windowId, bottom, top); break; case BLAST_FURNACE: - this.delegate = new BlastFurnaceMenu(windowId, bottom, top, new SimpleContainerData(4)); + delegate = new ContainerBlastFurnace(windowId, bottom, top, new ContainerProperties(4)); break; case LECTERN: - this.delegate = new LecternMenu(windowId, top, new SimpleContainerData(1), bottom); + delegate = new ContainerLectern(windowId, top, new ContainerProperties(1), bottom); break; case SMOKER: - this.delegate = new SmokerMenu(windowId, bottom, top, new SimpleContainerData(4)); + delegate = new ContainerSmoker(windowId, bottom, top, new ContainerProperties(4)); break; case LOOM: - this.delegate = new LoomMenu(windowId, bottom); + delegate = new ContainerLoom(windowId, bottom); break; case CARTOGRAPHY: - this.delegate = new CartographyTableMenu(windowId, bottom); + delegate = new ContainerCartography(windowId, bottom); break; case GRINDSTONE: - this.delegate = new GrindstoneMenu(windowId, bottom); + delegate = new ContainerGrindstone(windowId, bottom); break; case STONECUTTER: setupStoneCutter(top, bottom); // SPIGOT-7757 - manual setup required for individual slots break; case MERCHANT: - this.delegate = new MerchantMenu(windowId, bottom); + delegate = new ContainerMerchant(windowId, bottom); break; case SMITHING: case SMITHING_NEW: - this.setupSmithing(top, bottom); // SPIGOT-6783 - manually set up slots so we can use the delegated inventory and not the automatically created one + setupSmithing(top, bottom); // SPIGOT-6783 - manually set up slots so we can use the delegated inventory and not the automatically created one break; case CRAFTER: - this.delegate = new CrafterMenu(windowId, bottom); + delegate = new CrafterMenu(windowId, bottom); break; } - if (this.delegate != null) { - this.lastSlots = this.delegate.lastSlots; - this.slots = this.delegate.slots; - this.remoteSlots = this.delegate.remoteSlots; + if (delegate != null) { + this.lastSlots = delegate.lastSlots; + this.slots = delegate.slots; + this.remoteSlots = delegate.remoteSlots; } // SPIGOT-4598 - we should still delegate the shift click handler - switch (this.cachedType) { + switch (cachedType) { case WORKBENCH: - this.delegate = new CraftingMenu(windowId, bottom); + delegate = new ContainerWorkbench(windowId, bottom); break; case ANVIL: - this.delegate = new AnvilMenu(windowId, bottom); + delegate = new ContainerAnvil(windowId, bottom); break; } } - private void setupWorkbench(Container top, Container bottom) { + private void setupWorkbench(IInventory top, IInventory bottom) { // This code copied from ContainerWorkbench this.addSlot(new Slot(top, 0, 124, 35)); @@ -245,7 +247,7 @@ private void setupWorkbench(Container top, Container bottom) { // End copy from ContainerWorkbench } - private void setupAnvil(Container top, Container bottom) { + private void setupAnvil(IInventory top, IInventory bottom) { // This code copied from ContainerAnvilAbstract this.addSlot(new Slot(top, 0, 27, 47)); this.addSlot(new Slot(top, 1, 76, 47)); @@ -266,7 +268,7 @@ private void setupAnvil(Container top, Container bottom) { // End copy from ContainerAnvilAbstract } - private void setupSmithing(Container top, Container bottom) { + private void setupSmithing(IInventory top, IInventory bottom) { // This code copied from ContainerSmithing this.addSlot(new Slot(top, 0, 8, 48)); this.addSlot(new Slot(top, 1, 26, 48)); @@ -288,7 +290,7 @@ private void setupSmithing(Container top, Container bottom) { // End copy from ContainerSmithing } - private void setupStoneCutter(Container top, Container bottom) { + private void setupStoneCutter(IInventory top, IInventory bottom) { // This code copied from ContainerStonecutter this.addSlot(new Slot(top, 0, 20, 33)); this.addSlot(new Slot(top, 1, 143, 33)); @@ -309,17 +311,17 @@ private void setupStoneCutter(Container top, Container bottom) { } @Override - public ItemStack quickMoveStack(Player player, int slot) { - return (this.delegate != null) ? this.delegate.quickMoveStack(player, slot) : ItemStack.EMPTY; + public ItemStack quickMoveStack(EntityHuman entityhuman, int i) { + return (delegate != null) ? delegate.quickMoveStack(entityhuman, i) : ItemStack.EMPTY; } @Override - public boolean stillValid(Player player) { + public boolean stillValid(EntityHuman entity) { return true; } @Override - public MenuType getType() { - return CraftContainer.getNotchInventoryType(this.view.getTopInventory()); + public Containers getType() { + return getNotchInventoryType(view.getTopInventory()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java index cb704cef..dc4cb10f 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java @@ -1,7 +1,8 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Preconditions; -import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.EntityInsentient; +import net.minecraft.world.entity.EnumItemSlot; import org.bukkit.craftbukkit.CraftEquipmentSlot; import org.bukkit.craftbukkit.entity.CraftLivingEntity; import org.bukkit.entity.Entity; @@ -25,20 +26,20 @@ public void setItem(EquipmentSlot slot, ItemStack item) { @Override public void setItem(EquipmentSlot slot, ItemStack item, boolean silent) { Preconditions.checkArgument(slot != null, "slot must not be null"); - net.minecraft.world.entity.EquipmentSlot nmsSlot = CraftEquipmentSlot.getNMS(slot); - this.setEquipment(nmsSlot, item, silent); + EnumItemSlot nmsSlot = CraftEquipmentSlot.getNMS(slot); + setEquipment(nmsSlot, item, silent); } @Override public ItemStack getItem(EquipmentSlot slot) { Preconditions.checkArgument(slot != null, "slot must not be null"); - net.minecraft.world.entity.EquipmentSlot nmsSlot = CraftEquipmentSlot.getNMS(slot); - return this.getEquipment(nmsSlot); + EnumItemSlot nmsSlot = CraftEquipmentSlot.getNMS(slot); + return getEquipment(nmsSlot); } @Override public ItemStack getItemInMainHand() { - return this.getEquipment(net.minecraft.world.entity.EquipmentSlot.MAINHAND); + return getEquipment(EnumItemSlot.MAINHAND); } @Override @@ -48,12 +49,12 @@ public void setItemInMainHand(ItemStack item) { @Override public void setItemInMainHand(ItemStack item, boolean silent) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.MAINHAND, item, silent); + setEquipment(EnumItemSlot.MAINHAND, item, silent); } @Override public ItemStack getItemInOffHand() { - return this.getEquipment(net.minecraft.world.entity.EquipmentSlot.OFFHAND); + return getEquipment(EnumItemSlot.OFFHAND); } @Override @@ -63,22 +64,22 @@ public void setItemInOffHand(ItemStack item) { @Override public void setItemInOffHand(ItemStack item, boolean silent) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.OFFHAND, item, silent); + setEquipment(EnumItemSlot.OFFHAND, item, silent); } @Override public ItemStack getItemInHand() { - return this.getItemInMainHand(); + return getItemInMainHand(); } @Override public void setItemInHand(ItemStack stack) { - this.setItemInMainHand(stack); + setItemInMainHand(stack); } @Override public ItemStack getHelmet() { - return this.getEquipment(net.minecraft.world.entity.EquipmentSlot.HEAD); + return getEquipment(EnumItemSlot.HEAD); } @Override @@ -88,12 +89,12 @@ public void setHelmet(ItemStack helmet) { @Override public void setHelmet(ItemStack helmet, boolean silent) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.HEAD, helmet, silent); + setEquipment(EnumItemSlot.HEAD, helmet, silent); } @Override public ItemStack getChestplate() { - return this.getEquipment(net.minecraft.world.entity.EquipmentSlot.CHEST); + return getEquipment(EnumItemSlot.CHEST); } @Override @@ -103,12 +104,12 @@ public void setChestplate(ItemStack chestplate) { @Override public void setChestplate(ItemStack chestplate, boolean silent) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.CHEST, chestplate, silent); + setEquipment(EnumItemSlot.CHEST, chestplate, silent); } @Override public ItemStack getLeggings() { - return this.getEquipment(net.minecraft.world.entity.EquipmentSlot.LEGS); + return getEquipment(EnumItemSlot.LEGS); } @Override @@ -118,12 +119,12 @@ public void setLeggings(ItemStack leggings) { @Override public void setLeggings(ItemStack leggings, boolean silent) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.LEGS, leggings, silent); + setEquipment(EnumItemSlot.LEGS, leggings, silent); } @Override public ItemStack getBoots() { - return this.getEquipment(net.minecraft.world.entity.EquipmentSlot.FEET); + return getEquipment(EnumItemSlot.FEET); } @Override @@ -133,137 +134,137 @@ public void setBoots(ItemStack boots) { @Override public void setBoots(ItemStack boots, boolean silent) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.FEET, boots, silent); + setEquipment(EnumItemSlot.FEET, boots, silent); } @Override public ItemStack[] getArmorContents() { ItemStack[] armor = new ItemStack[]{ - this.getEquipment(net.minecraft.world.entity.EquipmentSlot.FEET), - this.getEquipment(net.minecraft.world.entity.EquipmentSlot.LEGS), - this.getEquipment(net.minecraft.world.entity.EquipmentSlot.CHEST), - this.getEquipment(net.minecraft.world.entity.EquipmentSlot.HEAD), + getEquipment(EnumItemSlot.FEET), + getEquipment(EnumItemSlot.LEGS), + getEquipment(EnumItemSlot.CHEST), + getEquipment(EnumItemSlot.HEAD), }; return armor; } @Override public void setArmorContents(ItemStack[] items) { - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.FEET, items.length >= 1 ? items[0] : null, false); - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.LEGS, items.length >= 2 ? items[1] : null, false); - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.CHEST, items.length >= 3 ? items[2] : null, false); - this.setEquipment(net.minecraft.world.entity.EquipmentSlot.HEAD, items.length >= 4 ? items[3] : null, false); + setEquipment(EnumItemSlot.FEET, items.length >= 1 ? items[0] : null, false); + setEquipment(EnumItemSlot.LEGS, items.length >= 2 ? items[1] : null, false); + setEquipment(EnumItemSlot.CHEST, items.length >= 3 ? items[2] : null, false); + setEquipment(EnumItemSlot.HEAD, items.length >= 4 ? items[3] : null, false); } - private ItemStack getEquipment(net.minecraft.world.entity.EquipmentSlot slot) { - return CraftItemStack.asBukkitCopy(this.entity.getHandle().getItemBySlot(slot)); + private ItemStack getEquipment(EnumItemSlot slot) { + return CraftItemStack.asBukkitCopy(entity.getHandle().getItemBySlot(slot)); } - private void setEquipment(net.minecraft.world.entity.EquipmentSlot slot, ItemStack stack, boolean silent) { - this.entity.getHandle().setItemSlot(slot, CraftItemStack.asNMSCopy(stack), silent); + private void setEquipment(EnumItemSlot slot, ItemStack stack, boolean silent) { + entity.getHandle().setItemSlot(slot, CraftItemStack.asNMSCopy(stack), silent); } @Override public void clear() { - for (net.minecraft.world.entity.EquipmentSlot slot : net.minecraft.world.entity.EquipmentSlot.values()) { - this.setEquipment(slot, null, false); + for (EnumItemSlot slot : EnumItemSlot.values()) { + setEquipment(slot, null, false); } } @Override public Entity getHolder() { - return this.entity; + return entity; } @Override public float getItemInHandDropChance() { - return this.getItemInMainHandDropChance(); + return getItemInMainHandDropChance(); } @Override public void setItemInHandDropChance(float chance) { - this.setItemInMainHandDropChance(chance); + setItemInMainHandDropChance(chance); } @Override public float getItemInMainHandDropChance() { - return this.getDropChance(net.minecraft.world.entity.EquipmentSlot.MAINHAND); + return getDropChance(EnumItemSlot.MAINHAND); } @Override public void setItemInMainHandDropChance(float chance) { - this.setDropChance(net.minecraft.world.entity.EquipmentSlot.MAINHAND, chance); + setDropChance(EnumItemSlot.MAINHAND, chance); } @Override public float getItemInOffHandDropChance() { - return this.getDropChance(net.minecraft.world.entity.EquipmentSlot.OFFHAND); + return getDropChance(EnumItemSlot.OFFHAND); } @Override public void setItemInOffHandDropChance(float chance) { - this.setDropChance(net.minecraft.world.entity.EquipmentSlot.OFFHAND, chance); + setDropChance(EnumItemSlot.OFFHAND, chance); } @Override public float getHelmetDropChance() { - return this.getDropChance(net.minecraft.world.entity.EquipmentSlot.HEAD); + return getDropChance(EnumItemSlot.HEAD); } @Override public void setHelmetDropChance(float chance) { - this.setDropChance(net.minecraft.world.entity.EquipmentSlot.HEAD, chance); + setDropChance(EnumItemSlot.HEAD, chance); } @Override public float getChestplateDropChance() { - return this.getDropChance(net.minecraft.world.entity.EquipmentSlot.CHEST); + return getDropChance(EnumItemSlot.CHEST); } @Override public void setChestplateDropChance(float chance) { - this.setDropChance(net.minecraft.world.entity.EquipmentSlot.CHEST, chance); + setDropChance(EnumItemSlot.CHEST, chance); } @Override public float getLeggingsDropChance() { - return this.getDropChance(net.minecraft.world.entity.EquipmentSlot.LEGS); + return getDropChance(EnumItemSlot.LEGS); } @Override public void setLeggingsDropChance(float chance) { - this.setDropChance(net.minecraft.world.entity.EquipmentSlot.LEGS, chance); + setDropChance(EnumItemSlot.LEGS, chance); } @Override public float getBootsDropChance() { - return this.getDropChance(net.minecraft.world.entity.EquipmentSlot.FEET); + return getDropChance(EnumItemSlot.FEET); } @Override public void setBootsDropChance(float chance) { - this.setDropChance(net.minecraft.world.entity.EquipmentSlot.FEET, chance); + setDropChance(EnumItemSlot.FEET, chance); } - private void setDropChance(net.minecraft.world.entity.EquipmentSlot slot, float chance) { - Preconditions.checkArgument(this.entity.getHandle() instanceof Mob, "Cannot set drop chance for non-Mob entity"); + private void setDropChance(EnumItemSlot slot, float chance) { + Preconditions.checkArgument(entity.getHandle() instanceof EntityInsentient, "Cannot set drop chance for non-Mob entity"); - if (slot == net.minecraft.world.entity.EquipmentSlot.MAINHAND || slot == net.minecraft.world.entity.EquipmentSlot.OFFHAND) { - ((Mob) this.entity.getHandle()).handDropChances[slot.getIndex()] = chance; + if (slot == EnumItemSlot.MAINHAND || slot == EnumItemSlot.OFFHAND) { + ((EntityInsentient) entity.getHandle()).handDropChances[slot.getIndex()] = chance; } else { - ((Mob) this.entity.getHandle()).armorDropChances[slot.getIndex()] = chance; + ((EntityInsentient) entity.getHandle()).armorDropChances[slot.getIndex()] = chance; } } - private float getDropChance(net.minecraft.world.entity.EquipmentSlot slot) { - if (!(this.entity.getHandle() instanceof Mob)) { + private float getDropChance(EnumItemSlot slot) { + if (!(entity.getHandle() instanceof EntityInsentient)) { return 1; } - if (slot == net.minecraft.world.entity.EquipmentSlot.MAINHAND || slot == net.minecraft.world.entity.EquipmentSlot.OFFHAND) { - return ((Mob) this.entity.getHandle()).handDropChances[slot.getIndex()]; + if (slot == EnumItemSlot.MAINHAND || slot == EnumItemSlot.OFFHAND) { + return ((EntityInsentient) entity.getHandle()).handDropChances[slot.getIndex()]; } else { - return ((Mob) this.entity.getHandle()).armorDropChances[slot.getIndex()]; + return ((EntityInsentient) entity.getHandle()).armorDropChances[slot.getIndex()]; } } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java index a3879d7b..4c620c9a 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.FurnaceRecipe; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; @@ -27,6 +26,6 @@ public static CraftFurnaceRecipe fromBukkitRecipe(FurnaceRecipe recipe) { public void addToCraftingManager() { ItemStack result = this.getResult(); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.SmeltingRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), this.toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), this.getExperience(), this.getCookingTime()))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.FurnaceRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime()))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java index 88d5590a..8a17d178 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java @@ -4,24 +4,25 @@ import java.util.HashMap; import java.util.List; import java.util.ListIterator; -import net.minecraft.world.Container; -import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.inventory.MerchantContainer; -import net.minecraft.world.inventory.PlayerEnderChestContainer; -import net.minecraft.world.level.block.ComposterBlock; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; -import net.minecraft.world.level.block.entity.BarrelBlockEntity; -import net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity; -import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; +import net.minecraft.world.IInventory; +import net.minecraft.world.entity.player.PlayerInventory; +import net.minecraft.world.inventory.InventoryCrafting; +import net.minecraft.world.inventory.InventoryEnderChest; +import net.minecraft.world.inventory.InventoryMerchant; +import net.minecraft.world.level.block.BlockComposter; import net.minecraft.world.level.block.entity.ChiseledBookShelfBlockEntity; import net.minecraft.world.level.block.entity.CrafterBlockEntity; -import net.minecraft.world.level.block.entity.DispenserBlockEntity; -import net.minecraft.world.level.block.entity.DropperBlockEntity; -import net.minecraft.world.level.block.entity.Hopper; -import net.minecraft.world.level.block.entity.JukeboxBlockEntity; -import net.minecraft.world.level.block.entity.LecternBlockEntity; -import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; -import net.minecraft.world.level.block.entity.SmokerBlockEntity; +import net.minecraft.world.level.block.entity.IHopper; +import net.minecraft.world.level.block.entity.TileEntityBarrel; +import net.minecraft.world.level.block.entity.TileEntityBlastFurnace; +import net.minecraft.world.level.block.entity.TileEntityBrewingStand; +import net.minecraft.world.level.block.entity.TileEntityDispenser; +import net.minecraft.world.level.block.entity.TileEntityDropper; +import net.minecraft.world.level.block.entity.TileEntityFurnace; +import net.minecraft.world.level.block.entity.TileEntityJukeBox; +import net.minecraft.world.level.block.entity.TileEntityLectern; +import net.minecraft.world.level.block.entity.TileEntityShulkerBox; +import net.minecraft.world.level.block.entity.TileEntitySmoker; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.util.CraftLegacy; @@ -32,24 +33,24 @@ import org.bukkit.inventory.ItemStack; public class CraftInventory implements Inventory { - protected final Container inventory; + protected final IInventory inventory; - public CraftInventory(Container inventory) { + public CraftInventory(IInventory inventory) { this.inventory = inventory; } - public Container getInventory() { - return this.inventory; + public IInventory getInventory() { + return inventory; } @Override public int getSize() { - return this.getInventory().getContainerSize(); + return getInventory().getContainerSize(); } @Override public ItemStack getItem(int index) { - net.minecraft.world.item.ItemStack item = this.getInventory().getItem(index); + net.minecraft.world.item.ItemStack item = getInventory().getItem(index); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } @@ -67,44 +68,44 @@ protected ItemStack[] asCraftMirror(List mcI @Override public ItemStack[] getStorageContents() { - return this.getContents(); + return getContents(); } @Override public void setStorageContents(ItemStack[] items) throws IllegalArgumentException { - this.setContents(items); + setContents(items); } @Override public ItemStack[] getContents() { - List mcItems = this.getInventory().getContents(); + List mcItems = getInventory().getContents(); - return this.asCraftMirror(mcItems); + return asCraftMirror(mcItems); } @Override public void setContents(ItemStack[] items) { - Preconditions.checkArgument(items.length <= this.getSize(), "Invalid inventory size (%s); expected %s or less", items.length, this.getSize()); + Preconditions.checkArgument(items.length <= getSize(), "Invalid inventory size (%s); expected %s or less", items.length, getSize()); - for (int i = 0; i < this.getSize(); i++) { + for (int i = 0; i < getSize(); i++) { if (i >= items.length) { - this.setItem(i, null); + setItem(i, null); } else { - this.setItem(i, items[i]); + setItem(i, items[i]); } } } @Override public void setItem(int index, ItemStack item) { - this.getInventory().setItem(index, CraftItemStack.asNMSCopy(item)); + getInventory().setItem(index, CraftItemStack.asNMSCopy(item)); } @Override public boolean contains(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); - for (ItemStack item : this.getStorageContents()) { + for (ItemStack item : getStorageContents()) { if (item != null && item.getType() == material) { return true; } @@ -117,7 +118,7 @@ public boolean contains(ItemStack item) { if (item == null) { return false; } - for (ItemStack i : this.getStorageContents()) { + for (ItemStack i : getStorageContents()) { if (item.equals(i)) { return true; } @@ -132,7 +133,7 @@ public boolean contains(Material material, int amount) { if (amount <= 0) { return true; } - for (ItemStack item : this.getStorageContents()) { + for (ItemStack item : getStorageContents()) { if (item != null && item.getType() == material) { if ((amount -= item.getAmount()) <= 0) { return true; @@ -150,7 +151,7 @@ public boolean contains(ItemStack item, int amount) { if (amount <= 0) { return true; } - for (ItemStack i : this.getStorageContents()) { + for (ItemStack i : getStorageContents()) { if (item.equals(i) && --amount <= 0) { return true; } @@ -166,7 +167,7 @@ public boolean containsAtLeast(ItemStack item, int amount) { if (amount <= 0) { return true; } - for (ItemStack i : this.getStorageContents()) { + for (ItemStack i : getStorageContents()) { if (item.isSimilar(i) && (amount -= i.getAmount()) <= 0) { return true; } @@ -180,7 +181,7 @@ public HashMap all(Material material) { material = CraftLegacy.fromLegacy(material); HashMap slots = new HashMap<>(); - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { ItemStack item = inventory[i]; if (item != null && item.getType() == material) { @@ -194,7 +195,7 @@ public HashMap all(Material material) { public HashMap all(ItemStack item) { HashMap slots = new HashMap<>(); if (item != null) { - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { if (item.equals(inventory[i])) { slots.put(i, inventory[i]); @@ -208,7 +209,7 @@ public HashMap all(ItemStack item) { public int first(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { ItemStack item = inventory[i]; if (item != null && item.getType() == material) { @@ -220,14 +221,14 @@ public int first(Material material) { @Override public int first(ItemStack item) { - return this.first(item, true); + return first(item, true); } private int first(ItemStack item, boolean withAmount) { if (item == null) { return -1; } - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { if (inventory[i] == null) continue; @@ -240,7 +241,7 @@ private int first(ItemStack item, boolean withAmount) { @Override public int firstEmpty() { - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { if (inventory[i] == null) { return i; @@ -251,13 +252,13 @@ public int firstEmpty() { @Override public boolean isEmpty() { - return this.inventory.isEmpty(); + return inventory.isEmpty(); } public int firstPartial(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { ItemStack item = inventory[i]; if (item != null && item.getType() == material && item.getAmount() < item.getMaxStackSize()) { @@ -268,7 +269,7 @@ public int firstPartial(Material material) { } private int firstPartial(ItemStack item) { - ItemStack[] inventory = this.getStorageContents(); + ItemStack[] inventory = getStorageContents(); ItemStack filteredItem = CraftItemStack.asCraftCopy(item); if (item == null) { return -1; @@ -298,12 +299,12 @@ public HashMap addItem(ItemStack... items) { Preconditions.checkArgument(item != null, "ItemStack cannot be null"); while (true) { // Do we already have a stack of it? - int firstPartial = this.firstPartial(item); + int firstPartial = firstPartial(item); // Drat! no partial stack if (firstPartial == -1) { // Find a free spot! - int firstFree = this.firstEmpty(); + int firstFree = firstEmpty(); if (firstFree == -1) { // No space at all! @@ -311,20 +312,20 @@ public HashMap addItem(ItemStack... items) { break; } else { // More than a single stack! - if (item.getAmount() > this.getMaxItemStack()) { + if (item.getAmount() > getMaxItemStack()) { CraftItemStack stack = CraftItemStack.asCraftCopy(item); - stack.setAmount(this.getMaxItemStack()); - this.setItem(firstFree, stack); - item.setAmount(item.getAmount() - this.getMaxItemStack()); + stack.setAmount(getMaxItemStack()); + setItem(firstFree, stack); + item.setAmount(item.getAmount() - getMaxItemStack()); } else { // Just store it - this.setItem(firstFree, item); + setItem(firstFree, item); break; } } } else { // So, apparently it might only partially fit, well lets do just that - ItemStack partialItem = this.getItem(firstPartial); + ItemStack partialItem = getItem(firstPartial); int amount = item.getAmount(); int partialAmount = partialItem.getAmount(); @@ -334,14 +335,14 @@ public HashMap addItem(ItemStack... items) { if (amount + partialAmount <= maxAmount) { partialItem.setAmount(amount + partialAmount); // To make sure the packet is sent to the client - this.setItem(firstPartial, partialItem); + setItem(firstPartial, partialItem); break; } // It fits partially partialItem.setAmount(maxAmount); // To make sure the packet is sent to the client - this.setItem(firstPartial, partialItem); + setItem(firstPartial, partialItem); item.setAmount(amount + partialAmount - maxAmount); } } @@ -362,7 +363,7 @@ public HashMap removeItem(ItemStack... items) { int toDelete = item.getAmount(); while (true) { - int first = this.first(item, false); + int first = first(item, false); // Drat! we don't have this type in the inventory if (first == -1) { @@ -370,17 +371,17 @@ public HashMap removeItem(ItemStack... items) { leftover.put(i, item); break; } else { - ItemStack itemStack = this.getItem(first); + ItemStack itemStack = getItem(first); int amount = itemStack.getAmount(); if (amount <= toDelete) { toDelete -= amount; // clear the slot, all used up - this.clear(first); + clear(first); } else { // split the stack and store itemStack.setAmount(amount - toDelete); - this.setItem(first, itemStack); + setItem(first, itemStack); toDelete = 0; } } @@ -395,40 +396,40 @@ public HashMap removeItem(ItemStack... items) { } private int getMaxItemStack() { - return this.getInventory().getMaxStackSize(); + return getInventory().getMaxStackSize(); } @Override public void remove(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); - ItemStack[] items = this.getStorageContents(); + ItemStack[] items = getStorageContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && items[i].getType() == material) { - this.clear(i); + clear(i); } } } @Override public void remove(ItemStack item) { - ItemStack[] items = this.getStorageContents(); + ItemStack[] items = getStorageContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && items[i].equals(item)) { - this.clear(i); + clear(i); } } } @Override public void clear(int index) { - this.setItem(index, null); + setItem(index, null); } @Override public void clear() { - for (int i = 0; i < this.getSize(); i++) { - this.clear(i); + for (int i = 0; i < getSize(); i++) { + clear(i); } } @@ -440,7 +441,7 @@ public ListIterator iterator() { @Override public ListIterator iterator(int index) { if (index < 0) { - index += this.getSize() + 1; // ie, with -1, previous() will return the last element + index += getSize() + 1; // ie, with -1, previous() will return the last element } return new InventoryIterator(this, index); } @@ -453,33 +454,33 @@ public List getViewers() { @Override public InventoryType getType() { // Thanks to Droppers extending Dispensers, Blast Furnaces & Smokers extending Furnace, order is important. - if (this.inventory instanceof CraftingContainer) { - if (this.inventory instanceof CrafterBlockEntity) { + if (inventory instanceof InventoryCrafting) { + if (inventory instanceof CrafterBlockEntity) { return InventoryType.CRAFTER; } else { - return this.inventory.getContainerSize() >= 9 ? InventoryType.WORKBENCH : InventoryType.CRAFTING; + return inventory.getContainerSize() >= 9 ? InventoryType.WORKBENCH : InventoryType.CRAFTING; } - } else if (this.inventory instanceof net.minecraft.world.entity.player.Inventory) { + } else if (inventory instanceof PlayerInventory) { return InventoryType.PLAYER; - } else if (this.inventory instanceof DropperBlockEntity) { + } else if (inventory instanceof TileEntityDropper) { return InventoryType.DROPPER; - } else if (this.inventory instanceof DispenserBlockEntity) { + } else if (inventory instanceof TileEntityDispenser) { return InventoryType.DISPENSER; - } else if (this.inventory instanceof BlastFurnaceBlockEntity) { + } else if (inventory instanceof TileEntityBlastFurnace) { return InventoryType.BLAST_FURNACE; - } else if (this.inventory instanceof SmokerBlockEntity) { + } else if (inventory instanceof TileEntitySmoker) { return InventoryType.SMOKER; - } else if (this.inventory instanceof AbstractFurnaceBlockEntity) { + } else if (inventory instanceof TileEntityFurnace) { return InventoryType.FURNACE; } else if (this instanceof CraftInventoryEnchanting) { return InventoryType.ENCHANTING; - } else if (this.inventory instanceof BrewingStandBlockEntity) { + } else if (inventory instanceof TileEntityBrewingStand) { return InventoryType.BREWING; - } else if (this.inventory instanceof CraftInventoryCustom.MinecraftInventory) { - return ((CraftInventoryCustom.MinecraftInventory) this.inventory).getType(); - } else if (this.inventory instanceof PlayerEnderChestContainer) { + } else if (inventory instanceof CraftInventoryCustom.MinecraftInventory) { + return ((CraftInventoryCustom.MinecraftInventory) inventory).getType(); + } else if (inventory instanceof InventoryEnderChest) { return InventoryType.ENDER_CHEST; - } else if (this.inventory instanceof MerchantContainer) { + } else if (inventory instanceof InventoryMerchant) { return InventoryType.MERCHANT; } else if (this instanceof CraftInventoryBeacon) { return InventoryType.BEACON; @@ -487,15 +488,15 @@ public InventoryType getType() { return InventoryType.ANVIL; } else if (this instanceof CraftInventorySmithing) { return InventoryType.SMITHING; - } else if (this.inventory instanceof Hopper) { + } else if (inventory instanceof IHopper) { return InventoryType.HOPPER; - } else if (this.inventory instanceof ShulkerBoxBlockEntity) { + } else if (inventory instanceof TileEntityShulkerBox) { return InventoryType.SHULKER_BOX; - } else if (this.inventory instanceof BarrelBlockEntity) { + } else if (inventory instanceof TileEntityBarrel) { return InventoryType.BARREL; - } else if (this.inventory instanceof LecternBlockEntity.LecternInventory) { + } else if (inventory instanceof TileEntityLectern.LecternInventory) { return InventoryType.LECTERN; - } else if (this.inventory instanceof ChiseledBookShelfBlockEntity) { + } else if (inventory instanceof ChiseledBookShelfBlockEntity) { return InventoryType.CHISELED_BOOKSHELF; } else if (this instanceof CraftInventoryLoom) { return InventoryType.LOOM; @@ -505,9 +506,9 @@ public InventoryType getType() { return InventoryType.GRINDSTONE; } else if (this instanceof CraftInventoryStonecutter) { return InventoryType.STONECUTTER; - } else if (this.inventory instanceof ComposterBlock.EmptyContainer || this.inventory instanceof ComposterBlock.InputContainer || this.inventory instanceof ComposterBlock.OutputContainer) { + } else if (inventory instanceof BlockComposter.ContainerEmpty || inventory instanceof BlockComposter.ContainerInput || inventory instanceof BlockComposter.ContainerOutput) { return InventoryType.COMPOSTER; - } else if (this.inventory instanceof JukeboxBlockEntity) { + } else if (inventory instanceof TileEntityJukeBox) { return InventoryType.JUKEBOX; } else { return InventoryType.CHEST; @@ -516,22 +517,22 @@ public InventoryType getType() { @Override public InventoryHolder getHolder() { - return this.inventory.getOwner(); + return inventory.getOwner(); } @Override public int getMaxStackSize() { - return this.inventory.getMaxStackSize(); + return inventory.getMaxStackSize(); } @Override public void setMaxStackSize(int size) { - this.inventory.setMaxStackSize(size); + inventory.setMaxStackSize(size); } @Override public int hashCode() { - return this.inventory.hashCode(); + return inventory.hashCode(); } @Override @@ -541,6 +542,6 @@ public boolean equals(final Object obj) { @Override public Location getLocation() { - return this.inventory.getLocation(); + return inventory.getLocation(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java index 4946da59..add8d95b 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java @@ -1,22 +1,22 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.AbstractHorseInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryAbstractHorse extends CraftInventory implements AbstractHorseInventory { - public CraftInventoryAbstractHorse(Container inventory) { + public CraftInventoryAbstractHorse(IInventory inventory) { super(inventory); } @Override public ItemStack getSaddle() { - return this.getItem(0); + return getItem(0); } @Override public void setSaddle(ItemStack stack) { - this.setItem(0, stack); + setItem(0, stack); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java index f481f8a1..5258224d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java @@ -2,8 +2,7 @@ import com.google.common.base.Preconditions; import java.util.function.Consumer; -import net.minecraft.world.Container; -import net.minecraft.world.inventory.AnvilMenu; +import net.minecraft.world.IInventory; import org.bukkit.Location; import org.bukkit.craftbukkit.inventory.view.CraftAnvilView; import org.bukkit.entity.HumanEntity; @@ -21,53 +20,53 @@ public class CraftInventoryAnvil extends CraftResultInventory implements AnvilIn private int repairCostAmount; private int maximumRepairCost; - public CraftInventoryAnvil(Location location, Container inventory, Container resultInventory) { + public CraftInventoryAnvil(Location location, IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); this.location = location; this.renameText = null; - this.repairCost = CraftInventoryAnvil.DEFAULT_REPAIR_COST; - this.repairCostAmount = CraftInventoryAnvil.DEFAULT_REPAIR_COST_AMOUNT; - this.maximumRepairCost = CraftInventoryAnvil.DEFAULT_MAXIMUM_REPAIR_COST; + this.repairCost = DEFAULT_REPAIR_COST; + this.repairCostAmount = DEFAULT_REPAIR_COST_AMOUNT; + this.maximumRepairCost = DEFAULT_MAXIMUM_REPAIR_COST; } @Override public Location getLocation() { - return this.location; + return location; } @Override public String getRenameText() { - this.syncWithArbitraryViewValue((cav) -> this.renameText = cav.getRenameText()); + syncWithArbitraryViewValue((cav) -> this.renameText = cav.getRenameText()); return this.renameText; } @Override public int getRepairCostAmount() { - this.syncWithArbitraryViewValue((cav) -> this.repairCostAmount = cav.getRepairItemCountCost()); + syncWithArbitraryViewValue((cav) -> this.repairCostAmount = cav.getRepairItemCountCost()); return this.repairCostAmount; } @Override public void setRepairCostAmount(int amount) { this.repairCostAmount = amount; - this.syncViews((cav) -> cav.setRepairItemCountCost(amount)); + syncViews((cav) -> cav.setRepairItemCountCost(amount)); } @Override public int getRepairCost() { - this.syncWithArbitraryViewValue((cav) -> this.repairCost = cav.getRepairCost()); + syncWithArbitraryViewValue((cav) -> this.repairCost = cav.getRepairCost()); return this.repairCost; } @Override public void setRepairCost(int i) { this.repairCost = i; - this.syncViews((cav) -> cav.setRepairCost(i)); + syncViews((cav) -> cav.setRepairCost(i)); } @Override public int getMaximumRepairCost() { - this.syncWithArbitraryViewValue((cav) -> this.maximumRepairCost = cav.getMaximumRepairCost()); + syncWithArbitraryViewValue((cav) -> this.maximumRepairCost = cav.getMaximumRepairCost()); return this.maximumRepairCost; } @@ -75,24 +74,24 @@ public int getMaximumRepairCost() { public void setMaximumRepairCost(int levels) { Preconditions.checkArgument(levels >= 0, "Maximum repair cost must be positive (or 0)"); this.maximumRepairCost = levels; - this.syncViews((cav) -> cav.setMaximumRepairCost(levels)); + syncViews((cav) -> cav.setMaximumRepairCost(levels)); } public boolean isRepairCostSet() { - return this.repairCost != CraftInventoryAnvil.DEFAULT_REPAIR_COST; + return this.repairCost != DEFAULT_REPAIR_COST; } public boolean isRepairCostAmountSet() { - return this.repairCostAmount != CraftInventoryAnvil.DEFAULT_REPAIR_COST_AMOUNT; + return this.repairCostAmount != DEFAULT_REPAIR_COST_AMOUNT; } public boolean isMaximumRepairCostSet() { - return this.maximumRepairCost != CraftInventoryAnvil.DEFAULT_MAXIMUM_REPAIR_COST; + return this.maximumRepairCost != DEFAULT_MAXIMUM_REPAIR_COST; } // used to lazily update and apply values from the view to the inventory private void syncViews(Consumer consumer) { - for (HumanEntity viewer : this.getViewers()) { + for (HumanEntity viewer : getViewers()) { if (viewer.getOpenInventory() instanceof CraftAnvilView cav) { consumer.accept(cav); } @@ -106,10 +105,10 @@ private void syncViews(Consumer consumer) { * not the inventory. */ private void syncWithArbitraryViewValue(Consumer consumer) { - if (this.getViewers().isEmpty()) { + if (getViewers().isEmpty()) { return; } - final HumanEntity entity = this.getViewers().get(0); + final HumanEntity entity = getViewers().get(0); if (entity != null && entity.getOpenInventory() instanceof CraftAnvilView cav) { consumer.accept(cav); } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java index 06f46292..7fa1184e 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java @@ -1,21 +1,21 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.BeaconInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryBeacon extends CraftInventory implements BeaconInventory { - public CraftInventoryBeacon(Container beacon) { + public CraftInventoryBeacon(IInventory beacon) { super(beacon); } @Override public void setItem(ItemStack item) { - this.setItem(0, item); + setItem(0, item); } @Override public ItemStack getItem() { - return this.getItem(0); + return getItem(0); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java index fa3a3022..6aaf363e 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java @@ -1,37 +1,37 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.block.BrewingStand; import org.bukkit.inventory.BrewerInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryBrewer extends CraftInventory implements BrewerInventory { - public CraftInventoryBrewer(Container inventory) { + public CraftInventoryBrewer(IInventory inventory) { super(inventory); } @Override public ItemStack getIngredient() { - return this.getItem(3); + return getItem(3); } @Override public void setIngredient(ItemStack ingredient) { - this.setItem(3, ingredient); + setItem(3, ingredient); } @Override public BrewingStand getHolder() { - return (BrewingStand) this.inventory.getOwner(); + return (BrewingStand) inventory.getOwner(); } @Override public ItemStack getFuel() { - return this.getItem(4); + return getItem(4); } @Override public void setFuel(ItemStack fuel) { - this.setItem(4, fuel); + setItem(4, fuel); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java index af455b3a..5829745e 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.CartographyInventory; public class CraftInventoryCartography extends CraftResultInventory implements CartographyInventory { - public CraftInventoryCartography(Container inventory, Container resultInventory) { + public CraftInventoryCartography(IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryChiseledBookshelf.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryChiseledBookshelf.java index 8b7ec544..f775a4d6 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryChiseledBookshelf.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryChiseledBookshelf.java @@ -25,6 +25,6 @@ public void setItem(int index, ItemStack item) { @Override public ChiseledBookshelf getHolder() { - return (ChiseledBookshelf) this.inventory.getOwner(); + return (ChiseledBookshelf) inventory.getOwner(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafter.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafter.java index b177ab58..d0440cd8 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafter.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafter.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.CrafterInventory; public class CraftInventoryCrafter extends CraftResultInventory implements CrafterInventory { - public CraftInventoryCrafter(Container inventory, Container resultInventory) { + public CraftInventoryCrafter(IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java index 9e6feea4..48e80f6d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java @@ -3,51 +3,51 @@ import com.google.common.base.Preconditions; import java.util.Arrays; import java.util.List; -import net.minecraft.world.Container; -import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.IInventory; +import net.minecraft.world.inventory.InventoryCrafting; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.inventory.CraftingInventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; public class CraftInventoryCrafting extends CraftInventory implements CraftingInventory { - private final Container resultInventory; + private final IInventory resultInventory; - public CraftInventoryCrafting(CraftingContainer inventory, Container resultInventory) { + public CraftInventoryCrafting(InventoryCrafting inventory, IInventory resultInventory) { super(inventory); this.resultInventory = resultInventory; } - public Container getResultInventory() { - return this.resultInventory; + public IInventory getResultInventory() { + return resultInventory; } - public CraftingContainer getMatrixInventory() { - return (CraftingContainer) this.inventory; + public InventoryCrafting getMatrixInventory() { + return (InventoryCrafting) inventory; } @Override public int getSize() { - return this.getResultInventory().getContainerSize() + this.getMatrixInventory().getContainerSize(); + return getResultInventory().getContainerSize() + getMatrixInventory().getContainerSize(); } @Override public void setContents(ItemStack[] items) { - Preconditions.checkArgument(items.length <= this.getSize(), "Invalid inventory size (%s); expected %s or less", items.length, this.getSize()); - this.setContents(items[0], Arrays.copyOfRange(items, 1, items.length)); + Preconditions.checkArgument(items.length <= getSize(), "Invalid inventory size (%s); expected %s or less", items.length, getSize()); + setContents(items[0], Arrays.copyOfRange(items, 1, items.length)); } @Override public ItemStack[] getContents() { - ItemStack[] items = new ItemStack[this.getSize()]; - List mcResultItems = this.getResultInventory().getContents(); + ItemStack[] items = new ItemStack[getSize()]; + List mcResultItems = getResultInventory().getContents(); int i = 0; for (i = 0; i < mcResultItems.size(); i++) { items[i] = CraftItemStack.asCraftMirror(mcResultItems.get(i)); } - List mcItems = this.getMatrixInventory().getContents(); + List mcItems = getMatrixInventory().getContents(); for (int j = 0; j < mcItems.size(); j++) { items[i + j] = CraftItemStack.asCraftMirror(mcItems.get(j)); @@ -57,66 +57,66 @@ public ItemStack[] getContents() { } public void setContents(ItemStack result, ItemStack[] contents) { - this.setResult(result); - this.setMatrix(contents); + setResult(result); + setMatrix(contents); } @Override public CraftItemStack getItem(int index) { - if (index < this.getResultInventory().getContainerSize()) { - net.minecraft.world.item.ItemStack item = this.getResultInventory().getItem(index); + if (index < getResultInventory().getContainerSize()) { + net.minecraft.world.item.ItemStack item = getResultInventory().getItem(index); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } else { - net.minecraft.world.item.ItemStack item = this.getMatrixInventory().getItem(index - this.getResultInventory().getContainerSize()); + net.minecraft.world.item.ItemStack item = getMatrixInventory().getItem(index - getResultInventory().getContainerSize()); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } } @Override public void setItem(int index, ItemStack item) { - if (index < this.getResultInventory().getContainerSize()) { - this.getResultInventory().setItem(index, CraftItemStack.asNMSCopy(item)); + if (index < getResultInventory().getContainerSize()) { + getResultInventory().setItem(index, CraftItemStack.asNMSCopy(item)); } else { - this.getMatrixInventory().setItem((index - this.getResultInventory().getContainerSize()), CraftItemStack.asNMSCopy(item)); + getMatrixInventory().setItem((index - getResultInventory().getContainerSize()), CraftItemStack.asNMSCopy(item)); } } @Override public ItemStack[] getMatrix() { - List matrix = this.getMatrixInventory().getContents(); + List matrix = getMatrixInventory().getContents(); - return this.asCraftMirror(matrix); + return asCraftMirror(matrix); } @Override public ItemStack getResult() { - net.minecraft.world.item.ItemStack item = this.getResultInventory().getItem(0); + net.minecraft.world.item.ItemStack item = getResultInventory().getItem(0); if (!item.isEmpty()) return CraftItemStack.asCraftMirror(item); return null; } @Override public void setMatrix(ItemStack[] contents) { - Preconditions.checkArgument(contents.length <= this.getMatrixInventory().getContainerSize(), "Invalid inventory size (%s); expected %s or less", contents.length, this.getMatrixInventory().getContainerSize()); + Preconditions.checkArgument(contents.length <= getMatrixInventory().getContainerSize(), "Invalid inventory size (%s); expected %s or less", contents.length, getMatrixInventory().getContainerSize()); - for (int i = 0; i < this.getMatrixInventory().getContainerSize(); i++) { + for (int i = 0; i < getMatrixInventory().getContainerSize(); i++) { if (i < contents.length) { - this.getMatrixInventory().setItem(i, CraftItemStack.asNMSCopy(contents[i])); + getMatrixInventory().setItem(i, CraftItemStack.asNMSCopy(contents[i])); } else { - this.getMatrixInventory().setItem(i, net.minecraft.world.item.ItemStack.EMPTY); + getMatrixInventory().setItem(i, net.minecraft.world.item.ItemStack.EMPTY); } } } @Override public void setResult(ItemStack item) { - List contents = this.getResultInventory().getContents(); + List contents = getResultInventory().getContents(); contents.set(0, CraftItemStack.asNMSCopy(item)); } @Override public Recipe getRecipe() { - RecipeHolder recipe = this.getMatrixInventory().getCurrentRecipe(); + RecipeHolder recipe = getMatrixInventory().getCurrentRecipe(); return recipe == null ? null : recipe.toBukkitRecipe(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java index fb853733..38e2eae5 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java @@ -5,8 +5,8 @@ import java.util.Iterator; import java.util.List; import net.minecraft.core.NonNullList; -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.IInventory; +import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.item.ItemStack; import org.bukkit.Location; import org.bukkit.craftbukkit.entity.CraftHumanEntity; @@ -31,11 +31,7 @@ public CraftInventoryCustom(InventoryHolder owner, int size, String title) { super(new MinecraftInventory(owner, size, title)); } - public CraftInventoryCustom(InventoryHolder owner, NonNullList items) { - super(new MinecraftInventory(owner, items)); - } - - static class MinecraftInventory implements Container { + static class MinecraftInventory implements IInventory { private final NonNullList items; private int maxStack = MAX_STACK; private final List viewers; @@ -66,47 +62,39 @@ public MinecraftInventory(InventoryHolder owner, int size, String title) { this.type = InventoryType.CHEST; } - public MinecraftInventory(InventoryHolder owner, NonNullList items) { - this.items = items; - this.title = "Chest"; - this.viewers = new ArrayList<>(); - this.owner = owner; - this.type = InventoryType.CHEST; - } - @Override public int getContainerSize() { - return this.items.size(); + return items.size(); } @Override - public ItemStack getItem(int slot) { - return this.items.get(slot); + public ItemStack getItem(int i) { + return items.get(i); } @Override - public ItemStack removeItem(int slot, int amount) { - ItemStack stack = this.getItem(slot); + public ItemStack removeItem(int i, int j) { + ItemStack stack = this.getItem(i); ItemStack result; if (stack == ItemStack.EMPTY) return stack; - if (stack.getCount() <= amount) { - this.setItem(slot, ItemStack.EMPTY); + if (stack.getCount() <= j) { + this.setItem(i, ItemStack.EMPTY); result = stack; } else { - result = CraftItemStack.copyNMSStack(stack, amount); - stack.shrink(amount); + result = CraftItemStack.copyNMSStack(stack, j); + stack.shrink(j); } this.setChanged(); return result; } @Override - public ItemStack removeItemNoUpdate(int slot) { - ItemStack stack = this.getItem(slot); + public ItemStack removeItemNoUpdate(int i) { + ItemStack stack = this.getItem(i); ItemStack result; if (stack == ItemStack.EMPTY) return stack; if (stack.getCount() <= 1) { - this.setItem(slot, null); + this.setItem(i, null); result = stack; } else { result = CraftItemStack.copyNMSStack(stack, 1); @@ -116,78 +104,78 @@ public ItemStack removeItemNoUpdate(int slot) { } @Override - public void setItem(int slot, ItemStack stack) { - this.items.set(slot, stack); - if (stack != ItemStack.EMPTY && this.getMaxStackSize() > 0 && stack.getCount() > this.getMaxStackSize()) { - stack.setCount(this.getMaxStackSize()); + public void setItem(int i, ItemStack itemstack) { + items.set(i, itemstack); + if (itemstack != ItemStack.EMPTY && this.getMaxStackSize() > 0 && itemstack.getCount() > this.getMaxStackSize()) { + itemstack.setCount(this.getMaxStackSize()); } } @Override public int getMaxStackSize() { - return this.maxStack; + return maxStack; } @Override public void setMaxStackSize(int size) { - this.maxStack = size; + maxStack = size; } @Override public void setChanged() {} @Override - public boolean stillValid(Player player) { + public boolean stillValid(EntityHuman entityhuman) { return true; } @Override public List getContents() { - return this.items; + return items; } @Override public void onOpen(CraftHumanEntity who) { - this.viewers.add(who); + viewers.add(who); } @Override public void onClose(CraftHumanEntity who) { - this.viewers.remove(who); + viewers.remove(who); } @Override public List getViewers() { - return this.viewers; + return viewers; } public InventoryType getType() { - return this.type; + return type; } @Override public InventoryHolder getOwner() { - return this.owner; + return owner; } @Override - public boolean canPlaceItem(int slot, ItemStack stack) { + public boolean canPlaceItem(int i, ItemStack itemstack) { return true; } @Override - public void startOpen(Player player) { + public void startOpen(EntityHuman entityHuman) { } @Override - public void stopOpen(Player player) { + public void stopOpen(EntityHuman entityHuman) { } @Override public void clearContent() { - this.items.clear(); + items.clear(); } @Override @@ -196,7 +184,7 @@ public Location getLocation() { } public String getTitle() { - return this.title; + return title; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDecoratedPot.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDecoratedPot.java index 4f224251..d9c70038 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDecoratedPot.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDecoratedPot.java @@ -1,28 +1,28 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.block.DecoratedPot; import org.bukkit.inventory.DecoratedPotInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryDecoratedPot extends CraftInventory implements DecoratedPotInventory { - public CraftInventoryDecoratedPot(Container inventory) { + public CraftInventoryDecoratedPot(IInventory inventory) { super(inventory); } @Override public void setItem(ItemStack item) { - this.setItem(0, item); + setItem(0, item); } @Override public ItemStack getItem() { - return this.getItem(0); + return getItem(0); } @Override public DecoratedPot getHolder() { - return (DecoratedPot) this.inventory.getOwner(); + return (DecoratedPot) inventory.getOwner(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java index c00c787a..4caa7c0f 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java @@ -1,9 +1,9 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Preconditions; -import net.minecraft.world.CompoundContainer; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.ITileInventory; +import net.minecraft.world.InventoryLargeChest; +import net.minecraft.world.level.block.BlockChest; import org.bukkit.Location; import org.bukkit.block.DoubleChest; import org.bukkit.inventory.DoubleChestInventory; @@ -11,50 +11,50 @@ import org.bukkit.inventory.ItemStack; public class CraftInventoryDoubleChest extends CraftInventory implements DoubleChestInventory { - public MenuProvider tile; + public ITileInventory tile; private final CraftInventory left; private final CraftInventory right; - public CraftInventoryDoubleChest(ChestBlock.DoubleInventory block) { + public CraftInventoryDoubleChest(BlockChest.DoubleInventory block) { super(block.inventorylargechest); this.tile = block; this.left = new CraftInventory(block.inventorylargechest.container1); this.right = new CraftInventory(block.inventorylargechest.container2); } - public CraftInventoryDoubleChest(CompoundContainer largeChest) { + public CraftInventoryDoubleChest(InventoryLargeChest largeChest) { super(largeChest); - if (largeChest.container1 instanceof CompoundContainer) { - this.left = new CraftInventoryDoubleChest((CompoundContainer) largeChest.container1); + if (largeChest.container1 instanceof InventoryLargeChest) { + left = new CraftInventoryDoubleChest((InventoryLargeChest) largeChest.container1); } else { - this.left = new CraftInventory(largeChest.container1); + left = new CraftInventory(largeChest.container1); } - if (largeChest.container2 instanceof CompoundContainer) { - this.right = new CraftInventoryDoubleChest((CompoundContainer) largeChest.container2); + if (largeChest.container2 instanceof InventoryLargeChest) { + right = new CraftInventoryDoubleChest((InventoryLargeChest) largeChest.container2); } else { - this.right = new CraftInventory(largeChest.container2); + right = new CraftInventory(largeChest.container2); } } @Override public Inventory getLeftSide() { - return this.left; + return left; } @Override public Inventory getRightSide() { - return this.right; + return right; } @Override public void setContents(ItemStack[] items) { - Preconditions.checkArgument(items.length <= this.getInventory().getContainerSize(), "Invalid inventory size (%s); expected %s or less", items.length, this.getInventory().getContainerSize()); - ItemStack[] leftItems = new ItemStack[this.left.getSize()], rightItems = new ItemStack[this.right.getSize()]; - System.arraycopy(items, 0, leftItems, 0, Math.min(this.left.getSize(), items.length)); - this.left.setContents(leftItems); - if (items.length >= this.left.getSize()) { - System.arraycopy(items, this.left.getSize(), rightItems, 0, Math.min(this.right.getSize(), items.length - this.left.getSize())); - this.right.setContents(rightItems); + Preconditions.checkArgument(items.length <= getInventory().getContainerSize(), "Invalid inventory size (%s); expected %s or less", items.length, getInventory().getContainerSize()); + ItemStack[] leftItems = new ItemStack[left.getSize()], rightItems = new ItemStack[right.getSize()]; + System.arraycopy(items, 0, leftItems, 0, Math.min(left.getSize(), items.length)); + left.setContents(leftItems); + if (items.length >= left.getSize()) { + System.arraycopy(items, left.getSize(), rightItems, 0, Math.min(right.getSize(), items.length - left.getSize())); + right.setContents(rightItems); } } @@ -65,6 +65,6 @@ public DoubleChest getHolder() { @Override public Location getLocation() { - return this.getLeftSide().getLocation().add(this.getRightSide().getLocation()).multiply(0.5); + return getLeftSide().getLocation().add(getRightSide().getLocation()).multiply(0.5); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java index 357aa749..34f6d058 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java @@ -1,31 +1,31 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.EnchantingInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryEnchanting extends CraftInventory implements EnchantingInventory { - public CraftInventoryEnchanting(Container inventory) { + public CraftInventoryEnchanting(IInventory inventory) { super(inventory); } @Override public void setItem(ItemStack item) { - this.setItem(0, item); + setItem(0, item); } @Override public ItemStack getItem() { - return this.getItem(0); + return getItem(0); } @Override public void setSecondary(ItemStack item) { - this.setItem(1, item); + setItem(1, item); } @Override public ItemStack getSecondary() { - return this.getItem(1); + return getItem(1); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java index 29a8cd76..09779f99 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java @@ -1,47 +1,47 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityFurnace; import org.bukkit.block.Furnace; import org.bukkit.inventory.FurnaceInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryFurnace extends CraftInventory implements FurnaceInventory { - public CraftInventoryFurnace(AbstractFurnaceBlockEntity inventory) { + public CraftInventoryFurnace(TileEntityFurnace inventory) { super(inventory); } @Override public ItemStack getResult() { - return this.getItem(2); + return getItem(2); } @Override public ItemStack getFuel() { - return this.getItem(1); + return getItem(1); } @Override public ItemStack getSmelting() { - return this.getItem(0); + return getItem(0); } @Override public void setFuel(ItemStack stack) { - this.setItem(1, stack); + setItem(1, stack); } @Override public void setResult(ItemStack stack) { - this.setItem(2, stack); + setItem(2, stack); } @Override public void setSmelting(ItemStack stack) { - this.setItem(0, stack); + setItem(0, stack); } @Override public Furnace getHolder() { - return (Furnace) this.inventory.getOwner(); + return (Furnace) inventory.getOwner(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java index 9adf5a44..6a128d63 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.GrindstoneInventory; public class CraftInventoryGrindstone extends CraftResultInventory implements GrindstoneInventory { - public CraftInventoryGrindstone(Container inventory, Container resultInventory) { + public CraftInventoryGrindstone(IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java index 6aaab1dc..478ac8cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.HorseInventory; import org.bukkit.inventory.ItemStack; public class CraftInventoryHorse extends CraftInventoryAbstractHorse implements HorseInventory { - private final Container bodyArmorInventory; + private final IInventory bodyArmorInventory; - public CraftInventoryHorse(Container inventory, Container bodyArmorInventory) { + public CraftInventoryHorse(IInventory inventory, IInventory bodyArmorInventory) { super(inventory); this.bodyArmorInventory = bodyArmorInventory; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryJukebox.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryJukebox.java index 3bdbd0f4..a864a17a 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryJukebox.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryJukebox.java @@ -1,32 +1,32 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.block.Jukebox; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.JukeboxInventory; public class CraftInventoryJukebox extends CraftInventory implements JukeboxInventory { - public CraftInventoryJukebox(Container inventory) { + public CraftInventoryJukebox(IInventory inventory) { super(inventory); } @Override public void setRecord(ItemStack item) { if (item == null) { - this.inventory.removeItem(0, 0); // Second parameter is unused in TileEntityJukebox + inventory.removeItem(0, 0); // Second parameter is unused in TileEntityJukebox } else { - this.setItem(0, item); + setItem(0, item); } } @Override public ItemStack getRecord() { - return this.getItem(0); + return getItem(0); } @Override public Jukebox getHolder() { - return (Jukebox) this.inventory.getOwner(); + return (Jukebox) inventory.getOwner(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java index 3605c957..1dc832ab 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java @@ -1,24 +1,24 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.level.block.entity.LecternBlockEntity; +import net.minecraft.world.IInventory; +import net.minecraft.world.ITileInventory; +import net.minecraft.world.level.block.entity.TileEntityLectern; import org.bukkit.block.Lectern; import org.bukkit.inventory.LecternInventory; public class CraftInventoryLectern extends CraftInventory implements LecternInventory { - public MenuProvider tile; + public ITileInventory tile; - public CraftInventoryLectern(Container inventory) { + public CraftInventoryLectern(IInventory inventory) { super(inventory); - if (inventory instanceof LecternBlockEntity.LecternInventory) { - this.tile = ((LecternBlockEntity.LecternInventory) inventory).getLectern(); + if (inventory instanceof TileEntityLectern.LecternInventory) { + this.tile = ((TileEntityLectern.LecternInventory) inventory).getLectern(); } } @Override public Lectern getHolder() { - return (Lectern) this.inventory.getOwner(); + return (Lectern) inventory.getOwner(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java index dcd227d3..729b3346 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.LlamaInventory; public class CraftInventoryLlama extends CraftInventoryAbstractHorse implements LlamaInventory { - private final Container bodyArmorInventory; + private final IInventory bodyArmorInventory; - public CraftInventoryLlama(Container inventory, Container bodyArmorInventory) { + public CraftInventoryLlama(IInventory inventory, IInventory bodyArmorInventory) { super(inventory); this.bodyArmorInventory = bodyArmorInventory; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java index b9c8790d..2c6ab7d5 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.LoomInventory; public class CraftInventoryLoom extends CraftResultInventory implements LoomInventory { - public CraftInventoryLoom(Container inventory, Container resultInventory) { + public CraftInventoryLoom(IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java index 9f2c4352..979ae513 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java @@ -1,37 +1,38 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.inventory.MerchantContainer; +import net.minecraft.world.inventory.InventoryMerchant; +import net.minecraft.world.item.trading.IMerchant; import org.bukkit.inventory.Merchant; import org.bukkit.inventory.MerchantInventory; import org.bukkit.inventory.MerchantRecipe; public class CraftInventoryMerchant extends CraftInventory implements MerchantInventory { - private final net.minecraft.world.item.trading.Merchant merchant; + private final IMerchant merchant; - public CraftInventoryMerchant(net.minecraft.world.item.trading.Merchant merchant, MerchantContainer inventory) { + public CraftInventoryMerchant(IMerchant merchant, InventoryMerchant inventory) { super(inventory); this.merchant = merchant; } @Override public int getSelectedRecipeIndex() { - return this.getInventory().selectionHint; + return getInventory().selectionHint; } @Override public MerchantRecipe getSelectedRecipe() { - net.minecraft.world.item.trading.MerchantOffer nmsRecipe = this.getInventory().getActiveOffer(); + net.minecraft.world.item.trading.MerchantRecipe nmsRecipe = getInventory().getActiveOffer(); return (nmsRecipe == null) ? null : nmsRecipe.asBukkit(); } @Override - public MerchantContainer getInventory() { - return (MerchantContainer) this.inventory; + public InventoryMerchant getInventory() { + return (InventoryMerchant) inventory; } @Override public Merchant getMerchant() { - return this.merchant.getCraftMerchant(); + return merchant.getCraftMerchant(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java index 23abd543..88327c35 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java @@ -1,10 +1,10 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Preconditions; -import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; -import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Inventory; +import net.minecraft.network.protocol.game.PacketPlayOutHeldItemSlot; +import net.minecraft.network.protocol.game.PacketPlayOutSetSlot; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.entity.player.PlayerInventory; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.EntityEquipment; @@ -12,67 +12,67 @@ import org.bukkit.inventory.ItemStack; public class CraftInventoryPlayer extends CraftInventory implements org.bukkit.inventory.PlayerInventory, EntityEquipment { - public CraftInventoryPlayer(net.minecraft.world.entity.player.Inventory inventory) { + public CraftInventoryPlayer(net.minecraft.world.entity.player.PlayerInventory inventory) { super(inventory); } @Override - public Inventory getInventory() { - return (Inventory) this.inventory; + public PlayerInventory getInventory() { + return (PlayerInventory) inventory; } @Override public ItemStack[] getStorageContents() { - return this.asCraftMirror(this.getInventory().items); + return asCraftMirror(getInventory().items); } @Override public ItemStack getItemInMainHand() { - return CraftItemStack.asCraftMirror(this.getInventory().getSelected()); + return CraftItemStack.asCraftMirror(getInventory().getSelected()); } @Override public void setItemInMainHand(ItemStack item) { - this.setItem(this.getHeldItemSlot(), item); + setItem(getHeldItemSlot(), item); } @Override public void setItemInMainHand(ItemStack item, boolean silent) { - this.setItemInMainHand(item); // Silence doesn't apply to players + setItemInMainHand(item); // Silence doesn't apply to players } @Override public ItemStack getItemInOffHand() { - return CraftItemStack.asCraftMirror(this.getInventory().offhand.get(0)); + return CraftItemStack.asCraftMirror(getInventory().offhand.get(0)); } @Override public void setItemInOffHand(ItemStack item) { - ItemStack[] extra = this.getExtraContents(); + ItemStack[] extra = getExtraContents(); extra[0] = item; - this.setExtraContents(extra); + setExtraContents(extra); } @Override public void setItemInOffHand(ItemStack item, boolean silent) { - this.setItemInOffHand(item); // Silence doesn't apply to players + setItemInOffHand(item); // Silence doesn't apply to players } @Override public ItemStack getItemInHand() { - return this.getItemInMainHand(); + return getItemInMainHand(); } @Override public void setItemInHand(ItemStack stack) { - this.setItemInMainHand(stack); + setItemInMainHand(stack); } @Override public void setItem(int index, ItemStack item) { super.setItem(index, item); if (this.getHolder() == null) return; - ServerPlayer player = ((CraftPlayer) this.getHolder()).getHandle(); + EntityPlayer player = ((CraftPlayer) this.getHolder()).getHandle(); if (player.connection == null) return; // PacketPlayOutSetSlot places the items differently than setItem() // @@ -102,14 +102,14 @@ public void setItem(int index, ItemStack item) { // to reverse the order of the index from 8. That means we need 0 to correspond to 8, 1 to correspond to 7, // 2 to correspond to 6, and 3 to correspond to 5. We do this simply by taking the result of (index - 36) and // subtracting that value from 8. - if (index < Inventory.getSelectionSize()) { + if (index < PlayerInventory.getSelectionSize()) { index += 36; } else if (index > 39) { index += 5; // Off hand } else if (index > 35) { index = 8 - (index - 36); } - player.connection.send(new ClientboundContainerSetSlotPacket(player.inventoryMenu.containerId, player.inventoryMenu.incrementStateId(), index, CraftItemStack.asNMSCopy(item))); + player.connection.send(new PacketPlayOutSetSlot(player.inventoryMenu.containerId, player.inventoryMenu.incrementStateId(), index, CraftItemStack.asNMSCopy(item))); } @Override @@ -136,13 +136,13 @@ public void setItem(EquipmentSlot slot, ItemStack item) { this.setHelmet(item); break; default: - throw new IllegalArgumentException("Not implemented. This is a bug"); + throw new IllegalArgumentException("Could not set slot " + slot + " - not a valid slot for PlayerInventory"); } } @Override public void setItem(EquipmentSlot slot, ItemStack item, boolean silent) { - this.setItem(slot, item); // Silence doesn't apply to players + setItem(slot, item); // Silence doesn't apply to players } @Override @@ -151,97 +151,97 @@ public ItemStack getItem(EquipmentSlot slot) { switch (slot) { case HAND: - return this.getItemInMainHand(); + return getItemInMainHand(); case OFF_HAND: - return this.getItemInOffHand(); + return getItemInOffHand(); case FEET: - return this.getBoots(); + return getBoots(); case LEGS: - return this.getLeggings(); + return getLeggings(); case CHEST: - return this.getChestplate(); + return getChestplate(); case HEAD: - return this.getHelmet(); + return getHelmet(); default: - throw new IllegalArgumentException("Not implemented. This is a bug"); + throw new IllegalArgumentException("Could not get slot " + slot + " - not a valid slot for PlayerInventory"); } } @Override public int getHeldItemSlot() { - return this.getInventory().selected; + return getInventory().selected; } @Override public void setHeldItemSlot(int slot) { - Preconditions.checkArgument(slot >= 0 && slot < Inventory.getSelectionSize(), "Slot (%s) is not between 0 and %s inclusive", slot, Inventory.getSelectionSize() - 1); + Preconditions.checkArgument(slot >= 0 && slot < PlayerInventory.getSelectionSize(), "Slot (%s) is not between 0 and %s inclusive", slot, PlayerInventory.getSelectionSize() - 1); this.getInventory().selected = slot; - ((CraftPlayer) this.getHolder()).getHandle().connection.send(new ClientboundSetCarriedItemPacket(slot)); + ((CraftPlayer) this.getHolder()).getHandle().connection.send(new PacketPlayOutHeldItemSlot(slot)); } @Override public ItemStack getHelmet() { - return this.getItem(this.getSize() - 2); + return getItem(getSize() - 2); } @Override public ItemStack getChestplate() { - return this.getItem(this.getSize() - 3); + return getItem(getSize() - 3); } @Override public ItemStack getLeggings() { - return this.getItem(this.getSize() - 4); + return getItem(getSize() - 4); } @Override public ItemStack getBoots() { - return this.getItem(this.getSize() - 5); + return getItem(getSize() - 5); } @Override public void setHelmet(ItemStack helmet) { - this.setItem(this.getSize() - 2, helmet); + setItem(getSize() - 2, helmet); } @Override public void setHelmet(ItemStack helmet, boolean silent) { - this.setHelmet(helmet); // Silence doesn't apply to players + setHelmet(helmet); // Silence doesn't apply to players } @Override public void setChestplate(ItemStack chestplate) { - this.setItem(this.getSize() - 3, chestplate); + setItem(getSize() - 3, chestplate); } @Override public void setChestplate(ItemStack chestplate, boolean silent) { - this.setChestplate(chestplate); // Silence doesn't apply to players + setChestplate(chestplate); // Silence doesn't apply to players } @Override public void setLeggings(ItemStack leggings) { - this.setItem(this.getSize() - 4, leggings); + setItem(getSize() - 4, leggings); } @Override public void setLeggings(ItemStack leggings, boolean silent) { - this.setLeggings(leggings); // Silence doesn't apply to players + setLeggings(leggings); // Silence doesn't apply to players } @Override public void setBoots(ItemStack boots) { - this.setItem(this.getSize() - 5, boots); + setItem(getSize() - 5, boots); } @Override public void setBoots(ItemStack boots, boolean silent) { - this.setBoots(boots); // Silence doesn't apply to players + setBoots(boots); // Silence doesn't apply to players } @Override public ItemStack[] getArmorContents() { - return this.asCraftMirror(this.getInventory().armor); + return asCraftMirror(getInventory().armor); } private void setSlots(ItemStack[] items, int baseSlot, int length) { @@ -252,46 +252,46 @@ private void setSlots(ItemStack[] items, int baseSlot, int length) { for (int i = 0; i < length; i++) { if (i >= items.length) { - this.setItem(baseSlot + i, null); + setItem(baseSlot + i, null); } else { - this.setItem(baseSlot + i, items[i]); + setItem(baseSlot + i, items[i]); } } } @Override public void setStorageContents(ItemStack[] items) throws IllegalArgumentException { - this.setSlots(items, 0, this.getInventory().items.size()); + setSlots(items, 0, getInventory().items.size()); } @Override public void setArmorContents(ItemStack[] items) { - this.setSlots(items, this.getInventory().items.size(), this.getInventory().armor.size()); + setSlots(items, getInventory().items.size(), getInventory().armor.size()); } @Override public ItemStack[] getExtraContents() { - return this.asCraftMirror(this.getInventory().offhand); + return asCraftMirror(getInventory().offhand); } @Override public void setExtraContents(ItemStack[] items) { - this.setSlots(items, this.getInventory().items.size() + this.getInventory().armor.size(), this.getInventory().offhand.size()); + setSlots(items, getInventory().items.size() + getInventory().armor.size(), getInventory().offhand.size()); } @Override public HumanEntity getHolder() { - return (HumanEntity) this.inventory.getOwner(); + return (HumanEntity) inventory.getOwner(); } @Override public float getItemInHandDropChance() { - return this.getItemInMainHandDropChance(); + return getItemInMainHandDropChance(); } @Override public void setItemInHandDropChance(float chance) { - this.setItemInMainHandDropChance(chance); + setItemInMainHandDropChance(chance); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventorySmithing.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventorySmithing.java index 42c00a9e..3259b09d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventorySmithing.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventorySmithing.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; -import net.minecraft.world.inventory.ResultContainer; +import net.minecraft.world.IInventory; +import net.minecraft.world.inventory.InventoryCraftResult; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.Location; import org.bukkit.inventory.ItemStack; @@ -12,34 +12,34 @@ public class CraftInventorySmithing extends CraftResultInventory implements Smit private final Location location; - public CraftInventorySmithing(Location location, Container inventory, ResultContainer resultInventory) { + public CraftInventorySmithing(Location location, IInventory inventory, InventoryCraftResult resultInventory) { super(inventory, resultInventory); this.location = location; } @Override - public ResultContainer getResultInventory() { - return (ResultContainer) super.getResultInventory(); + public InventoryCraftResult getResultInventory() { + return (InventoryCraftResult) super.getResultInventory(); } @Override public Location getLocation() { - return this.location; + return location; } @Override public ItemStack getResult() { - return this.getItem(3); + return getItem(3); } @Override public void setResult(ItemStack item) { - this.setItem(3, item); + setItem(3, item); } @Override public Recipe getRecipe() { - RecipeHolder recipe = this.getResultInventory().getRecipeUsed(); + RecipeHolder recipe = getResultInventory().getRecipeUsed(); return (recipe == null) ? null : recipe.toBukkitRecipe(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java index d0a2f4da..016aa57b 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.StonecutterInventory; public class CraftInventoryStonecutter extends CraftResultInventory implements StonecutterInventory { - public CraftInventoryStonecutter(Container inventory, Container resultInventory) { + public CraftInventoryStonecutter(IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java index 07d406de..b3bab079 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java @@ -1,10 +1,10 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Preconditions; -import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; +import net.minecraft.network.protocol.game.PacketPlayOutOpenWindow; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.Containers; import org.bukkit.GameMode; import org.bukkit.craftbukkit.entity.CraftHumanEntity; import org.bukkit.craftbukkit.util.CraftChatMessage; @@ -15,41 +15,41 @@ import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; -public class CraftInventoryView extends CraftAbstractInventoryView { +public class CraftInventoryView extends CraftAbstractInventoryView { protected final T container; private final CraftHumanEntity player; - private final CraftInventory viewing; + private final I viewing; private final String originalTitle; private String title; - public CraftInventoryView(HumanEntity player, Inventory viewing, T container) { + public CraftInventoryView(HumanEntity player, I viewing, T container) { // TODO: Should we make sure it really IS a CraftHumanEntity first? And a CraftInventory? this.player = (CraftHumanEntity) player; - this.viewing = (CraftInventory) viewing; + this.viewing = viewing; this.container = container; this.originalTitle = CraftChatMessage.fromComponent(container.getTitle()); - this.title = this.originalTitle; + this.title = originalTitle; } @Override - public Inventory getTopInventory() { - return this.viewing; + public I getTopInventory() { + return viewing; } @Override public Inventory getBottomInventory() { - return this.player.getInventory(); + return player.getInventory(); } @Override public HumanEntity getPlayer() { - return this.player; + return player; } @Override public InventoryType getType() { - InventoryType type = this.viewing.getType(); - if (type == InventoryType.CRAFTING && this.player.getGameMode() == GameMode.CREATIVE) { + InventoryType type = viewing.getType(); + if (type == InventoryType.CRAFTING && player.getGameMode() == GameMode.CREATIVE) { return InventoryType.CREATIVE; } return type; @@ -59,9 +59,9 @@ public InventoryType getType() { public void setItem(int slot, ItemStack item) { net.minecraft.world.item.ItemStack stack = CraftItemStack.asNMSCopy(item); if (slot >= 0) { - this.container.getSlot(slot).set(stack); + container.getSlot(slot).set(stack); } else { - this.player.getHandle().drop(stack, false); + player.getHandle().drop(stack, false); } } @@ -70,31 +70,31 @@ public ItemStack getItem(int slot) { if (slot < 0) { return null; } - return CraftItemStack.asCraftMirror(this.container.getSlot(slot).getItem()); + return CraftItemStack.asCraftMirror(container.getSlot(slot).getItem()); } @Override public String getTitle() { - return this.title; + return title; } @Override public String getOriginalTitle() { - return this.originalTitle; + return originalTitle; } @Override public void setTitle(String title) { - CraftInventoryView.sendInventoryTitleChange(this, title); + sendInventoryTitleChange(this, title); this.title = title; } public boolean isInTop(int rawSlot) { - return rawSlot < this.viewing.getSize(); + return rawSlot < viewing.getSize(); } - public AbstractContainerMenu getHandle() { - return this.container; + public Container getHandle() { + return container; } public static void sendInventoryTitleChange(InventoryView view, String title) { @@ -103,10 +103,10 @@ public static void sendInventoryTitleChange(InventoryView view, String title) { Preconditions.checkArgument(view.getPlayer() instanceof Player, "NPCs are not currently supported for this function"); Preconditions.checkArgument(view.getTopInventory().getType().isCreatable(), "Only creatable inventories can have their title changed"); - final ServerPlayer entityPlayer = (ServerPlayer) ((CraftHumanEntity) view.getPlayer()).getHandle(); + final EntityPlayer entityPlayer = (EntityPlayer) ((CraftHumanEntity) view.getPlayer()).getHandle(); final int containerId = entityPlayer.containerMenu.containerId; - final MenuType windowType = CraftContainer.getNotchInventoryType(view.getTopInventory()); - entityPlayer.connection.send(new ClientboundOpenScreenPacket(containerId, windowType, CraftChatMessage.fromString(title)[0])); + final Containers windowType = CraftContainer.getNotchInventoryType(view.getTopInventory()); + entityPlayer.connection.send(new PacketPlayOutOpenWindow(containerId, windowType, CraftChatMessage.fromString(title)[0])); ((Player) view.getPlayer()).updateInventory(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemCraftResult.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemCraftResult.java index 79a807e3..44a919a4 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemCraftResult.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemCraftResult.java @@ -18,27 +18,27 @@ public CraftItemCraftResult(ItemStack result) { this.resultMatrix = new ItemStack[9]; this.overflowItems = new ArrayList<>(); - for (int i = 0; i < this.resultMatrix.length; i++) { - this.resultMatrix[i] = new ItemStack(Material.AIR); + for (int i = 0; i < resultMatrix.length; i++) { + resultMatrix[i] = new ItemStack(Material.AIR); } } @Override public ItemStack getResult() { - return this.result; + return result; } @Override public ItemStack[] getResultingMatrix() { - return this.resultMatrix; + return resultMatrix; } @Override public List getOverflowItems() { - return this.overflowItems; + return overflowItems; } public void setResultMatrix(int i, ItemStack itemStack) { - this.resultMatrix[i] = Objects.requireNonNullElseGet(itemStack, () -> new ItemStack(Material.AIR)); + resultMatrix[i] = Objects.requireNonNullElseGet(itemStack, () -> new ItemStack(Material.AIR)); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java index 6d1ab463..5de47c7d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java @@ -4,19 +4,19 @@ import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import java.util.Optional; -import net.minecraft.commands.arguments.item.ItemParser; +import net.minecraft.commands.arguments.item.ArgumentParserItemStack; import net.minecraft.core.HolderSet; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.IRegistryCustom; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.registries.Registries; import net.minecraft.server.MinecraftServer; import net.minecraft.tags.EnchantmentTags; import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.item.Item; -import net.minecraft.world.item.SpawnEggItem; +import net.minecraft.world.item.ItemMonsterEgg; import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.EnchantmentManager; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; @@ -25,8 +25,11 @@ import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.entity.CraftEntity; import org.bukkit.craftbukkit.entity.CraftEntityType; +import org.bukkit.craftbukkit.inventory.components.CraftEquippableComponent; import org.bukkit.craftbukkit.inventory.components.CraftFoodComponent; +import org.bukkit.craftbukkit.inventory.components.CraftJukeboxComponent; import org.bukkit.craftbukkit.inventory.components.CraftToolComponent; +import org.bukkit.craftbukkit.inventory.components.CraftUseCooldownComponent; import org.bukkit.craftbukkit.util.CraftLegacy; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; @@ -42,10 +45,12 @@ public final class CraftItemFactory implements ItemFactory { static { instance = new CraftItemFactory(); ConfigurationSerialization.registerClass(SerializableMeta.class); + ConfigurationSerialization.registerClass(CraftEquippableComponent.class); ConfigurationSerialization.registerClass(CraftFoodComponent.class); - ConfigurationSerialization.registerClass(CraftFoodComponent.CraftFoodEffect.class); ConfigurationSerialization.registerClass(CraftToolComponent.class); ConfigurationSerialization.registerClass(CraftToolComponent.CraftToolRule.class); + ConfigurationSerialization.registerClass(CraftJukeboxComponent.class); + ConfigurationSerialization.registerClass(CraftUseCooldownComponent.class); } private CraftItemFactory() { @@ -56,7 +61,7 @@ public boolean isApplicable(ItemMeta meta, ItemStack itemstack) { if (itemstack == null) { return false; } - return this.isApplicable(meta, itemstack.getType()); + return isApplicable(meta, itemstack.getType()); } @Override @@ -74,322 +79,18 @@ public boolean isApplicable(ItemMeta meta, Material type) { @Override public ItemMeta getItemMeta(Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); - return this.getItemMeta(material, null); + return getItemMeta(material, null); } private ItemMeta getItemMeta(Material material, CraftMetaItem meta) { material = CraftLegacy.fromLegacy(material); // This may be called from legacy item stacks, try to get the right material - switch (material) { - case AIR: - return null; - case WRITTEN_BOOK: - return meta instanceof CraftMetaBookSigned ? meta : new CraftMetaBookSigned(meta); - case WRITABLE_BOOK: - return meta != null && meta.getClass().equals(CraftMetaBook.class) ? meta : new CraftMetaBook(meta); - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PIGLIN_HEAD: - case PIGLIN_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return meta instanceof CraftMetaSkull ? meta : new CraftMetaSkull(meta); - case CHAINMAIL_HELMET: - case CHAINMAIL_CHESTPLATE: - case CHAINMAIL_LEGGINGS: - case CHAINMAIL_BOOTS: - case DIAMOND_HELMET: - case DIAMOND_CHESTPLATE: - case DIAMOND_LEGGINGS: - case DIAMOND_BOOTS: - case GOLDEN_HELMET: - case GOLDEN_CHESTPLATE: - case GOLDEN_LEGGINGS: - case GOLDEN_BOOTS: - case IRON_HELMET: - case IRON_CHESTPLATE: - case IRON_LEGGINGS: - case IRON_BOOTS: - case NETHERITE_HELMET: - case NETHERITE_CHESTPLATE: - case NETHERITE_LEGGINGS: - case NETHERITE_BOOTS: - case TURTLE_HELMET: - return meta != null && meta.getClass().equals(CraftMetaArmor.class) ? meta : new CraftMetaArmor(meta); - case LEATHER_HELMET: - case LEATHER_CHESTPLATE: - case LEATHER_LEGGINGS: - case LEATHER_BOOTS: - case WOLF_ARMOR: - return meta instanceof CraftMetaColorableArmor ? meta : new CraftMetaColorableArmor(meta); - case LEATHER_HORSE_ARMOR: - return meta instanceof CraftMetaLeatherArmor ? meta : new CraftMetaLeatherArmor(meta); - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - case TIPPED_ARROW: - return meta instanceof CraftMetaPotion ? meta : new CraftMetaPotion(meta); - case FILLED_MAP: - return meta instanceof CraftMetaMap ? meta : new CraftMetaMap(meta); - case FIREWORK_ROCKET: - return meta instanceof CraftMetaFirework ? meta : new CraftMetaFirework(meta); - case FIREWORK_STAR: - return meta instanceof CraftMetaCharge ? meta : new CraftMetaCharge(meta); - case ENCHANTED_BOOK: - return meta instanceof CraftMetaEnchantedBook ? meta : new CraftMetaEnchantedBook(meta); - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - return meta instanceof CraftMetaBanner ? meta : new CraftMetaBanner(meta); - case ARMADILLO_SPAWN_EGG: - case ALLAY_SPAWN_EGG: - case AXOLOTL_SPAWN_EGG: - case BAT_SPAWN_EGG: - case BEE_SPAWN_EGG: - case BLAZE_SPAWN_EGG: - case BOGGED_SPAWN_EGG: - case BREEZE_SPAWN_EGG: - case CAT_SPAWN_EGG: - case CAMEL_SPAWN_EGG: - case CAVE_SPIDER_SPAWN_EGG: - case CHICKEN_SPAWN_EGG: - case COD_SPAWN_EGG: - case COW_SPAWN_EGG: - case CREEPER_SPAWN_EGG: - case DOLPHIN_SPAWN_EGG: - case DONKEY_SPAWN_EGG: - case DROWNED_SPAWN_EGG: - case ELDER_GUARDIAN_SPAWN_EGG: - case ENDER_DRAGON_SPAWN_EGG: - case ENDERMAN_SPAWN_EGG: - case ENDERMITE_SPAWN_EGG: - case EVOKER_SPAWN_EGG: - case FOX_SPAWN_EGG: - case FROG_SPAWN_EGG: - case GHAST_SPAWN_EGG: - case GLOW_SQUID_SPAWN_EGG: - case GOAT_SPAWN_EGG: - case GUARDIAN_SPAWN_EGG: - case HOGLIN_SPAWN_EGG: - case HORSE_SPAWN_EGG: - case HUSK_SPAWN_EGG: - case IRON_GOLEM_SPAWN_EGG: - case LLAMA_SPAWN_EGG: - case MAGMA_CUBE_SPAWN_EGG: - case MOOSHROOM_SPAWN_EGG: - case MULE_SPAWN_EGG: - case OCELOT_SPAWN_EGG: - case PANDA_SPAWN_EGG: - case PARROT_SPAWN_EGG: - case PHANTOM_SPAWN_EGG: - case PIGLIN_BRUTE_SPAWN_EGG: - case PIGLIN_SPAWN_EGG: - case PIG_SPAWN_EGG: - case PILLAGER_SPAWN_EGG: - case POLAR_BEAR_SPAWN_EGG: - case PUFFERFISH_SPAWN_EGG: - case RABBIT_SPAWN_EGG: - case RAVAGER_SPAWN_EGG: - case SALMON_SPAWN_EGG: - case SHEEP_SPAWN_EGG: - case SHULKER_SPAWN_EGG: - case SILVERFISH_SPAWN_EGG: - case SKELETON_HORSE_SPAWN_EGG: - case SKELETON_SPAWN_EGG: - case SLIME_SPAWN_EGG: - case SNIFFER_SPAWN_EGG: - case SNOW_GOLEM_SPAWN_EGG: - case SPIDER_SPAWN_EGG: - case SQUID_SPAWN_EGG: - case STRAY_SPAWN_EGG: - case STRIDER_SPAWN_EGG: - case TADPOLE_SPAWN_EGG: - case TRADER_LLAMA_SPAWN_EGG: - case TROPICAL_FISH_SPAWN_EGG: - case TURTLE_SPAWN_EGG: - case VEX_SPAWN_EGG: - case VILLAGER_SPAWN_EGG: - case VINDICATOR_SPAWN_EGG: - case WANDERING_TRADER_SPAWN_EGG: - case WARDEN_SPAWN_EGG: - case WITCH_SPAWN_EGG: - case WITHER_SKELETON_SPAWN_EGG: - case WITHER_SPAWN_EGG: - case WOLF_SPAWN_EGG: - case ZOGLIN_SPAWN_EGG: - case ZOMBIE_HORSE_SPAWN_EGG: - case ZOMBIE_SPAWN_EGG: - case ZOMBIE_VILLAGER_SPAWN_EGG: - case ZOMBIFIED_PIGLIN_SPAWN_EGG: - return meta instanceof CraftMetaSpawnEgg ? meta : new CraftMetaSpawnEgg(meta); - case ARMOR_STAND: - return meta instanceof CraftMetaArmorStand ? meta : new CraftMetaArmorStand(meta); - case KNOWLEDGE_BOOK: - return meta instanceof CraftMetaKnowledgeBook ? meta : new CraftMetaKnowledgeBook(meta); - case FURNACE: - case CHEST: - case TRAPPED_CHEST: - case JUKEBOX: - case DISPENSER: - case DROPPER: - case ACACIA_HANGING_SIGN: - case ACACIA_SIGN: - case ACACIA_WALL_HANGING_SIGN: - case ACACIA_WALL_SIGN: - case BAMBOO_HANGING_SIGN: - case BAMBOO_SIGN: - case BAMBOO_WALL_HANGING_SIGN: - case BAMBOO_WALL_SIGN: - case BIRCH_HANGING_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_HANGING_SIGN: - case BIRCH_WALL_SIGN: - case CHERRY_HANGING_SIGN: - case CHERRY_SIGN: - case CHERRY_WALL_HANGING_SIGN: - case CHERRY_WALL_SIGN: - case CRIMSON_HANGING_SIGN: - case CRIMSON_SIGN: - case CRIMSON_WALL_HANGING_SIGN: - case CRIMSON_WALL_SIGN: - case DARK_OAK_HANGING_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_HANGING_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_HANGING_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_HANGING_SIGN: - case JUNGLE_WALL_SIGN: - case MANGROVE_HANGING_SIGN: - case MANGROVE_SIGN: - case MANGROVE_WALL_HANGING_SIGN: - case MANGROVE_WALL_SIGN: - case OAK_HANGING_SIGN: - case OAK_SIGN: - case OAK_WALL_HANGING_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_HANGING_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_HANGING_SIGN: - case SPRUCE_WALL_SIGN: - case WARPED_HANGING_SIGN: - case WARPED_SIGN: - case WARPED_WALL_HANGING_SIGN: - case WARPED_WALL_SIGN: - case SPAWNER: - case BREWING_STAND: - case ENCHANTING_TABLE: - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - case BEACON: - case DAYLIGHT_DETECTOR: - case HOPPER: - case COMPARATOR: - case SHIELD: - case STRUCTURE_BLOCK: - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case ENDER_CHEST: - case BARREL: - case BELL: - case BLAST_FURNACE: - case CAMPFIRE: - case SOUL_CAMPFIRE: - case JIGSAW: - case LECTERN: - case SMOKER: - case BEEHIVE: - case BEE_NEST: - case SCULK_CATALYST: - case SCULK_SHRIEKER: - case SCULK_SENSOR: - case CALIBRATED_SCULK_SENSOR: - case CHISELED_BOOKSHELF: - case DECORATED_POT: - case SUSPICIOUS_SAND: - case SUSPICIOUS_GRAVEL: - case CRAFTER: - case TRIAL_SPAWNER: - case VAULT: - return new CraftMetaBlockState(meta, material); - case TROPICAL_FISH_BUCKET: - return meta instanceof CraftMetaTropicalFishBucket ? meta : new CraftMetaTropicalFishBucket(meta); - case AXOLOTL_BUCKET: - return meta instanceof CraftMetaAxolotlBucket ? meta : new CraftMetaAxolotlBucket(meta); - case CROSSBOW: - return meta instanceof CraftMetaCrossbow ? meta : new CraftMetaCrossbow(meta); - case SUSPICIOUS_STEW: - return meta instanceof CraftMetaSuspiciousStew ? meta : new CraftMetaSuspiciousStew(meta); - case COD_BUCKET: - case PUFFERFISH_BUCKET: - case SALMON_BUCKET: - case ITEM_FRAME: - case GLOW_ITEM_FRAME: - case PAINTING: - return meta instanceof CraftMetaEntityTag ? meta : new CraftMetaEntityTag(meta); - case COMPASS: - return meta instanceof CraftMetaCompass ? meta : new CraftMetaCompass(meta); - case BUNDLE: - return meta instanceof CraftMetaBundle ? meta : new CraftMetaBundle(meta); - case GOAT_HORN: - return meta instanceof CraftMetaMusicInstrument ? meta : new CraftMetaMusicInstrument(meta); - case OMINOUS_BOTTLE: - return meta instanceof CraftMetaOminousBottle ? meta : new CraftMetaOminousBottle(meta); - default: + + if (!material.isItem()) { + // default behavior for none items is a new CraftMetaItem return new CraftMetaItem(meta); } + + return ((CraftItemType) material.asItemType()).getItemMeta(meta); } @Override @@ -409,7 +110,7 @@ public boolean equals(ItemMeta meta1, ItemMeta meta2) { return ((CraftMetaItem) meta1).isEmpty(); } - return this.equals((CraftMetaItem) meta1, (CraftMetaItem) meta2); + return equals((CraftMetaItem) meta1, (CraftMetaItem) meta2); } boolean equals(CraftMetaItem meta1, CraftMetaItem meta2) { @@ -426,31 +127,31 @@ boolean equals(CraftMetaItem meta1, CraftMetaItem meta2) { } public static CraftItemFactory instance() { - return CraftItemFactory.instance; + return instance; } @Override public ItemMeta asMetaFor(ItemMeta meta, ItemStack stack) { Preconditions.checkArgument(stack != null, "ItemStack stack cannot be null"); - return this.asMetaFor(meta, stack.getType()); + return asMetaFor(meta, stack.getType()); } @Override public ItemMeta asMetaFor(ItemMeta meta, Material material) { Preconditions.checkArgument(material != null, "Material cannot be null"); Preconditions.checkArgument(meta instanceof CraftMetaItem, "ItemMeta of %s not created by %s", (meta != null ? meta.getClass().toString() : "null"), CraftItemFactory.class.getName()); - return this.getItemMeta(material, (CraftMetaItem) meta); + return getItemMeta(material, (CraftMetaItem) meta); } @Override public Color getDefaultLeatherColor() { - return CraftItemFactory.DEFAULT_LEATHER_COLOR; + return DEFAULT_LEATHER_COLOR; } @Override public ItemStack createItemStack(String input) throws IllegalArgumentException { try { - ItemParser.ItemResult arg = new ItemParser(MinecraftServer.getDefaultRegistryAccess()).parse(new StringReader(input)); + ArgumentParserItemStack.a arg = new ArgumentParserItemStack(MinecraftServer.getDefaultRegistryAccess()).parse(new StringReader(input)); Item item = arg.item().value(); net.minecraft.world.item.ItemStack nmsItemStack = new net.minecraft.world.item.ItemStack(item); @@ -471,8 +172,8 @@ public Material getSpawnEgg(EntityType type) { if (type == EntityType.UNKNOWN) { return null; } - net.minecraft.world.entity.EntityType nmsType = CraftEntityType.bukkitToMinecraft(type); - Item nmsItem = SpawnEggItem.byId(nmsType); + EntityTypes nmsType = CraftEntityType.bukkitToMinecraft(type); + Item nmsItem = ItemMonsterEgg.byId(nmsType); if (nmsItem == null) { return null; @@ -485,19 +186,19 @@ public Material getSpawnEgg(EntityType type) { public ItemStack enchantItem(Entity entity, ItemStack itemStack, int level, boolean allowTreasures) { Preconditions.checkArgument(entity != null, "The entity must not be null"); - return CraftItemFactory.enchantItem(((CraftEntity) entity).getHandle().random, itemStack, level, allowTreasures); + return enchantItem(((CraftEntity) entity).getHandle().random, itemStack, level, allowTreasures); } @Override public ItemStack enchantItem(final World world, final ItemStack itemStack, final int level, final boolean allowTreasures) { Preconditions.checkArgument(world != null, "The world must not be null"); - return CraftItemFactory.enchantItem(((CraftWorld) world).getHandle().random, itemStack, level, allowTreasures); + return enchantItem(((CraftWorld) world).getHandle().random, itemStack, level, allowTreasures); } @Override public ItemStack enchantItem(final ItemStack itemStack, final int level, final boolean allowTreasures) { - return CraftItemFactory.enchantItem(CraftItemFactory.randomSource, itemStack, level, allowTreasures); + return enchantItem(randomSource, itemStack, level, allowTreasures); } private static ItemStack enchantItem(RandomSource source, ItemStack itemStack, int level, boolean allowTreasures) { @@ -505,8 +206,8 @@ private static ItemStack enchantItem(RandomSource source, ItemStack itemStack, i Preconditions.checkArgument(!itemStack.getType().isAir(), "ItemStack must not be air"); itemStack = CraftItemStack.asCraftCopy(itemStack); CraftItemStack craft = (CraftItemStack) itemStack; - RegistryAccess registry = CraftRegistry.getMinecraftRegistry(); - Optional> optional = (allowTreasures) ? Optional.empty() : registry.registryOrThrow(Registries.ENCHANTMENT).getTag(EnchantmentTags.IN_ENCHANTING_TABLE); - return CraftItemStack.asCraftMirror(EnchantmentHelper.enchantItem(source, craft.handle, level, registry, optional)); + IRegistryCustom registry = CraftRegistry.getMinecraftRegistry(); + Optional> optional = (allowTreasures) ? Optional.empty() : registry.lookupOrThrow(Registries.ENCHANTMENT).get(EnchantmentTags.IN_ENCHANTING_TABLE); + return CraftItemStack.asCraftMirror(EnchantmentManager.enchantItem(source, craft.handle, level, registry, optional)); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFlag.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFlag.java index cc6289be..902fb5f2 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFlag.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFlag.java @@ -20,4 +20,4 @@ public static ItemFlag stringToBukkit(String string) { string = FieldRename.convertItemFlagName(ApiVersion.CURRENT, string); return ItemFlag.valueOf(string); } -} \ No newline at end of file +} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemMetas.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemMetas.java index 4b078b4f..ca8009cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemMetas.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemMetas.java @@ -2,8 +2,15 @@ import java.util.function.BiFunction; import java.util.function.Function; +import net.minecraft.world.item.BundleItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemBanner; +import net.minecraft.world.item.ItemBlock; +import net.minecraft.world.item.ItemMonsterEgg; +import net.minecraft.world.item.ItemSign; import net.minecraft.world.item.ItemStack; -import org.bukkit.Tag; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.BlockShulkerBox; import org.bukkit.inventory.ItemType; import org.bukkit.inventory.meta.ArmorMeta; import org.bukkit.inventory.meta.AxolotlBucketMeta; @@ -24,6 +31,7 @@ import org.bukkit.inventory.meta.MusicInstrumentMeta; import org.bukkit.inventory.meta.OminousBottleMeta; import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.inventory.meta.ShieldMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.SpawnEggMeta; import org.bukkit.inventory.meta.SuspiciousStewMeta; @@ -107,6 +115,10 @@ public record ItemMetaData(Class metaClass, Function new CraftMetaBlockState(item.getComponentsPatch(), CraftItemType.minecraftToBukkit(item.getItem())), (type, meta) -> new CraftMetaBlockState(meta, type.asMaterial())); + private static final ItemMetaData SHIELD_META_DATA = new ItemMetaData<>(ShieldMeta.class, + item -> new CraftMetaShield(item.getComponentsPatch()), + (type, meta) -> new CraftMetaShield(meta)); + private static final ItemMetaData TROPICAL_FISH_BUCKET_META_DATA = new ItemMetaData<>(TropicalFishBucketMeta.class, item -> new CraftMetaTropicalFishBucket(item.getComponentsPatch()), (type, meta) -> meta instanceof CraftMetaTropicalFishBucket tropicalFishBucket ? tropicalFishBucket : new CraftMetaTropicalFishBucket(meta)); @@ -145,7 +157,10 @@ public record ItemMetaData(Class metaClass, Function ItemMetaData getItemMetaData(ItemType itemType) { + public static ItemMetaData getItemMetaData(CraftItemType itemType) { + Item itemHandle = itemType.getHandle(); + Block blockHandle = (itemHandle instanceof ItemBlock itemBlock) ? itemBlock.getBlock() : null; + if (itemType == ItemType.AIR) { return asType(EMPTY_META_DATA); } @@ -198,50 +213,10 @@ public static ItemMetaData getItemMetaData(ItemType item if (itemType == ItemType.ENCHANTED_BOOK) { return asType(ENCHANTED_BOOK_META_DATA); } - if (itemType.hasBlockType() && Tag.BANNERS.isTagged(itemType.getBlockType().asMaterial())) { + if (itemHandle instanceof ItemBanner) { return asType(BANNER_META_DATA); } - if (itemType == ItemType.ARMADILLO_SPAWN_EGG || itemType == ItemType.ALLAY_SPAWN_EGG - || itemType == ItemType.ARMADILLO_SPAWN_EGG || itemType == ItemType.ALLAY_SPAWN_EGG - || itemType == ItemType.AXOLOTL_SPAWN_EGG || itemType == ItemType.BAT_SPAWN_EGG - || itemType == ItemType.BEE_SPAWN_EGG || itemType == ItemType.BLAZE_SPAWN_EGG - || itemType == ItemType.BOGGED_SPAWN_EGG || itemType == ItemType.BREEZE_SPAWN_EGG - || itemType == ItemType.CAT_SPAWN_EGG || itemType == ItemType.CAMEL_SPAWN_EGG - || itemType == ItemType.CAVE_SPIDER_SPAWN_EGG || itemType == ItemType.CHICKEN_SPAWN_EGG - || itemType == ItemType.COD_SPAWN_EGG || itemType == ItemType.COW_SPAWN_EGG - || itemType == ItemType.CREEPER_SPAWN_EGG || itemType == ItemType.DOLPHIN_SPAWN_EGG - || itemType == ItemType.DONKEY_SPAWN_EGG || itemType == ItemType.DROWNED_SPAWN_EGG - || itemType == ItemType.ELDER_GUARDIAN_SPAWN_EGG || itemType == ItemType.ENDER_DRAGON_SPAWN_EGG - || itemType == ItemType.ENDERMAN_SPAWN_EGG || itemType == ItemType.ENDERMITE_SPAWN_EGG - || itemType == ItemType.EVOKER_SPAWN_EGG || itemType == ItemType.FOX_SPAWN_EGG - || itemType == ItemType.FROG_SPAWN_EGG || itemType == ItemType.GHAST_SPAWN_EGG - || itemType == ItemType.GLOW_SQUID_SPAWN_EGG || itemType == ItemType.GOAT_SPAWN_EGG - || itemType == ItemType.GUARDIAN_SPAWN_EGG || itemType == ItemType.HOGLIN_SPAWN_EGG - || itemType == ItemType.HORSE_SPAWN_EGG || itemType == ItemType.HUSK_SPAWN_EGG - || itemType == ItemType.IRON_GOLEM_SPAWN_EGG || itemType == ItemType.LLAMA_SPAWN_EGG - || itemType == ItemType.MAGMA_CUBE_SPAWN_EGG || itemType == ItemType.MOOSHROOM_SPAWN_EGG - || itemType == ItemType.MULE_SPAWN_EGG || itemType == ItemType.OCELOT_SPAWN_EGG - || itemType == ItemType.PANDA_SPAWN_EGG || itemType == ItemType.PARROT_SPAWN_EGG - || itemType == ItemType.PHANTOM_SPAWN_EGG || itemType == ItemType.PIGLIN_BRUTE_SPAWN_EGG - || itemType == ItemType.PIGLIN_SPAWN_EGG || itemType == ItemType.PIG_SPAWN_EGG - || itemType == ItemType.PILLAGER_SPAWN_EGG || itemType == ItemType.POLAR_BEAR_SPAWN_EGG - || itemType == ItemType.PUFFERFISH_SPAWN_EGG || itemType == ItemType.RABBIT_SPAWN_EGG - || itemType == ItemType.RAVAGER_SPAWN_EGG || itemType == ItemType.SALMON_SPAWN_EGG - || itemType == ItemType.SHEEP_SPAWN_EGG || itemType == ItemType.SHULKER_SPAWN_EGG - || itemType == ItemType.SILVERFISH_SPAWN_EGG || itemType == ItemType.SKELETON_HORSE_SPAWN_EGG - || itemType == ItemType.SKELETON_SPAWN_EGG || itemType == ItemType.SLIME_SPAWN_EGG - || itemType == ItemType.SNIFFER_SPAWN_EGG || itemType == ItemType.SNOW_GOLEM_SPAWN_EGG - || itemType == ItemType.SPIDER_SPAWN_EGG || itemType == ItemType.SQUID_SPAWN_EGG - || itemType == ItemType.STRAY_SPAWN_EGG || itemType == ItemType.STRIDER_SPAWN_EGG - || itemType == ItemType.TADPOLE_SPAWN_EGG || itemType == ItemType.TRADER_LLAMA_SPAWN_EGG - || itemType == ItemType.TROPICAL_FISH_SPAWN_EGG || itemType == ItemType.TURTLE_SPAWN_EGG - || itemType == ItemType.VEX_SPAWN_EGG || itemType == ItemType.VILLAGER_SPAWN_EGG - || itemType == ItemType.VINDICATOR_SPAWN_EGG || itemType == ItemType.WANDERING_TRADER_SPAWN_EGG - || itemType == ItemType.WARDEN_SPAWN_EGG || itemType == ItemType.WITCH_SPAWN_EGG - || itemType == ItemType.WITHER_SKELETON_SPAWN_EGG || itemType == ItemType.WITHER_SPAWN_EGG - || itemType == ItemType.WOLF_SPAWN_EGG || itemType == ItemType.ZOGLIN_SPAWN_EGG - || itemType == ItemType.ZOMBIE_HORSE_SPAWN_EGG || itemType == ItemType.ZOMBIE_SPAWN_EGG - || itemType == ItemType.ZOMBIE_VILLAGER_SPAWN_EGG || itemType == ItemType.ZOMBIFIED_PIGLIN_SPAWN_EGG) { + if (itemHandle instanceof ItemMonsterEgg) { return asType(SPAWN_EGG_META_DATA); } if (itemType == ItemType.ARMOR_STAND) { @@ -253,13 +228,13 @@ public static ItemMetaData getItemMetaData(ItemType item if (itemType == ItemType.FURNACE || itemType == ItemType.CHEST || itemType == ItemType.TRAPPED_CHEST || itemType == ItemType.JUKEBOX || itemType == ItemType.DISPENSER || itemType == ItemType.DROPPER - || (itemType.hasBlockType() && Tag.SIGNS.isTagged(itemType.getBlockType().asMaterial())) || itemType == ItemType.SPAWNER + || itemHandle instanceof ItemSign || itemType == ItemType.SPAWNER || itemType == ItemType.BREWING_STAND || itemType == ItemType.ENCHANTING_TABLE || itemType == ItemType.COMMAND_BLOCK || itemType == ItemType.REPEATING_COMMAND_BLOCK || itemType == ItemType.CHAIN_COMMAND_BLOCK || itemType == ItemType.BEACON || itemType == ItemType.DAYLIGHT_DETECTOR || itemType == ItemType.HOPPER - || itemType == ItemType.COMPARATOR || itemType == ItemType.SHIELD - || itemType == ItemType.STRUCTURE_BLOCK || (itemType.hasBlockType() && Tag.SHULKER_BOXES.isTagged(itemType.getBlockType().asMaterial())) + || itemType == ItemType.COMPARATOR || itemType == ItemType.STRUCTURE_BLOCK + || blockHandle instanceof BlockShulkerBox || itemType == ItemType.ENDER_CHEST || itemType == ItemType.BARREL || itemType == ItemType.BELL || itemType == ItemType.BLAST_FURNACE || itemType == ItemType.CAMPFIRE || itemType == ItemType.SOUL_CAMPFIRE @@ -270,9 +245,13 @@ public static ItemMetaData getItemMetaData(ItemType item || itemType == ItemType.CALIBRATED_SCULK_SENSOR || itemType == ItemType.CHISELED_BOOKSHELF || itemType == ItemType.DECORATED_POT || itemType == ItemType.SUSPICIOUS_SAND || itemType == ItemType.SUSPICIOUS_GRAVEL || itemType == ItemType.CRAFTER - || itemType == ItemType.TRIAL_SPAWNER || itemType == ItemType.VAULT) { + || itemType == ItemType.TRIAL_SPAWNER || itemType == ItemType.VAULT + || itemType == ItemType.CREAKING_HEART) { return asType(BLOCK_STATE_META_DATA); } + if (itemType == ItemType.SHIELD) { + return asType(SHIELD_META_DATA); + } if (itemType == ItemType.TROPICAL_FISH_BUCKET) { return asType(TROPICAL_FISH_BUCKET_META_DATA); } @@ -293,7 +272,7 @@ public static ItemMetaData getItemMetaData(ItemType item if (itemType == ItemType.COMPASS) { return asType(COMPASS_META_DATA); } - if (itemType == ItemType.BUNDLE) { + if (itemHandle instanceof BundleItem) { return asType(BUNDLE_META_DATA); } if (itemType == ItemType.GOAT_HORN) { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java index e145aa32..83653c1f 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java @@ -2,12 +2,20 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; +import java.util.Collections; import java.util.Map; +import java.util.Optional; +import net.minecraft.advancements.critereon.CriterionConditionItem; +import net.minecraft.advancements.critereon.CriterionConditionValue; import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.DataComponentPredicate; import net.minecraft.core.component.DataComponents; +import net.minecraft.core.component.PatchedDataComponentMap; import net.minecraft.world.item.Item; -import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.EnchantmentManager; import net.minecraft.world.item.enchantment.ItemEnchantments; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -18,6 +26,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.MaterialData; +import org.jetbrains.annotations.ApiStatus; @DelegateDeserialization(ItemStack.class) public final class CraftItemStack extends ItemStack { @@ -39,7 +48,7 @@ public static net.minecraft.world.item.ItemStack asNMSCopy(ItemStack original) { net.minecraft.world.item.ItemStack stack = new net.minecraft.world.item.ItemStack(item, original.getAmount()); if (original.hasItemMeta()) { - CraftItemStack.setItemMeta(stack, original.getItemMeta()); + setItemMeta(stack, original.getItemMeta()); } return stack; } @@ -58,8 +67,8 @@ public static ItemStack asBukkitCopy(net.minecraft.world.item.ItemStack original return new ItemStack(Material.AIR); } ItemStack stack = new ItemStack(CraftItemType.minecraftToBukkit(original.getItem()), original.getCount()); - if (CraftItemStack.hasItemMeta(original)) { - stack.setItemMeta(CraftItemStack.getItemMeta(original)); + if (hasItemMeta(original)) { + stack.setItemMeta(getItemMeta(original)); } return stack; } @@ -77,14 +86,22 @@ public static CraftItemStack asCraftCopy(ItemStack original) { } public static CraftItemStack asNewCraftStack(Item item) { - return CraftItemStack.asNewCraftStack(item, 1); + return asNewCraftStack(item, 1); } public static CraftItemStack asNewCraftStack(Item item, int amount) { return new CraftItemStack(CraftItemType.minecraftToBukkit(item), amount, (short) 0, null); } + public static CriterionConditionItem asCriterionConditionItem(ItemStack original) { + net.minecraft.world.item.ItemStack nms = CraftItemStack.asNMSCopy(original); + DataComponentPredicate predicate = DataComponentPredicate.allOf(PatchedDataComponentMap.fromPatch(DataComponentMap.EMPTY, nms.getComponentsPatch())); + + return new CriterionConditionItem(Optional.of(HolderSet.direct(nms.getItemHolder())), CriterionConditionValue.IntegerRange.ANY, predicate, Collections.emptyMap()); + } + net.minecraft.world.item.ItemStack handle; + private boolean isForInventoryDrop; /** * Mirror @@ -98,71 +115,92 @@ private CraftItemStack(ItemStack item) { } private CraftItemStack(Material type, int amount, short durability, ItemMeta itemMeta) { - this.setType(type); - this.setAmount(amount); - this.setDurability(durability); - this.setItemMeta(itemMeta); + setType(type); + setAmount(amount); + setDurability(durability); + setItemMeta(itemMeta); + } + + /** + * Gets if the item is marked as an inventory drop in death events. + * + * @return true if the item is marked as an inventory drop + */ + @ApiStatus.Internal + public boolean isForInventoryDrop() { + return this.isForInventoryDrop; + } + + /** + * Marks this item as an inventory drop in death events. + * + * @return the ItemStack marked as an inventory drop + */ + @ApiStatus.Internal + public ItemStack markForInventoryDrop() { + this.isForInventoryDrop = true; + return this; } @Override public MaterialData getData() { - return this.handle != null ? CraftMagicNumbers.getMaterialData(this.handle.getItem()) : super.getData(); + return handle != null ? CraftMagicNumbers.getMaterialData(handle.getItem()) : super.getData(); } @Override public Material getType() { - return this.handle != null ? CraftItemType.minecraftToBukkit(this.handle.getItem()) : Material.AIR; + return handle != null ? CraftItemType.minecraftToBukkit(handle.getItem()) : Material.AIR; } @Override public void setType(Material type) { - if (this.getType() == type) { + if (getType() == type) { return; } else if (type == Material.AIR) { - this.handle = null; + handle = null; } else if (CraftItemType.bukkitToMinecraft(type) == null) { // :( - this.handle = null; - } else if (this.handle == null) { - this.handle = new net.minecraft.world.item.ItemStack(CraftItemType.bukkitToMinecraft(type), 1); + handle = null; + } else if (handle == null) { + handle = new net.minecraft.world.item.ItemStack(CraftItemType.bukkitToMinecraft(type), 1); } else { - this.handle.setItem(CraftItemType.bukkitToMinecraft(type)); - if (this.hasItemMeta()) { + handle.setItem(CraftItemType.bukkitToMinecraft(type)); + if (hasItemMeta()) { // This will create the appropriate item meta, which will contain all the data we intend to keep - CraftItemStack.setItemMeta(this.handle, CraftItemStack.getItemMeta(this.handle)); + setItemMeta(handle, getItemMeta(handle)); } } - this.setData(null); + setData(null); } @Override public int getAmount() { - return this.handle != null ? this.handle.getCount() : 0; + return handle != null ? handle.getCount() : 0; } @Override public void setAmount(int amount) { - if (this.handle == null) { + if (handle == null) { return; } - this.handle.setCount(amount); + handle.setCount(amount); if (amount == 0) { - this.handle = null; + handle = null; } } @Override public void setDurability(final short durability) { // Ignore damage if item is null - if (this.handle != null) { - this.handle.setDamageValue(durability); + if (handle != null) { + handle.setDamageValue(durability); } } @Override public short getDurability() { - if (this.handle != null) { - return (short) this.handle.getDamageValue(); + if (handle != null) { + return (short) handle.getDamageValue(); } else { return -1; } @@ -170,23 +208,23 @@ public short getDurability() { @Override public int getMaxStackSize() { - return (this.handle == null) ? Material.AIR.getMaxStackSize() : this.handle.getMaxStackSize(); + return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getMaxStackSize(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - if (!CraftItemStack.makeTag(this.handle)) { + if (!makeTag(handle)) { return; } - ItemEnchantments list = CraftItemStack.getEnchantmentList(this.handle); + ItemEnchantments list = getEnchantmentList(handle); if (list == null) { list = ItemEnchantments.EMPTY; } - ItemEnchantments.Mutable listCopy = new ItemEnchantments.Mutable(list); + ItemEnchantments.a listCopy = new ItemEnchantments.a(list); listCopy.set(CraftEnchantment.bukkitToMinecraftHolder(ench), level); - this.handle.set(DataComponents.ENCHANTMENTS, listCopy.toImmutable()); + handle.set(DataComponents.ENCHANTMENTS, listCopy.toImmutable()); } static boolean makeTag(net.minecraft.world.item.ItemStack item) { @@ -199,52 +237,52 @@ static boolean makeTag(net.minecraft.world.item.ItemStack item) { @Override public boolean containsEnchantment(Enchantment ench) { - return this.getEnchantmentLevel(ench) > 0; + return getEnchantmentLevel(ench) > 0; } @Override public int getEnchantmentLevel(Enchantment ench) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - if (this.handle == null) { + if (handle == null) { return 0; } - return EnchantmentHelper.getItemEnchantmentLevel(CraftEnchantment.bukkitToMinecraftHolder(ench), this.handle); + return EnchantmentManager.getItemEnchantmentLevel(CraftEnchantment.bukkitToMinecraftHolder(ench), handle); } @Override public int removeEnchantment(Enchantment ench) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - ItemEnchantments list = CraftItemStack.getEnchantmentList(this.handle); + ItemEnchantments list = getEnchantmentList(handle); if (list == null) { return 0; } - int level = this.getEnchantmentLevel(ench); + int level = getEnchantmentLevel(ench); if (level <= 0) { return 0; } int size = list.size(); if (size == 1) { - this.handle.remove(DataComponents.ENCHANTMENTS); + handle.remove(DataComponents.ENCHANTMENTS); return level; } - ItemEnchantments.Mutable listCopy = new ItemEnchantments.Mutable(list); + ItemEnchantments.a listCopy = new ItemEnchantments.a(list); listCopy.set(CraftEnchantment.bukkitToMinecraftHolder(ench), -1); // Negative to remove - this.handle.set(DataComponents.ENCHANTMENTS, listCopy.toImmutable()); + handle.set(DataComponents.ENCHANTMENTS, listCopy.toImmutable()); return level; } @Override public void removeEnchantments() { - this.handle.remove(DataComponents.ENCHANTMENTS); + handle.remove(DataComponents.ENCHANTMENTS); } @Override public Map getEnchantments() { - return CraftItemStack.getEnchantments(this.handle); + return getEnchantments(handle); } static Map getEnchantments(net.minecraft.world.item.ItemStack item) { @@ -284,322 +322,15 @@ public CraftItemStack clone() { @Override public ItemMeta getItemMeta() { - return CraftItemStack.getItemMeta(this.handle); + return getItemMeta(handle); } public static ItemMeta getItemMeta(net.minecraft.world.item.ItemStack item) { - if (!CraftItemStack.hasItemMeta(item)) { - return CraftItemFactory.instance().getItemMeta(CraftItemStack.getType(item)); - } - switch (CraftItemStack.getType(item)) { - case WRITTEN_BOOK: - return new CraftMetaBookSigned(item.getComponentsPatch()); - case WRITABLE_BOOK: - return new CraftMetaBook(item.getComponentsPatch()); - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PIGLIN_HEAD: - case PIGLIN_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return new CraftMetaSkull(item.getComponentsPatch()); - case CHAINMAIL_HELMET: - case CHAINMAIL_CHESTPLATE: - case CHAINMAIL_LEGGINGS: - case CHAINMAIL_BOOTS: - case DIAMOND_HELMET: - case DIAMOND_CHESTPLATE: - case DIAMOND_LEGGINGS: - case DIAMOND_BOOTS: - case GOLDEN_HELMET: - case GOLDEN_CHESTPLATE: - case GOLDEN_LEGGINGS: - case GOLDEN_BOOTS: - case IRON_HELMET: - case IRON_CHESTPLATE: - case IRON_LEGGINGS: - case IRON_BOOTS: - case NETHERITE_HELMET: - case NETHERITE_CHESTPLATE: - case NETHERITE_LEGGINGS: - case NETHERITE_BOOTS: - case TURTLE_HELMET: - return new CraftMetaArmor(item.getComponentsPatch()); - case LEATHER_HELMET: - case LEATHER_CHESTPLATE: - case LEATHER_LEGGINGS: - case LEATHER_BOOTS: - case WOLF_ARMOR: - return new CraftMetaColorableArmor(item.getComponentsPatch()); - case LEATHER_HORSE_ARMOR: - return new CraftMetaLeatherArmor(item.getComponentsPatch()); - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - case TIPPED_ARROW: - return new CraftMetaPotion(item.getComponentsPatch()); - case FILLED_MAP: - return new CraftMetaMap(item.getComponentsPatch()); - case FIREWORK_ROCKET: - return new CraftMetaFirework(item.getComponentsPatch()); - case FIREWORK_STAR: - return new CraftMetaCharge(item.getComponentsPatch()); - case ENCHANTED_BOOK: - return new CraftMetaEnchantedBook(item.getComponentsPatch()); - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - return new CraftMetaBanner(item.getComponentsPatch()); - case ARMADILLO_SPAWN_EGG: - case ALLAY_SPAWN_EGG: - case AXOLOTL_SPAWN_EGG: - case BAT_SPAWN_EGG: - case BEE_SPAWN_EGG: - case BLAZE_SPAWN_EGG: - case BOGGED_SPAWN_EGG: - case BREEZE_SPAWN_EGG: - case CAT_SPAWN_EGG: - case CAMEL_SPAWN_EGG: - case CAVE_SPIDER_SPAWN_EGG: - case CHICKEN_SPAWN_EGG: - case COD_SPAWN_EGG: - case COW_SPAWN_EGG: - case CREEPER_SPAWN_EGG: - case DOLPHIN_SPAWN_EGG: - case DONKEY_SPAWN_EGG: - case DROWNED_SPAWN_EGG: - case ELDER_GUARDIAN_SPAWN_EGG: - case ENDER_DRAGON_SPAWN_EGG: - case ENDERMAN_SPAWN_EGG: - case ENDERMITE_SPAWN_EGG: - case EVOKER_SPAWN_EGG: - case FOX_SPAWN_EGG: - case FROG_SPAWN_EGG: - case GHAST_SPAWN_EGG: - case GLOW_SQUID_SPAWN_EGG: - case GOAT_SPAWN_EGG: - case GUARDIAN_SPAWN_EGG: - case HOGLIN_SPAWN_EGG: - case HORSE_SPAWN_EGG: - case HUSK_SPAWN_EGG: - case IRON_GOLEM_SPAWN_EGG: - case LLAMA_SPAWN_EGG: - case MAGMA_CUBE_SPAWN_EGG: - case MOOSHROOM_SPAWN_EGG: - case MULE_SPAWN_EGG: - case OCELOT_SPAWN_EGG: - case PANDA_SPAWN_EGG: - case PARROT_SPAWN_EGG: - case PHANTOM_SPAWN_EGG: - case PIGLIN_BRUTE_SPAWN_EGG: - case PIGLIN_SPAWN_EGG: - case PIG_SPAWN_EGG: - case PILLAGER_SPAWN_EGG: - case POLAR_BEAR_SPAWN_EGG: - case PUFFERFISH_SPAWN_EGG: - case RABBIT_SPAWN_EGG: - case RAVAGER_SPAWN_EGG: - case SALMON_SPAWN_EGG: - case SHEEP_SPAWN_EGG: - case SHULKER_SPAWN_EGG: - case SILVERFISH_SPAWN_EGG: - case SKELETON_HORSE_SPAWN_EGG: - case SKELETON_SPAWN_EGG: - case SLIME_SPAWN_EGG: - case SNIFFER_SPAWN_EGG: - case SNOW_GOLEM_SPAWN_EGG: - case SPIDER_SPAWN_EGG: - case SQUID_SPAWN_EGG: - case STRAY_SPAWN_EGG: - case STRIDER_SPAWN_EGG: - case TADPOLE_SPAWN_EGG: - case TRADER_LLAMA_SPAWN_EGG: - case TROPICAL_FISH_SPAWN_EGG: - case TURTLE_SPAWN_EGG: - case VEX_SPAWN_EGG: - case VILLAGER_SPAWN_EGG: - case VINDICATOR_SPAWN_EGG: - case WANDERING_TRADER_SPAWN_EGG: - case WARDEN_SPAWN_EGG: - case WITCH_SPAWN_EGG: - case WITHER_SKELETON_SPAWN_EGG: - case WITHER_SPAWN_EGG: - case WOLF_SPAWN_EGG: - case ZOGLIN_SPAWN_EGG: - case ZOMBIE_HORSE_SPAWN_EGG: - case ZOMBIE_SPAWN_EGG: - case ZOMBIE_VILLAGER_SPAWN_EGG: - case ZOMBIFIED_PIGLIN_SPAWN_EGG: - return new CraftMetaSpawnEgg(item.getComponentsPatch()); - case ARMOR_STAND: - return new CraftMetaArmorStand(item.getComponentsPatch()); - case KNOWLEDGE_BOOK: - return new CraftMetaKnowledgeBook(item.getComponentsPatch()); - case FURNACE: - case CHEST: - case TRAPPED_CHEST: - case JUKEBOX: - case DISPENSER: - case DROPPER: - case ACACIA_HANGING_SIGN: - case ACACIA_SIGN: - case ACACIA_WALL_HANGING_SIGN: - case ACACIA_WALL_SIGN: - case BAMBOO_HANGING_SIGN: - case BAMBOO_SIGN: - case BAMBOO_WALL_HANGING_SIGN: - case BAMBOO_WALL_SIGN: - case BIRCH_HANGING_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_HANGING_SIGN: - case BIRCH_WALL_SIGN: - case CHERRY_HANGING_SIGN: - case CHERRY_SIGN: - case CHERRY_WALL_HANGING_SIGN: - case CHERRY_WALL_SIGN: - case CRIMSON_HANGING_SIGN: - case CRIMSON_SIGN: - case CRIMSON_WALL_HANGING_SIGN: - case CRIMSON_WALL_SIGN: - case DARK_OAK_HANGING_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_HANGING_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_HANGING_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_HANGING_SIGN: - case JUNGLE_WALL_SIGN: - case MANGROVE_HANGING_SIGN: - case MANGROVE_SIGN: - case MANGROVE_WALL_HANGING_SIGN: - case MANGROVE_WALL_SIGN: - case OAK_HANGING_SIGN: - case OAK_SIGN: - case OAK_WALL_HANGING_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_HANGING_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_HANGING_SIGN: - case SPRUCE_WALL_SIGN: - case WARPED_HANGING_SIGN: - case WARPED_SIGN: - case WARPED_WALL_HANGING_SIGN: - case WARPED_WALL_SIGN: - case SPAWNER: - case BREWING_STAND: - case ENCHANTING_TABLE: - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - case BEACON: - case DAYLIGHT_DETECTOR: - case HOPPER: - case COMPARATOR: - case SHIELD: - case STRUCTURE_BLOCK: - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case ENDER_CHEST: - case BARREL: - case BELL: - case BLAST_FURNACE: - case CAMPFIRE: - case SOUL_CAMPFIRE: - case JIGSAW: - case LECTERN: - case SMOKER: - case BEEHIVE: - case BEE_NEST: - case SCULK_CATALYST: - case SCULK_SHRIEKER: - case SCULK_SENSOR: - case CALIBRATED_SCULK_SENSOR: - case CHISELED_BOOKSHELF: - case DECORATED_POT: - case SUSPICIOUS_SAND: - case SUSPICIOUS_GRAVEL: - case CRAFTER: - case TRIAL_SPAWNER: - case VAULT: - return new CraftMetaBlockState(item.getComponentsPatch(), CraftItemType.minecraftToBukkit(item.getItem())); - case TROPICAL_FISH_BUCKET: - return new CraftMetaTropicalFishBucket(item.getComponentsPatch()); - case AXOLOTL_BUCKET: - return new CraftMetaAxolotlBucket(item.getComponentsPatch()); - case CROSSBOW: - return new CraftMetaCrossbow(item.getComponentsPatch()); - case SUSPICIOUS_STEW: - return new CraftMetaSuspiciousStew(item.getComponentsPatch()); - case COD_BUCKET: - case PUFFERFISH_BUCKET: - case SALMON_BUCKET: - case ITEM_FRAME: - case GLOW_ITEM_FRAME: - case PAINTING: - return new CraftMetaEntityTag(item.getComponentsPatch()); - case COMPASS: - return new CraftMetaCompass(item.getComponentsPatch()); - case BUNDLE: - return new CraftMetaBundle(item.getComponentsPatch()); - case GOAT_HORN: - return new CraftMetaMusicInstrument(item.getComponentsPatch()); - case OMINOUS_BOTTLE: - return new CraftMetaOminousBottle(item.getComponentsPatch()); - default: - return new CraftMetaItem(item.getComponentsPatch()); + if (!hasItemMeta(item)) { + return CraftItemFactory.instance().getItemMeta(getType(item)); } + + return ((CraftItemType) CraftItemType.minecraftToBukkitNew(item.getItem())).getItemMeta(item); } static Material getType(net.minecraft.world.item.ItemStack item) { @@ -608,7 +339,7 @@ static Material getType(net.minecraft.world.item.ItemStack item) { @Override public boolean setItemMeta(ItemMeta itemMeta) { - return CraftItemStack.setItemMeta(this.handle, itemMeta); + return setItemMeta(handle, itemMeta); } public static boolean setItemMeta(net.minecraft.world.item.ItemStack item, ItemMeta itemMeta) { @@ -619,11 +350,11 @@ public static boolean setItemMeta(net.minecraft.world.item.ItemStack item, ItemM item.restorePatch(DataComponentPatch.EMPTY); return true; } - if (!CraftItemFactory.instance().isApplicable(itemMeta, CraftItemStack.getType(item))) { + if (!CraftItemFactory.instance().isApplicable(itemMeta, getType(item))) { return false; } - itemMeta = CraftItemFactory.instance().asMetaFor(itemMeta, CraftItemStack.getType(item)); + itemMeta = CraftItemFactory.instance().asMetaFor(itemMeta, getType(item)); if (itemMeta == null) return true; if (!((CraftMetaItem) itemMeta).isEmpty()) { @@ -653,22 +384,22 @@ public boolean isSimilar(ItemStack stack) { } CraftItemStack that = (CraftItemStack) stack; - if (this.handle == that.handle) { + if (handle == that.handle) { return true; } - if (this.handle == null || that.handle == null) { + if (handle == null || that.handle == null) { return false; } Material comparisonType = CraftLegacy.fromLegacy(that.getType()); // This may be called from legacy item stacks, try to get the right material - if (!(comparisonType == this.getType() && this.getDurability() == that.getDurability())) { + if (!(comparisonType == getType() && getDurability() == that.getDurability())) { return false; } - return this.hasItemMeta() ? that.hasItemMeta() && this.handle.getComponents().equals(that.handle.getComponents()) : !that.hasItemMeta(); + return hasItemMeta() ? that.hasItemMeta() && handle.getComponents().equals(that.handle.getComponents()) : !that.hasItemMeta(); } @Override public boolean hasItemMeta() { - return CraftItemStack.hasItemMeta(this.handle) && !CraftItemFactory.instance().equals(this.getItemMeta(), null); + return hasItemMeta(handle) && !CraftItemFactory.instance().equals(getItemMeta(), null); } static boolean hasItemMeta(net.minecraft.world.item.ItemStack item) { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemType.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemType.java index 23243460..23590940 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemType.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemType.java @@ -1,16 +1,18 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Preconditions; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import java.util.function.Consumer; +import java.util.function.Supplier; import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; -import net.minecraft.world.item.BlockItem; +import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemBlock; import net.minecraft.world.item.component.ItemAttributeModifiers; -import net.minecraft.world.level.block.ComposterBlock; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.level.block.BlockComposter; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -38,7 +40,7 @@ public class CraftItemType implements ItemType.Typed, Han private final NamespacedKey key; private final Item item; - private final Class itemMetaClass; + private final Supplier> itemMetaData; public static Material minecraftToBukkit(Item item) { return CraftMagicNumbers.getMaterial(item); @@ -59,18 +61,7 @@ public static Item bukkitToMinecraftNew(ItemType bukkit) { public CraftItemType(NamespacedKey key, Item item) { this.key = key; this.item = item; - this.itemMetaClass = getItemMetaClass(item); - } - - // Cursed, this should be refactored when possible - private Class getItemMetaClass(Item item) { - ItemMeta meta = new ItemStack(asMaterial()).getItemMeta(); - if (meta != null) { - if (CraftMetaEntityTag.class != meta.getClass() && CraftMetaArmorStand.class != meta.getClass()) { - return (Class) meta.getClass().getInterfaces()[0]; - } - } - return (Class) ItemMeta.class; + this.itemMetaData = Suppliers.memoize(() -> CraftItemMetas.getItemMetaData(this)); } @NotNull @@ -83,7 +74,7 @@ public Typed typed() { @Override @SuppressWarnings("unchecked") public Typed typed(@NotNull final Class itemMetaType) { - if (itemMetaType.isAssignableFrom(this.itemMetaClass)) return (Typed) this; + if (itemMetaType.isAssignableFrom(this.itemMetaData.get().metaClass())) return (Typed) this; throw new IllegalArgumentException("Cannot type item type " + this.key.toString() + " to meta type " + itemMetaType.getSimpleName()); } @@ -123,15 +114,23 @@ public Item getHandle() { return item; } + public M getItemMeta(net.minecraft.world.item.ItemStack itemStack) { + return itemMetaData.get().fromItemStack().apply(itemStack); + } + + public M getItemMeta(ItemMeta itemMeta) { + return itemMetaData.get().fromItemMeta().apply(this, (CraftMetaItem) itemMeta); + } + @Override public boolean hasBlockType() { - return item instanceof BlockItem; + return item instanceof ItemBlock; } @NotNull @Override public BlockType getBlockType() { - if (!(item instanceof BlockItem block)) { + if (!(item instanceof ItemBlock block)) { throw new IllegalStateException("The item type " + getKey() + " has no corresponding block type"); } @@ -143,7 +142,7 @@ public Class getItemMetaClass() { if (this == ItemType.AIR) { throw new UnsupportedOperationException("Air does not have ItemMeta"); } - return itemMetaClass; + return itemMetaData.get().metaClass(); } @Override @@ -173,24 +172,24 @@ public boolean isRecord() { @Override public boolean isFuel() { - return AbstractFurnaceBlockEntity.isFuel(new net.minecraft.world.item.ItemStack(item)); + return MinecraftServer.getServer().fuelValues().isFuel(new net.minecraft.world.item.ItemStack(item)); } @Override public boolean isCompostable() { - return ComposterBlock.COMPOSTABLES.containsKey(item); + return BlockComposter.COMPOSTABLES.containsKey(item); } @Override public float getCompostChance() { Preconditions.checkArgument(isCompostable(), "The item type " + getKey() + " is not compostable"); - return ComposterBlock.COMPOSTABLES.getFloat(item); + return BlockComposter.COMPOSTABLES.getFloat(item); } @Override public ItemType getCraftingRemainingItem() { - Item expectedItem = item.getCraftingRemainingItem(); - return expectedItem == null ? null : minecraftToBukkitNew(expectedItem); + net.minecraft.world.item.ItemStack expectedItem = item.getCraftingRemainder(); + return expectedItem.isEmpty() ? null : minecraftToBukkitNew(expectedItem.getItem()); } // @Override @@ -203,9 +202,6 @@ public Multimap getDefaultAttributeModifiers(Equip ImmutableMultimap.Builder defaultAttributes = ImmutableMultimap.builder(); ItemAttributeModifiers nmsDefaultAttributes = item.components().getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY); - if (nmsDefaultAttributes.modifiers().isEmpty()) { - nmsDefaultAttributes = item.getDefaultAttributeModifiers(); - } nmsDefaultAttributes.forEach(CraftEquipmentSlot.getNMS(slot), (key, value) -> { Attribute attribute = CraftAttribute.minecraftToBukkit(key.value()); diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMenuType.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMenuType.java index 57c4dec0..52c98335 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMenuType.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMenuType.java @@ -5,8 +5,9 @@ import java.util.function.Supplier; import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.Containers; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.craftbukkit.CraftRegistry; @@ -18,20 +19,20 @@ import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.MenuType; -public class CraftMenuType implements MenuType.Typed, Handleable> { +public class CraftMenuType implements MenuType.Typed, Handleable> { private final NamespacedKey key; - private final net.minecraft.world.inventory.MenuType handle; + private final Containers handle; private final Supplier> typeData; - public CraftMenuType(NamespacedKey key, net.minecraft.world.inventory.MenuType handle) { + public CraftMenuType(NamespacedKey key, Containers handle) { this.key = key; this.handle = handle; this.typeData = Suppliers.memoize(() -> CraftMenus.getMenuTypeData(this)); } @Override - public net.minecraft.world.inventory.MenuType getHandle() { + public Containers getHandle() { return this.handle; } @@ -41,10 +42,10 @@ public V create(final HumanEntity player, final String title) { Preconditions.checkArgument(title != null, "The given title must not be null"); Preconditions.checkArgument(player instanceof CraftHumanEntity, "The given player must be a CraftHumanEntity"); final CraftHumanEntity craftHuman = (CraftHumanEntity) player; - Preconditions.checkArgument(craftHuman.getHandle() instanceof ServerPlayer, "The given player must be an EntityPlayer"); - final ServerPlayer serverPlayer = (ServerPlayer) craftHuman.getHandle(); + Preconditions.checkArgument(craftHuman.getHandle() instanceof EntityPlayer, "The given player must be an EntityPlayer"); + final EntityPlayer serverPlayer = (EntityPlayer) craftHuman.getHandle(); - final AbstractContainerMenu container = typeData.get().menuBuilder().build(serverPlayer, this.handle); + final Container container = typeData.get().menuBuilder().build(serverPlayer, this.handle); container.setTitle(CraftChatMessage.fromString(title)[0]); container.checkReachable = false; return (V) container.getBukkitView(); @@ -74,15 +75,15 @@ public NamespacedKey getKey() { return this.key; } - public static net.minecraft.world.inventory.MenuType bukkitToMinecraft(MenuType bukkit) { + public static Containers bukkitToMinecraft(MenuType bukkit) { return CraftRegistry.bukkitToMinecraft(bukkit); } - public static MenuType minecraftToBukkit(net.minecraft.world.inventory.MenuType minecraft) { + public static MenuType minecraftToBukkit(Containers minecraft) { return CraftRegistry.minecraftToBukkit(minecraft, Registries.MENU, Registry.MENU); } - public static MenuType minecraftHolderToBukkit(Holder> minecraft) { + public static MenuType minecraftHolderToBukkit(Holder> minecraft) { return minecraftToBukkit(minecraft.value()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java index f3b0898d..df3b7219 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java @@ -4,29 +4,30 @@ import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.trading.MerchantOffers; +import net.minecraft.world.entity.player.EntityHuman; +import net.minecraft.world.item.trading.IMerchant; +import net.minecraft.world.item.trading.MerchantRecipeList; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.Merchant; import org.bukkit.inventory.MerchantRecipe; public interface CraftMerchant extends Merchant { - net.minecraft.world.item.trading.Merchant getMerchant(); + IMerchant getMerchant(); @Override - default List getRecipes() { - return Collections.unmodifiableList(Lists.transform(this.getMerchant().getOffers(), new Function() { + default List getRecipes() { + return Collections.unmodifiableList(Lists.transform(getMerchant().getOffers(), new Function() { @Override - public MerchantRecipe apply(net.minecraft.world.item.trading.MerchantOffer recipe) { + public MerchantRecipe apply(net.minecraft.world.item.trading.MerchantRecipe recipe) { return recipe.asBukkit(); } })); } @Override - default void setRecipes(List recipes) { - MerchantOffers recipesList = this.getMerchant().getOffers(); + default void setRecipes(List recipes) { + MerchantRecipeList recipesList = getMerchant().getOffers(); recipesList.clear(); for (MerchantRecipe recipe : recipes) { recipesList.add(CraftMerchantRecipe.fromBukkit(recipe).toMinecraft()); @@ -34,28 +35,28 @@ default void setRecipes(List recipes) { } @Override - default MerchantRecipe getRecipe(int i) { - return this.getMerchant().getOffers().get(i).asBukkit(); + default MerchantRecipe getRecipe(int i) { + return getMerchant().getOffers().get(i).asBukkit(); } @Override - default void setRecipe(int i, MerchantRecipe merchantRecipe) { - this.getMerchant().getOffers().set(i, CraftMerchantRecipe.fromBukkit(merchantRecipe).toMinecraft()); + default void setRecipe(int i, MerchantRecipe merchantRecipe) { + getMerchant().getOffers().set(i, CraftMerchantRecipe.fromBukkit(merchantRecipe).toMinecraft()); } @Override - default int getRecipeCount() { - return this.getMerchant().getOffers().size(); + default int getRecipeCount() { + return getMerchant().getOffers().size(); } @Override - default boolean isTrading() { - return this.getTrader() != null; + default boolean isTrading() { + return getTrader() != null; } @Override - default HumanEntity getTrader() { - Player eh = this.getMerchant().getTradingPlayer(); + default HumanEntity getTrader() { + EntityHuman eh = getMerchant().getTradingPlayer(); return eh == null ? null : eh.getBukkitEntity(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java index b9025adf..34e49c53 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java @@ -1,14 +1,14 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Preconditions; -import net.minecraft.network.chat.Component; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.sounds.SoundEffect; +import net.minecraft.sounds.SoundEffects; +import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.trading.Merchant; -import net.minecraft.world.item.trading.MerchantOffer; -import net.minecraft.world.item.trading.MerchantOffers; +import net.minecraft.world.item.trading.IMerchant; +import net.minecraft.world.item.trading.MerchantRecipe; +import net.minecraft.world.item.trading.MerchantRecipeList; import org.bukkit.craftbukkit.util.CraftChatMessage; public class CraftMerchantCustom implements CraftMerchant { @@ -17,7 +17,7 @@ public class CraftMerchantCustom implements CraftMerchant { public CraftMerchantCustom(String title) { this.merchant = new MinecraftMerchant(title); - this.getMerchant().craftMerchant = this; + getMerchant().craftMerchant = this; } @Override @@ -30,11 +30,11 @@ public MinecraftMerchant getMerchant() { return this.merchant; } - public static class MinecraftMerchant implements Merchant { + public static class MinecraftMerchant implements IMerchant { - private final Component title; - private final MerchantOffers trades = new MerchantOffers(); - private Player tradingPlayer; + private final IChatBaseComponent title; + private final MerchantRecipeList trades = new MerchantRecipeList(); + private EntityHuman tradingPlayer; protected CraftMerchant craftMerchant; public MinecraftMerchant(String title) { @@ -44,36 +44,36 @@ public MinecraftMerchant(String title) { @Override public CraftMerchant getCraftMerchant() { - return this.craftMerchant; + return craftMerchant; } @Override - public void setTradingPlayer(Player customer) { - this.tradingPlayer = customer; + public void setTradingPlayer(EntityHuman entityhuman) { + this.tradingPlayer = entityhuman; } @Override - public Player getTradingPlayer() { + public EntityHuman getTradingPlayer() { return this.tradingPlayer; } @Override - public MerchantOffers getOffers() { + public MerchantRecipeList getOffers() { return this.trades; } @Override - public void notifyTrade(MerchantOffer offer) { + public void notifyTrade(MerchantRecipe merchantrecipe) { // increase recipe's uses - offer.increaseUses(); + merchantrecipe.increaseUses(); } @Override - public void notifyTradeUpdated(ItemStack stack) { + public void notifyTradeUpdated(ItemStack itemstack) { } - public Component getScoreboardDisplayName() { - return this.title; + public IChatBaseComponent getScoreboardDisplayName() { + return title; } @Override @@ -82,7 +82,7 @@ public int getVillagerXp() { } @Override - public void overrideXp(int experience) { + public void overrideXp(int i) { } @Override @@ -91,12 +91,12 @@ public boolean showProgressBar() { } @Override - public SoundEvent getNotifyTradeSound() { - return SoundEvents.VILLAGER_YES; + public SoundEffect getNotifyTradeSound() { + return SoundEffects.VILLAGER_YES; } @Override - public void overrideOffers(MerchantOffers offers) { + public void overrideOffers(MerchantRecipeList merchantrecipelist) { } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java index 2e7bcec0..6030c562 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java @@ -3,7 +3,9 @@ import com.google.common.base.Preconditions; import java.util.List; import java.util.Optional; +import net.minecraft.core.component.DataComponentMap; import net.minecraft.core.component.DataComponentPredicate; +import net.minecraft.core.component.PatchedDataComponentMap; import net.minecraft.world.item.Items; import net.minecraft.world.item.trading.ItemCost; import org.bukkit.inventory.ItemStack; @@ -11,13 +13,13 @@ public class CraftMerchantRecipe extends MerchantRecipe { - private final net.minecraft.world.item.trading.MerchantOffer handle; + private final net.minecraft.world.item.trading.MerchantRecipe handle; - public CraftMerchantRecipe(net.minecraft.world.item.trading.MerchantOffer merchantRecipe) { + public CraftMerchantRecipe(net.minecraft.world.item.trading.MerchantRecipe merchantRecipe) { super(CraftItemStack.asBukkitCopy(merchantRecipe.result), 0); this.handle = merchantRecipe; - this.addIngredient(CraftItemStack.asBukkitCopy(merchantRecipe.baseCostA.itemStack())); - merchantRecipe.costB.ifPresent((costB) -> this.addIngredient(CraftItemStack.asBukkitCopy(costB.itemStack()))); + addIngredient(CraftItemStack.asBukkitCopy(merchantRecipe.baseCostA.itemStack())); + merchantRecipe.costB.ifPresent((costB) -> addIngredient(CraftItemStack.asBukkitCopy(costB.itemStack()))); } @Deprecated @@ -27,7 +29,7 @@ public CraftMerchantRecipe(ItemStack result, int uses, int maxUses, boolean expe public CraftMerchantRecipe(ItemStack result, int uses, int maxUses, boolean experienceReward, int experience, float priceMultiplier, int demand, int specialPrice) { super(result, uses, maxUses, experienceReward, experience, priceMultiplier, demand, specialPrice); - this.handle = new net.minecraft.world.item.trading.MerchantOffer( + this.handle = new net.minecraft.world.item.trading.MerchantRecipe( new ItemCost(Items.AIR), Optional.empty(), CraftItemStack.asNMSCopy(result), @@ -44,86 +46,88 @@ public CraftMerchantRecipe(ItemStack result, int uses, int maxUses, boolean expe @Override public int getSpecialPrice() { - return this.handle.getSpecialPriceDiff(); + return handle.getSpecialPriceDiff(); } @Override public void setSpecialPrice(int specialPrice) { - this.handle.specialPriceDiff = specialPrice; + handle.specialPriceDiff = specialPrice; } @Override public int getDemand() { - return this.handle.demand; + return handle.demand; } @Override public void setDemand(int demand) { - this.handle.demand = demand; + handle.demand = demand; } @Override public int getUses() { - return this.handle.uses; + return handle.uses; } @Override public void setUses(int uses) { - this.handle.uses = uses; + handle.uses = uses; } @Override public int getMaxUses() { - return this.handle.maxUses; + return handle.maxUses; } @Override public void setMaxUses(int maxUses) { - this.handle.maxUses = maxUses; + handle.maxUses = maxUses; } @Override public boolean hasExperienceReward() { - return this.handle.rewardExp; + return handle.rewardExp; } @Override public void setExperienceReward(boolean flag) { - this.handle.rewardExp = flag; + handle.rewardExp = flag; } @Override public int getVillagerExperience() { - return this.handle.xp; + return handle.xp; } @Override public void setVillagerExperience(int villagerExperience) { - this.handle.xp = villagerExperience; + handle.xp = villagerExperience; } @Override public float getPriceMultiplier() { - return this.handle.priceMultiplier; + return handle.priceMultiplier; } @Override public void setPriceMultiplier(float priceMultiplier) { - this.handle.priceMultiplier = priceMultiplier; + handle.priceMultiplier = priceMultiplier; } - public net.minecraft.world.item.trading.MerchantOffer toMinecraft() { - List ingredients = this.getIngredients(); + public net.minecraft.world.item.trading.MerchantRecipe toMinecraft() { + List ingredients = getIngredients(); Preconditions.checkState(!ingredients.isEmpty(), "No offered ingredients"); net.minecraft.world.item.ItemStack baseCostA = CraftItemStack.asNMSCopy(ingredients.get(0)); - this.handle.baseCostA = new ItemCost(baseCostA.getItemHolder(), baseCostA.getCount(), DataComponentPredicate.allOf(baseCostA.getComponents()), baseCostA); + DataComponentPredicate baseCostAPredicate = DataComponentPredicate.allOf(PatchedDataComponentMap.fromPatch(DataComponentMap.EMPTY, baseCostA.getComponentsPatch())); + handle.baseCostA = new ItemCost(baseCostA.getItemHolder(), baseCostA.getCount(), baseCostAPredicate, baseCostA); if (ingredients.size() > 1) { net.minecraft.world.item.ItemStack costB = CraftItemStack.asNMSCopy(ingredients.get(1)); - this.handle.costB = Optional.of(new ItemCost(costB.getItemHolder(), costB.getCount(), DataComponentPredicate.allOf(costB.getComponents()), costB)); + DataComponentPredicate costBPredicate = DataComponentPredicate.allOf(PatchedDataComponentMap.fromPatch(DataComponentMap.EMPTY, costB.getComponentsPatch())); + handle.costB = Optional.of(new ItemCost(costB.getItemHolder(), costB.getCount(), costBPredicate, costB)); } else { handle.costB = Optional.empty(); } - return this.handle; + return handle; } public static CraftMerchantRecipe fromBukkit(MerchantRecipe recipe) { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmor.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmor.java index 12b95c44..a1c65d94 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmor.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmor.java @@ -1,14 +1,11 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.collect.Sets; import java.util.HashMap; import java.util.Map; import java.util.Objects; -import java.util.Set; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -23,35 +20,7 @@ @DelegateDeserialization(SerializableMeta.class) public class CraftMetaArmor extends CraftMetaItem implements ArmorMeta { - private static final Set ARMOR_MATERIALS = Sets.newHashSet( - Material.CHAINMAIL_HELMET, - Material.CHAINMAIL_CHESTPLATE, - Material.CHAINMAIL_LEGGINGS, - Material.CHAINMAIL_BOOTS, - Material.DIAMOND_HELMET, - Material.DIAMOND_CHESTPLATE, - Material.DIAMOND_LEGGINGS, - Material.DIAMOND_BOOTS, - Material.GOLDEN_HELMET, - Material.GOLDEN_CHESTPLATE, - Material.GOLDEN_LEGGINGS, - Material.GOLDEN_BOOTS, - Material.IRON_HELMET, - Material.IRON_CHESTPLATE, - Material.IRON_LEGGINGS, - Material.IRON_BOOTS, - Material.LEATHER_HELMET, - Material.LEATHER_CHESTPLATE, - Material.LEATHER_LEGGINGS, - Material.LEATHER_BOOTS, - Material.NETHERITE_HELMET, - Material.NETHERITE_CHESTPLATE, - Material.NETHERITE_LEGGINGS, - Material.NETHERITE_BOOTS, - Material.TURTLE_HELMET - ); - - static final ItemMetaKeyType TRIM = new ItemMetaKeyType<>(DataComponents.TRIM, "trim"); + static final ItemMetaKeyType TRIM = new ItemMetaKeyType<>(DataComponents.TRIM, "trim"); static final ItemMetaKey TRIM_MATERIAL = new ItemMetaKey("material"); static final ItemMetaKey TRIM_PATTERN = new ItemMetaKey("pattern"); @@ -68,14 +37,14 @@ public class CraftMetaArmor extends CraftMetaItem implements ArmorMeta { CraftMetaArmor(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaArmor.TRIM).ifPresent((trimCompound) -> { + getOrEmpty(tag, TRIM).ifPresent((trimCompound) -> { TrimMaterial trimMaterial = CraftTrimMaterial.minecraftHolderToBukkit(trimCompound.material()); TrimPattern trimPattern = CraftTrimPattern.minecraftHolderToBukkit(trimCompound.pattern()); this.trim = new ArmorTrim(trimMaterial, trimPattern); - if (!trimCompound.showInTooltip) { - this.addItemFlags(ItemFlag.HIDE_ARMOR_TRIM); + if (!trimCompound.showInTooltip()) { + addItemFlags(ItemFlag.HIDE_ARMOR_TRIM); } }); } @@ -83,10 +52,10 @@ public class CraftMetaArmor extends CraftMetaItem implements ArmorMeta { CraftMetaArmor(Map map) { super(map); - Map trimData = SerializableMeta.getObject(Map.class, map, CraftMetaArmor.TRIM.BUKKIT, true); + Map trimData = SerializableMeta.getObject(Map.class, map, TRIM.BUKKIT, true); if (trimData != null) { - String materialKeyString = SerializableMeta.getString(trimData, CraftMetaArmor.TRIM_MATERIAL.BUKKIT, true); - String patternKeyString = SerializableMeta.getString(trimData, CraftMetaArmor.TRIM_PATTERN.BUKKIT, true); + String materialKeyString = SerializableMeta.getString(trimData, TRIM_MATERIAL.BUKKIT, true); + String patternKeyString = SerializableMeta.getString(trimData, TRIM_PATTERN.BUKKIT, true); if (materialKeyString != null && patternKeyString != null) { NamespacedKey materialKey = NamespacedKey.fromString(materialKeyString); @@ -108,16 +77,11 @@ public class CraftMetaArmor extends CraftMetaItem implements ArmorMeta { void applyToItem(CraftMetaItem.Applicator itemTag) { super.applyToItem(itemTag); - if (this.hasTrim()) { - itemTag.put(CraftMetaArmor.TRIM, new net.minecraft.world.item.armortrim.ArmorTrim(CraftTrimMaterial.bukkitToMinecraftHolder(this.trim.getMaterial()), CraftTrimPattern.bukkitToMinecraftHolder(this.trim.getPattern()), !this.hasItemFlag(ItemFlag.HIDE_ARMOR_TRIM))); + if (hasTrim()) { + itemTag.put(TRIM, new net.minecraft.world.item.equipment.trim.ArmorTrim(CraftTrimMaterial.bukkitToMinecraftHolder(trim.getMaterial()), CraftTrimPattern.bukkitToMinecraftHolder(trim.getPattern()), !hasItemFlag(ItemFlag.HIDE_ARMOR_TRIM))); } } - @Override - boolean applicableTo(Material type) { - return CraftMetaArmor.ARMOR_MATERIALS.contains(type); - } - @Override boolean equalsCommon(CraftMetaItem that) { if (!super.equalsCommon(that)) { @@ -125,7 +89,7 @@ boolean equalsCommon(CraftMetaItem that) { } if (that instanceof CraftMetaArmor armorMeta) { - return Objects.equals(this.trim, armorMeta.trim); + return Objects.equals(trim, armorMeta.trim); } return true; @@ -133,16 +97,16 @@ boolean equalsCommon(CraftMetaItem that) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaArmor || this.isArmorEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaArmor || isArmorEmpty()); } @Override boolean isEmpty() { - return super.isEmpty() && this.isArmorEmpty(); + return super.isEmpty() && isArmorEmpty(); } private boolean isArmorEmpty() { - return !this.hasTrim(); + return !hasTrim(); } @Override @@ -150,8 +114,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasTrim()) { - hash = 61 * hash + this.trim.hashCode(); + if (hasTrim()) { + hash = 61 * hash + trim.hashCode(); } return original != hash ? CraftMetaArmor.class.hashCode() ^ hash : hash; @@ -168,11 +132,11 @@ public CraftMetaArmor clone() { Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasTrim()) { + if (hasTrim()) { Map trimData = new HashMap<>(); - trimData.put(CraftMetaArmor.TRIM_MATERIAL.BUKKIT, this.trim.getMaterial().getKey().toString()); - trimData.put(CraftMetaArmor.TRIM_PATTERN.BUKKIT, this.trim.getPattern().getKey().toString()); - builder.put(CraftMetaArmor.TRIM.BUKKIT, trimData); + trimData.put(TRIM_MATERIAL.BUKKIT, trim.getMaterial().getKey().toString()); + trimData.put(TRIM_PATTERN.BUKKIT, trim.getPattern().getKey().toString()); + builder.put(TRIM.BUKKIT, trimData); } return builder; @@ -180,7 +144,7 @@ Builder serialize(Builder builder) { @Override public boolean hasTrim() { - return this.trim != null; + return trim != null; } @Override @@ -190,6 +154,6 @@ public void setTrim(ArmorTrim trim) { @Override public ArmorTrim getTrim() { - return this.trim; + return trim; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java index c4f12f96..7d02f8ec 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java @@ -4,8 +4,8 @@ import java.util.Map; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.item.component.CustomData; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -14,7 +14,7 @@ public class CraftMetaArmorStand extends CraftMetaItem { static final ItemMetaKeyType ENTITY_TAG = new ItemMetaKeyType<>(DataComponents.ENTITY_DATA, "entity-tag"); - CompoundTag entityTag; + NBTTagCompound entityTag; CraftMetaArmorStand(CraftMetaItem meta) { super(meta); @@ -30,8 +30,8 @@ public class CraftMetaArmorStand extends CraftMetaItem { CraftMetaArmorStand(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaArmorStand.ENTITY_TAG).ifPresent((nbt) -> { - this.entityTag = nbt.copyTag(); + getOrEmpty(tag, ENTITY_TAG).ifPresent((nbt) -> { + entityTag = nbt.copyTag(); }); } @@ -40,18 +40,18 @@ public class CraftMetaArmorStand extends CraftMetaItem { } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaArmorStand.ENTITY_TAG.NBT)) { - this.entityTag = tag.getCompound(CraftMetaArmorStand.ENTITY_TAG.NBT); + if (tag.contains(ENTITY_TAG.NBT)) { + entityTag = tag.getCompound(ENTITY_TAG.NBT); } } @Override - void serializeInternal(Map internalTags) { - if (this.entityTag != null && !this.entityTag.isEmpty()) { - internalTags.put(CraftMetaArmorStand.ENTITY_TAG.NBT, this.entityTag); + void serializeInternal(Map internalTags) { + if (entityTag != null && !entityTag.isEmpty()) { + internalTags.put(ENTITY_TAG.NBT, entityTag); } } @@ -59,8 +59,8 @@ void serializeInternal(Map internalTags) { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.entityTag != null) { - tag.put(CraftMetaArmorStand.ENTITY_TAG, CustomData.of(this.entityTag)); + if (entityTag != null) { + tag.put(ENTITY_TAG, CustomData.of(entityTag)); } } @@ -71,11 +71,11 @@ boolean applicableTo(Material type) { @Override boolean isEmpty() { - return super.isEmpty() && this.isArmorStandEmpty(); + return super.isEmpty() && isArmorStandEmpty(); } boolean isArmorStandEmpty() { - return !(this.entityTag != null); + return !(entityTag != null); } @Override @@ -86,14 +86,14 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaArmorStand) { CraftMetaArmorStand that = (CraftMetaArmorStand) meta; - return this.entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : this.entityTag == null; + return entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : entityTag == null; } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaArmorStand || this.isArmorStandEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaArmorStand || isArmorStandEmpty()); } @Override @@ -101,8 +101,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.entityTag != null) { - hash = 73 * hash + this.entityTag.hashCode(); + if (entityTag != null) { + hash = 73 * hash + entityTag.hashCode(); } return original != hash ? CraftMetaArmorStand.class.hashCode() ^ hash : hash; @@ -119,8 +119,8 @@ Builder serialize(Builder builder) { public CraftMetaArmorStand clone() { CraftMetaArmorStand clone = (CraftMetaArmorStand) super.clone(); - if (this.entityTag != null) { - clone.entityTag = this.entityTag.copy(); + if (entityTag != null) { + clone.entityTag = entityTag.copy(); } return clone; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaAxolotlBucket.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaAxolotlBucket.java index 19fc22a8..e43e68c3 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaAxolotlBucket.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaAxolotlBucket.java @@ -4,10 +4,9 @@ import java.util.Map; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.item.component.CustomData; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.entity.Axolotl; @@ -21,8 +20,8 @@ public class CraftMetaAxolotlBucket extends CraftMetaItem implements AxolotlBuck static final ItemMetaKeyType BUCKET_ENTITY_TAG = new ItemMetaKeyType<>(DataComponents.BUCKET_ENTITY_DATA, "bucket-entity-tag"); private Integer variant; - private CompoundTag entityTag; - private CompoundTag bucketEntityTag; + private NBTTagCompound entityTag; + private NBTTagCompound bucketEntityTag; CraftMetaAxolotlBucket(CraftMetaItem meta) { super(meta); @@ -40,8 +39,8 @@ public class CraftMetaAxolotlBucket extends CraftMetaItem implements AxolotlBuck CraftMetaAxolotlBucket(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaAxolotlBucket.ENTITY_TAG).ifPresent((nbt) -> { - this.entityTag = nbt.copyTag(); + getOrEmpty(tag, ENTITY_TAG).ifPresent((nbt) -> { + entityTag = nbt.copyTag(); if (entityTag.contains(VARIANT.NBT, CraftMagicNumbers.NBT.TAG_INT)) { this.variant = entityTag.getInt(VARIANT.NBT); @@ -59,18 +58,18 @@ public class CraftMetaAxolotlBucket extends CraftMetaItem implements AxolotlBuck CraftMetaAxolotlBucket(Map map) { super(map); - Integer variant = SerializableMeta.getObject(Integer.class, map, CraftMetaAxolotlBucket.VARIANT.BUKKIT, true); + Integer variant = SerializableMeta.getObject(Integer.class, map, VARIANT.BUKKIT, true); if (variant != null) { this.variant = variant; } } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaAxolotlBucket.ENTITY_TAG.NBT)) { - this.entityTag = tag.getCompound(CraftMetaAxolotlBucket.ENTITY_TAG.NBT); + if (tag.contains(ENTITY_TAG.NBT)) { + entityTag = tag.getCompound(ENTITY_TAG.NBT); } if (tag.contains(BUCKET_ENTITY_TAG.NBT)) { bucketEntityTag = tag.getCompound(BUCKET_ENTITY_TAG.NBT); @@ -78,9 +77,9 @@ void deserializeInternal(CompoundTag tag, Object context) { } @Override - void serializeInternal(Map internalTags) { - if (this.entityTag != null && !this.entityTag.isEmpty()) { - internalTags.put(CraftMetaAxolotlBucket.ENTITY_TAG.NBT, this.entityTag); + void serializeInternal(Map internalTags) { + if (entityTag != null && !entityTag.isEmpty()) { + internalTags.put(ENTITY_TAG.NBT, entityTag); } if (bucketEntityTag != null && !bucketEntityTag.isEmpty()) { internalTags.put(BUCKET_ENTITY_TAG.NBT, bucketEntityTag); @@ -95,36 +94,31 @@ void applyToItem(CraftMetaItem.Applicator tag) { tag.put(ENTITY_TAG, CustomData.of(entityTag)); } - CompoundTag bucketEntityTag = (this.bucketEntityTag != null) ? this.bucketEntityTag.copy() : null; - if (this.hasVariant()) { + NBTTagCompound bucketEntityTag = (this.bucketEntityTag != null) ? this.bucketEntityTag.copy() : null; + if (hasVariant()) { if (bucketEntityTag == null) { - bucketEntityTag = new CompoundTag(); + bucketEntityTag = new NBTTagCompound(); } - bucketEntityTag.putInt("Variant", this.variant); + bucketEntityTag.putInt(VARIANT.NBT, variant); } if (bucketEntityTag != null) { - tag.put(CraftMetaAxolotlBucket.ENTITY_TAG, CustomData.of(bucketEntityTag)); + tag.put(BUCKET_ENTITY_TAG, CustomData.of(bucketEntityTag)); } } - @Override - boolean applicableTo(Material type) { - return type == Material.AXOLOTL_BUCKET; - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isBucketEmpty(); + return super.isEmpty() && isBucketEmpty(); } boolean isBucketEmpty() { - return !(this.hasVariant() || this.entityTag != null || bucketEntityTag != null); + return !(hasVariant() || entityTag != null || bucketEntityTag != null); } @Override public Axolotl.Variant getVariant() { - return Axolotl.Variant.values()[this.variant]; + return Axolotl.Variant.values()[variant]; } @Override @@ -137,7 +131,7 @@ public void setVariant(Axolotl.Variant variant) { @Override public boolean hasVariant() { - return this.variant != null; + return variant != null; } @Override @@ -148,7 +142,7 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaAxolotlBucket) { CraftMetaAxolotlBucket that = (CraftMetaAxolotlBucket) meta; - return (this.hasVariant() ? that.hasVariant() && this.variant.equals(that.variant) : !that.hasVariant()) + return (hasVariant() ? that.hasVariant() && this.variant.equals(that.variant) : !that.hasVariant()) && (entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : that.entityTag == null) && (bucketEntityTag != null ? that.bucketEntityTag != null && this.bucketEntityTag.equals(that.bucketEntityTag) : that.bucketEntityTag == null); } @@ -157,7 +151,7 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaAxolotlBucket || this.isBucketEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaAxolotlBucket || isBucketEmpty()); } @Override @@ -165,11 +159,11 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasVariant()) { - hash = 61 * hash + this.variant; + if (hasVariant()) { + hash = 61 * hash + variant; } - if (this.entityTag != null) { - hash = 61 * hash + this.entityTag.hashCode(); + if (entityTag != null) { + hash = 61 * hash + entityTag.hashCode(); } if (bucketEntityTag != null) { hash = 61 * hash + bucketEntityTag.hashCode(); @@ -182,8 +176,8 @@ int applyHash() { public CraftMetaAxolotlBucket clone() { CraftMetaAxolotlBucket clone = (CraftMetaAxolotlBucket) super.clone(); - if (this.entityTag != null) { - clone.entityTag = this.entityTag.copy(); + if (entityTag != null) { + clone.entityTag = entityTag.copy(); } if (bucketEntityTag != null) { clone.bucketEntityTag = bucketEntityTag.copy(); @@ -196,8 +190,8 @@ public CraftMetaAxolotlBucket clone() { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.hasVariant()) { - builder.put(CraftMetaAxolotlBucket.VARIANT.BUKKIT, this.variant); + if (hasVariant()) { + builder.put(VARIANT.BUKKIT, variant); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java index 524aadad..74b62d6d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java @@ -3,16 +3,14 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Set; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.EnumColor; import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.bukkit.DyeColor; -import org.bukkit.Material; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -22,41 +20,6 @@ @DelegateDeserialization(SerializableMeta.class) public class CraftMetaBanner extends CraftMetaItem implements BannerMeta { - private static final Set BANNER_MATERIALS = Sets.newHashSet( - Material.BLACK_BANNER, - Material.BLACK_WALL_BANNER, - Material.BLUE_BANNER, - Material.BLUE_WALL_BANNER, - Material.BROWN_BANNER, - Material.BROWN_WALL_BANNER, - Material.CYAN_BANNER, - Material.CYAN_WALL_BANNER, - Material.GRAY_BANNER, - Material.GRAY_WALL_BANNER, - Material.GREEN_BANNER, - Material.GREEN_WALL_BANNER, - Material.LIGHT_BLUE_BANNER, - Material.LIGHT_BLUE_WALL_BANNER, - Material.LIGHT_GRAY_BANNER, - Material.LIGHT_GRAY_WALL_BANNER, - Material.LIME_BANNER, - Material.LIME_WALL_BANNER, - Material.MAGENTA_BANNER, - Material.MAGENTA_WALL_BANNER, - Material.ORANGE_BANNER, - Material.ORANGE_WALL_BANNER, - Material.PINK_BANNER, - Material.PINK_WALL_BANNER, - Material.PURPLE_BANNER, - Material.PURPLE_WALL_BANNER, - Material.RED_BANNER, - Material.RED_WALL_BANNER, - Material.WHITE_BANNER, - Material.WHITE_WALL_BANNER, - Material.YELLOW_BANNER, - Material.YELLOW_WALL_BANNER - ); - static final ItemMetaKeyType PATTERNS = new ItemMetaKeyType<>(DataComponents.BANNER_PATTERNS, "patterns"); private List patterns = new ArrayList(); @@ -69,16 +32,16 @@ public class CraftMetaBanner extends CraftMetaItem implements BannerMeta { } CraftMetaBanner banner = (CraftMetaBanner) meta; - this.patterns = new ArrayList(banner.patterns); + patterns = new ArrayList(banner.patterns); } CraftMetaBanner(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaBanner.PATTERNS).ifPresent((entityTag) -> { - List patterns = entityTag.layers(); + getOrEmpty(tag, PATTERNS).ifPresent((entityTag) -> { + List patterns = entityTag.layers(); for (int i = 0; i < Math.min(patterns.size(), 20); i++) { - BannerPatternLayers.Layer p = patterns.get(i); + BannerPatternLayers.b p = patterns.get(i); DyeColor color = DyeColor.getByWoolData((byte) p.color().getId()); PatternType pattern = CraftPatternType.minecraftHolderToBukkit(p.pattern()); @@ -92,14 +55,14 @@ public class CraftMetaBanner extends CraftMetaItem implements BannerMeta { CraftMetaBanner(Map map) { super(map); - Iterable rawPatternList = SerializableMeta.getObject(Iterable.class, map, CraftMetaBanner.PATTERNS.BUKKIT, true); + Iterable rawPatternList = SerializableMeta.getObject(Iterable.class, map, PATTERNS.BUKKIT, true); if (rawPatternList == null) { return; } for (Object obj : rawPatternList) { Preconditions.checkArgument(obj instanceof Pattern, "Object (%s) in pattern list is not valid", obj.getClass()); - this.addPattern((Pattern) obj); + addPattern((Pattern) obj); } } @@ -107,18 +70,18 @@ public class CraftMetaBanner extends CraftMetaItem implements BannerMeta { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - List newPatterns = new ArrayList<>(); + List newPatterns = new ArrayList<>(); - for (Pattern p : this.patterns) { - newPatterns.add(new BannerPatternLayers.Layer(CraftPatternType.bukkitToMinecraftHolder(p.getPattern()), net.minecraft.world.item.DyeColor.byId(p.getColor().getWoolData()))); + for (Pattern p : patterns) { + newPatterns.add(new BannerPatternLayers.b(CraftPatternType.bukkitToMinecraftHolder(p.getPattern()), EnumColor.byId(p.getColor().getWoolData()))); } - tag.put(CraftMetaBanner.PATTERNS, new BannerPatternLayers(newPatterns)); + tag.put(PATTERNS, new BannerPatternLayers(newPatterns)); } @Override public List getPatterns() { - return new ArrayList(this.patterns); + return new ArrayList(patterns); } @Override @@ -128,35 +91,35 @@ public void setPatterns(List patterns) { @Override public void addPattern(Pattern pattern) { - this.patterns.add(pattern); + patterns.add(pattern); } @Override public Pattern getPattern(int i) { - return this.patterns.get(i); + return patterns.get(i); } @Override public Pattern removePattern(int i) { - return this.patterns.remove(i); + return patterns.remove(i); } @Override public void setPattern(int i, Pattern pattern) { - this.patterns.set(i, pattern); + patterns.set(i, pattern); } @Override public int numberOfPatterns() { - return this.patterns.size(); + return patterns.size(); } @Override ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (!this.patterns.isEmpty()) { - builder.put(CraftMetaBanner.PATTERNS.BUKKIT, ImmutableList.copyOf(this.patterns)); + if (!patterns.isEmpty()) { + builder.put(PATTERNS.BUKKIT, ImmutableList.copyOf(patterns)); } return builder; @@ -166,8 +129,8 @@ ImmutableMap.Builder serialize(ImmutableMap.Builder(this.patterns); + meta.patterns = new ArrayList<>(patterns); return meta; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java index 0ca93154..a6a25ddd 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java @@ -4,8 +4,6 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; -import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Set; import net.minecraft.core.BlockPos; @@ -15,10 +13,12 @@ import net.minecraft.core.component.DataComponents; import net.minecraft.core.component.PatchedDataComponentMap; import net.minecraft.core.component.TypedDataComponent; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.item.EnumColor; import net.minecraft.world.item.component.CustomData; -import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.TileEntity; +import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -26,6 +26,7 @@ import org.bukkit.craftbukkit.block.CraftBlockStates; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.inventory.meta.BlockStateMeta; +import org.bukkit.util.BlockVector; @DelegateDeserialization(SerializableMeta.class) public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta { @@ -50,104 +51,13 @@ public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta Material.BLACK_SHULKER_BOX ); - private static final Set BLOCK_STATE_MATERIALS = Sets.newHashSet( - Material.FURNACE, - Material.CHEST, - Material.TRAPPED_CHEST, - Material.JUKEBOX, - Material.DISPENSER, - Material.DROPPER, - Material.ACACIA_HANGING_SIGN, - Material.ACACIA_SIGN, - Material.ACACIA_WALL_HANGING_SIGN, - Material.ACACIA_WALL_SIGN, - Material.BAMBOO_HANGING_SIGN, - Material.BAMBOO_SIGN, - Material.BAMBOO_WALL_HANGING_SIGN, - Material.BAMBOO_WALL_SIGN, - Material.BIRCH_HANGING_SIGN, - Material.BIRCH_SIGN, - Material.BIRCH_WALL_HANGING_SIGN, - Material.BIRCH_WALL_SIGN, - Material.CHERRY_HANGING_SIGN, - Material.CHERRY_SIGN, - Material.CHERRY_WALL_HANGING_SIGN, - Material.CHERRY_WALL_SIGN, - Material.CRIMSON_HANGING_SIGN, - Material.CRIMSON_SIGN, - Material.CRIMSON_WALL_HANGING_SIGN, - Material.CRIMSON_WALL_SIGN, - Material.DARK_OAK_HANGING_SIGN, - Material.DARK_OAK_SIGN, - Material.DARK_OAK_WALL_HANGING_SIGN, - Material.DARK_OAK_WALL_SIGN, - Material.JUNGLE_HANGING_SIGN, - Material.JUNGLE_SIGN, - Material.JUNGLE_WALL_HANGING_SIGN, - Material.JUNGLE_WALL_SIGN, - Material.MANGROVE_HANGING_SIGN, - Material.MANGROVE_SIGN, - Material.MANGROVE_WALL_HANGING_SIGN, - Material.MANGROVE_WALL_SIGN, - Material.OAK_HANGING_SIGN, - Material.OAK_SIGN, - Material.OAK_WALL_HANGING_SIGN, - Material.OAK_WALL_SIGN, - Material.SPRUCE_HANGING_SIGN, - Material.SPRUCE_SIGN, - Material.SPRUCE_WALL_HANGING_SIGN, - Material.SPRUCE_WALL_SIGN, - Material.WARPED_HANGING_SIGN, - Material.WARPED_SIGN, - Material.WARPED_WALL_HANGING_SIGN, - Material.WARPED_WALL_SIGN, - Material.SPAWNER, - Material.BREWING_STAND, - Material.ENCHANTING_TABLE, - Material.COMMAND_BLOCK, - Material.REPEATING_COMMAND_BLOCK, - Material.CHAIN_COMMAND_BLOCK, - Material.BEACON, - Material.DAYLIGHT_DETECTOR, - Material.HOPPER, - Material.COMPARATOR, - Material.SHIELD, - Material.STRUCTURE_BLOCK, - Material.ENDER_CHEST, - Material.BARREL, - Material.BELL, - Material.BLAST_FURNACE, - Material.CAMPFIRE, - Material.SOUL_CAMPFIRE, - Material.JIGSAW, - Material.LECTERN, - Material.SMOKER, - Material.BEEHIVE, - Material.BEE_NEST, - Material.SCULK_CATALYST, - Material.SCULK_SHRIEKER, - Material.CALIBRATED_SCULK_SENSOR, - Material.SCULK_SENSOR, - Material.CHISELED_BOOKSHELF, - Material.DECORATED_POT, - Material.SUSPICIOUS_SAND, - Material.SUSPICIOUS_GRAVEL, - Material.TRIAL_SPAWNER, - Material.CRAFTER, - Material.VAULT - ); - - static { - // Add shulker boxes to the list of block state materials too - BLOCK_STATE_MATERIALS.addAll(SHULKER_BOX_MATERIALS); - } - @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) static final ItemMetaKeyType BLOCK_ENTITY_TAG = new ItemMetaKeyType<>(DataComponents.BLOCK_ENTITY_DATA, "BlockEntityTag"); final Material material; private CraftBlockEntityState blockEntityTag; - private CompoundTag internalTag; + private BlockVector position; + private NBTTagCompound internalTag; CraftMetaBlockState(CraftMetaItem meta, Material material) { super(meta); @@ -155,26 +65,32 @@ public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta if (!(meta instanceof CraftMetaBlockState) || ((CraftMetaBlockState) meta).material != material) { - this.blockEntityTag = null; + blockEntityTag = null; return; } CraftMetaBlockState te = (CraftMetaBlockState) meta; this.blockEntityTag = te.blockEntityTag; + this.position = te.position; } CraftMetaBlockState(DataComponentPatch tag, Material material) { super(tag); this.material = material; - getOrEmpty(tag, CraftMetaBlockState.BLOCK_ENTITY_TAG).ifPresent((nbt) -> { - this.blockEntityTag = CraftMetaBlockState.getBlockState(material, nbt.copyTag()); + getOrEmpty(tag, BLOCK_ENTITY_TAG).ifPresent((blockTag) -> { + NBTTagCompound nbt = blockTag.copyTag(); + + blockEntityTag = getBlockState(material, nbt); + if (nbt.contains("x", CraftMagicNumbers.NBT.TAG_ANY_NUMBER) && nbt.contains("y", CraftMagicNumbers.NBT.TAG_ANY_NUMBER) && nbt.contains("z", CraftMagicNumbers.NBT.TAG_ANY_NUMBER)) { + position = new BlockVector(nbt.getInt("x"), nbt.getInt("y"), nbt.getInt("z")); + } }); if (!tag.isEmpty()) { CraftBlockEntityState blockEntityTag = this.blockEntityTag; if (blockEntityTag == null) { - blockEntityTag = CraftMetaBlockState.getBlockState(material, null); + blockEntityTag = getBlockState(material, null); } // Convert to map @@ -184,7 +100,7 @@ public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta Set> applied = blockEntityTag.applyComponents(map, tag); // Mark applied components as handled for (DataComponentType seen : applied) { - this.unhandledTags.clear(seen); + unhandledTags.clear(seen); } // Only set blockEntityTag if something was applied if (!applied.isEmpty()) { @@ -198,49 +114,72 @@ public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta String matName = SerializableMeta.getString(map, "blockMaterial", true); Material m = Material.getMaterial(matName); if (m != null) { - this.material = m; + material = m; } else { - this.material = Material.AIR; + material = Material.AIR; } if (internalTag != null) { blockEntityTag = getBlockState(material, internalTag); internalTag = null; } + position = SerializableMeta.getObject(BlockVector.class, map, "blockPosition", true); } @Override void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.blockEntityTag != null) { - tag.put(CraftMetaBlockState.BLOCK_ENTITY_TAG, CustomData.of(this.blockEntityTag.getSnapshotNBTWithoutComponents())); + NBTTagCompound nbt = null; + if (blockEntityTag != null) { + nbt = blockEntityTag.getItemNBT(); - for (TypedDataComponent component : this.blockEntityTag.collectComponents()) { + for (TypedDataComponent component : blockEntityTag.collectComponents()) { tag.putIfAbsent(component); } } + + if (position != null) { + if (nbt == null) { + nbt = new NBTTagCompound(); + } + + nbt.putInt("x", position.getBlockX()); + nbt.putInt("y", position.getBlockY()); + nbt.putInt("z", position.getBlockZ()); + } + + if (nbt != null && !nbt.isEmpty()) { + CraftBlockEntityState tile = (blockEntityTag != null) ? blockEntityTag : getBlockState(material, null); + // See ItemBlock#setBlockEntityData + tile.addEntityType(nbt); + + tag.put(BLOCK_ENTITY_TAG, CustomData.of(nbt)); + } } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaBlockState.BLOCK_ENTITY_TAG.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - this.internalTag = tag.getCompound(CraftMetaBlockState.BLOCK_ENTITY_TAG.NBT); + if (tag.contains(BLOCK_ENTITY_TAG.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { + internalTag = tag.getCompound(BLOCK_ENTITY_TAG.NBT); } } @Override - void serializeInternal(final Map internalTags) { - if (this.blockEntityTag != null) { - internalTags.put(CraftMetaBlockState.BLOCK_ENTITY_TAG.NBT, this.blockEntityTag.getSnapshotNBT()); + void serializeInternal(final Map internalTags) { + if (blockEntityTag != null) { + internalTags.put(BLOCK_ENTITY_TAG.NBT, blockEntityTag.getSnapshotNBT()); } } @Override ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - builder.put("blockMaterial", this.material.name()); + builder.put("blockMaterial", material.name()); + if (position != null) { + builder.put("blockPosition", position); + } return builder; } @@ -248,9 +187,12 @@ ImmutableMap.Builder serialize(ImmutableMap.Builder getBlockState(Material material, CompoundTag blockEntityTag) { + private static CraftBlockEntityState getBlockState(Material material, NBTTagCompound blockEntityTag) { BlockPos pos = BlockPos.ZERO; - Material stateMaterial = (material != Material.SHIELD) ? material : CraftMetaBlockState.shieldToBannerHack(); // Only actually used for jigsaws + Material stateMaterial = (material != Material.SHIELD) ? material : shieldToBannerHack(blockEntityTag); // Only actually used for jigsaws if (blockEntityTag != null) { if (material == Material.SHIELD) { blockEntityTag.putString("id", "minecraft:banner"); } else if (material == Material.BEE_NEST || material == Material.BEEHIVE) { blockEntityTag.putString("id", "minecraft:beehive"); - } else if (CraftMetaBlockState.SHULKER_BOX_MATERIALS.contains(material)) { + } else if (SHULKER_BOX_MATERIALS.contains(material)) { blockEntityTag.putString("id", "minecraft:shulker_box"); } - pos = BlockEntity.getPosFromTag(blockEntityTag); + pos = TileEntity.getPosFromTag(blockEntityTag); } // This is expected to always return a CraftBlockEntityState for the passed material: @@ -324,14 +268,25 @@ private static CraftBlockEntityState getBlockState(Material material, Compoun public void setBlockState(BlockState blockState) { Preconditions.checkArgument(blockState != null, "blockState must not be null"); - Material stateMaterial = (this.material != Material.SHIELD) ? this.material : CraftMetaBlockState.shieldToBannerHack(); + Material stateMaterial = (material != Material.SHIELD) ? material : shieldToBannerHack(null); Class blockStateType = CraftBlockStates.getBlockStateType(stateMaterial); - Preconditions.checkArgument(blockStateType == blockState.getClass() && blockState instanceof CraftBlockEntityState, "Invalid blockState for " + this.material); + Preconditions.checkArgument(blockStateType == blockState.getClass() && blockState instanceof CraftBlockEntityState, "Invalid blockState for %s", material); this.blockEntityTag = (CraftBlockEntityState) blockState; } - private static Material shieldToBannerHack() { + private static Material shieldToBannerHack(NBTTagCompound tag) { + if (tag != null) { + if (tag.contains("components", CraftMagicNumbers.NBT.TAG_COMPOUND)) { + NBTTagCompound components = tag.getCompound("components"); + if (components.contains("minecraft:base_color", CraftMagicNumbers.NBT.TAG_STRING)) { + DyeColor color = DyeColor.getByWoolData((byte) EnumColor.byName(components.getString("minecraft:base_color"), EnumColor.WHITE).getId()); + + return CraftMetaShield.shieldToBannerHack(color); + } + } + } + return Material.WHITE_BANNER; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java index 3ab6b212..d338430f 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java @@ -11,7 +11,6 @@ import java.util.Objects; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.network.chat.Component; import net.minecraft.server.network.Filterable; import net.minecraft.server.network.FilteredText; import net.minecraft.world.item.component.WritableBookContent; @@ -21,13 +20,6 @@ import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.WritableBookMeta; -// Spigot start -import java.util.AbstractList; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.chat.ComponentSerializer; -import org.bukkit.craftbukkit.util.CraftChatMessage; -// Spigot end - @DelegateDeserialization(SerializableMeta.class) public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBookMeta { @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) @@ -49,7 +41,7 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo if (bookMeta.pages != null) { this.pages = new ArrayList(bookMeta.pages.size()); - this.pages.addAll(bookMeta.pages); + pages.addAll(bookMeta.pages); } } else if (meta instanceof CraftMetaBookSigned) { CraftMetaBookSigned bookMeta = (CraftMetaBookSigned) meta; @@ -58,7 +50,7 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo this.pages = new ArrayList(bookMeta.pages.size()); // Convert from JSON to plain Strings: - this.pages.addAll(Lists.transform(bookMeta.pages, CraftChatMessage::fromComponent)); + pages.addAll(Lists.transform(bookMeta.pages, CraftChatMessage::fromComponent)); } } } @@ -66,15 +58,15 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo CraftMetaBook(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaBook.BOOK_CONTENT).ifPresent((writable) -> { + getOrEmpty(tag, BOOK_CONTENT).ifPresent((writable) -> { List> pages = writable.pages(); this.pages = new ArrayList(pages.size()); // Note: We explicitly check for and truncate oversized books and pages, // because they can come directly from clients when handling book edits. - for (int i = 0; i < Math.min(pages.size(), CraftMetaBook.MAX_PAGES); i++) { + for (int i = 0; i < Math.min(pages.size(), MAX_PAGES); i++) { String page = pages.get(i).raw(); - page = this.validatePage(page); + page = validatePage(page); this.pages.add(page); } @@ -84,12 +76,12 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo CraftMetaBook(Map map) { super(map); - Iterable pages = SerializableMeta.getObject(Iterable.class, map, CraftMetaBook.BOOK_PAGES.BUKKIT, true); + Iterable pages = SerializableMeta.getObject(Iterable.class, map, BOOK_PAGES.BUKKIT, true); if (pages != null) { this.pages = new ArrayList(); for (Object page : pages) { if (page instanceof String) { - this.internalAddPage(this.validatePage((String) page)); + internalAddPage(validatePage((String) page)); } } } @@ -99,22 +91,22 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo void applyToItem(CraftMetaItem.Applicator itemData) { super.applyToItem(itemData); - if (this.pages != null) { + if (pages != null) { List> list = new ArrayList<>(); - for (String page : this.pages) { + for (String page : pages) { list.add(Filterable.from(FilteredText.passThrough(page))); } - itemData.put(CraftMetaBook.BOOK_CONTENT, new WritableBookContent(list)); + itemData.put(BOOK_CONTENT, new WritableBookContent(list)); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isBookEmpty(); + return super.isEmpty() && isBookEmpty(); } boolean isBookEmpty() { - return !(this.pages != null); + return !(pages != null); } @Override @@ -134,7 +126,7 @@ public boolean hasTitle() { @Override public boolean hasPages() { - return (this.pages != null) && !this.pages.isEmpty(); + return (pages != null) && !pages.isEmpty(); } @Override @@ -172,38 +164,38 @@ public void setGeneration(Generation generation) { @Override public String getPage(final int page) { - Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s)", page); + Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s)", page); // assert: pages != null - return this.pages.get(page - 1); + return pages.get(page - 1); } @Override public void setPage(final int page, final String text) { - Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s/%s)", page, this.getPageCount()); + Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s/%s)", page, getPageCount()); // assert: pages != null - String newText = this.validatePage(text); - this.pages.set(page - 1, newText); + String newText = validatePage(text); + pages.set(page - 1, newText); } @Override public void setPages(final String... pages) { - this.setPages(Arrays.asList(pages)); + setPages(Arrays.asList(pages)); } @Override public void addPage(final String... pages) { for (String page : pages) { - page = this.validatePage(page); - this.internalAddPage(page); + page = validatePage(page); + internalAddPage(page); } } String validatePage(String page) { if (page == null) { page = ""; - } else if (page.length() > CraftMetaBook.MAX_PAGE_LENGTH) { - page = page.substring(0, CraftMetaBook.MAX_PAGE_LENGTH); + } else if (page.length() > MAX_PAGE_LENGTH) { + page = page.substring(0, MAX_PAGE_LENGTH); } return page; } @@ -212,7 +204,7 @@ private void internalAddPage(String page) { // asserted: page != null if (this.pages == null) { this.pages = new ArrayList(); - } else if (this.pages.size() >= CraftMetaBook.MAX_PAGES) { + } else if (this.pages.size() >= MAX_PAGES) { return; } this.pages.add(page); @@ -220,13 +212,13 @@ private void internalAddPage(String page) { @Override public int getPageCount() { - return (this.pages == null) ? 0 : this.pages.size(); + return (pages == null) ? 0 : pages.size(); } @Override public List getPages() { - if (this.pages == null) return ImmutableList.of(); - return this.pages.stream().collect(ImmutableList.toImmutableList()); + if (pages == null) return ImmutableList.of(); + return pages.stream().collect(ImmutableList.toImmutableList()); } @Override @@ -240,12 +232,12 @@ public void setPages(List pages) { this.pages.clear(); } for (String page : pages) { - this.addPage(page); + addPage(page); } } private boolean isValidPage(int page) { - return page > 0 && page <= this.getPageCount(); + return page > 0 && page <= getPageCount(); } @Override @@ -254,7 +246,6 @@ public CraftMetaBook clone() { if (this.pages != null) { meta.pages = new ArrayList(this.pages); } - meta.spigot = meta.new SpigotMeta(); // Spigot return meta; } @@ -282,106 +273,17 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaBook || this.isBookEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaBook || isBookEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.pages != null) { - builder.put(CraftMetaBook.BOOK_PAGES.BUKKIT, ImmutableList.copyOf(this.pages)); + if (pages != null) { + builder.put(BOOK_PAGES.BUKKIT, ImmutableList.copyOf(pages)); } return builder; } - - // Spigot start - private BookMeta.Spigot spigot = new SpigotMeta(); - private class SpigotMeta extends BookMeta.Spigot { - - private String pageToJSON(String page) { - // Convert from plain String to JSON (similar to conversion between writable books and written books): - Component component = CraftChatMessage.fromString(page, true, true)[0]; - return CraftChatMessage.toJSON(component); - } - - private String componentsToPage(BaseComponent[] components) { - // Convert component to plain String: - Component component = CraftChatMessage.fromJSONOrNull(ComponentSerializer.toString(components)); - return CraftChatMessage.fromComponent(component); - } - - @Override - public BaseComponent[] getPage(final int page) { - Preconditions.checkArgument(CraftMetaBook.this.isValidPage(page), "Invalid page number"); - return ComponentSerializer.parse(this.pageToJSON(CraftMetaBook.this.pages.get(page - 1))); - } - - @Override - public void setPage(final int page, final BaseComponent... text) { - if (!CraftMetaBook.this.isValidPage(page)) { - throw new IllegalArgumentException("Invalid page number " + page + "/" + CraftMetaBook.this.getPageCount()); - } - - BaseComponent[] newText = text == null ? new BaseComponent[0] : text; - CraftMetaBook.this.pages.set(page - 1, this.componentsToPage(newText)); - } - - @Override - public void setPages(final BaseComponent[]... pages) { - this.setPages(Arrays.asList(pages)); - } - - @Override - public void addPage(final BaseComponent[]... pages) { - for (BaseComponent[] page : pages) { - if (page == null) { - page = new BaseComponent[0]; - } - - CraftMetaBook.this.internalAddPage(this.componentsToPage(page)); - } - } - - @Override - public List getPages() { - if (CraftMetaBook.this.pages == null) return ImmutableList.of(); - final List copy = ImmutableList.copyOf(CraftMetaBook.this.pages); - return new AbstractList() { - - @Override - public BaseComponent[] get(int index) { - return ComponentSerializer.parse(SpigotMeta.this.pageToJSON(copy.get(index))); - } - - @Override - public int size() { - return copy.size(); - } - }; - } - - @Override - public void setPages(List pages) { - if (pages.isEmpty()) { - CraftMetaBook.this.pages = null; - return; - } - - if (CraftMetaBook.this.pages != null) { - CraftMetaBook.this.pages.clear(); - } - - for (BaseComponent[] page : pages) { - this.addPage(page); - } - } - }; - - @Override - public BookMeta.Spigot spigot() { - return this.spigot; - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java index 4a711373..7a7c7192 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java @@ -11,7 +11,7 @@ import java.util.Objects; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.server.network.Filterable; import net.minecraft.server.network.FilteredText; import net.minecraft.world.item.component.WritableBookContent; @@ -21,12 +21,6 @@ import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.inventory.meta.BookMeta; -// Spigot start -import java.util.AbstractList; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.chat.ComponentSerializer; -// Spigot end - @DelegateDeserialization(SerializableMeta.class) public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta { @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) @@ -43,7 +37,7 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta { protected String title; protected String author; // Stored as components and serialized as JSON. See SPIGOT-5063, SPIGOT-5350, SPIGOT-3206 - protected List pages; // null and empty are two different states internally + protected List pages; // null and empty are two different states internally protected boolean resolved; protected int generation; @@ -58,21 +52,21 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta { this.generation = bookMeta.generation; if (bookMeta.pages != null) { - this.pages = new ArrayList(bookMeta.pages.size()); - this.pages.addAll(bookMeta.pages); + this.pages = new ArrayList(bookMeta.pages.size()); + pages.addAll(bookMeta.pages); } } else if (meta instanceof CraftMetaBook) { CraftMetaBook bookMeta = (CraftMetaBook) meta; if (bookMeta.pages != null) { - this.pages = new ArrayList(bookMeta.pages.size()); + this.pages = new ArrayList(bookMeta.pages.size()); // Convert from plain Strings to JSON: // This happens for example during book signing. for (String page : bookMeta.pages) { // We don't insert any non-plain text features (such as clickable links) during this conversion. - Component component = CraftChatMessage.fromString(page, true, true)[0]; - this.pages.add(component); + IChatBaseComponent component = CraftChatMessage.fromString(page, true, true)[0]; + pages.add(component); } } } @@ -81,18 +75,18 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta { CraftMetaBookSigned(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaBookSigned.BOOK_CONTENT).ifPresent((written) -> { + getOrEmpty(tag, BOOK_CONTENT).ifPresent((written) -> { this.title = written.title().raw(); this.author = written.author(); this.resolved = written.resolved(); this.generation = written.generation(); - List> pages = written.pages(); - this.pages = new ArrayList(pages.size()); + List> pages = written.pages(); + this.pages = new ArrayList(pages.size()); // Note: We explicitly check for and truncate oversized books and pages, // because they can come directly from clients when handling book edits. - for (int i = 0; i < Math.min(pages.size(), CraftMetaBookSigned.MAX_PAGES); i++) { - Component page = pages.get(i).raw(); + for (int i = 0; i < Math.min(pages.size(), MAX_PAGES); i++) { + IChatBaseComponent page = pages.get(i).raw(); this.pages.add(page); } @@ -102,13 +96,13 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta { CraftMetaBookSigned(Map map) { super(map); - this.setAuthor(SerializableMeta.getString(map, CraftMetaBookSigned.BOOK_AUTHOR.BUKKIT, true)); + setAuthor(SerializableMeta.getString(map, BOOK_AUTHOR.BUKKIT, true)); - this.setTitle(SerializableMeta.getString(map, CraftMetaBookSigned.BOOK_TITLE.BUKKIT, true)); + setTitle(SerializableMeta.getString(map, BOOK_TITLE.BUKKIT, true)); - Iterable pages = SerializableMeta.getObject(Iterable.class, map, CraftMetaBookSigned.BOOK_PAGES.BUKKIT, true); + Iterable pages = SerializableMeta.getObject(Iterable.class, map, BOOK_PAGES.BUKKIT, true); if (pages != null) { - this.pages = new ArrayList(); + this.pages = new ArrayList(); for (Object page : pages) { if (page instanceof String) { internalAddPage(CraftChatMessage.fromJSONOrString((String) page, false, true, MAX_PAGE_LENGTH, false)); @@ -124,22 +118,22 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta { void applyToItem(CraftMetaItem.Applicator itemData) { super.applyToItem(itemData); - if (this.pages != null) { - List> list = new ArrayList<>(); - for (Component page : this.pages) { + if (pages != null) { + List> list = new ArrayList<>(); + for (IChatBaseComponent page : pages) { list.add(Filterable.passThrough(page)); } - itemData.put(CraftMetaBookSigned.BOOK_CONTENT, new WrittenBookContent(Filterable.from(FilteredText.passThrough(this.title)), this.author, this.generation, list, this.resolved)); + itemData.put(BOOK_CONTENT, new WrittenBookContent(Filterable.from(FilteredText.passThrough(title)), this.author, this.generation, list, this.resolved)); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isBookEmpty(); + return super.isEmpty() && isBookEmpty(); } boolean isBookEmpty() { - return !((this.pages != null) || this.hasAuthor() || this.hasTitle() || this.hasGeneration() || this.resolved); + return !((pages != null) || hasAuthor() || hasTitle() || hasGeneration() || resolved); } @Override @@ -159,12 +153,12 @@ public boolean hasTitle() { @Override public boolean hasPages() { - return (this.pages != null) && !this.pages.isEmpty(); + return (pages != null) && !pages.isEmpty(); } @Override public boolean hasGeneration() { - return this.generation != 0; + return generation != 0; } @Override @@ -177,7 +171,7 @@ public boolean setTitle(final String title) { if (title == null) { this.title = null; return true; - } else if (title.length() > CraftMetaBookSigned.MAX_TITLE_LENGTH) { + } else if (title.length() > MAX_TITLE_LENGTH) { return false; } @@ -197,7 +191,7 @@ public void setAuthor(final String author) { @Override public Generation getGeneration() { - return Generation.values()[this.generation]; + return Generation.values()[generation]; } @Override @@ -207,47 +201,47 @@ public void setGeneration(Generation generation) { @Override public String getPage(final int page) { - Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s)", page); + Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s)", page); // assert: pages != null - return CraftChatMessage.fromComponent(this.pages.get(page - 1)); + return CraftChatMessage.fromComponent(pages.get(page - 1)); } @Override public void setPage(final int page, final String text) { - Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s/%s)", page, this.getPageCount()); + Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s/%s)", page, getPageCount()); // assert: pages != null - String newText = this.validatePage(text); - this.pages.set(page - 1, CraftChatMessage.fromStringOrEmpty(newText, true)); + String newText = validatePage(text); + pages.set(page - 1, CraftChatMessage.fromStringOrEmpty(newText, true)); } @Override public void setPages(final String... pages) { - this.setPages(Arrays.asList(pages)); + setPages(Arrays.asList(pages)); } @Override public void addPage(final String... pages) { for (String page : pages) { - page = this.validatePage(page); - this.internalAddPage(CraftChatMessage.fromStringOrEmpty(page, true)); + page = validatePage(page); + internalAddPage(CraftChatMessage.fromStringOrEmpty(page, true)); } } String validatePage(String page) { if (page == null) { page = ""; - } else if (page.length() > CraftMetaBookSigned.MAX_PAGE_LENGTH) { - page = page.substring(0, CraftMetaBookSigned.MAX_PAGE_LENGTH); + } else if (page.length() > MAX_PAGE_LENGTH) { + page = page.substring(0, MAX_PAGE_LENGTH); } return page; } - private void internalAddPage(Component page) { + private void internalAddPage(IChatBaseComponent page) { // asserted: page != null if (this.pages == null) { - this.pages = new ArrayList(); - } else if (this.pages.size() >= CraftMetaBookSigned.MAX_PAGES) { + this.pages = new ArrayList(); + } else if (this.pages.size() >= MAX_PAGES) { return; } this.pages.add(page); @@ -255,13 +249,13 @@ private void internalAddPage(Component page) { @Override public int getPageCount() { - return (this.pages == null) ? 0 : this.pages.size(); + return (pages == null) ? 0 : pages.size(); } @Override public List getPages() { - if (this.pages == null) return ImmutableList.of(); - return this.pages.stream().map(CraftChatMessage::fromComponent).collect(ImmutableList.toImmutableList()); + if (pages == null) return ImmutableList.of(); + return pages.stream().map(CraftChatMessage::fromComponent).collect(ImmutableList.toImmutableList()); } @Override @@ -275,17 +269,17 @@ public void setPages(List pages) { this.pages.clear(); } for (String page : pages) { - this.addPage(page); + addPage(page); } } private boolean isValidPage(int page) { - return page > 0 && page <= this.getPageCount(); + return page > 0 && page <= getPageCount(); } // TODO Expose this attribute in Bukkit? public boolean isResolved() { - return this.resolved; + return resolved; } public void setResolved(boolean resolved) { @@ -296,9 +290,8 @@ public void setResolved(boolean resolved) { public CraftMetaBookSigned clone() { CraftMetaBookSigned meta = (CraftMetaBookSigned) super.clone(); if (this.pages != null) { - meta.pages = new ArrayList(this.pages); + meta.pages = new ArrayList(this.pages); } - meta.spigot = meta.new SpigotMeta(); // Spigot return meta; } @@ -306,10 +299,10 @@ public CraftMetaBookSigned clone() { int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasTitle()) { + if (hasTitle()) { hash = 61 * hash + this.title.hashCode(); } - if (this.hasAuthor()) { + if (hasAuthor()) { hash = 61 * hash + 13 * this.author.hashCode(); } if (this.pages != null) { @@ -318,7 +311,7 @@ int applyHash() { if (this.resolved) { hash = 61 * hash + 17 * Boolean.hashCode(this.resolved); } - if (this.hasGeneration()) { + if (hasGeneration()) { hash = 61 * hash + 19 * Integer.hashCode(this.generation); } return original != hash ? CraftMetaBook.class.hashCode() ^ hash : hash; @@ -331,8 +324,8 @@ boolean equalsCommon(CraftMetaItem meta) { } if (meta instanceof CraftMetaBookSigned that) { - return (this.hasTitle() ? that.hasTitle() && this.title.equals(that.title) : !that.hasTitle()) - && (this.hasAuthor() ? that.hasAuthor() && this.author.equals(that.author) : !that.hasAuthor()) + return (hasTitle() ? that.hasTitle() && this.title.equals(that.title) : !that.hasTitle()) + && (hasAuthor() ? that.hasAuthor() && this.author.equals(that.author) : !that.hasAuthor()) && (Objects.equals(this.pages, that.pages)) && (Objects.equals(this.resolved, that.resolved)) && (Objects.equals(this.generation, that.generation)); @@ -342,121 +335,33 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaBookSigned || this.isBookEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaBookSigned || isBookEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasTitle()) { - builder.put(CraftMetaBookSigned.BOOK_TITLE.BUKKIT, this.title); + if (hasTitle()) { + builder.put(BOOK_TITLE.BUKKIT, title); } - if (this.hasAuthor()) { - builder.put(CraftMetaBookSigned.BOOK_AUTHOR.BUKKIT, this.author); + if (hasAuthor()) { + builder.put(BOOK_AUTHOR.BUKKIT, author); } - if (this.pages != null) { - builder.put(CraftMetaBookSigned.BOOK_PAGES.BUKKIT, ImmutableList.copyOf(Lists.transform(pages, CraftChatMessage::toJSON))); + if (pages != null) { + builder.put(BOOK_PAGES.BUKKIT, ImmutableList.copyOf(Lists.transform(pages, CraftChatMessage::toJSON))); } - if (this.resolved) { - builder.put(CraftMetaBookSigned.RESOLVED.BUKKIT, this.resolved); + if (resolved) { + builder.put(RESOLVED.BUKKIT, resolved); } - if (this.generation != 0) { - builder.put(CraftMetaBookSigned.GENERATION.BUKKIT, this.generation); + if (generation != 0) { + builder.put(GENERATION.BUKKIT, generation); } return builder; } - - // Spigot start - private BookMeta.Spigot spigot = new SpigotMeta(); - private class SpigotMeta extends BookMeta.Spigot { - - private String pageToJSON(Component page) { - // Page data is already in JSON format: - return CraftChatMessage.toJSON(page); - } - - private Component componentsToPage(BaseComponent[] components) { - // asserted: components != null - // Pages are in JSON format: - return CraftChatMessage.fromJSON(ComponentSerializer.toString(components)); - } - - @Override - public BaseComponent[] getPage(final int page) { - Preconditions.checkArgument(CraftMetaBookSigned.this.isValidPage(page), "Invalid page number"); - return ComponentSerializer.parse(this.pageToJSON(CraftMetaBookSigned.this.pages.get(page - 1))); - } - - @Override - public void setPage(final int page, final BaseComponent... text) { - if (!CraftMetaBookSigned.this.isValidPage(page)) { - throw new IllegalArgumentException("Invalid page number " + page + "/" + CraftMetaBookSigned.this.getPageCount()); - } - - BaseComponent[] newText = text == null ? new BaseComponent[0] : text; - CraftMetaBookSigned.this.pages.set(page - 1, this.componentsToPage(newText)); - } - - @Override - public void setPages(final BaseComponent[]... pages) { - this.setPages(Arrays.asList(pages)); - } - - @Override - public void addPage(final BaseComponent[]... pages) { - for (BaseComponent[] page : pages) { - if (page == null) { - page = new BaseComponent[0]; - } - - CraftMetaBookSigned.this.internalAddPage(this.componentsToPage(page)); - } - } - - @Override - public List getPages() { - if (CraftMetaBookSigned.this.pages == null) return ImmutableList.of(); - final List copy = ImmutableList.copyOf(CraftMetaBookSigned.this.pages); - return new AbstractList() { - - @Override - public BaseComponent[] get(int index) { - return ComponentSerializer.parse(SpigotMeta.this.pageToJSON(copy.get(index))); - } - - @Override - public int size() { - return copy.size(); - } - }; - } - - @Override - public void setPages(List pages) { - if (pages.isEmpty()) { - CraftMetaBookSigned.this.pages = null; - return; - } - - if (CraftMetaBookSigned.this.pages != null) { - CraftMetaBookSigned.this.pages.clear(); - } - - for (BaseComponent[] page : pages) { - this.addPage(page); - } - } - }; - - @Override - public BookMeta.Spigot spigot() { - return this.spigot; - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBundle.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBundle.java index dfaec374..f1ad91a9 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBundle.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBundle.java @@ -9,7 +9,6 @@ import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.component.BundleContents; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BundleMeta; @@ -38,12 +37,12 @@ public class CraftMetaBundle extends CraftMetaItem implements BundleMeta { CraftMetaBundle(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaBundle.ITEMS).ifPresent((bundle) -> { + getOrEmpty(tag, ITEMS).ifPresent((bundle) -> { bundle.items().forEach((item) -> { ItemStack itemStack = CraftItemStack.asCraftMirror(item); if (!itemStack.getType().isAir()) { // SPIGOT-7174 - Avoid adding air - this.addItem(itemStack); + addItem(itemStack); } }); }); @@ -52,11 +51,11 @@ public class CraftMetaBundle extends CraftMetaItem implements BundleMeta { CraftMetaBundle(Map map) { super(map); - Iterable items = SerializableMeta.getObject(Iterable.class, map, CraftMetaBundle.ITEMS.BUKKIT, true); + Iterable items = SerializableMeta.getObject(Iterable.class, map, ITEMS.BUKKIT, true); if (items != null) { for (Object stack : items) { if (stack instanceof ItemStack itemStack && !itemStack.getType().isAir()) { // SPIGOT-7174 - Avoid adding air - this.addItem(itemStack); + addItem(itemStack); } } } @@ -66,39 +65,34 @@ public class CraftMetaBundle extends CraftMetaItem implements BundleMeta { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.hasItems()) { + if (hasItems()) { List list = new ArrayList<>(); - for (ItemStack item : this.items) { + for (ItemStack item : items) { list.add(CraftItemStack.asNMSCopy(item)); } - tag.put(CraftMetaBundle.ITEMS, new BundleContents(list)); + tag.put(ITEMS, new BundleContents(list)); } } - @Override - boolean applicableTo(Material type) { - return type == Material.BUNDLE; - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isBundleEmpty(); + return super.isEmpty() && isBundleEmpty(); } boolean isBundleEmpty() { - return !(this.hasItems()); + return !(hasItems()); } @Override public boolean hasItems() { - return this.items != null && !this.items.isEmpty(); + return items != null && !items.isEmpty(); } @Override public List getItems() { - return (this.items == null) ? ImmutableList.of() : ImmutableList.copyOf(this.items); + return (items == null) ? ImmutableList.of() : ImmutableList.copyOf(items); } @Override @@ -110,7 +104,7 @@ public void setItems(List items) { } for (ItemStack i : items) { - this.addItem(i); + addItem(i); } } @@ -118,11 +112,11 @@ public void setItems(List items) { public void addItem(ItemStack item) { Preconditions.checkArgument(item != null && !item.getType().isAir(), "item is null or air"); - if (this.items == null) { - this.items = new ArrayList<>(); + if (items == null) { + items = new ArrayList<>(); } - this.items.add(item); + items.add(item); } @Override @@ -133,14 +127,14 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaBundle) { CraftMetaBundle that = (CraftMetaBundle) meta; - return (this.hasItems() ? that.hasItems() && this.items.equals(that.items) : !that.hasItems()); + return (hasItems() ? that.hasItems() && this.items.equals(that.items) : !that.hasItems()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaBundle || this.isBundleEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaBundle || isBundleEmpty()); } @Override @@ -148,8 +142,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasItems()) { - hash = 61 * hash + this.items.hashCode(); + if (hasItems()) { + hash = 61 * hash + items.hashCode(); } return original != hash ? CraftMetaBundle.class.hashCode() ^ hash : hash; @@ -164,8 +158,8 @@ public CraftMetaBundle clone() { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.hasItems()) { - builder.put(CraftMetaBundle.ITEMS.BUKKIT, this.items); + if (hasItems()) { + builder.put(ITEMS.BUKKIT, items); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java index 40d55374..2e3e70b8 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java @@ -6,7 +6,6 @@ import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.component.FireworkExplosion; import org.bukkit.FireworkEffect; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.inventory.meta.FireworkEffectMeta; @@ -20,22 +19,22 @@ class CraftMetaCharge extends CraftMetaItem implements FireworkEffectMeta { super(meta); if (meta instanceof CraftMetaCharge) { - this.effect = ((CraftMetaCharge) meta).effect; + effect = ((CraftMetaCharge) meta).effect; } } CraftMetaCharge(Map map) { super(map); - this.setEffect(SerializableMeta.getObject(FireworkEffect.class, map, CraftMetaCharge.EXPLOSION.BUKKIT, true)); + setEffect(SerializableMeta.getObject(FireworkEffect.class, map, EXPLOSION.BUKKIT, true)); } CraftMetaCharge(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaCharge.EXPLOSION).ifPresent((f) -> { + getOrEmpty(tag, EXPLOSION).ifPresent((f) -> { try { - this.effect = CraftMetaFirework.getEffect(f); + effect = CraftMetaFirework.getEffect(f); } catch (IllegalArgumentException ex) { // Ignore invalid effects } @@ -49,35 +48,30 @@ public void setEffect(FireworkEffect effect) { @Override public boolean hasEffect() { - return this.effect != null; + return effect != null; } @Override public FireworkEffect getEffect() { - return this.effect; + return effect; } @Override void applyToItem(CraftMetaItem.Applicator itemTag) { super.applyToItem(itemTag); - if (this.hasEffect()) { - itemTag.put(CraftMetaCharge.EXPLOSION, CraftMetaFirework.getExplosion(this.effect)); + if (hasEffect()) { + itemTag.put(EXPLOSION, CraftMetaFirework.getExplosion(effect)); } } - @Override - boolean applicableTo(Material type) { - return type == Material.FIREWORK_STAR; - } - @Override boolean isEmpty() { - return super.isEmpty() && !this.hasChargeMeta(); + return super.isEmpty() && !hasChargeMeta(); } boolean hasChargeMeta() { - return this.hasEffect(); + return hasEffect(); } @Override @@ -88,14 +82,14 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaCharge) { CraftMetaCharge that = (CraftMetaCharge) meta; - return (this.hasEffect() ? that.hasEffect() && this.effect.equals(that.effect) : !that.hasEffect()); + return (hasEffect() ? that.hasEffect() && this.effect.equals(that.effect) : !that.hasEffect()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaCharge || !this.hasChargeMeta()); + return super.notUncommon(meta) && (meta instanceof CraftMetaCharge || !hasChargeMeta()); } @Override @@ -103,8 +97,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasEffect()) { - hash = 61 * hash + this.effect.hashCode(); + if (hasEffect()) { + hash = 61 * hash + effect.hashCode(); } return hash != original ? CraftMetaCharge.class.hashCode() ^ hash : hash; @@ -119,8 +113,8 @@ public CraftMetaCharge clone() { Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasEffect()) { - builder.put(CraftMetaCharge.EXPLOSION.BUKKIT, this.effect); + if (hasEffect()) { + builder.put(EXPLOSION.BUKKIT, effect); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaColorableArmor.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaColorableArmor.java index c74d5976..fb4fe1d2 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaColorableArmor.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaColorableArmor.java @@ -2,26 +2,15 @@ import static org.bukkit.craftbukkit.inventory.CraftItemFactory.*; import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.collect.Sets; import java.util.Map; -import java.util.Set; import net.minecraft.core.component.DataComponentPatch; import org.bukkit.Color; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.inventory.meta.ColorableArmorMeta; @DelegateDeserialization(SerializableMeta.class) public class CraftMetaColorableArmor extends CraftMetaArmor implements ColorableArmorMeta { - private static final Set LEATHER_ARMOR_MATERIALS = Sets.newHashSet( - Material.LEATHER_HELMET, - Material.LEATHER_CHESTPLATE, - Material.LEATHER_LEGGINGS, - Material.LEATHER_BOOTS, - Material.WOLF_ARMOR - ); - private Color color = DEFAULT_LEATHER_COLOR; CraftMetaColorableArmor(CraftMetaItem meta) { @@ -47,16 +36,11 @@ void applyToItem(CraftMetaItem.Applicator itemTag) { @Override boolean isEmpty() { - return super.isEmpty() && this.isLeatherArmorEmpty(); + return super.isEmpty() && isLeatherArmorEmpty(); } boolean isLeatherArmorEmpty() { - return !(this.hasColor()); - } - - @Override - boolean applicableTo(Material type) { - return CraftMetaColorableArmor.LEATHER_ARMOR_MATERIALS.contains(type); + return !(hasColor()); } @Override @@ -68,7 +52,7 @@ public CraftMetaColorableArmor clone() { @Override public Color getColor() { - return this.color; + return color; } @Override @@ -97,22 +81,22 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaColorableArmor) { CraftMetaColorableArmor that = (CraftMetaColorableArmor) meta; - return this.color.equals(that.color); + return color.equals(that.color); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaColorableArmor || this.isLeatherArmorEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaColorableArmor || isLeatherArmorEmpty()); } @Override int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasColor()) { - hash ^= this.color.hashCode(); + if (hasColor()) { + hash ^= color.hashCode(); } return original != hash ? CraftMetaColorableArmor.class.hashCode() ^ hash : hash; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCompass.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCompass.java index 820b4e61..9dd3d25d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCompass.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCompass.java @@ -9,13 +9,12 @@ import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; +import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.WorldServer; import net.minecraft.world.item.component.LodestoneTracker; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.World; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.CraftWorld; @@ -32,7 +31,7 @@ public class CraftMetaCompass extends CraftMetaItem implements CompassMeta { static final ItemMetaKey LODESTONE_POS_Z = new ItemMetaKey("LodestonePosZ"); static final ItemMetaKey LODESTONE_TRACKED = new ItemMetaKey("LodestoneTracked"); - private ResourceKey lodestoneWorld; + private ResourceKey lodestoneWorld; private int lodestoneX; private int lodestoneY; private int lodestoneZ; @@ -44,43 +43,43 @@ public class CraftMetaCompass extends CraftMetaItem implements CompassMeta { return; } CraftMetaCompass compassMeta = (CraftMetaCompass) meta; - this.lodestoneWorld = compassMeta.lodestoneWorld; - this.lodestoneX = compassMeta.lodestoneX; - this.lodestoneY = compassMeta.lodestoneY; - this.lodestoneZ = compassMeta.lodestoneZ; - this.tracked = compassMeta.tracked; + lodestoneWorld = compassMeta.lodestoneWorld; + lodestoneX = compassMeta.lodestoneX; + lodestoneY = compassMeta.lodestoneY; + lodestoneZ = compassMeta.lodestoneZ; + tracked = compassMeta.tracked; } CraftMetaCompass(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaCompass.LODESTONE_TARGET).ifPresent((lodestoneTarget) -> { + getOrEmpty(tag, LODESTONE_TARGET).ifPresent((lodestoneTarget) -> { lodestoneTarget.target().ifPresent((target) -> { - this.lodestoneWorld = target.dimension(); + lodestoneWorld = target.dimension(); BlockPos pos = target.pos(); - this.lodestoneX = pos.getX(); - this.lodestoneY = pos.getY(); - this.lodestoneZ = pos.getZ(); + lodestoneX = pos.getX(); + lodestoneY = pos.getY(); + lodestoneZ = pos.getZ(); }); - this.tracked = lodestoneTarget.tracked(); + tracked = lodestoneTarget.tracked(); }); } CraftMetaCompass(Map map) { super(map); - String lodestoneWorldString = SerializableMeta.getString(map, CraftMetaCompass.LODESTONE_POS_WORLD.BUKKIT, true); + String lodestoneWorldString = SerializableMeta.getString(map, LODESTONE_POS_WORLD.BUKKIT, true); if (lodestoneWorldString != null) { - this.lodestoneWorld = ResourceKey.create(Registries.DIMENSION, ResourceLocation.tryParse(lodestoneWorldString)); - this.lodestoneX = (Integer) map.get(CraftMetaCompass.LODESTONE_POS_X.BUKKIT); - this.lodestoneY = (Integer) map.get(CraftMetaCompass.LODESTONE_POS_Y.BUKKIT); - this.lodestoneZ = (Integer) map.get(CraftMetaCompass.LODESTONE_POS_Z.BUKKIT); + lodestoneWorld = ResourceKey.create(Registries.DIMENSION, MinecraftKey.tryParse(lodestoneWorldString)); + lodestoneX = (Integer) map.get(LODESTONE_POS_X.BUKKIT); + lodestoneY = (Integer) map.get(LODESTONE_POS_Y.BUKKIT); + lodestoneZ = (Integer) map.get(LODESTONE_POS_Z.BUKKIT); } else { // legacy - Location lodestone = SerializableMeta.getObject(Location.class, map, CraftMetaCompass.LODESTONE_POS.BUKKIT, true); + Location lodestone = SerializableMeta.getObject(Location.class, map, LODESTONE_POS.BUKKIT, true); if (lodestone != null && lodestone.getWorld() != null) { - this.setLodestone(lodestone); + setLodestone(lodestone); } } - this.tracked = SerializableMeta.getBoolean(map, CraftMetaCompass.LODESTONE_TRACKED.BUKKIT); + tracked = SerializableMeta.getBoolean(map, LODESTONE_TRACKED.BUKKIT); } @Override @@ -88,27 +87,22 @@ void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); Optional target = Optional.empty(); - if (this.lodestoneWorld != null) { - target = Optional.of(new GlobalPos(this.lodestoneWorld, new BlockPos(this.lodestoneX, this.lodestoneY, this.lodestoneZ))); + if (lodestoneWorld != null) { + target = Optional.of(new GlobalPos(lodestoneWorld, new BlockPos(lodestoneX, lodestoneY, lodestoneZ))); } - if (target.isPresent() || this.hasLodestoneTracked()) { - tag.put(CraftMetaCompass.LODESTONE_TARGET, new LodestoneTracker(target, this.tracked)); + if (target.isPresent() || hasLodestoneTracked()) { + tag.put(LODESTONE_TARGET, new LodestoneTracker(target, tracked)); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isCompassEmpty(); + return super.isEmpty() && isCompassEmpty(); } boolean isCompassEmpty() { - return !(this.hasLodestone() || this.hasLodestoneTracked()); - } - - @Override - boolean applicableTo(Material type) { - return type == Material.COMPASS; + return !(hasLodestone() || hasLodestoneTracked()); } @Override @@ -119,17 +113,17 @@ public CraftMetaCompass clone() { @Override public boolean hasLodestone() { - return this.lodestoneWorld != null; + return lodestoneWorld != null; } @Override public Location getLodestone() { - if (this.lodestoneWorld == null) { + if (lodestoneWorld == null) { return null; } - ServerLevel worldServer = MinecraftServer.getServer().getLevel(this.lodestoneWorld); + WorldServer worldServer = MinecraftServer.getServer().getLevel(lodestoneWorld); World world = worldServer != null ? worldServer.getWorld() : null; - return new Location(world, this.lodestoneX, this.lodestoneY, this.lodestoneZ); // world may be null here, if the referenced world is not loaded + return new Location(world, lodestoneX, lodestoneY, lodestoneZ); // world may be null here, if the referenced world is not loaded } @Override @@ -146,12 +140,12 @@ public void setLodestone(Location lodestone) { } boolean hasLodestoneTracked() { - return !this.tracked; + return !tracked; } @Override public boolean isLodestoneTracked() { - return this.tracked; + return tracked; } @Override @@ -163,14 +157,14 @@ public void setLodestoneTracked(boolean tracked) { int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasLodestone()) { - hash = 73 * hash + this.lodestoneWorld.hashCode(); - hash = 73 * hash + this.lodestoneX; - hash = 73 * hash + this.lodestoneY; - hash = 73 * hash + this.lodestoneZ; + if (hasLodestone()) { + hash = 73 * hash + lodestoneWorld.hashCode(); + hash = 73 * hash + lodestoneX; + hash = 73 * hash + lodestoneY; + hash = 73 * hash + lodestoneZ; } - if (this.hasLodestoneTracked()) { - hash = 73 * hash + (this.isLodestoneTracked() ? 1231 : 1237); + if (hasLodestoneTracked()) { + hash = 73 * hash + (isLodestoneTracked() ? 1231 : 1237); } return original != hash ? CraftMetaCompass.class.hashCode() ^ hash : hash; @@ -194,21 +188,21 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaCompass || this.isCompassEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaCompass || isCompassEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasLodestone()) { - builder.put(CraftMetaCompass.LODESTONE_POS_WORLD.BUKKIT, this.lodestoneWorld.location().toString()); - builder.put(CraftMetaCompass.LODESTONE_POS_X.BUKKIT, this.lodestoneX); - builder.put(CraftMetaCompass.LODESTONE_POS_Y.BUKKIT, this.lodestoneY); - builder.put(CraftMetaCompass.LODESTONE_POS_Z.BUKKIT, this.lodestoneZ); + if (hasLodestone()) { + builder.put(LODESTONE_POS_WORLD.BUKKIT, lodestoneWorld.location().toString()); + builder.put(LODESTONE_POS_X.BUKKIT, lodestoneX); + builder.put(LODESTONE_POS_Y.BUKKIT, lodestoneY); + builder.put(LODESTONE_POS_Z.BUKKIT, lodestoneZ); } - if (this.hasLodestoneTracked()) { - builder.put(CraftMetaCompass.LODESTONE_TRACKED.BUKKIT, this.tracked); + if (hasLodestoneTracked()) { + builder.put(LODESTONE_TRACKED.BUKKIT, tracked); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java index de7b06f9..2660a019 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java @@ -8,7 +8,7 @@ import java.util.Map; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.world.item.ArrowItem; +import net.minecraft.world.item.ItemArrow; import net.minecraft.world.item.component.ChargedProjectiles; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -39,16 +39,16 @@ public class CraftMetaCrossbow extends CraftMetaItem implements CrossbowMeta { CraftMetaCrossbow(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaCrossbow.CHARGED_PROJECTILES).ifPresent((p) -> { + getOrEmpty(tag, CHARGED_PROJECTILES).ifPresent((p) -> { List list = p.getItems(); if (list != null && !list.isEmpty()) { - this.chargedProjectiles = new ArrayList<>(); + chargedProjectiles = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { net.minecraft.world.item.ItemStack nbttagcompound1 = list.get(i); - this.chargedProjectiles.add(CraftItemStack.asCraftMirror(nbttagcompound1)); + chargedProjectiles.add(CraftItemStack.asCraftMirror(nbttagcompound1)); } } }); @@ -57,11 +57,11 @@ public class CraftMetaCrossbow extends CraftMetaItem implements CrossbowMeta { CraftMetaCrossbow(Map map) { super(map); - Iterable projectiles = SerializableMeta.getObject(Iterable.class, map, CraftMetaCrossbow.CHARGED_PROJECTILES.BUKKIT, true); + Iterable projectiles = SerializableMeta.getObject(Iterable.class, map, CHARGED_PROJECTILES.BUKKIT, true); if (projectiles != null) { for (Object stack : projectiles) { if (stack instanceof ItemStack) { - this.addChargedProjectile((ItemStack) stack); + addChargedProjectile((ItemStack) stack); } } } @@ -71,64 +71,59 @@ public class CraftMetaCrossbow extends CraftMetaItem implements CrossbowMeta { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.hasChargedProjectiles()) { + if (hasChargedProjectiles()) { List list = new ArrayList<>(); - for (ItemStack item : this.chargedProjectiles) { + for (ItemStack item : chargedProjectiles) { list.add(CraftItemStack.asNMSCopy(item)); } - tag.put(CraftMetaCrossbow.CHARGED_PROJECTILES, ChargedProjectiles.of(list)); + tag.put(CHARGED_PROJECTILES, ChargedProjectiles.of(list)); } } - @Override - boolean applicableTo(Material type) { - return type == Material.CROSSBOW; - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isCrossbowEmpty(); + return super.isEmpty() && isCrossbowEmpty(); } boolean isCrossbowEmpty() { - return !(this.hasChargedProjectiles()); + return !(hasChargedProjectiles()); } @Override public boolean hasChargedProjectiles() { - return this.chargedProjectiles != null; + return chargedProjectiles != null; } @Override public List getChargedProjectiles() { - return (this.chargedProjectiles == null) ? ImmutableList.of() : ImmutableList.copyOf(this.chargedProjectiles); + return (chargedProjectiles == null) ? ImmutableList.of() : ImmutableList.copyOf(chargedProjectiles); } @Override public void setChargedProjectiles(List projectiles) { - this.chargedProjectiles = null; + chargedProjectiles = null; if (projectiles == null) { return; } for (ItemStack i : projectiles) { - this.addChargedProjectile(i); + addChargedProjectile(i); } } @Override public void addChargedProjectile(ItemStack item) { Preconditions.checkArgument(item != null, "item"); - Preconditions.checkArgument(item.getType() == Material.FIREWORK_ROCKET || CraftItemType.bukkitToMinecraft(item.getType()) instanceof ArrowItem, "Item %s is not an arrow or firework rocket", item); + Preconditions.checkArgument(item.getType() == Material.FIREWORK_ROCKET || CraftItemType.bukkitToMinecraft(item.getType()) instanceof ItemArrow, "Item %s is not an arrow or firework rocket", item); - if (this.chargedProjectiles == null) { - this.chargedProjectiles = new ArrayList<>(); + if (chargedProjectiles == null) { + chargedProjectiles = new ArrayList<>(); } - this.chargedProjectiles.add(item); + chargedProjectiles.add(item); } @Override @@ -139,14 +134,14 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaCrossbow) { CraftMetaCrossbow that = (CraftMetaCrossbow) meta; - return (this.hasChargedProjectiles() ? that.hasChargedProjectiles() && this.chargedProjectiles.equals(that.chargedProjectiles) : !that.hasChargedProjectiles()); + return (hasChargedProjectiles() ? that.hasChargedProjectiles() && this.chargedProjectiles.equals(that.chargedProjectiles) : !that.hasChargedProjectiles()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaCrossbow || this.isCrossbowEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaCrossbow || isCrossbowEmpty()); } @Override @@ -154,8 +149,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasChargedProjectiles()) { - hash = 61 * hash + this.chargedProjectiles.hashCode(); + if (hasChargedProjectiles()) { + hash = 61 * hash + chargedProjectiles.hashCode(); } return original != hash ? CraftMetaCrossbow.class.hashCode() ^ hash : hash; @@ -170,8 +165,8 @@ public CraftMetaCrossbow clone() { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.hasChargedProjectiles()) { - builder.put(CraftMetaCrossbow.CHARGED_PROJECTILES.BUKKIT, this.chargedProjectiles); + if (hasChargedProjectiles()) { + builder.put(CHARGED_PROJECTILES.BUKKIT, chargedProjectiles); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java index fca0cfba..ad1ab6ad 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java @@ -7,7 +7,6 @@ import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.enchantment.ItemEnchantments; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; @@ -36,10 +35,10 @@ class CraftMetaEnchantedBook extends CraftMetaItem implements EnchantmentStorage CraftMetaEnchantedBook(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaEnchantedBook.STORED_ENCHANTMENTS).ifPresent((itemEnchantments) -> { - this.enchantments = buildEnchantments(itemEnchantments); + getOrEmpty(tag, STORED_ENCHANTMENTS).ifPresent((itemEnchantments) -> { + enchantments = buildEnchantments(itemEnchantments); if (!itemEnchantments.showInTooltip) { - this.addItemFlags(ItemFlag.HIDE_ADDITIONAL_TOOLTIP); + addItemFlags(ItemFlag.HIDE_ADDITIONAL_TOOLTIP); } }); } @@ -47,24 +46,19 @@ class CraftMetaEnchantedBook extends CraftMetaItem implements EnchantmentStorage CraftMetaEnchantedBook(Map map) { super(map); - this.enchantments = buildEnchantments(map, CraftMetaEnchantedBook.STORED_ENCHANTMENTS); + enchantments = buildEnchantments(map, STORED_ENCHANTMENTS); } @Override void applyToItem(CraftMetaItem.Applicator itemTag) { super.applyToItem(itemTag); - this.applyEnchantments(this.enchantments, itemTag, CraftMetaEnchantedBook.STORED_ENCHANTMENTS, ItemFlag.HIDE_ADDITIONAL_TOOLTIP); - } - - @Override - boolean applicableTo(Material type) { - return type == Material.ENCHANTED_BOOK; + applyEnchantments(enchantments, itemTag, STORED_ENCHANTMENTS, ItemFlag.HIDE_ADDITIONAL_TOOLTIP); } @Override boolean isEmpty() { - return super.isEmpty() && this.isEnchantedEmpty(); + return super.isEmpty() && isEnchantedEmpty(); } @Override @@ -75,14 +69,14 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaEnchantedBook) { CraftMetaEnchantedBook that = (CraftMetaEnchantedBook) meta; - return (this.hasStoredEnchants() ? that.hasStoredEnchants() && this.enchantments.equals(that.enchantments) : !that.hasStoredEnchants()); + return (hasStoredEnchants() ? that.hasStoredEnchants() && this.enchantments.equals(that.enchantments) : !that.hasStoredEnchants()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaEnchantedBook || this.isEnchantedEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaEnchantedBook || isEnchantedEmpty()); } @Override @@ -90,8 +84,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasStoredEnchants()) { - hash = 61 * hash + this.enchantments.hashCode(); + if (hasStoredEnchants()) { + hash = 61 * hash + enchantments.hashCode(); } return original != hash ? CraftMetaEnchantedBook.class.hashCode() ^ hash : hash; @@ -112,23 +106,23 @@ public CraftMetaEnchantedBook clone() { Builder serialize(Builder builder) { super.serialize(builder); - serializeEnchantments(this.enchantments, builder, CraftMetaEnchantedBook.STORED_ENCHANTMENTS); + serializeEnchantments(enchantments, builder, STORED_ENCHANTMENTS); return builder; } boolean isEnchantedEmpty() { - return !this.hasStoredEnchants(); + return !hasStoredEnchants(); } @Override public boolean hasStoredEnchant(Enchantment ench) { - return this.hasStoredEnchants() && this.enchantments.containsKey(ench); + return hasStoredEnchants() && enchantments.containsKey(ench); } @Override public int getStoredEnchantLevel(Enchantment ench) { - Integer level = this.hasStoredEnchants() ? this.enchantments.get(ench) : null; + Integer level = hasStoredEnchants() ? enchantments.get(ench) : null; if (level == null) { return 0; } @@ -137,17 +131,17 @@ public int getStoredEnchantLevel(Enchantment ench) { @Override public Map getStoredEnchants() { - return this.hasStoredEnchants() ? ImmutableMap.copyOf(this.enchantments) : ImmutableMap.of(); + return hasStoredEnchants() ? ImmutableMap.copyOf(enchantments) : ImmutableMap.of(); } @Override public boolean addStoredEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { - if (this.enchantments == null) { - this.enchantments = new LinkedHashMap(4); + if (enchantments == null) { + enchantments = new LinkedHashMap(4); } if (ignoreRestrictions || level >= ench.getStartLevel() && level <= ench.getMaxLevel()) { - Integer old = this.enchantments.put(ench, level); + Integer old = enchantments.put(ench, level); return old == null || old != level; } return false; @@ -155,16 +149,16 @@ public boolean addStoredEnchant(Enchantment ench, int level, boolean ignoreRestr @Override public boolean removeStoredEnchant(Enchantment ench) { - return this.hasStoredEnchants() && this.enchantments.remove(ench) != null; + return hasStoredEnchants() && enchantments.remove(ench) != null; } @Override public boolean hasStoredEnchants() { - return !(this.enchantments == null || this.enchantments.isEmpty()); + return !(enchantments == null || enchantments.isEmpty()); } @Override public boolean hasConflictingStoredEnchant(Enchantment ench) { - return checkConflictingEnchants(this.enchantments, ench); + return checkConflictingEnchants(enchantments, ench); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEntityTag.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEntityTag.java index 27af7ca9..6721b845 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEntityTag.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEntityTag.java @@ -6,8 +6,8 @@ import java.util.Set; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.item.component.CustomData; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -25,7 +25,7 @@ public class CraftMetaEntityTag extends CraftMetaItem { ); static final ItemMetaKeyType ENTITY_TAG = new ItemMetaKeyType<>(DataComponents.ENTITY_DATA, "EntityTag", "entity-tag"); - CompoundTag entityTag; + NBTTagCompound entityTag; CraftMetaEntityTag(CraftMetaItem meta) { super(meta); @@ -41,8 +41,8 @@ public class CraftMetaEntityTag extends CraftMetaItem { CraftMetaEntityTag(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaEntityTag.ENTITY_TAG).ifPresent((nbt) -> { - this.entityTag = nbt.copyTag(); + getOrEmpty(tag, ENTITY_TAG).ifPresent((nbt) -> { + entityTag = nbt.copyTag(); }); } @@ -51,18 +51,18 @@ public class CraftMetaEntityTag extends CraftMetaItem { } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaEntityTag.ENTITY_TAG.NBT)) { - this.entityTag = tag.getCompound(CraftMetaEntityTag.ENTITY_TAG.NBT); + if (tag.contains(ENTITY_TAG.NBT)) { + entityTag = tag.getCompound(ENTITY_TAG.NBT); } } @Override - void serializeInternal(Map internalTags) { - if (this.entityTag != null && !this.entityTag.isEmpty()) { - internalTags.put(CraftMetaEntityTag.ENTITY_TAG.NBT, this.entityTag); + void serializeInternal(Map internalTags) { + if (entityTag != null && !entityTag.isEmpty()) { + internalTags.put(ENTITY_TAG.NBT, entityTag); } } @@ -70,23 +70,23 @@ void serializeInternal(Map internalTags) { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.entityTag != null) { - tag.put(CraftMetaEntityTag.ENTITY_TAG, CustomData.of(this.entityTag)); + if (entityTag != null) { + tag.put(ENTITY_TAG, CustomData.of(entityTag)); } } @Override boolean applicableTo(Material type) { - return CraftMetaEntityTag.ENTITY_TAGGABLE_MATERIALS.contains(type); + return ENTITY_TAGGABLE_MATERIALS.contains(type); } @Override boolean isEmpty() { - return super.isEmpty() && this.isEntityTagEmpty(); + return super.isEmpty() && isEntityTagEmpty(); } boolean isEntityTagEmpty() { - return !(this.entityTag != null); + return !(entityTag != null); } @Override @@ -97,14 +97,14 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaEntityTag) { CraftMetaEntityTag that = (CraftMetaEntityTag) meta; - return this.entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : this.entityTag == null; + return entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : entityTag == null; } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaEntityTag || this.isEntityTagEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaEntityTag || isEntityTagEmpty()); } @Override @@ -112,8 +112,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.entityTag != null) { - hash = 73 * hash + this.entityTag.hashCode(); + if (entityTag != null) { + hash = 73 * hash + entityTag.hashCode(); } return original != hash ? CraftMetaEntityTag.class.hashCode() ^ hash : hash; @@ -130,8 +130,8 @@ Builder serialize(Builder builder) { public CraftMetaEntityTag clone() { CraftMetaEntityTag clone = (CraftMetaEntityTag) super.clone(); - if (this.entityTag != null) { - clone.entityTag = this.entityTag.copy(); + if (entityTag != null) { + clone.entityTag = entityTag.copy(); } return clone; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java index 1b51fab1..681aed86 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java @@ -16,7 +16,6 @@ import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect.Type; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific; import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific.To; @@ -64,15 +63,15 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { CraftMetaFirework(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaFirework.FIREWORKS).ifPresent((fireworks) -> { - this.power = fireworks.flightDuration(); + getOrEmpty(tag, FIREWORKS).ifPresent((fireworks) -> { + power = fireworks.flightDuration(); List fireworkEffects = fireworks.explosions(); List effects = this.effects = new ArrayList(fireworkEffects.size()); for (int i = 0; i < fireworkEffects.size(); i++) { try { - effects.add(CraftMetaFirework.getEffect(fireworkEffects.get(i))); + effects.add(getEffect(fireworkEffects.get(i))); } catch (IllegalArgumentException ex) { // Ignore invalid effects } @@ -92,12 +91,11 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { safelyAddEffects(effects); } - static FireworkEffect getEffect(FireworkExplosion explosion) { FireworkEffect.Builder effect = FireworkEffect.builder() .flicker(explosion.hasTwinkle()) .trail(explosion.hasTrail()) - .with(CraftMetaFirework.getEffectType(explosion.shape())); + .with(getEffectType(explosion.shape())); IntList colors = explosion.colors(); // People using buggy command generators specify a list rather than an int here, so recover with dummy data. @@ -119,30 +117,30 @@ static FireworkEffect getEffect(FireworkExplosion explosion) { } static FireworkExplosion getExplosion(FireworkEffect effect) { - IntList colors = CraftMetaFirework.addColors(effect.getColors()); - IntList fadeColors = CraftMetaFirework.addColors(effect.getFadeColors()); + IntList colors = addColors(effect.getColors()); + IntList fadeColors = addColors(effect.getFadeColors()); - return new FireworkExplosion(CraftMetaFirework.getNBT(effect.getType()), colors, fadeColors, effect.hasTrail(), effect.hasFlicker()); + return new FireworkExplosion(getNBT(effect.getType()), colors, fadeColors, effect.hasTrail(), effect.hasFlicker()); } - static FireworkExplosion.Shape getNBT(Type type) { + static FireworkExplosion.a getNBT(Type type) { switch (type) { case BALL: - return FireworkExplosion.Shape.SMALL_BALL; + return FireworkExplosion.a.SMALL_BALL; case BALL_LARGE: - return FireworkExplosion.Shape.LARGE_BALL; + return FireworkExplosion.a.LARGE_BALL; case STAR: - return FireworkExplosion.Shape.STAR; + return FireworkExplosion.a.STAR; case CREEPER: - return FireworkExplosion.Shape.CREEPER; + return FireworkExplosion.a.CREEPER; case BURST: - return FireworkExplosion.Shape.BURST; + return FireworkExplosion.a.BURST; default: throw new IllegalArgumentException("Unknown effect type " + type); } } - static Type getEffectType(FireworkExplosion.Shape nbt) { + static Type getEffectType(FireworkExplosion.a nbt) { switch (nbt) { case SMALL_BALL: return Type.BALL; @@ -161,7 +159,7 @@ static Type getEffectType(FireworkExplosion.Shape nbt) { @Override public boolean hasEffects() { - return !(this.effects == null || this.effects.isEmpty()); + return !(effects == null || effects.isEmpty()); } void safelyAddEffects(Iterable collection) { @@ -183,7 +181,7 @@ void safelyAddEffects(Iterable collection) { @Override void applyToItem(CraftMetaItem.Applicator itemTag) { super.applyToItem(itemTag); - if (this.isFireworkEmpty()) { + if (isFireworkEmpty()) { return; } @@ -194,7 +192,7 @@ void applyToItem(CraftMetaItem.Applicator itemTag) { } } - itemTag.put(CraftMetaFirework.FIREWORKS, new Fireworks(this.getPower(), effects)); + itemTag.put(FIREWORKS, new Fireworks(this.getPower(), effects)); } static IntList addColors(List colors) { @@ -211,18 +209,13 @@ static IntList addColors(List colors) { return IntList.of(colorArray); } - @Override - boolean applicableTo(Material type) { - return type == Material.FIREWORK_ROCKET; - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isFireworkEmpty(); + return super.isEmpty() && isFireworkEmpty(); } boolean isFireworkEmpty() { - return !(this.hasEffects() || this.hasPower()); + return !(hasEffects() || hasPower()); } @Override @@ -239,7 +232,7 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaFirework that) { return (Objects.equals(this.power, that.power)) - && (this.hasEffects() ? that.hasEffects() && this.effects.equals(that.effects) : !that.hasEffects()); + && (hasEffects() ? that.hasEffects() && this.effects.equals(that.effects) : !that.hasEffects()); } return true; @@ -247,18 +240,18 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaFirework || this.isFireworkEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaFirework || isFireworkEmpty()); } @Override int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasPower()) { - hash = 61 * hash + this.power; + if (hasPower()) { + hash = 61 * hash + power; } - if (this.hasEffects()) { - hash = 61 * hash + 13 * this.effects.hashCode(); + if (hasEffects()) { + hash = 61 * hash + 13 * effects.hashCode(); } return hash != original ? CraftMetaFirework.class.hashCode() ^ hash : hash; } @@ -267,12 +260,12 @@ int applyHash() { Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasEffects()) { - builder.put(CraftMetaFirework.EXPLOSIONS.BUKKIT, ImmutableList.copyOf(this.effects)); + if (hasEffects()) { + builder.put(EXPLOSIONS.BUKKIT, ImmutableList.copyOf(effects)); } - if (this.hasPower()) { - builder.put(CraftMetaFirework.FLIGHT.BUKKIT, this.power); + if (hasPower()) { + builder.put(FLIGHT.BUKKIT, power); } return builder; @@ -319,7 +312,7 @@ public void addEffects(FireworkEffect... effects) { @Override public void addEffects(Iterable effects) { Preconditions.checkArgument(effects != null, "effects cannot be null"); - this.safelyAddEffects(effects); + safelyAddEffects(effects); } @Override @@ -348,7 +341,7 @@ public void clearEffects() { @Override public int getPower() { - return this.hasPower() ? this.power : 0; + return hasPower() ? this.power : 0; } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java index 4e29df19..a2f2201a 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java @@ -40,40 +40,51 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.IRegistry; +import net.minecraft.core.IRegistryCustom; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponentType; import net.minecraft.core.component.DataComponents; import net.minecraft.core.component.TypedDataComponent; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtAccounter; -import net.minecraft.nbt.NbtIo; -import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.DynamicOpsNBT; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTCompressedStreamTools; +import net.minecraft.nbt.NBTReadLimiter; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.SnbtPrinterTagVisitor; -import net.minecraft.nbt.Tag; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.resources.MinecraftKey; import net.minecraft.server.MinecraftServer; +import net.minecraft.tags.TagKey; import net.minecraft.util.Unit; +import net.minecraft.world.entity.EnumItemSlot; import net.minecraft.world.entity.EquipmentSlotGroup; -import net.minecraft.world.food.FoodProperties; +import net.minecraft.world.entity.ai.attributes.AttributeBase; +import net.minecraft.world.food.FoodInfo; import net.minecraft.world.item.EitherHolder; +import net.minecraft.world.item.EnumItemRarity; import net.minecraft.world.item.JukeboxPlayable; import net.minecraft.world.item.JukeboxSongs; -import net.minecraft.world.item.Rarity; import net.minecraft.world.item.component.BlockItemStateProperties; import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.component.CustomModelData; +import net.minecraft.world.item.component.DamageResistant; import net.minecraft.world.item.component.ItemAttributeModifiers; import net.minecraft.world.item.component.ItemLore; import net.minecraft.world.item.component.Tool; import net.minecraft.world.item.component.Unbreakable; +import net.minecraft.world.item.component.UseCooldown; +import net.minecraft.world.item.component.UseRemainder; +import net.minecraft.world.item.enchantment.Enchantable; import net.minecraft.world.item.enchantment.ItemEnchantments; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.item.equipment.Equippable; +import net.minecraft.world.level.block.state.IBlockData; +import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.block.data.BlockData; @@ -87,28 +98,37 @@ import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.bukkit.craftbukkit.enchantments.CraftEnchantment; import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific; +import org.bukkit.craftbukkit.inventory.components.CraftEquippableComponent; import org.bukkit.craftbukkit.inventory.components.CraftFoodComponent; import org.bukkit.craftbukkit.inventory.components.CraftJukeboxComponent; import org.bukkit.craftbukkit.inventory.components.CraftToolComponent; +import org.bukkit.craftbukkit.inventory.components.CraftUseCooldownComponent; import org.bukkit.craftbukkit.inventory.tags.DeprecatedCustomTagContainer; import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry; +import org.bukkit.craftbukkit.tag.CraftDamageTag; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer; +import org.bukkit.craftbukkit.util.CraftNamespacedKey; +import org.bukkit.damage.DamageType; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemRarity; +import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockDataMeta; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.Repairable; +import org.bukkit.inventory.meta.components.EquippableComponent; import org.bukkit.inventory.meta.components.FoodComponent; import org.bukkit.inventory.meta.components.JukeboxPlayableComponent; import org.bukkit.inventory.meta.components.ToolComponent; +import org.bukkit.inventory.meta.components.UseCooldownComponent; import org.bukkit.inventory.meta.tags.CustomItemTagContainer; import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.tag.DamageTypeTags; /** * Children must include the following: @@ -133,6 +153,7 @@ *
  • SerializableMeta.Deserializers deserializer() */ @DelegateDeserialization(SerializableMeta.class) +// Important: ItemMeta needs to be the first interface see #applicableTo(Material) class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { static class ItemMetaKey { @@ -181,10 +202,10 @@ static final class ItemMetaKeyType extends ItemMetaKey { static final class Applicator { - private final DataComponentPatch.Builder builder = DataComponentPatch.builder(); + private final DataComponentPatch.a builder = DataComponentPatch.builder(); Applicator put(ItemMetaKeyType key, T value) { - this.builder.set(key.TYPE, value); + builder.set(key.TYPE, value); return this; } @@ -196,14 +217,15 @@ Applicator putIfAbsent(TypedDataComponent component) { } DataComponentPatch build() { - return this.builder.build(); + return builder.build(); } } - static final ItemMetaKeyType NAME = new ItemMetaKeyType(DataComponents.CUSTOM_NAME, "display-name"); - static final ItemMetaKeyType ITEM_NAME = new ItemMetaKeyType(DataComponents.ITEM_NAME, "item-name"); + static final ItemMetaKeyType NAME = new ItemMetaKeyType(DataComponents.CUSTOM_NAME, "display-name"); + static final ItemMetaKeyType ITEM_NAME = new ItemMetaKeyType(DataComponents.ITEM_NAME, "item-name"); static final ItemMetaKeyType LORE = new ItemMetaKeyType<>(DataComponents.LORE, "lore"); static final ItemMetaKeyType CUSTOM_MODEL_DATA = new ItemMetaKeyType<>(DataComponents.CUSTOM_MODEL_DATA, "custom-model-data"); + static final ItemMetaKeyType ENCHANTABLE = new ItemMetaKeyType<>(DataComponents.ENCHANTABLE, "enchantable"); static final ItemMetaKeyType ENCHANTMENTS = new ItemMetaKeyType<>(DataComponents.ENCHANTMENTS, "enchants"); static final ItemMetaKeyType REPAIR = new ItemMetaKeyType<>(DataComponents.REPAIR_COST, "repair-cost"); static final ItemMetaKeyType ATTRIBUTES = new ItemMetaKeyType<>(DataComponents.ATTRIBUTE_MODIFIERS, "attribute-modifiers"); @@ -216,20 +238,32 @@ DataComponentPatch build() { @Specific(Specific.To.NBT) static final ItemMetaKeyType HIDE_TOOLTIP = new ItemMetaKeyType<>(DataComponents.HIDE_TOOLTIP, "hide-tool-tip"); @Specific(Specific.To.NBT) + static final ItemMetaKeyType TOOLTIP_STYLE = new ItemMetaKeyType<>(DataComponents.TOOLTIP_STYLE, "tool-tip-style"); + @Specific(Specific.To.NBT) + static final ItemMetaKeyType ITEM_MODEL = new ItemMetaKeyType<>(DataComponents.ITEM_MODEL, "item-model"); + @Specific(Specific.To.NBT) static final ItemMetaKeyType UNBREAKABLE = new ItemMetaKeyType<>(DataComponents.UNBREAKABLE, "Unbreakable"); @Specific(Specific.To.NBT) static final ItemMetaKeyType ENCHANTMENT_GLINT_OVERRIDE = new ItemMetaKeyType<>(DataComponents.ENCHANTMENT_GLINT_OVERRIDE, "enchantment-glint-override"); @Specific(Specific.To.NBT) - static final ItemMetaKeyType FIRE_RESISTANT = new ItemMetaKeyType<>(DataComponents.FIRE_RESISTANT, "fire-resistant"); + static final ItemMetaKeyType GLIDER = new ItemMetaKeyType<>(DataComponents.GLIDER, "glider"); + @Specific(Specific.To.NBT) + static final ItemMetaKeyType DAMAGE_RESISTANT = new ItemMetaKeyType<>(DataComponents.DAMAGE_RESISTANT, "damage-resistant"); @Specific(Specific.To.NBT) static final ItemMetaKeyType MAX_STACK_SIZE = new ItemMetaKeyType<>(DataComponents.MAX_STACK_SIZE, "max-stack-size"); @Specific(Specific.To.NBT) - static final ItemMetaKeyType RARITY = new ItemMetaKeyType<>(DataComponents.RARITY, "rarity"); + static final ItemMetaKeyType RARITY = new ItemMetaKeyType<>(DataComponents.RARITY, "rarity"); + @Specific(Specific.To.NBT) + static final ItemMetaKeyType USE_REMAINDER = new ItemMetaKeyType<>(DataComponents.USE_REMAINDER, "use-remainder"); + @Specific(Specific.To.NBT) + static final ItemMetaKeyType USE_COOLDOWN = new ItemMetaKeyType<>(DataComponents.USE_COOLDOWN, "use-cooldown"); @Specific(Specific.To.NBT) - static final ItemMetaKeyType FOOD = new ItemMetaKeyType<>(DataComponents.FOOD, "food"); + static final ItemMetaKeyType FOOD = new ItemMetaKeyType<>(DataComponents.FOOD, "food"); @Specific(Specific.To.NBT) static final ItemMetaKeyType TOOL = new ItemMetaKeyType<>(DataComponents.TOOL, "tool"); @Specific(Specific.To.NBT) + static final ItemMetaKeyType EQUIPPABLE = new ItemMetaKeyType<>(DataComponents.EQUIPPABLE, "equippable"); + @Specific(Specific.To.NBT) static final ItemMetaKeyType JUKEBOX_PLAYABLE = new ItemMetaKeyType<>(DataComponents.JUKEBOX_PLAYABLE, "jukebox-playable"); @Specific(Specific.To.NBT) static final ItemMetaKeyType DAMAGE = new ItemMetaKeyType<>(DataComponents.DAMAGE, "Damage"); @@ -244,23 +278,30 @@ DataComponentPatch build() { static final ItemMetaKeyType CUSTOM_DATA = new ItemMetaKeyType<>(DataComponents.CUSTOM_DATA); // We store the raw original JSON representation of all text data. See SPIGOT-5063, SPIGOT-5656, SPIGOT-5304 - private Component displayName; - private Component itemName; - private List lore; // null and empty are two different states internally + private IChatBaseComponent displayName; + private IChatBaseComponent itemName; + private List lore; // null and empty are two different states internally private Integer customModelData; + private Integer enchantableValue; private Map blockData; private Map enchantments; private Multimap attributeModifiers; private int repairCost; private int hideFlag; private boolean hideTooltip; + private NamespacedKey tooltipStyle; + private NamespacedKey itemModel; private boolean unbreakable; private Boolean enchantmentGlintOverride; - private boolean fireResistant; + private boolean glider; + private TagKey damageResistant; private Integer maxStackSize; private ItemRarity rarity; + private ItemStack useRemainder; + private CraftUseCooldownComponent useCooldown; private CraftFoodComponent food; private CraftToolComponent tool; + private CraftEquippableComponent equippable; private CraftJukeboxComponent jukebox; private int damage; private Integer maxDamage; @@ -268,10 +309,10 @@ DataComponentPatch build() { private static final Set HANDLED_TAGS = Sets.newHashSet(); private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry(); - private CompoundTag customTag; - protected DataComponentPatch.Builder unhandledTags = DataComponentPatch.builder(); + private NBTTagCompound customTag; + protected DataComponentPatch.a unhandledTags = DataComponentPatch.builder(); private Set> removedTags = Sets.newHashSet(); - private CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(CraftMetaItem.DATA_TYPE_REGISTRY); + private CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(DATA_TYPE_REGISTRY); private int version = CraftMagicNumbers.INSTANCE.getDataVersion(); // Internal use only @@ -284,10 +325,11 @@ DataComponentPatch build() { this.itemName = meta.itemName; if (meta.lore != null) { - this.lore = new ArrayList(meta.lore); + this.lore = new ArrayList(meta.lore); } this.customModelData = meta.customModelData; + this.enchantableValue = meta.enchantableValue; this.blockData = meta.blockData; if (meta.enchantments != null) { @@ -301,17 +343,29 @@ DataComponentPatch build() { this.repairCost = meta.repairCost; this.hideFlag = meta.hideFlag; this.hideTooltip = meta.hideTooltip; + this.tooltipStyle = meta.tooltipStyle; + this.itemModel = meta.itemModel; this.unbreakable = meta.unbreakable; this.enchantmentGlintOverride = meta.enchantmentGlintOverride; - this.fireResistant = meta.fireResistant; + this.glider = meta.glider; + this.damageResistant = meta.damageResistant; this.maxStackSize = meta.maxStackSize; this.rarity = meta.rarity; + if (meta.hasUseRemainder()) { + this.useRemainder = meta.useRemainder.clone(); + } + if (meta.hasUseCooldown()) { + this.useCooldown = new CraftUseCooldownComponent(meta.useCooldown); + } if (meta.hasFood()) { this.food = new CraftFoodComponent(meta.food); } if (meta.hasTool()) { this.tool = new CraftToolComponent(meta.tool); } + if (meta.hasEquippable()) { + this.equippable = new CraftEquippableComponent(meta.equippable); + } if (meta.hasJukeboxPlayable()) { this.jukebox = new CraftJukeboxComponent(meta.jukebox); } @@ -327,93 +381,115 @@ DataComponentPatch build() { } CraftMetaItem(DataComponentPatch tag) { - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.NAME).ifPresent((component) -> { - this.displayName = component; + getOrEmpty(tag, NAME).ifPresent((component) -> { + displayName = component; }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.ITEM_NAME).ifPresent((component) -> { - this.itemName = component; + getOrEmpty(tag, ITEM_NAME).ifPresent((component) -> { + itemName = component; }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.LORE).ifPresent((l) -> { - List list = l.lines(); - this.lore = new ArrayList(list.size()); + getOrEmpty(tag, LORE).ifPresent((l) -> { + List list = l.lines(); + lore = new ArrayList(list.size()); for (int index = 0; index < list.size(); index++) { - Component line = list.get(index); - this.lore.add(line); + IChatBaseComponent line = list.get(index); + lore.add(line); } }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.CUSTOM_MODEL_DATA).ifPresent((i) -> { - this.customModelData = i.value(); + getOrEmpty(tag, CUSTOM_MODEL_DATA).ifPresent((i) -> { + customModelData = i.value(); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.BLOCK_DATA).ifPresent((t) -> { - this.blockData = t.properties(); + getOrEmpty(tag, ENCHANTABLE).ifPresent((i) -> { + enchantableValue = i.value(); + }); + getOrEmpty(tag, BLOCK_DATA).ifPresent((t) -> { + blockData = t.properties(); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.ENCHANTMENTS).ifPresent((en) -> { - this.enchantments = CraftMetaItem.buildEnchantments(en); + getOrEmpty(tag, ENCHANTMENTS).ifPresent((en) -> { + this.enchantments = buildEnchantments(en); if (!en.showInTooltip) { - this.addItemFlags(ItemFlag.HIDE_ENCHANTS); + addItemFlags(ItemFlag.HIDE_ENCHANTS); } }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.ATTRIBUTES).ifPresent((en) -> { - this.attributeModifiers = CraftMetaItem.buildModifiers(en); + getOrEmpty(tag, ATTRIBUTES).ifPresent((en) -> { + this.attributeModifiers = buildModifiers(en); if (!en.showInTooltip()) { - this.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + addItemFlags(ItemFlag.HIDE_ATTRIBUTES); } }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.REPAIR).ifPresent((i) -> { - this.repairCost = i; + getOrEmpty(tag, REPAIR).ifPresent((i) -> { + repairCost = i; }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.HIDE_ADDITIONAL_TOOLTIP).ifPresent((h) -> { - this.addItemFlags(ItemFlag.HIDE_ADDITIONAL_TOOLTIP); + getOrEmpty(tag, HIDE_ADDITIONAL_TOOLTIP).ifPresent((h) -> { + addItemFlags(ItemFlag.HIDE_ADDITIONAL_TOOLTIP); + }); + getOrEmpty(tag, HIDE_TOOLTIP).ifPresent((u) -> { + hideTooltip = true; + }); + getOrEmpty(tag, TOOLTIP_STYLE).ifPresent((key) -> { + tooltipStyle = CraftNamespacedKey.fromMinecraft(key); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.HIDE_TOOLTIP).ifPresent((u) -> { - this.hideTooltip = true; + getOrEmpty(tag, ITEM_MODEL).ifPresent((key) -> { + itemModel = CraftNamespacedKey.fromMinecraft(key); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.UNBREAKABLE).ifPresent((u) -> { - this.unbreakable = true; + getOrEmpty(tag, UNBREAKABLE).ifPresent((u) -> { + unbreakable = true; if (!u.showInTooltip()) { - this.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); + addItemFlags(ItemFlag.HIDE_UNBREAKABLE); } }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.ENCHANTMENT_GLINT_OVERRIDE).ifPresent((override) -> { - this.enchantmentGlintOverride = override; + getOrEmpty(tag, ENCHANTMENT_GLINT_OVERRIDE).ifPresent((override) -> { + enchantmentGlintOverride = override; + }); + getOrEmpty(tag, GLIDER).ifPresent((u) -> { + glider = true; + }); + getOrEmpty(tag, DAMAGE_RESISTANT).ifPresent((tags) -> { + damageResistant = tags.types(); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.FIRE_RESISTANT).ifPresent((u) -> { - this.fireResistant = true; + getOrEmpty(tag, MAX_STACK_SIZE).ifPresent((i) -> { + maxStackSize = i; }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.MAX_STACK_SIZE).ifPresent((i) -> { - this.maxStackSize = i; + getOrEmpty(tag, RARITY).ifPresent((enumItemRarity) -> { + rarity = ItemRarity.valueOf(enumItemRarity.name()); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.RARITY).ifPresent((enumItemRarity) -> { - this.rarity = ItemRarity.valueOf(enumItemRarity.name()); + getOrEmpty(tag, USE_REMAINDER).ifPresent((remainder) -> { + useRemainder = CraftItemStack.asCraftMirror(remainder.convertInto()); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.FOOD).ifPresent((foodInfo) -> { - this.food = new CraftFoodComponent(foodInfo); + getOrEmpty(tag, USE_COOLDOWN).ifPresent((cooldown) -> { + useCooldown = new CraftUseCooldownComponent(cooldown); + }); + getOrEmpty(tag, FOOD).ifPresent((foodInfo) -> { + food = new CraftFoodComponent(foodInfo); }); getOrEmpty(tag, TOOL).ifPresent((toolInfo) -> { tool = new CraftToolComponent(toolInfo); }); + getOrEmpty(tag, EQUIPPABLE).ifPresent((equippableInfo) -> { + equippable = new CraftEquippableComponent(equippableInfo); + }); getOrEmpty(tag, JUKEBOX_PLAYABLE).ifPresent((jukeboxPlayable) -> { jukebox = new CraftJukeboxComponent(jukeboxPlayable); }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.DAMAGE).ifPresent((i) -> { - this.damage = i; + getOrEmpty(tag, DAMAGE).ifPresent((i) -> { + damage = i; }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.MAX_DAMAGE).ifPresent((i) -> { - this.maxDamage = i; + getOrEmpty(tag, MAX_DAMAGE).ifPresent((i) -> { + maxDamage = i; }); - CraftMetaItem.getOrEmpty(tag, CraftMetaItem.CUSTOM_DATA).ifPresent((customData) -> { - this.customTag = customData.copyTag(); - if (this.customTag.contains(CraftMetaItem.BUKKIT_CUSTOM_TAG.NBT)) { - CompoundTag compound = this.customTag.getCompound(CraftMetaItem.BUKKIT_CUSTOM_TAG.NBT); + getOrEmpty(tag, CUSTOM_DATA).ifPresent((customData) -> { + customTag = customData.copyTag(); + if (customTag.contains(BUKKIT_CUSTOM_TAG.NBT)) { + NBTTagCompound compound = customTag.getCompound(BUKKIT_CUSTOM_TAG.NBT); Set keys = compound.getAllKeys(); for (String key : keys) { - this.persistentDataContainer.put(key, compound.get(key).copy()); + persistentDataContainer.put(key, compound.get(key).copy()); } + customTag.remove(BUKKIT_CUSTOM_TAG.NBT); } @@ -424,9 +500,9 @@ DataComponentPatch build() { Set, Optional>> keys = tag.entrySet(); for (Map.Entry, Optional> key : keys) { - if (!CraftMetaItem.getHandledTags().contains(key.getKey())) { + if (!getHandledTags().contains(key.getKey())) { key.getValue().ifPresent((value) -> { - this.unhandledTags.set((DataComponentType) key.getKey(), value); + unhandledTags.set((DataComponentType) key.getKey(), value); }); } @@ -454,11 +530,11 @@ static Map buildEnchantments(ItemEnchantments tag) { static Multimap buildModifiers(ItemAttributeModifiers tag) { Multimap modifiers = LinkedHashMultimap.create(); - List mods = tag.modifiers(); + List mods = tag.modifiers(); int size = mods.size(); for (int i = 0; i < size; i++) { - ItemAttributeModifiers.Entry entry = mods.get(i); + ItemAttributeModifiers.b entry = mods.get(i); net.minecraft.world.entity.ai.attributes.AttributeModifier nmsModifier = entry.modifier(); if (nmsModifier == null) { continue; @@ -498,20 +574,24 @@ static Multimap buildModifiers(ItemAttributeModifi } CraftMetaItem(Map map) { - this.displayName = CraftChatMessage.fromJSONOrString(SerializableMeta.getString(map, CraftMetaItem.NAME.BUKKIT, true), true, false); - this.itemName = CraftChatMessage.fromJSONOrNull(SerializableMeta.getString(map, CraftMetaItem.ITEM_NAME.BUKKIT, true)); + displayName = CraftChatMessage.fromJSONOrString(SerializableMeta.getString(map, NAME.BUKKIT, true), true, false); + itemName = CraftChatMessage.fromJSONOrNull(SerializableMeta.getString(map, ITEM_NAME.BUKKIT, true)); - Iterable lore = SerializableMeta.getObject(Iterable.class, map, CraftMetaItem.LORE.BUKKIT, true); + Iterable lore = SerializableMeta.getObject(Iterable.class, map, LORE.BUKKIT, true); if (lore != null) { - CraftMetaItem.safelyAdd(lore, this.lore = new ArrayList(), true); + safelyAdd(lore, this.lore = new ArrayList(), true); } - Integer customModelData = SerializableMeta.getObject(Integer.class, map, CraftMetaItem.CUSTOM_MODEL_DATA.BUKKIT, true); + Integer customModelData = SerializableMeta.getObject(Integer.class, map, CUSTOM_MODEL_DATA.BUKKIT, true); if (customModelData != null) { - this.setCustomModelData(customModelData); + setCustomModelData(customModelData); + } + Integer enchantmentValue = SerializableMeta.getObject(Integer.class, map, ENCHANTABLE.BUKKIT, true); + if (enchantmentValue != null) { + setEnchantable(enchantmentValue); } - Object blockData = SerializableMeta.getObject(Object.class, map, CraftMetaItem.BLOCK_DATA.BUKKIT, true); + Object blockData = SerializableMeta.getObject(Object.class, map, BLOCK_DATA.BUKKIT, true); if (blockData != null) { Map mapBlockData = new HashMap<>(); @@ -521,7 +601,7 @@ static Multimap buildModifiers(ItemAttributeModifi } } else { // Legacy pre 1.20.5: - CompoundTag nbtBlockData = (CompoundTag) CraftNBTTagConfigSerializer.deserialize(blockData); + NBTTagCompound nbtBlockData = (NBTTagCompound) CraftNBTTagConfigSerializer.deserialize(blockData); for (String key : nbtBlockData.getAllKeys()) { mapBlockData.put(key, nbtBlockData.getString(key)); } @@ -530,60 +610,88 @@ static Multimap buildModifiers(ItemAttributeModifi this.blockData = mapBlockData; } - this.enchantments = CraftMetaItem.buildEnchantments(map, CraftMetaItem.ENCHANTMENTS); - this.attributeModifiers = CraftMetaItem.buildModifiers(map, CraftMetaItem.ATTRIBUTES); + enchantments = buildEnchantments(map, ENCHANTMENTS); + attributeModifiers = buildModifiers(map, ATTRIBUTES); - Integer repairCost = SerializableMeta.getObject(Integer.class, map, CraftMetaItem.REPAIR.BUKKIT, true); + Integer repairCost = SerializableMeta.getObject(Integer.class, map, REPAIR.BUKKIT, true); if (repairCost != null) { - this.setRepairCost(repairCost); + setRepairCost(repairCost); } - Iterable hideFlags = SerializableMeta.getObject(Iterable.class, map, CraftMetaItem.HIDEFLAGS.BUKKIT, true); + Iterable hideFlags = SerializableMeta.getObject(Iterable.class, map, HIDEFLAGS.BUKKIT, true); if (hideFlags != null) { for (Object hideFlagObject : hideFlags) { String hideFlagString = (String) hideFlagObject; try { ItemFlag hideFlatEnum = CraftItemFlag.stringToBukkit(hideFlagString); - this.addItemFlags(hideFlatEnum); + addItemFlags(hideFlatEnum); } catch (IllegalArgumentException ex) { // Ignore when we got a old String which does not map to a Enum value anymore } } } - Boolean hideTooltip = SerializableMeta.getObject(Boolean.class, map, CraftMetaItem.HIDE_TOOLTIP.BUKKIT, true); + Boolean hideTooltip = SerializableMeta.getObject(Boolean.class, map, HIDE_TOOLTIP.BUKKIT, true); if (hideTooltip != null) { - this.setHideTooltip(hideTooltip); + setHideTooltip(hideTooltip); } - Boolean unbreakable = SerializableMeta.getObject(Boolean.class, map, CraftMetaItem.UNBREAKABLE.BUKKIT, true); + String tooltipStyle = SerializableMeta.getString(map, TOOLTIP_STYLE.BUKKIT, true); + if (tooltipStyle != null) { + setTooltipStyle(NamespacedKey.fromString(tooltipStyle)); + } + + String itemModel = SerializableMeta.getString(map, ITEM_MODEL.BUKKIT, true); + if (itemModel != null) { + setItemModel(NamespacedKey.fromString(itemModel)); + } + + Boolean unbreakable = SerializableMeta.getObject(Boolean.class, map, UNBREAKABLE.BUKKIT, true); if (unbreakable != null) { - this.setUnbreakable(unbreakable); + setUnbreakable(unbreakable); } - Boolean enchantmentGlintOverride = SerializableMeta.getObject(Boolean.class, map, CraftMetaItem.ENCHANTMENT_GLINT_OVERRIDE.BUKKIT, true); + Boolean enchantmentGlintOverride = SerializableMeta.getObject(Boolean.class, map, ENCHANTMENT_GLINT_OVERRIDE.BUKKIT, true); if (enchantmentGlintOverride != null) { - this.setEnchantmentGlintOverride(enchantmentGlintOverride); + setEnchantmentGlintOverride(enchantmentGlintOverride); } - Boolean fireResistant = SerializableMeta.getObject(Boolean.class, map, CraftMetaItem.FIRE_RESISTANT.BUKKIT, true); - if (fireResistant != null) { - this.setFireResistant(fireResistant); + Boolean glider = SerializableMeta.getObject(Boolean.class, map, GLIDER.BUKKIT, true); + if (glider != null) { + setGlider(glider); } - Integer maxStackSize = SerializableMeta.getObject(Integer.class, map, CraftMetaItem.MAX_STACK_SIZE.BUKKIT, true); + String damageResistant = SerializableMeta.getString(map, DAMAGE_RESISTANT.BUKKIT, true); + if (damageResistant != null) { + Tag tag = Bukkit.getTag(DamageTypeTags.REGISTRY_DAMAGE_TYPES, NamespacedKey.fromString(damageResistant), DamageType.class); + if (tag != null) { + setDamageResistant(tag); + } + } + + Integer maxStackSize = SerializableMeta.getObject(Integer.class, map, MAX_STACK_SIZE.BUKKIT, true); if (maxStackSize != null) { - this.setMaxStackSize(maxStackSize); + setMaxStackSize(maxStackSize); } - String rarity = SerializableMeta.getString(map, CraftMetaItem.RARITY.BUKKIT, true); + String rarity = SerializableMeta.getString(map, RARITY.BUKKIT, true); if (rarity != null) { - this.setRarity(ItemRarity.valueOf(rarity)); + setRarity(ItemRarity.valueOf(rarity)); + } + + ItemStack remainder = SerializableMeta.getObject(ItemStack.class, map, USE_REMAINDER.BUKKIT, true); + if (remainder != null) { + setUseRemainder(remainder); } - CraftFoodComponent food = SerializableMeta.getObject(CraftFoodComponent.class, map, CraftMetaItem.FOOD.BUKKIT, true); + CraftUseCooldownComponent cooldown = SerializableMeta.getObject(CraftUseCooldownComponent.class, map, USE_COOLDOWN.BUKKIT, true); + if (cooldown != null) { + setUseCooldown(cooldown); + } + + CraftFoodComponent food = SerializableMeta.getObject(CraftFoodComponent.class, map, FOOD.BUKKIT, true); if (food != null) { - this.setFood(food); + setFood(food); } CraftToolComponent tool = SerializableMeta.getObject(CraftToolComponent.class, map, TOOL.BUKKIT, true); @@ -591,27 +699,32 @@ static Multimap buildModifiers(ItemAttributeModifi setTool(tool); } + CraftEquippableComponent equippable = SerializableMeta.getObject(CraftEquippableComponent.class, map, EQUIPPABLE.BUKKIT, true); + if (equippable != null) { + setEquippable(equippable); + } + CraftJukeboxComponent jukeboxPlayable = SerializableMeta.getObject(CraftJukeboxComponent.class, map, JUKEBOX_PLAYABLE.BUKKIT, true); if (jukeboxPlayable != null) { setJukeboxPlayable(jukeboxPlayable); } - Integer damage = SerializableMeta.getObject(Integer.class, map, CraftMetaItem.DAMAGE.BUKKIT, true); + Integer damage = SerializableMeta.getObject(Integer.class, map, DAMAGE.BUKKIT, true); if (damage != null) { - this.setDamage(damage); + setDamage(damage); } - Integer maxDamage = SerializableMeta.getObject(Integer.class, map, CraftMetaItem.MAX_DAMAGE.BUKKIT, true); + Integer maxDamage = SerializableMeta.getObject(Integer.class, map, MAX_DAMAGE.BUKKIT, true); if (maxDamage != null) { - this.setMaxDamage(maxDamage); + setMaxDamage(maxDamage); } String internal = SerializableMeta.getString(map, "internal", true); if (internal != null) { ByteArrayInputStream buf = new ByteArrayInputStream(Base64.getDecoder().decode(internal)); try { - CompoundTag internalTag = NbtIo.readCompressed(buf, NbtAccounter.unlimitedHeap()); - this.deserializeInternal(internalTag, map); + NBTTagCompound internalTag = NBTCompressedStreamTools.readCompressed(buf, NBTReadLimiter.unlimitedHeap()); + deserializeInternal(internalTag, map); } catch (IOException ex) { Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); } @@ -621,8 +734,8 @@ static Multimap buildModifiers(ItemAttributeModifi if (unhandled != null) { ByteArrayInputStream buf = new ByteArrayInputStream(Base64.getDecoder().decode(unhandled)); try { - CompoundTag unhandledTag = NbtIo.readCompressed(buf, NbtAccounter.unlimitedHeap()); - DataComponentPatch unhandledPatch = DataComponentPatch.CODEC.parse(MinecraftServer.getDefaultRegistryAccess().createSerializationContext(NbtOps.INSTANCE), unhandledTag).result().get(); + NBTTagCompound unhandledTag = NBTCompressedStreamTools.readCompressed(buf, NBTReadLimiter.unlimitedHeap()); + DataComponentPatch unhandledPatch = DataComponentPatch.CODEC.parse(MinecraftServer.getDefaultRegistryAccess().createSerializationContext(DynamicOpsNBT.INSTANCE), unhandledTag).result().get(); this.unhandledTags.copy(unhandledPatch); for (Entry, Optional> entry : unhandledPatch.entrySet()) { @@ -641,52 +754,52 @@ static Multimap buildModifiers(ItemAttributeModifi Iterable removed = SerializableMeta.getObject(Iterable.class, map, "removed", true); if (removed != null) { - net.minecraft.core.RegistryAccess registryAccess = CraftRegistry.getMinecraftRegistry(); - net.minecraft.core.Registry> componentTypeRegistry = registryAccess.registryOrThrow(Registries.DATA_COMPONENT_TYPE); + IRegistryCustom registryAccess = CraftRegistry.getMinecraftRegistry(); + IRegistry> componentTypeRegistry = registryAccess.lookupOrThrow(Registries.DATA_COMPONENT_TYPE); for (Object removedObject : removed) { String removedString = (String) removedObject; - DataComponentType component = componentTypeRegistry.get(ResourceLocation.parse(removedString)); + DataComponentType component = componentTypeRegistry.getValue(MinecraftKey.parse(removedString)); if (component != null) { this.removedTags.add(component); } } } - Object nbtMap = SerializableMeta.getObject(Object.class, map, CraftMetaItem.BUKKIT_CUSTOM_TAG.BUKKIT, true); // We read both legacy maps and potential modern snbt strings here + Object nbtMap = SerializableMeta.getObject(Object.class, map, BUKKIT_CUSTOM_TAG.BUKKIT, true); // We read both legacy maps and potential modern snbt strings here if (nbtMap != null) { - this.persistentDataContainer.putAll((CompoundTag) CraftNBTTagConfigSerializer.deserialize(nbtMap)); + this.persistentDataContainer.putAll((NBTTagCompound) CraftNBTTagConfigSerializer.deserialize(nbtMap)); } String custom = SerializableMeta.getString(map, "custom", true); if (custom != null) { ByteArrayInputStream buf = new ByteArrayInputStream(Base64.getDecoder().decode(custom)); try { - this.customTag = NbtIo.readCompressed(buf, NbtAccounter.unlimitedHeap()); + customTag = NBTCompressedStreamTools.readCompressed(buf, NBTReadLimiter.unlimitedHeap()); } catch (IOException ex) { Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); } } } - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { // SPIGOT-4576: Need to migrate from internal to proper data - if (tag.contains(CraftMetaItem.ATTRIBUTES.NBT, CraftMagicNumbers.NBT.TAG_LIST)) { - this.attributeModifiers = CraftMetaItem.buildModifiersLegacy(tag, CraftMetaItem.ATTRIBUTES); + if (tag.contains(ATTRIBUTES.NBT, CraftMagicNumbers.NBT.TAG_LIST)) { + this.attributeModifiers = buildModifiersLegacy(tag, ATTRIBUTES); } } - private static Multimap buildModifiersLegacy(CompoundTag tag, ItemMetaKey key) { + private static Multimap buildModifiersLegacy(NBTTagCompound tag, ItemMetaKey key) { Multimap modifiers = LinkedHashMultimap.create(); if (!tag.contains(key.NBT, CraftMagicNumbers.NBT.TAG_LIST)) { return modifiers; } - ListTag mods = tag.getList(key.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); + NBTTagList mods = tag.getList(key.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); int size = mods.size(); for (int i = 0; i < size; i++) { - CompoundTag entry = mods.getCompound(i); + NBTTagCompound entry = mods.getCompound(i); if (entry.isEmpty()) { // entry is not an actual NBTTagCompound. getCompound returns empty NBTTagCompound in that case continue; @@ -698,7 +811,7 @@ private static Multimap buildModifiersLegacy(Compo AttributeModifier attribMod = CraftAttributeInstance.convert(nmsModifier); - String attributeName = entry.getString(CraftMetaItem.ATTRIBUTES_IDENTIFIER.NBT); + String attributeName = entry.getString(ATTRIBUTES_IDENTIFIER.NBT); if (attributeName == null || attributeName.isEmpty()) { continue; } @@ -708,8 +821,8 @@ private static Multimap buildModifiersLegacy(Compo continue; } - if (entry.contains(CraftMetaItem.ATTRIBUTES_SLOT.NBT, CraftMagicNumbers.NBT.TAG_STRING)) { - String slotName = entry.getString(CraftMetaItem.ATTRIBUTES_SLOT.NBT); + if (entry.contains(ATTRIBUTES_SLOT.NBT, CraftMagicNumbers.NBT.TAG_STRING)) { + String slotName = entry.getString(ATTRIBUTES_SLOT.NBT); if (slotName == null || slotName.isEmpty()) { modifiers.put(attribute, attribMod); continue; @@ -717,7 +830,7 @@ private static Multimap buildModifiersLegacy(Compo EquipmentSlot slot = null; try { - slot = CraftEquipmentSlot.getSlot(net.minecraft.world.entity.EquipmentSlot.byName(slotName.toLowerCase(Locale.ROOT))); + slot = CraftEquipmentSlot.getSlot(EnumItemSlot.byName(slotName.toLowerCase(Locale.ROOT))); } catch (IllegalArgumentException ex) { // SPIGOT-4551 - Slot is invalid, should really match nothing but this is undefined behaviour anyway } @@ -789,84 +902,112 @@ static Multimap buildModifiers(Map @Overridden void applyToItem(CraftMetaItem.Applicator itemTag) { - if (this.hasDisplayName()) { - itemTag.put(CraftMetaItem.NAME, this.displayName); + if (hasDisplayName()) { + itemTag.put(NAME, displayName); } - if (this.hasItemName()) { - itemTag.put(CraftMetaItem.ITEM_NAME, this.itemName); + if (hasItemName()) { + itemTag.put(ITEM_NAME, itemName); } - if (this.lore != null) { - itemTag.put(CraftMetaItem.LORE, new ItemLore(this.lore)); + if (lore != null) { + itemTag.put(LORE, new ItemLore(lore)); } - if (this.hasCustomModelData()) { - itemTag.put(CraftMetaItem.CUSTOM_MODEL_DATA, new CustomModelData(this.customModelData)); + if (hasCustomModelData()) { + itemTag.put(CUSTOM_MODEL_DATA, new CustomModelData(customModelData)); } - if (this.hasBlockData()) { - itemTag.put(CraftMetaItem.BLOCK_DATA, new BlockItemStateProperties(this.blockData)); + if (hasEnchantable()) { + itemTag.put(ENCHANTABLE, new Enchantable(enchantableValue)); } - if (this.hideFlag != 0) { - if (this.hasItemFlag(ItemFlag.HIDE_ADDITIONAL_TOOLTIP)) { - itemTag.put(CraftMetaItem.HIDE_ADDITIONAL_TOOLTIP, Unit.INSTANCE); + if (hasBlockData()) { + itemTag.put(BLOCK_DATA, new BlockItemStateProperties(blockData)); + } + + if (hideFlag != 0) { + if (hasItemFlag(ItemFlag.HIDE_ADDITIONAL_TOOLTIP)) { + itemTag.put(HIDE_ADDITIONAL_TOOLTIP, Unit.INSTANCE); } } - this.applyEnchantments(this.enchantments, itemTag, CraftMetaItem.ENCHANTMENTS, ItemFlag.HIDE_ENCHANTS); - this.applyModifiers(this.attributeModifiers, itemTag); + applyEnchantments(enchantments, itemTag, ENCHANTMENTS, ItemFlag.HIDE_ENCHANTS); + applyModifiers(attributeModifiers, itemTag); + + if (hasRepairCost()) { + itemTag.put(REPAIR, repairCost); + } + + if (isHideTooltip()) { + itemTag.put(HIDE_TOOLTIP, Unit.INSTANCE); + } - if (this.hasRepairCost()) { - itemTag.put(CraftMetaItem.REPAIR, this.repairCost); + if (hasTooltipStyle()) { + itemTag.put(TOOLTIP_STYLE, CraftNamespacedKey.toMinecraft(getTooltipStyle())); } - if (this.isHideTooltip()) { - itemTag.put(CraftMetaItem.HIDE_TOOLTIP, Unit.INSTANCE); + if (hasItemModel()) { + itemTag.put(ITEM_MODEL, CraftNamespacedKey.toMinecraft(getItemModel())); } - if (this.isUnbreakable()) { - itemTag.put(CraftMetaItem.UNBREAKABLE, new Unbreakable(!this.hasItemFlag(ItemFlag.HIDE_UNBREAKABLE))); + if (isUnbreakable()) { + itemTag.put(UNBREAKABLE, new Unbreakable(!hasItemFlag(ItemFlag.HIDE_UNBREAKABLE))); } - if (this.hasEnchantmentGlintOverride()) { - itemTag.put(CraftMetaItem.ENCHANTMENT_GLINT_OVERRIDE, this.getEnchantmentGlintOverride()); + if (hasEnchantmentGlintOverride()) { + itemTag.put(ENCHANTMENT_GLINT_OVERRIDE, getEnchantmentGlintOverride()); } - if (this.isFireResistant()) { - itemTag.put(CraftMetaItem.FIRE_RESISTANT, Unit.INSTANCE); + if (isGlider()) { + itemTag.put(GLIDER, Unit.INSTANCE); } - if (this.hasMaxStackSize()) { - itemTag.put(CraftMetaItem.MAX_STACK_SIZE, this.maxStackSize); + if (hasDamageResistant()) { + itemTag.put(DAMAGE_RESISTANT, new DamageResistant(damageResistant)); } - if (this.hasRarity()) { - itemTag.put(CraftMetaItem.RARITY, Rarity.valueOf(this.rarity.name())); + if (hasMaxStackSize()) { + itemTag.put(MAX_STACK_SIZE, maxStackSize); } - if (this.hasFood()) { - itemTag.put(CraftMetaItem.FOOD, this.food.getHandle()); + if (hasRarity()) { + itemTag.put(RARITY, EnumItemRarity.valueOf(rarity.name())); + } + + if (hasUseRemainder()) { + itemTag.put(USE_REMAINDER, new UseRemainder(CraftItemStack.asNMSCopy(useRemainder))); + } + + if (hasUseCooldown()) { + itemTag.put(USE_COOLDOWN, useCooldown.getHandle()); + } + + if (hasFood()) { + itemTag.put(FOOD, food.getHandle()); } if (hasTool()) { itemTag.put(TOOL, tool.getHandle()); } + if (hasEquippable()) { + itemTag.put(EQUIPPABLE, equippable.getHandle()); + } + if (hasJukeboxPlayable()) { itemTag.put(JUKEBOX_PLAYABLE, jukebox.getHandle()); } - if (this.hasDamage()) { - itemTag.put(CraftMetaItem.DAMAGE, this.damage); + if (hasDamage()) { + itemTag.put(DAMAGE, damage); } - if (this.hasMaxDamage()) { - itemTag.put(CraftMetaItem.MAX_DAMAGE, this.maxDamage); + if (hasMaxDamage()) { + itemTag.put(MAX_DAMAGE, maxDamage); } - for (Map.Entry, Optional> e : this.unhandledTags.build().entrySet()) { + for (Map.Entry, Optional> e : unhandledTags.build().entrySet()) { e.getValue().ifPresent((value) -> { itemTag.builder.set((DataComponentType) e.getKey(), value); }); @@ -878,37 +1019,40 @@ void applyToItem(CraftMetaItem.Applicator itemTag) { } } - if (!this.persistentDataContainer.isEmpty()) { - CompoundTag bukkitCustomCompound = new CompoundTag(); - Map rawPublicMap = this.persistentDataContainer.getRaw(); + NBTTagCompound customTag = (this.customTag != null) ? this.customTag.copy() : null; + if (!persistentDataContainer.isEmpty()) { + NBTTagCompound bukkitCustomCompound = new NBTTagCompound(); + Map rawPublicMap = persistentDataContainer.getRaw(); - for (Map.Entry nbtBaseEntry : rawPublicMap.entrySet()) { + for (Map.Entry nbtBaseEntry : rawPublicMap.entrySet()) { bukkitCustomCompound.put(nbtBaseEntry.getKey(), nbtBaseEntry.getValue()); } - if (this.customTag == null) { - this.customTag = new CompoundTag(); + if (customTag == null) { + customTag = new NBTTagCompound(); } - this.customTag.put(CraftMetaItem.BUKKIT_CUSTOM_TAG.BUKKIT, bukkitCustomCompound); + customTag.put(BUKKIT_CUSTOM_TAG.BUKKIT, bukkitCustomCompound); } - if (this.customTag != null) { - itemTag.put(CraftMetaItem.CUSTOM_DATA, CustomData.of(this.customTag)); + if (customTag != null) { + itemTag.put(CUSTOM_DATA, CustomData.of(customTag)); } } void applyEnchantments(Map enchantments, CraftMetaItem.Applicator tag, ItemMetaKeyType key, ItemFlag itemFlag) { - if (enchantments == null) { + if (enchantments == null && !hasItemFlag(itemFlag)) { return; } - ItemEnchantments.Mutable list = new ItemEnchantments.Mutable(ItemEnchantments.EMPTY); + ItemEnchantments.a list = new ItemEnchantments.a(ItemEnchantments.EMPTY); - for (Map.Entry entry : enchantments.entrySet()) { - list.set(CraftEnchantment.bukkitToMinecraftHolder(entry.getKey()), entry.getValue()); + if (enchantments != null) { + for (Map.Entry entry : enchantments.entrySet()) { + list.set(CraftEnchantment.bukkitToMinecraftHolder(entry.getKey()), entry.getValue()); + } } - list.showInTooltip = !this.hasItemFlag(itemFlag); + list.showInTooltip = !hasItemFlag(itemFlag); tag.put(key, list.toImmutable()); } @@ -920,14 +1064,14 @@ void applyModifiers(Multimap modifiers, CraftMetaI return; } - ItemAttributeModifiers.Builder list = ItemAttributeModifiers.builder(); + ItemAttributeModifiers.a list = ItemAttributeModifiers.builder(); for (Map.Entry entry : modifiers.entries()) { if (entry.getKey() == null || entry.getValue() == null) { continue; } net.minecraft.world.entity.ai.attributes.AttributeModifier nmsModifier = CraftAttributeInstance.convert(entry.getValue()); - Holder name = CraftAttribute.bukkitToMinecraftHolder(entry.getKey()); + Holder name = CraftAttribute.bukkitToMinecraftHolder(entry.getKey()); if (name == null) { continue; } @@ -935,22 +1079,30 @@ void applyModifiers(Multimap modifiers, CraftMetaI EquipmentSlotGroup group = CraftEquipmentSlot.getNMSGroup(entry.getValue().getSlotGroup()); list.add(name, nmsModifier, group); } - tag.put(CraftMetaItem.ATTRIBUTES, list.build().withTooltip(!this.hasItemFlag(ItemFlag.HIDE_ATTRIBUTES))); + tag.put(ATTRIBUTES, list.build().withTooltip(!hasItemFlag(ItemFlag.HIDE_ATTRIBUTES))); } - @Overridden boolean applicableTo(Material type) { - return type != Material.AIR; + if (type == Material.AIR || !type.isItem()) { + return false; + } + + if (getClass() == CraftMetaItem.class) { + return true; + } + + // We assume that the corresponding bukkit interface is always the first one + return type.asItemType().getItemMetaClass() == getClass().getInterfaces()[0]; } @Overridden boolean isEmpty() { - return !(hasDisplayName() || hasItemName() || hasLocalizedName() || hasEnchants() || (lore != null) || hasCustomModelData() || hasBlockData() || hasRepairCost() || !unhandledTags.build().isEmpty() || !removedTags.isEmpty() || !persistentDataContainer.isEmpty() || hideFlag != 0 || isHideTooltip() || isUnbreakable() || hasEnchantmentGlintOverride() || isFireResistant() || hasMaxStackSize() || hasRarity() || hasFood() || hasTool() || hasDamage() || hasMaxDamage() || hasAttributeModifiers() || customTag != null); + return !(hasDisplayName() || hasItemName() || hasLocalizedName() || hasEnchants() || (lore != null) || hasCustomModelData() || hasEnchantable() || hasBlockData() || hasRepairCost() || !unhandledTags.build().isEmpty() || !removedTags.isEmpty() || !persistentDataContainer.isEmpty() || hideFlag != 0 || isHideTooltip() || hasTooltipStyle() || hasItemModel() || isUnbreakable() || hasEnchantmentGlintOverride() || isGlider() || hasDamageResistant() || hasMaxStackSize() || hasRarity() || hasUseRemainder() || hasUseCooldown() || hasFood() || hasTool() || hasJukeboxPlayable() || hasEquippable() || hasDamage() || hasMaxDamage() || hasAttributeModifiers() || customTag != null); } @Override public String getDisplayName() { - return CraftChatMessage.fromComponent(this.displayName); + return CraftChatMessage.fromComponent(displayName); } @Override @@ -960,12 +1112,12 @@ public final void setDisplayName(String name) { @Override public boolean hasDisplayName() { - return this.displayName != null; + return displayName != null; } @Override public String getItemName() { - return CraftChatMessage.fromComponent(this.itemName); + return CraftChatMessage.fromComponent(itemName); } @Override @@ -975,12 +1127,12 @@ public final void setItemName(String name) { @Override public boolean hasItemName() { - return this.itemName != null; + return itemName != null; } @Override public String getLocalizedName() { - return this.getDisplayName(); + return getDisplayName(); } @Override @@ -999,19 +1151,19 @@ public boolean hasLore() { @Override public boolean hasRepairCost() { - return this.repairCost > 0; + return repairCost > 0; } @Override public boolean hasEnchant(Enchantment ench) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - return this.hasEnchants() && this.enchantments.containsKey(ench); + return hasEnchants() && enchantments.containsKey(ench); } @Override public int getEnchantLevel(Enchantment ench) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - Integer level = this.hasEnchants() ? this.enchantments.get(ench) : null; + Integer level = hasEnchants() ? enchantments.get(ench) : null; if (level == null) { return 0; } @@ -1020,18 +1172,18 @@ public int getEnchantLevel(Enchantment ench) { @Override public Map getEnchants() { - return this.hasEnchants() ? ImmutableMap.copyOf(this.enchantments) : ImmutableMap.of(); + return hasEnchants() ? ImmutableMap.copyOf(enchantments) : ImmutableMap.of(); } @Override public boolean addEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - if (this.enchantments == null) { - this.enchantments = new LinkedHashMap(4); + if (enchantments == null) { + enchantments = new LinkedHashMap(4); } if (ignoreRestrictions || level >= ench.getStartLevel() && level <= ench.getMaxLevel()) { - Integer old = this.enchantments.put(ench, level); + Integer old = enchantments.put(ench, level); return old == null || old != level; } return false; @@ -1040,42 +1192,42 @@ public boolean addEnchant(Enchantment ench, int level, boolean ignoreRestriction @Override public boolean removeEnchant(Enchantment ench) { Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); - boolean enchantmentRemoved = this.hasEnchants() && this.enchantments.remove(ench) != null; + boolean enchantmentRemoved = hasEnchants() && enchantments.remove(ench) != null; // If we no longer have any enchantments, then clear enchantment tag - if (enchantmentRemoved && this.enchantments.isEmpty()) { - this.enchantments = null; + if (enchantmentRemoved && enchantments.isEmpty()) { + enchantments = null; } return enchantmentRemoved; } @Override public void removeEnchantments() { - if (this.hasEnchants()) { - this.enchantments.clear(); + if (hasEnchants()) { + enchantments.clear(); } } @Override public boolean hasEnchants() { - return !(this.enchantments == null || this.enchantments.isEmpty()); + return !(enchantments == null || enchantments.isEmpty()); } @Override public boolean hasConflictingEnchant(Enchantment ench) { - return CraftMetaItem.checkConflictingEnchants(this.enchantments, ench); + return checkConflictingEnchants(enchantments, ench); } @Override public void addItemFlags(ItemFlag... hideFlags) { for (ItemFlag f : hideFlags) { - this.hideFlag |= this.getBitModifier(f); + this.hideFlag |= getBitModifier(f); } } @Override public void removeItemFlags(ItemFlag... hideFlags) { for (ItemFlag f : hideFlags) { - this.hideFlag &= ~this.getBitModifier(f); + this.hideFlag &= ~getBitModifier(f); } } @@ -1084,7 +1236,7 @@ public Set getItemFlags() { Set currentFlags = EnumSet.noneOf(ItemFlag.class); for (ItemFlag f : ItemFlag.values()) { - if (this.hasItemFlag(f)) { + if (hasItemFlag(f)) { currentFlags.add(f); } } @@ -1094,7 +1246,7 @@ public Set getItemFlags() { @Override public boolean hasItemFlag(ItemFlag flag) { - int bitModifier = this.getBitModifier(flag); + int bitModifier = getBitModifier(flag); return (this.hideFlag & bitModifier) == bitModifier; } @@ -1113,23 +1265,23 @@ public void setLore(List lore) { this.lore = null; } else { if (this.lore == null) { - this.lore = new ArrayList(lore.size()); + this.lore = new ArrayList(lore.size()); } else { this.lore.clear(); } - CraftMetaItem.safelyAdd(lore, this.lore, false); + safelyAdd(lore, this.lore, false); } } @Override public boolean hasCustomModelData() { - return this.customModelData != null; + return customModelData != null; } @Override public int getCustomModelData() { - Preconditions.checkState(this.hasCustomModelData(), "We don't have CustomModelData! Check hasCustomModelData first!"); - return this.customModelData; + Preconditions.checkState(hasCustomModelData(), "We don't have CustomModelData! Check hasCustomModelData first!"); + return customModelData; } @Override @@ -1137,6 +1289,22 @@ public void setCustomModelData(Integer data) { this.customModelData = data; } + @Override + public boolean hasEnchantable() { + return enchantableValue != null; + } + + @Override + public int getEnchantable() { + Preconditions.checkState(hasEnchantable(), "We don't have Enchantable! Check hasEnchantable first!"); + return enchantableValue; + } + + @Override + public void setEnchantable(Integer data) { + this.enchantableValue = data; + } + @Override public boolean hasBlockData() { return this.blockData != null; @@ -1144,8 +1312,8 @@ public boolean hasBlockData() { @Override public BlockData getBlockData(Material material) { - BlockState defaultData = CraftBlockType.bukkitToMinecraft(material).defaultBlockState(); - return CraftBlockData.fromData((this.hasBlockData()) ? new BlockItemStateProperties(this.blockData).apply(defaultData) : defaultData); + IBlockData defaultData = CraftBlockType.bukkitToMinecraft(material).defaultBlockState(); + return CraftBlockData.fromData((hasBlockData()) ? new BlockItemStateProperties(blockData).apply(defaultData) : defaultData); } @Override @@ -1155,12 +1323,12 @@ public void setBlockData(BlockData blockData) { @Override public int getRepairCost() { - return this.repairCost; + return repairCost; } @Override public void setRepairCost(int cost) { // TODO: Does this have limits? - this.repairCost = cost; + repairCost = cost; } @Override @@ -1173,9 +1341,39 @@ public void setHideTooltip(boolean hideTooltip) { this.hideTooltip = hideTooltip; } + @Override + public boolean hasTooltipStyle() { + return this.tooltipStyle != null; + } + + @Override + public NamespacedKey getTooltipStyle() { + return this.tooltipStyle; + } + + @Override + public void setTooltipStyle(NamespacedKey tooltipStyle) { + this.tooltipStyle = tooltipStyle; + } + + @Override + public boolean hasItemModel() { + return this.itemModel != null; + } + + @Override + public NamespacedKey getItemModel() { + return this.itemModel; + } + + @Override + public void setItemModel(NamespacedKey itemModel) { + this.itemModel = itemModel; + } + @Override public boolean isUnbreakable() { - return this.unbreakable; + return unbreakable; } @Override @@ -1190,7 +1388,7 @@ public boolean hasEnchantmentGlintOverride() { @Override public Boolean getEnchantmentGlintOverride() { - Preconditions.checkState(this.hasEnchantmentGlintOverride(), "We don't have enchantment_glint_override! Check hasEnchantmentGlintOverride first!"); + Preconditions.checkState(hasEnchantmentGlintOverride(), "We don't have enchantment_glint_override! Check hasEnchantmentGlintOverride first!"); return this.enchantmentGlintOverride; } @@ -1199,14 +1397,39 @@ public void setEnchantmentGlintOverride(Boolean override) { this.enchantmentGlintOverride = override; } + @Override + public boolean isGlider() { + return this.glider; + } + + @Override + public void setGlider(boolean glider) { + this.glider = glider; + } + @Override public boolean isFireResistant() { - return this.fireResistant; + return hasDamageResistant() && DamageTypeTags.IS_FIRE.equals(getDamageResistant()); } @Override public void setFireResistant(boolean fireResistant) { - this.fireResistant = fireResistant; + setDamageResistant(DamageTypeTags.IS_FIRE); + } + + @Override + public boolean hasDamageResistant() { + return this.damageResistant != null; + } + + @Override + public Tag getDamageResistant() { + return (hasDamageResistant()) ? Bukkit.getTag(DamageTypeTags.REGISTRY_DAMAGE_TYPES, CraftNamespacedKey.fromMinecraft(this.damageResistant.location()), DamageType.class) : null; + } + + @Override + public void setDamageResistant(Tag tag) { + this.damageResistant = (tag != null) ? ((CraftDamageTag) tag).getHandle().key() : null; } @Override @@ -1216,7 +1439,7 @@ public boolean hasMaxStackSize() { @Override public int getMaxStackSize() { - Preconditions.checkState(this.hasMaxStackSize(), "We don't have max_stack_size! Check hasMaxStackSize first!"); + Preconditions.checkState(hasMaxStackSize(), "We don't have max_stack_size! Check hasMaxStackSize first!"); return this.maxStackSize; } @@ -1234,7 +1457,7 @@ public boolean hasRarity() { @Override public ItemRarity getRarity() { - Preconditions.checkState(this.hasRarity(), "We don't have rarity! Check hasRarity first!"); + Preconditions.checkState(hasRarity(), "We don't have rarity! Check hasRarity first!"); return this.rarity; } @@ -1243,6 +1466,36 @@ public void setRarity(ItemRarity rarity) { this.rarity = rarity; } + @Override + public boolean hasUseRemainder() { + return this.useRemainder != null; + } + + @Override + public ItemStack getUseRemainder() { + return this.useRemainder; + } + + @Override + public void setUseRemainder(ItemStack useRemainder) { + this.useRemainder = useRemainder; + } + + @Override + public boolean hasUseCooldown() { + return this.useCooldown != null; + } + + @Override + public UseCooldownComponent getUseCooldown() { + return (this.hasUseCooldown()) ? new CraftUseCooldownComponent(this.useCooldown) : new CraftUseCooldownComponent(new UseCooldown(0)); + } + + @Override + public void setUseCooldown(UseCooldownComponent cooldown) { + this.useCooldown = (cooldown == null) ? null : new CraftUseCooldownComponent((CraftUseCooldownComponent) cooldown); + } + @Override public boolean hasFood() { return this.food != null; @@ -1250,7 +1503,7 @@ public boolean hasFood() { @Override public FoodComponent getFood() { - return (this.hasFood()) ? new CraftFoodComponent(this.food) : new CraftFoodComponent(new FoodProperties(0, 0, false, 0, Optional.empty(), Collections.emptyList())); + return (this.hasFood()) ? new CraftFoodComponent(this.food) : new CraftFoodComponent(new FoodInfo(0, 0, false)); } @Override @@ -1273,6 +1526,21 @@ public void setTool(ToolComponent tool) { this.tool = (tool == null) ? null : new CraftToolComponent((CraftToolComponent) tool); } + @Override + public boolean hasEquippable() { + return this.equippable != null; + } + + @Override + public EquippableComponent getEquippable() { + return (this.hasEquippable()) ? new CraftEquippableComponent(this.equippable) : new CraftEquippableComponent(Equippable.builder(EnumItemSlot.HEAD).build()); + } + + @Override + public void setEquippable(EquippableComponent equippable) { + this.equippable = (equippable == null) ? null : new CraftEquippableComponent((CraftEquippableComponent) this.equippable); + } + @Override public boolean hasJukeboxPlayable() { return this.jukebox != null; @@ -1290,25 +1558,25 @@ public void setJukeboxPlayable(JukeboxPlayableComponent jukeboxPlayable) { @Override public boolean hasAttributeModifiers() { - return this.attributeModifiers != null && !this.attributeModifiers.isEmpty(); + return attributeModifiers != null && !attributeModifiers.isEmpty(); } @Override public Multimap getAttributeModifiers() { - return this.hasAttributeModifiers() ? ImmutableMultimap.copyOf(this.attributeModifiers) : null; + return hasAttributeModifiers() ? ImmutableMultimap.copyOf(attributeModifiers) : null; } private void checkAttributeList() { - if (this.attributeModifiers == null) { - this.attributeModifiers = LinkedHashMultimap.create(); + if (attributeModifiers == null) { + attributeModifiers = LinkedHashMultimap.create(); } } @Override public Multimap getAttributeModifiers(@Nullable EquipmentSlot slot) { - this.checkAttributeList(); + checkAttributeList(); SetMultimap result = LinkedHashMultimap.create(); - for (Map.Entry entry : this.attributeModifiers.entries()) { + for (Map.Entry entry : attributeModifiers.entries()) { if (entry.getValue().getSlot() == null || entry.getValue().getSlot() == slot) { result.put(entry.getKey(), entry.getValue()); } @@ -1319,18 +1587,18 @@ public Multimap getAttributeModifiers(@Nullable Eq @Override public Collection getAttributeModifiers(@Nonnull Attribute attribute) { Preconditions.checkNotNull(attribute, "Attribute cannot be null"); - return this.attributeModifiers.containsKey(attribute) ? ImmutableList.copyOf(this.attributeModifiers.get(attribute)) : null; + return attributeModifiers.containsKey(attribute) ? ImmutableList.copyOf(attributeModifiers.get(attribute)) : null; } @Override public boolean addAttributeModifier(@Nonnull Attribute attribute, @Nonnull AttributeModifier modifier) { Preconditions.checkNotNull(attribute, "Attribute cannot be null"); Preconditions.checkNotNull(modifier, "AttributeModifier cannot be null"); - this.checkAttributeList(); - for (Map.Entry entry : this.attributeModifiers.entries()) { + checkAttributeList(); + for (Map.Entry entry : attributeModifiers.entries()) { Preconditions.checkArgument(!entry.getValue().getKey().equals(modifier.getKey()), "Cannot register AttributeModifier. Modifier is already applied! %s", modifier); } - return this.attributeModifiers.put(attribute, modifier); + return attributeModifiers.put(attribute, modifier); } @Override @@ -1340,7 +1608,7 @@ public void setAttributeModifiers(@Nullable Multimap> iterator = attributeModifiers.entries().iterator(); @@ -1358,15 +1626,15 @@ public void setAttributeModifiers(@Nullable Multimap> iter = this.attributeModifiers.entries().iterator(); + Iterator> iter = attributeModifiers.entries().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -1384,9 +1652,9 @@ public boolean removeAttributeModifier(@Nullable EquipmentSlot slot) { public boolean removeAttributeModifier(@Nonnull Attribute attribute, @Nonnull AttributeModifier modifier) { Preconditions.checkNotNull(attribute, "Attribute cannot be null"); Preconditions.checkNotNull(modifier, "AttributeModifier cannot be null"); - this.checkAttributeList(); + checkAttributeList(); int removed = 0; - Iterator> iter = this.attributeModifiers.entries().iterator(); + Iterator> iter = attributeModifiers.entries().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -1407,9 +1675,9 @@ public boolean removeAttributeModifier(@Nonnull Attribute attribute, @Nonnull At @Override public String getAsString() { CraftMetaItem.Applicator tag = new CraftMetaItem.Applicator(); - this.applyToItem(tag); + applyToItem(tag); DataComponentPatch patch = tag.build(); - Tag nbt = DataComponentPatch.CODEC.encodeStart(MinecraftServer.getDefaultRegistryAccess().createSerializationContext(NbtOps.INSTANCE), patch).getOrThrow(); + NBTBase nbt = DataComponentPatch.CODEC.encodeStart(MinecraftServer.getDefaultRegistryAccess().createSerializationContext(DynamicOpsNBT.INSTANCE), patch).getOrThrow(); return nbt.toString(); } @@ -1419,18 +1687,18 @@ public String getAsComponentString() { applyToItem(tag); DataComponentPatch patch = tag.build(); - RegistryAccess registryAccess = CraftRegistry.getMinecraftRegistry(); - DynamicOps ops = registryAccess.createSerializationContext(NbtOps.INSTANCE); - net.minecraft.core.Registry> componentTypeRegistry = registryAccess.registryOrThrow(Registries.DATA_COMPONENT_TYPE); + IRegistryCustom registryAccess = CraftRegistry.getMinecraftRegistry(); + DynamicOps ops = registryAccess.createSerializationContext(DynamicOpsNBT.INSTANCE); + IRegistry> componentTypeRegistry = registryAccess.lookupOrThrow(Registries.DATA_COMPONENT_TYPE); StringJoiner componentString = new StringJoiner(",", "[", "]"); - for (Map.Entry, Optional> entry : patch.entrySet()) { + for (Entry, Optional> entry : patch.entrySet()) { DataComponentType componentType = entry.getKey(); Optional componentValue = entry.getValue(); String componentKey = componentTypeRegistry.getResourceKey(componentType).orElseThrow().location().toString(); if (componentValue.isPresent()) { - Tag componentValueAsNBT = (Tag) ((DataComponentType) componentType).codecOrThrow().encodeStart(ops, componentValue.get()).getOrThrow(); + NBTBase componentValueAsNBT = (NBTBase) ((DataComponentType) componentType).codecOrThrow().encodeStart(ops, componentValue.get()).getOrThrow(); String componentValueAsNBTString = new SnbtPrinterTagVisitor("", 0, new ArrayList<>()).visit(componentValueAsNBT); componentString.add(componentKey + "=" + componentValueAsNBTString); } else { @@ -1470,12 +1738,12 @@ private static boolean compareModifiers(Multimap f @Override public boolean hasDamage() { - return this.damage > 0; + return damage > 0; } @Override public int getDamage() { - return this.damage; + return damage; } @Override @@ -1490,7 +1758,7 @@ public boolean hasMaxDamage() { @Override public int getMaxDamage() { - Preconditions.checkState(this.hasMaxDamage(), "We don't have max_damage! Check hasMaxDamage first!"); + Preconditions.checkState(hasMaxDamage(), "We don't have max_damage! Check hasMaxDamage first!"); return this.maxDamage; } @@ -1525,22 +1793,29 @@ boolean equalsCommon(CraftMetaItem that) { && (this.hasEnchants() ? that.hasEnchants() && this.enchantments.equals(that.enchantments) : !that.hasEnchants()) && (Objects.equals(this.lore, that.lore)) && (this.hasCustomModelData() ? that.hasCustomModelData() && this.customModelData.equals(that.customModelData) : !that.hasCustomModelData()) + && (this.hasEnchantable() ? that.hasEnchantable() && this.enchantableValue.equals(that.enchantableValue) : !that.hasEnchantable()) && (this.hasBlockData() ? that.hasBlockData() && this.blockData.equals(that.blockData) : !that.hasBlockData()) && (this.hasRepairCost() ? that.hasRepairCost() && this.repairCost == that.repairCost : !that.hasRepairCost()) - && (this.hasAttributeModifiers() ? that.hasAttributeModifiers() && CraftMetaItem.compareModifiers(this.attributeModifiers, that.attributeModifiers) : !that.hasAttributeModifiers()) + && (this.hasAttributeModifiers() ? that.hasAttributeModifiers() && compareModifiers(this.attributeModifiers, that.attributeModifiers) : !that.hasAttributeModifiers()) && (this.unhandledTags.equals(that.unhandledTags)) && (this.removedTags.equals(that.removedTags)) && (Objects.equals(this.customTag, that.customTag)) && (this.persistentDataContainer.equals(that.persistentDataContainer)) && (this.hideFlag == that.hideFlag) && (this.isHideTooltip() == that.isHideTooltip()) + && (this.hasTooltipStyle() ? that.hasTooltipStyle() && this.tooltipStyle.equals(that.tooltipStyle) : !that.hasTooltipStyle()) + && (this.hasItemModel() ? that.hasItemModel() && this.itemModel.equals(that.itemModel) : !that.hasItemModel()) && (this.isUnbreakable() == that.isUnbreakable()) && (this.hasEnchantmentGlintOverride() ? that.hasEnchantmentGlintOverride() && this.enchantmentGlintOverride.equals(that.enchantmentGlintOverride) : !that.hasEnchantmentGlintOverride()) - && (this.fireResistant == that.fireResistant) + && (this.glider == that.glider) + && (this.hasDamageResistant() ? that.hasDamageResistant() && this.damageResistant.equals(that.damageResistant) : !that.hasDamageResistant()) && (this.hasMaxStackSize() ? that.hasMaxStackSize() && this.maxStackSize.equals(that.maxStackSize) : !that.hasMaxStackSize()) && (this.rarity == that.rarity) + && (this.hasUseRemainder() ? that.hasUseRemainder() && this.useRemainder.equals(that.useRemainder) : !that.hasUseRemainder()) + && (this.hasUseCooldown() ? that.hasUseCooldown() && this.useCooldown.equals(that.useCooldown) : !that.hasUseCooldown()) && (this.hasFood() ? that.hasFood() && this.food.equals(that.food) : !that.hasFood()) && (this.hasTool() ? that.hasTool() && this.tool.equals(that.tool) : !that.hasTool()) + && (this.hasEquippable() ? that.hasEquippable() && this.equippable.equals(that.equippable) : !that.hasEquippable()) && (this.hasJukeboxPlayable() ? that.hasJukeboxPlayable() && this.jukebox.equals(that.jukebox) : !that.hasJukeboxPlayable()) && (this.hasDamage() ? that.hasDamage() && this.damage == that.damage : !that.hasDamage()) && (this.hasMaxDamage() ? that.hasMaxDamage() && this.maxDamage.equals(that.maxDamage) : !that.hasMaxDamage()) @@ -1559,37 +1834,44 @@ boolean notUncommon(CraftMetaItem meta) { @Override public final int hashCode() { - return this.applyHash(); + return applyHash(); } @Overridden int applyHash() { int hash = 3; - hash = 61 * hash + (this.hasDisplayName() ? this.displayName.hashCode() : 0); - hash = 61 * hash + (this.hasItemName() ? this.itemName.hashCode() : 0); - hash = 61 * hash + ((this.lore != null) ? this.lore.hashCode() : 0); - hash = 61 * hash + (this.hasCustomModelData() ? this.customModelData.hashCode() : 0); - hash = 61 * hash + (this.hasBlockData() ? this.blockData.hashCode() : 0); - hash = 61 * hash + (this.hasEnchants() ? this.enchantments.hashCode() : 0); - hash = 61 * hash + (this.hasRepairCost() ? this.repairCost : 0); - hash = 61 * hash + this.unhandledTags.hashCode(); + hash = 61 * hash + (hasDisplayName() ? this.displayName.hashCode() : 0); + hash = 61 * hash + (hasItemName() ? this.itemName.hashCode() : 0); + hash = 61 * hash + ((lore != null) ? this.lore.hashCode() : 0); + hash = 61 * hash + (hasCustomModelData() ? this.customModelData.hashCode() : 0); + hash = 61 * hash + (hasEnchantable() ? this.enchantableValue.hashCode() : 0); + hash = 61 * hash + (hasBlockData() ? this.blockData.hashCode() : 0); + hash = 61 * hash + (hasEnchants() ? this.enchantments.hashCode() : 0); + hash = 61 * hash + (hasRepairCost() ? this.repairCost : 0); + hash = 61 * hash + unhandledTags.hashCode(); hash = 61 * hash + removedTags.hashCode(); - hash = 61 * hash + ((this.customTag != null) ? this.customTag.hashCode() : 0); - hash = 61 * hash + (!this.persistentDataContainer.isEmpty() ? this.persistentDataContainer.hashCode() : 0); - hash = 61 * hash + this.hideFlag; - hash = 61 * hash + (this.isHideTooltip() ? 1231 : 1237); - hash = 61 * hash + (this.isUnbreakable() ? 1231 : 1237); - hash = 61 * hash + (this.hasEnchantmentGlintOverride() ? this.enchantmentGlintOverride.hashCode() : 0); - hash = 61 * hash + (this.isFireResistant() ? 1231 : 1237); - hash = 61 * hash + (this.hasMaxStackSize() ? this.maxStackSize.hashCode() : 0); - hash = 61 * hash + (this.hasRarity() ? this.rarity.hashCode() : 0); - hash = 61 * hash + (this.hasFood() ? this.food.hashCode() : 0); + hash = 61 * hash + ((customTag != null) ? this.customTag.hashCode() : 0); + hash = 61 * hash + (!persistentDataContainer.isEmpty() ? persistentDataContainer.hashCode() : 0); + hash = 61 * hash + hideFlag; + hash = 61 * hash + (isHideTooltip() ? 1231 : 1237); + hash = 61 * hash + (hasTooltipStyle() ? this.tooltipStyle.hashCode() : 0); + hash = 61 * hash + (hasItemModel() ? this.itemModel.hashCode() : 0); + hash = 61 * hash + (isUnbreakable() ? 1231 : 1237); + hash = 61 * hash + (hasEnchantmentGlintOverride() ? this.enchantmentGlintOverride.hashCode() : 0); + hash = 61 * hash + (isGlider() ? 1231 : 1237); + hash = 61 * hash + (hasDamageResistant() ? this.damageResistant.hashCode() : 0); + hash = 61 * hash + (hasMaxStackSize() ? this.maxStackSize.hashCode() : 0); + hash = 61 * hash + (hasRarity() ? this.rarity.hashCode() : 0); + hash = 61 * hash + (hasUseRemainder() ? this.useRemainder.hashCode() : 0); + hash = 61 * hash + (hasUseCooldown() ? this.useCooldown.hashCode() : 0); + hash = 61 * hash + (hasFood() ? this.food.hashCode() : 0); hash = 61 * hash + (hasTool() ? this.tool.hashCode() : 0); hash = 61 * hash + (hasJukeboxPlayable() ? this.jukebox.hashCode() : 0); - hash = 61 * hash + (this.hasDamage() ? this.damage : 0); - hash = 61 * hash + (this.hasMaxDamage() ? 1231 : 1237); - hash = 61 * hash + (this.hasAttributeModifiers() ? this.attributeModifiers.hashCode() : 0); - hash = 61 * hash + this.version; + hash = 61 * hash + (hasEquippable() ? this.equippable.hashCode() : 0); + hash = 61 * hash + (hasDamage() ? this.damage : 0); + hash = 61 * hash + (hasMaxDamage() ? 1231 : 1237); + hash = 61 * hash + (hasAttributeModifiers() ? this.attributeModifiers.hashCode() : 0); + hash = 61 * hash + version; return hash; } @@ -1599,9 +1881,10 @@ public CraftMetaItem clone() { try { CraftMetaItem clone = (CraftMetaItem) super.clone(); if (this.lore != null) { - clone.lore = new ArrayList(this.lore); + clone.lore = new ArrayList(this.lore); } clone.customModelData = this.customModelData; + clone.enchantableValue = this.enchantableValue; clone.blockData = this.blockData; if (this.enchantments != null) { clone.enchantments = new LinkedHashMap(this.enchantments); @@ -1613,20 +1896,32 @@ public CraftMetaItem clone() { clone.customTag = this.customTag.copy(); } clone.removedTags = Sets.newHashSet(this.removedTags); - clone.persistentDataContainer = new CraftPersistentDataContainer(this.persistentDataContainer.getRaw(), CraftMetaItem.DATA_TYPE_REGISTRY); + clone.persistentDataContainer = new CraftPersistentDataContainer(this.persistentDataContainer.getRaw(), DATA_TYPE_REGISTRY); clone.hideFlag = this.hideFlag; clone.hideTooltip = this.hideTooltip; + clone.tooltipStyle = this.tooltipStyle; + clone.itemModel = this.itemModel; clone.unbreakable = this.unbreakable; clone.enchantmentGlintOverride = this.enchantmentGlintOverride; - clone.fireResistant = this.fireResistant; - clone.maxStackSize = this.maxStackSize; - clone.rarity = this.rarity; + clone.glider = glider; + clone.damageResistant = damageResistant; + clone.maxStackSize = maxStackSize; + clone.rarity = rarity; + if (this.hasUseRemainder()) { + clone.useRemainder = useRemainder.clone(); + } + if (this.hasUseCooldown()) { + clone.useCooldown = new CraftUseCooldownComponent(useCooldown); + } if (this.hasFood()) { - clone.food = new CraftFoodComponent(this.food); + clone.food = new CraftFoodComponent(food); } if (this.hasTool()) { clone.tool = new CraftToolComponent(tool); } + if (this.hasEquippable()) { + clone.equippable = new CraftEquippableComponent(equippable); + } if (this.hasJukeboxPlayable()) { clone.jukebox = new CraftJukeboxComponent(jukebox); } @@ -1642,119 +1937,146 @@ public CraftMetaItem clone() { @Override public final Map serialize() { ImmutableMap.Builder map = ImmutableMap.builder(); - map.put(SerializableMeta.TYPE_FIELD, SerializableMeta.classMap.get(this.getClass())); - this.serialize(map); + map.put(SerializableMeta.TYPE_FIELD, SerializableMeta.classMap.get(getClass())); + serialize(map); return map.build(); } @Overridden ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { - if (this.hasDisplayName()) { - builder.put(CraftMetaItem.NAME.BUKKIT, CraftChatMessage.toJSON(this.displayName)); + if (hasDisplayName()) { + builder.put(NAME.BUKKIT, CraftChatMessage.toJSON(displayName)); } - if (this.hasItemName()) { - builder.put(CraftMetaItem.ITEM_NAME.BUKKIT, CraftChatMessage.toJSON(this.itemName)); + if (hasItemName()) { + builder.put(ITEM_NAME.BUKKIT, CraftChatMessage.toJSON(itemName)); } - if (this.hasLore()) { + if (hasLore()) { // SPIGOT-7625: Convert lore to json before serializing it List jsonLore = new ArrayList<>(); - for (Component component : this.lore) { + for (IChatBaseComponent component : lore) { jsonLore.add(CraftChatMessage.toJSON(component)); } - builder.put(CraftMetaItem.LORE.BUKKIT, jsonLore); + builder.put(LORE.BUKKIT, jsonLore); } - if (this.hasCustomModelData()) { - builder.put(CraftMetaItem.CUSTOM_MODEL_DATA.BUKKIT, this.customModelData); + if (hasCustomModelData()) { + builder.put(CUSTOM_MODEL_DATA.BUKKIT, customModelData); + } + if (hasEnchantable()) { + builder.put(ENCHANTABLE.BUKKIT, enchantableValue); } - if (this.hasBlockData()) { - builder.put(CraftMetaItem.BLOCK_DATA.BUKKIT, this.blockData); + if (hasBlockData()) { + builder.put(BLOCK_DATA.BUKKIT, blockData); } - CraftMetaItem.serializeEnchantments(this.enchantments, builder, CraftMetaItem.ENCHANTMENTS); - CraftMetaItem.serializeModifiers(this.attributeModifiers, builder, CraftMetaItem.ATTRIBUTES); + serializeEnchantments(enchantments, builder, ENCHANTMENTS); + serializeModifiers(attributeModifiers, builder, ATTRIBUTES); - if (this.hasRepairCost()) { - builder.put(CraftMetaItem.REPAIR.BUKKIT, this.repairCost); + if (hasRepairCost()) { + builder.put(REPAIR.BUKKIT, repairCost); } List hideFlags = new ArrayList(); - for (ItemFlag hideFlagEnum : this.getItemFlags()) { + for (ItemFlag hideFlagEnum : getItemFlags()) { hideFlags.add(CraftItemFlag.bukkitToString(hideFlagEnum)); } if (!hideFlags.isEmpty()) { - builder.put(CraftMetaItem.HIDEFLAGS.BUKKIT, hideFlags); + builder.put(HIDEFLAGS.BUKKIT, hideFlags); + } + + if (isHideTooltip()) { + builder.put(HIDE_TOOLTIP.BUKKIT, hideTooltip); + } + + if (hasTooltipStyle()) { + builder.put(TOOLTIP_STYLE.BUKKIT, tooltipStyle.toString()); } - if (this.isHideTooltip()) { - builder.put(CraftMetaItem.HIDE_TOOLTIP.BUKKIT, this.hideTooltip); + if (hasItemModel()) { + builder.put(ITEM_MODEL.BUKKIT, itemModel.toString()); } - if (this.isUnbreakable()) { - builder.put(CraftMetaItem.UNBREAKABLE.BUKKIT, this.unbreakable); + if (isUnbreakable()) { + builder.put(UNBREAKABLE.BUKKIT, unbreakable); } - if (this.hasEnchantmentGlintOverride()) { - builder.put(CraftMetaItem.ENCHANTMENT_GLINT_OVERRIDE.BUKKIT, this.enchantmentGlintOverride); + if (hasEnchantmentGlintOverride()) { + builder.put(ENCHANTMENT_GLINT_OVERRIDE.BUKKIT, enchantmentGlintOverride); } - if (this.isFireResistant()) { - builder.put(CraftMetaItem.FIRE_RESISTANT.BUKKIT, this.fireResistant); + if (isGlider()) { + builder.put(GLIDER.BUKKIT, glider); } - if (this.hasMaxStackSize()) { - builder.put(CraftMetaItem.MAX_STACK_SIZE.BUKKIT, this.maxStackSize); + if (hasDamageResistant()) { + builder.put(DAMAGE_RESISTANT.BUKKIT, damageResistant.location().toString()); } - if (this.hasRarity()) { - builder.put(CraftMetaItem.RARITY.BUKKIT, this.rarity.name()); + if (hasMaxStackSize()) { + builder.put(MAX_STACK_SIZE.BUKKIT, maxStackSize); } - if (this.hasFood()) { - builder.put(CraftMetaItem.FOOD.BUKKIT, this.food); + if (hasRarity()) { + builder.put(RARITY.BUKKIT, rarity.name()); + } + + if (hasUseRemainder()) { + builder.put(USE_REMAINDER.BUKKIT, useRemainder); + } + + if (hasUseCooldown()) { + builder.put(USE_COOLDOWN.BUKKIT, useCooldown); + } + + if (hasFood()) { + builder.put(FOOD.BUKKIT, food); } if (hasTool()) { builder.put(TOOL.BUKKIT, tool); } + if (hasEquippable()) { + builder.put(EQUIPPABLE.BUKKIT, equippable); + } + if (hasJukeboxPlayable()) { builder.put(JUKEBOX_PLAYABLE.BUKKIT, jukebox); } - if (this.hasDamage()) { - builder.put(CraftMetaItem.DAMAGE.BUKKIT, this.damage); + if (hasDamage()) { + builder.put(DAMAGE.BUKKIT, damage); } - if (this.hasMaxDamage()) { - builder.put(CraftMetaItem.MAX_DAMAGE.BUKKIT, this.maxDamage); + if (hasMaxDamage()) { + builder.put(MAX_DAMAGE.BUKKIT, maxDamage); } - final Map internalTags = new HashMap(); - this.serializeInternal(internalTags); + final Map internalTags = new HashMap(); + serializeInternal(internalTags); if (!internalTags.isEmpty()) { - CompoundTag internal = new CompoundTag(); - for (Map.Entry e : internalTags.entrySet()) { + NBTTagCompound internal = new NBTTagCompound(); + for (Map.Entry e : internalTags.entrySet()) { internal.put(e.getKey(), e.getValue()); } try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); - NbtIo.writeCompressed(internal, buf); + NBTCompressedStreamTools.writeCompressed(internal, buf); builder.put("internal", Base64.getEncoder().encodeToString(buf.toByteArray())); } catch (IOException ex) { Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); } } - if (!this.unhandledTags.isEmpty()) { - Tag unhandled = DataComponentPatch.CODEC.encodeStart(MinecraftServer.getDefaultRegistryAccess().createSerializationContext(NbtOps.INSTANCE), this.unhandledTags.build()).getOrThrow(IllegalStateException::new); + if (!unhandledTags.isEmpty()) { + NBTBase unhandled = DataComponentPatch.CODEC.encodeStart(MinecraftServer.getDefaultRegistryAccess().createSerializationContext(DynamicOpsNBT.INSTANCE), unhandledTags.build()).getOrThrow(IllegalStateException::new); try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); - NbtIo.writeCompressed((CompoundTag) unhandled, buf); + NBTCompressedStreamTools.writeCompressed((NBTTagCompound) unhandled, buf); builder.put("unhandled", Base64.getEncoder().encodeToString(buf.toByteArray())); } catch (IOException ex) { Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); @@ -1762,8 +2084,8 @@ ImmutableMap.Builder serialize(ImmutableMap.Builder> componentTypeRegistry = registryAccess.registryOrThrow(Registries.DATA_COMPONENT_TYPE); + IRegistryCustom registryAccess = CraftRegistry.getMinecraftRegistry(); + IRegistry> componentTypeRegistry = registryAccess.lookupOrThrow(Registries.DATA_COMPONENT_TYPE); List removedTags = new ArrayList<>(); for (DataComponentType removed : this.removedTags) { @@ -1775,14 +2097,14 @@ ImmutableMap.Builder serialize(ImmutableMap.Builder serialize(ImmutableMap.Builder unhandledTags) { + void serializeInternal(final Map unhandledTags) { } static void serializeEnchantments(Map enchantments, ImmutableMap.Builder builder, ItemMetaKey key) { @@ -1827,7 +2149,7 @@ static void serializeModifiers(Multimap modifiers, builder.put(key.BUKKIT, mods); } - static void safelyAdd(Iterable addFrom, Collection addTo, boolean possiblyJsonInput) { + static void safelyAdd(Iterable addFrom, Collection addTo, boolean possiblyJsonInput) { if (addFrom == null) { return; } @@ -1841,15 +2163,15 @@ static void safelyAdd(Iterable addFrom, Collection addTo, boolean throw new IllegalArgumentException(addFrom + " cannot contain non-string " + object.getClass().getName()); } - addTo.add(Component.empty()); + addTo.add(IChatBaseComponent.empty()); } else { String entry = object.toString(); - Component component = (possiblyJsonInput) ? CraftChatMessage.fromJSONOrString(entry) : CraftChatMessage.fromStringOrNull(entry); + IChatBaseComponent component = (possiblyJsonInput) ? CraftChatMessage.fromJSONOrString(entry) : CraftChatMessage.fromStringOrNull(entry); if (component != null) { addTo.add(component); } else { - addTo.add(Component.empty()); + addTo.add(IChatBaseComponent.empty()); } } } @@ -1871,11 +2193,11 @@ static boolean checkConflictingEnchants(Map enchantments, @Override public final String toString() { - return SerializableMeta.classMap.get(this.getClass()) + "_META:" + this.serialize(); // TODO: cry + return SerializableMeta.classMap.get(getClass()) + "_META:" + serialize(); // TODO: cry } public int getVersion() { - return this.version; + return version; } @Override @@ -1884,30 +2206,37 @@ public void setVersion(int version) { } public static Set getHandledTags() { - synchronized (CraftMetaItem.HANDLED_TAGS) { - if (CraftMetaItem.HANDLED_TAGS.isEmpty()) { - CraftMetaItem.HANDLED_TAGS.addAll(Arrays.asList( - CraftMetaItem.NAME.TYPE, - CraftMetaItem.ITEM_NAME.TYPE, - CraftMetaItem.LORE.TYPE, - CraftMetaItem.CUSTOM_MODEL_DATA.TYPE, - CraftMetaItem.BLOCK_DATA.TYPE, - CraftMetaItem.REPAIR.TYPE, - CraftMetaItem.ENCHANTMENTS.TYPE, - CraftMetaItem.HIDE_ADDITIONAL_TOOLTIP.TYPE, - CraftMetaItem.HIDE_TOOLTIP.TYPE, - CraftMetaItem.UNBREAKABLE.TYPE, - CraftMetaItem.ENCHANTMENT_GLINT_OVERRIDE.TYPE, - CraftMetaItem.FIRE_RESISTANT.TYPE, - CraftMetaItem.MAX_STACK_SIZE.TYPE, - CraftMetaItem.RARITY.TYPE, - CraftMetaItem.FOOD.TYPE, + synchronized (HANDLED_TAGS) { + if (HANDLED_TAGS.isEmpty()) { + HANDLED_TAGS.addAll(Arrays.asList( + NAME.TYPE, + ITEM_NAME.TYPE, + LORE.TYPE, + CUSTOM_MODEL_DATA.TYPE, + ENCHANTABLE.TYPE, + BLOCK_DATA.TYPE, + REPAIR.TYPE, + ENCHANTMENTS.TYPE, + HIDE_ADDITIONAL_TOOLTIP.TYPE, + HIDE_TOOLTIP.TYPE, + TOOLTIP_STYLE.TYPE, + ITEM_MODEL.TYPE, + UNBREAKABLE.TYPE, + ENCHANTMENT_GLINT_OVERRIDE.TYPE, + GLIDER.TYPE, + DAMAGE_RESISTANT.TYPE, + MAX_STACK_SIZE.TYPE, + RARITY.TYPE, + USE_REMAINDER.TYPE, + USE_COOLDOWN.TYPE, + FOOD.TYPE, TOOL.TYPE, + EQUIPPABLE.TYPE, JUKEBOX_PLAYABLE.TYPE, - CraftMetaItem.DAMAGE.TYPE, - CraftMetaItem.MAX_DAMAGE.TYPE, - CraftMetaItem.CUSTOM_DATA.TYPE, - CraftMetaItem.ATTRIBUTES.TYPE, + DAMAGE.TYPE, + MAX_DAMAGE.TYPE, + CUSTOM_DATA.TYPE, + ATTRIBUTES.TYPE, CraftMetaArmor.TRIM.TYPE, CraftMetaArmorStand.ENTITY_TAG.TYPE, CraftMetaBanner.PATTERNS.TYPE, @@ -1917,6 +2246,7 @@ public static Set getHandledTags() { CraftMetaMap.MAP_COLOR.TYPE, CraftMetaMap.MAP_ID.TYPE, CraftMetaPotion.POTION_CONTENTS.TYPE, + CraftMetaShield.BASE_COLOR.TYPE, CraftMetaSkull.SKULL_PROFILE.TYPE, CraftMetaSkull.NOTE_BLOCK_SOUND.TYPE, CraftMetaSpawnEgg.ENTITY_TAG.TYPE, @@ -1939,7 +2269,7 @@ public static Set getHandledTags() { CraftMetaOminousBottle.OMINOUS_BOTTLE_AMPLIFIER.TYPE )); } - return CraftMetaItem.HANDLED_TAGS; + return HANDLED_TAGS; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java index bd44481a..334f809c 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java @@ -7,8 +7,9 @@ import java.util.Map; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.resources.ResourceLocation; -import org.bukkit.Material; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.item.crafting.IRecipe; import org.bukkit.NamespacedKey; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftNamespacedKey; @@ -17,7 +18,7 @@ @DelegateDeserialization(SerializableMeta.class) public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBookMeta { - static final ItemMetaKeyType> BOOK_RECIPES = new ItemMetaKeyType<>(DataComponents.RECIPES, "Recipes"); + static final ItemMetaKeyType>>> BOOK_RECIPES = new ItemMetaKeyType<>(DataComponents.RECIPES, "Recipes"); static final int MAX_RECIPES = Short.MAX_VALUE; protected List recipes = new ArrayList(); @@ -34,11 +35,11 @@ public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBo CraftMetaKnowledgeBook(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaKnowledgeBook.BOOK_RECIPES).ifPresent((pages) -> { + getOrEmpty(tag, BOOK_RECIPES).ifPresent((pages) -> { for (int i = 0; i < pages.size(); i++) { - ResourceLocation recipe = pages.get(i); + MinecraftKey recipe = pages.get(i).location(); - this.addRecipe(CraftNamespacedKey.fromMinecraft(recipe)); + addRecipe(CraftNamespacedKey.fromMinecraft(recipe)); } }); } @@ -46,11 +47,11 @@ public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBo CraftMetaKnowledgeBook(Map map) { super(map); - Iterable pages = SerializableMeta.getObject(Iterable.class, map, CraftMetaKnowledgeBook.BOOK_RECIPES.BUKKIT, true); + Iterable pages = SerializableMeta.getObject(Iterable.class, map, BOOK_RECIPES.BUKKIT, true); if (pages != null) { for (Object page : pages) { if (page instanceof String) { - this.addRecipe(CraftNamespacedKey.fromString((String) page)); + addRecipe(CraftNamespacedKey.fromString((String) page)); } } } @@ -60,39 +61,34 @@ public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBo void applyToItem(CraftMetaItem.Applicator itemData) { super.applyToItem(itemData); - if (this.hasRecipes()) { - List list = new ArrayList<>(); + if (hasRecipes()) { + List>> list = new ArrayList<>(); for (NamespacedKey recipe : this.recipes) { - list.add(CraftNamespacedKey.toMinecraft(recipe)); + list.add(CraftRecipe.toMinecraft(recipe)); } - itemData.put(CraftMetaKnowledgeBook.BOOK_RECIPES, list); + itemData.put(BOOK_RECIPES, list); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isBookEmpty(); + return super.isEmpty() && isBookEmpty(); } boolean isBookEmpty() { - return !(this.hasRecipes()); - } - - @Override - boolean applicableTo(Material type) { - return type == Material.KNOWLEDGE_BOOK; + return !(hasRecipes()); } @Override public boolean hasRecipes() { - return !this.recipes.isEmpty(); + return !recipes.isEmpty(); } @Override public void addRecipe(NamespacedKey... recipes) { for (NamespacedKey recipe : recipes) { if (recipe != null) { - if (this.recipes.size() >= CraftMetaKnowledgeBook.MAX_RECIPES) { + if (this.recipes.size() >= MAX_RECIPES) { return; } @@ -103,21 +99,21 @@ public void addRecipe(NamespacedKey... recipes) { @Override public List getRecipes() { - return Collections.unmodifiableList(this.recipes); + return Collections.unmodifiableList(recipes); } @Override public void setRecipes(List recipes) { this.recipes.clear(); for (NamespacedKey recipe : recipes) { - this.addRecipe(recipe); + addRecipe(recipe); } } @Override public CraftMetaKnowledgeBook clone() { CraftMetaKnowledgeBook meta = (CraftMetaKnowledgeBook) super.clone(); - meta.recipes = new ArrayList(this.recipes); + meta.recipes = new ArrayList(recipes); return meta; } @@ -125,7 +121,7 @@ public CraftMetaKnowledgeBook clone() { int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasRecipes()) { + if (hasRecipes()) { hash = 61 * hash + 17 * this.recipes.hashCode(); } return original != hash ? CraftMetaKnowledgeBook.class.hashCode() ^ hash : hash; @@ -139,26 +135,26 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaKnowledgeBook) { CraftMetaKnowledgeBook that = (CraftMetaKnowledgeBook) meta; - return (this.hasRecipes() ? that.hasRecipes() && this.recipes.equals(that.recipes) : !that.hasRecipes()); + return (hasRecipes() ? that.hasRecipes() && this.recipes.equals(that.recipes) : !that.hasRecipes()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaKnowledgeBook || this.isBookEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaKnowledgeBook || isBookEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasRecipes()) { + if (hasRecipes()) { List recipesString = new ArrayList(); - for (NamespacedKey recipe : this.recipes) { + for (NamespacedKey recipe : recipes) { recipesString.add(recipe.toString()); } - builder.put(CraftMetaKnowledgeBook.BOOK_RECIPES.BUKKIT, recipesString); + builder.put(BOOK_RECIPES.BUKKIT, recipesString); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java index b97e9a8f..e4f521d9 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java @@ -2,9 +2,7 @@ import static org.bukkit.craftbukkit.inventory.CraftItemFactory.*; import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.collect.Sets; import java.util.Map; -import java.util.Set; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.component.DyedItemColor; @@ -12,57 +10,53 @@ import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.meta.ColorableArmorMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; @DelegateDeserialization(SerializableMeta.class) class CraftMetaLeatherArmor extends CraftMetaItem implements LeatherArmorMeta { - private static final Set LEATHER_ARMOR_MATERIALS = Sets.newHashSet( - Material.LEATHER_HELMET, - Material.LEATHER_HORSE_ARMOR, - Material.LEATHER_CHESTPLATE, - Material.LEATHER_LEGGINGS, - Material.LEATHER_BOOTS, - Material.WOLF_ARMOR - ); - static final ItemMetaKeyType COLOR = new ItemMetaKeyType<>(DataComponents.DYED_COLOR, "color"); private Color color = DEFAULT_LEATHER_COLOR; CraftMetaLeatherArmor(CraftMetaItem meta) { super(meta); - CraftMetaLeatherArmor.readColor(this, meta); + readColor(this, meta); } CraftMetaLeatherArmor(DataComponentPatch tag) { super(tag); - CraftMetaLeatherArmor.readColor(this, tag); + readColor(this, tag); } CraftMetaLeatherArmor(Map map) { super(map); - CraftMetaLeatherArmor.readColor(this, map); + readColor(this, map); } @Override void applyToItem(CraftMetaItem.Applicator itemTag) { super.applyToItem(itemTag); - CraftMetaLeatherArmor.applyColor(this, itemTag); + applyColor(this, itemTag); } @Override boolean isEmpty() { - return super.isEmpty() && this.isLeatherArmorEmpty(); + return super.isEmpty() && isLeatherArmorEmpty(); } boolean isLeatherArmorEmpty() { - return !(this.hasColor()); + return !(hasColor()); } @Override boolean applicableTo(Material type) { - return CraftMetaLeatherArmor.LEATHER_ARMOR_MATERIALS.contains(type); + if (!type.isItem()) { + return false; + } + + return type.asItemType().getItemMetaClass() == LeatherArmorMeta.class || type.asItemType().getItemMetaClass() == ColorableArmorMeta.class; } @Override @@ -72,7 +66,7 @@ public CraftMetaLeatherArmor clone() { @Override public Color getColor() { - return this.color; + return color; } @Override @@ -81,14 +75,14 @@ public void setColor(Color color) { } boolean hasColor() { - return CraftMetaLeatherArmor.hasColor(this); + return hasColor(this); } @Override Builder serialize(Builder builder) { super.serialize(builder); - CraftMetaLeatherArmor.serialize(this, builder); + serialize(this, builder); return builder; } @@ -101,22 +95,22 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaLeatherArmor) { CraftMetaLeatherArmor that = (CraftMetaLeatherArmor) meta; - return this.color.equals(that.color); + return color.equals(that.color); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaLeatherArmor || this.isLeatherArmorEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaLeatherArmor || isLeatherArmorEmpty()); } @Override int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasColor()) { - hash ^= this.color.hashCode(); + if (hasColor()) { + hash ^= color.hashCode(); } return original != hash ? CraftMetaLeatherArmor.class.hashCode() ^ hash : hash; } @@ -130,7 +124,7 @@ static void readColor(LeatherArmorMeta meta, CraftMetaItem other) { } static void readColor(LeatherArmorMeta meta, DataComponentPatch tag) { - getOrEmpty(tag, CraftMetaLeatherArmor.COLOR).ifPresent((dyedItemColor) -> { + getOrEmpty(tag, COLOR).ifPresent((dyedItemColor) -> { if (!dyedItemColor.showInTooltip()) { meta.addItemFlags(ItemFlag.HIDE_DYE); } @@ -144,7 +138,7 @@ static void readColor(LeatherArmorMeta meta, DataComponentPatch tag) { } static void readColor(LeatherArmorMeta meta, Map map) { - meta.setColor(SerializableMeta.getObject(Color.class, map, CraftMetaLeatherArmor.COLOR.BUKKIT, true)); + meta.setColor(SerializableMeta.getObject(Color.class, map, COLOR.BUKKIT, true)); } static boolean hasColor(LeatherArmorMeta meta) { @@ -152,14 +146,14 @@ static boolean hasColor(LeatherArmorMeta meta) { } static void applyColor(LeatherArmorMeta meta, CraftMetaItem.Applicator tag) { - if (CraftMetaLeatherArmor.hasColor(meta)) { - tag.put(CraftMetaLeatherArmor.COLOR, new DyedItemColor(meta.getColor().asRGB(), !meta.hasItemFlag(ItemFlag.HIDE_DYE))); + if (hasColor(meta)) { + tag.put(COLOR, new DyedItemColor(meta.getColor().asRGB(), !meta.hasItemFlag(ItemFlag.HIDE_DYE))); } } static void serialize(LeatherArmorMeta meta, Builder builder) { - if (CraftMetaLeatherArmor.hasColor(meta)) { - builder.put(CraftMetaLeatherArmor.COLOR.BUKKIT, meta.getColor()); + if (hasColor(meta)) { + builder.put(COLOR.BUKKIT, meta.getColor()); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java index 6b34a8d3..4936b3bd 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java @@ -10,7 +10,6 @@ import net.minecraft.world.level.saveddata.maps.MapId; import org.bukkit.Bukkit; import org.bukkit.Color; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.inventory.meta.MapMeta; import org.bukkit.map.MapView; @@ -29,7 +28,7 @@ class CraftMetaMap extends CraftMetaItem implements MapMeta { static final byte SCALING_FALSE = (byte) 2; private Integer mapId; - private byte scaling = CraftMetaMap.SCALING_EMPTY; + private byte scaling = SCALING_EMPTY; private Color color; CraftMetaMap(CraftMetaItem meta) { @@ -48,17 +47,17 @@ class CraftMetaMap extends CraftMetaItem implements MapMeta { CraftMetaMap(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaMap.MAP_ID).ifPresent((mapId) -> { + getOrEmpty(tag, MAP_ID).ifPresent((mapId) -> { this.mapId = mapId.id(); }); - getOrEmpty(tag, CraftMetaMap.MAP_POST_PROCESSING).ifPresent((mapPostProcessing) -> { - this.scaling = (mapPostProcessing == MapPostProcessing.SCALE) ? CraftMetaMap.SCALING_TRUE : CraftMetaMap.SCALING_FALSE; + getOrEmpty(tag, MAP_POST_PROCESSING).ifPresent((mapPostProcessing) -> { + this.scaling = (mapPostProcessing == MapPostProcessing.SCALE) ? SCALING_TRUE : SCALING_FALSE; }); - getOrEmpty(tag, CraftMetaMap.MAP_COLOR).ifPresent((mapColor) -> { + getOrEmpty(tag, MAP_COLOR).ifPresent((mapColor) -> { try { - this.color = Color.fromRGB(mapColor.rgb()); + color = Color.fromRGB(mapColor.rgb()); } catch (IllegalArgumentException ex) { // Invalid colour } @@ -68,24 +67,24 @@ class CraftMetaMap extends CraftMetaItem implements MapMeta { CraftMetaMap(Map map) { super(map); - Integer id = SerializableMeta.getObject(Integer.class, map, CraftMetaMap.MAP_ID.BUKKIT, true); + Integer id = SerializableMeta.getObject(Integer.class, map, MAP_ID.BUKKIT, true); if (id != null) { - this.setMapId(id); + setMapId(id); } - Boolean scaling = SerializableMeta.getObject(Boolean.class, map, CraftMetaMap.MAP_SCALING.BUKKIT, true); + Boolean scaling = SerializableMeta.getObject(Boolean.class, map, MAP_SCALING.BUKKIT, true); if (scaling != null) { - this.setScaling(scaling); + setScaling(scaling); } - String locName = SerializableMeta.getString(map, CraftMetaMap.MAP_LOC_NAME.BUKKIT, true); + String locName = SerializableMeta.getString(map, MAP_LOC_NAME.BUKKIT, true); if (locName != null) { - this.setLocationName(locName); + setLocationName(locName); } - Color color = SerializableMeta.getObject(Color.class, map, CraftMetaMap.MAP_COLOR.BUKKIT, true); + Color color = SerializableMeta.getObject(Color.class, map, MAP_COLOR.BUKKIT, true); if (color != null) { - this.setColor(color); + setColor(color); } } @@ -93,41 +92,36 @@ class CraftMetaMap extends CraftMetaItem implements MapMeta { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.hasMapId()) { - tag.put(CraftMetaMap.MAP_ID, new MapId(this.getMapId())); + if (hasMapId()) { + tag.put(MAP_ID, new MapId(getMapId())); } - if (this.hasScaling()) { - tag.put(CraftMetaMap.MAP_POST_PROCESSING, (this.isScaling()) ? MapPostProcessing.SCALE : MapPostProcessing.LOCK); + if (hasScaling()) { + tag.put(MAP_POST_PROCESSING, (isScaling()) ? MapPostProcessing.SCALE : MapPostProcessing.LOCK); } - if (this.hasColor()) { - tag.put(CraftMetaMap.MAP_COLOR, new MapItemColor(this.color.asRGB())); + if (hasColor()) { + tag.put(MAP_COLOR, new MapItemColor(color.asRGB())); } } - @Override - boolean applicableTo(Material type) { - return type == Material.FILLED_MAP; - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isMapEmpty(); + return super.isEmpty() && isMapEmpty(); } boolean isMapEmpty() { - return !(this.hasMapId() || this.hasScaling() | this.hasLocationName() || this.hasColor()); + return !(hasMapId() || hasScaling() | hasLocationName() || hasColor()); } @Override public boolean hasMapId() { - return this.mapId != null; + return mapId != null; } @Override public int getMapId() { - return this.mapId; + return mapId; } @Override @@ -137,13 +131,13 @@ public void setMapId(int id) { @Override public boolean hasMapView() { - return this.mapId != null; + return mapId != null; } @Override public MapView getMapView() { - Preconditions.checkState(this.hasMapView(), "Item does not have map associated - check hasMapView() first!"); - return Bukkit.getMap(this.mapId); + Preconditions.checkState(hasMapView(), "Item does not have map associated - check hasMapView() first!"); + return Bukkit.getMap(mapId); } @Override @@ -152,17 +146,17 @@ public void setMapView(MapView map) { } boolean hasScaling() { - return this.scaling != CraftMetaMap.SCALING_EMPTY; + return scaling != SCALING_EMPTY; } @Override public boolean isScaling() { - return this.scaling == CraftMetaMap.SCALING_TRUE; + return scaling == SCALING_TRUE; } @Override public void setScaling(boolean scaling) { - this.scaling = scaling ? CraftMetaMap.SCALING_TRUE : CraftMetaMap.SCALING_FALSE; + this.scaling = scaling ? SCALING_TRUE : SCALING_FALSE; } @Override @@ -204,15 +198,15 @@ boolean equalsCommon(CraftMetaItem meta) { CraftMetaMap that = (CraftMetaMap) meta; return (this.scaling == that.scaling) - && (this.hasMapId() ? that.hasMapId() && this.mapId.equals(that.mapId) : !that.hasMapId()) - && (this.hasColor() ? that.hasColor() && this.color.equals(that.color) : !that.hasColor()); + && (hasMapId() ? that.hasMapId() && this.mapId.equals(that.mapId) : !that.hasMapId()) + && (hasColor() ? that.hasColor() && this.color.equals(that.color) : !that.hasColor()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaMap || this.isMapEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaMap || isMapEmpty()); } @Override @@ -220,14 +214,14 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasMapId()) { - hash = 61 * hash + this.mapId.hashCode(); + if (hasMapId()) { + hash = 61 * hash + mapId.hashCode(); } - if (this.hasScaling()) { - hash ^= 0x22222222 << (this.isScaling() ? 1 : -1); + if (hasScaling()) { + hash ^= 0x22222222 << (isScaling() ? 1 : -1); } - if (this.hasColor()) { - hash = 61 * hash + this.color.hashCode(); + if (hasColor()) { + hash = 61 * hash + color.hashCode(); } return original != hash ? CraftMetaMap.class.hashCode() ^ hash : hash; @@ -243,16 +237,16 @@ public CraftMetaMap clone() { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.hasMapId()) { - builder.put(CraftMetaMap.MAP_ID.BUKKIT, this.getMapId()); + if (hasMapId()) { + builder.put(MAP_ID.BUKKIT, getMapId()); } - if (this.hasScaling()) { - builder.put(CraftMetaMap.MAP_SCALING.BUKKIT, this.isScaling()); + if (hasScaling()) { + builder.put(MAP_SCALING.BUKKIT, isScaling()); } - if (this.hasColor()) { - builder.put(CraftMetaMap.MAP_COLOR.BUKKIT, this.getColor()); + if (hasColor()) { + builder.put(MAP_COLOR.BUKKIT, getColor()); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMusicInstrument.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMusicInstrument.java index d7bf9044..1492081b 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMusicInstrument.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMusicInstrument.java @@ -6,10 +6,7 @@ import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.Instrument; -import org.bukkit.Material; import org.bukkit.MusicInstrument; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.CraftMusicInstrument; import org.bukkit.inventory.meta.MusicInstrumentMeta; @@ -32,7 +29,7 @@ public class CraftMetaMusicInstrument extends CraftMetaItem implements MusicInst CraftMetaMusicInstrument(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaMusicInstrument.GOAT_HORN_INSTRUMENT).ifPresent((instrument) -> { + getOrEmpty(tag, GOAT_HORN_INSTRUMENT).ifPresent((instrument) -> { this.instrument = CraftMusicInstrument.minecraftHolderToBukkit(instrument); }); } @@ -40,7 +37,7 @@ public class CraftMetaMusicInstrument extends CraftMetaItem implements MusicInst CraftMetaMusicInstrument(Map map) { super(map); - String instrumentString = SerializableMeta.getString(map, CraftMetaMusicInstrument.GOAT_HORN_INSTRUMENT.BUKKIT, true); + String instrumentString = SerializableMeta.getString(map, GOAT_HORN_INSTRUMENT.BUKKIT, true); if (instrumentString != null) { this.instrument = CraftMusicInstrument.stringToBukkit(instrumentString); } @@ -50,16 +47,11 @@ public class CraftMetaMusicInstrument extends CraftMetaItem implements MusicInst void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.instrument != null) { - tag.put(CraftMetaMusicInstrument.GOAT_HORN_INSTRUMENT, CraftMusicInstrument.bukkitToMinecraftHolder(this.instrument)); + if (instrument != null) { + tag.put(GOAT_HORN_INSTRUMENT, CraftMusicInstrument.bukkitToMinecraftHolder(instrument)); } } - @Override - boolean applicableTo(Material type) { - return type == Material.GOAT_HORN; - } - @Override boolean equalsCommon(CraftMetaItem meta) { if (!super.equalsCommon(meta)) { @@ -74,16 +66,16 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaMusicInstrument || this.isInstrumentEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaMusicInstrument || isInstrumentEmpty()); } @Override boolean isEmpty() { - return super.isEmpty() && this.isInstrumentEmpty(); + return super.isEmpty() && isInstrumentEmpty(); } boolean isInstrumentEmpty() { - return this.instrument == null; + return instrument == null; } @Override @@ -91,8 +83,8 @@ int applyHash() { final int orginal; int hash = orginal = super.applyHash(); - if (this.hasInstrument()) { - hash = 61 * hash + this.instrument.hashCode(); + if (hasInstrument()) { + hash = 61 * hash + instrument.hashCode(); } return orginal != hash ? CraftMetaMusicInstrument.class.hashCode() ^ hash : hash; @@ -109,8 +101,8 @@ public CraftMetaMusicInstrument clone() { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.hasInstrument()) { - builder.put(CraftMetaMusicInstrument.GOAT_HORN_INSTRUMENT.BUKKIT, CraftMusicInstrument.bukkitToString(instrument)); + if (hasInstrument()) { + builder.put(GOAT_HORN_INSTRUMENT.BUKKIT, CraftMusicInstrument.bukkitToString(instrument)); } return builder; @@ -118,11 +110,11 @@ ImmutableMap.Builder serialize(ImmutableMap.Builder OMINOUS_BOTTLE_AMPLIFIER = new ItemMetaKeyType<>(DataComponents.OMINOUS_BOTTLE_AMPLIFIER, "ominous-bottle-amplifier"); + static final ItemMetaKeyType OMINOUS_BOTTLE_AMPLIFIER = new ItemMetaKeyType<>(DataComponents.OMINOUS_BOTTLE_AMPLIFIER, "ominous-bottle-amplifier"); private Integer ominousBottleAmplifier; CraftMetaOminousBottle(CraftMetaItem meta) { @@ -21,21 +21,21 @@ public class CraftMetaOminousBottle extends CraftMetaItem implements OminousBott return; } CraftMetaOminousBottle bottleMeta = (CraftMetaOminousBottle) meta; - this.ominousBottleAmplifier = bottleMeta.ominousBottleAmplifier; + ominousBottleAmplifier = bottleMeta.ominousBottleAmplifier; } CraftMetaOminousBottle(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaOminousBottle.OMINOUS_BOTTLE_AMPLIFIER).ifPresent((amplifier) -> { - this.ominousBottleAmplifier = amplifier; + getOrEmpty(tag, OMINOUS_BOTTLE_AMPLIFIER).ifPresent((amplifier) -> { + ominousBottleAmplifier = amplifier.value(); }); } CraftMetaOminousBottle(Map map) { super(map); - Integer ominousBottleAmplifier = SerializableMeta.getObject(Integer.class, map, CraftMetaOminousBottle.OMINOUS_BOTTLE_AMPLIFIER.BUKKIT, true); + Integer ominousBottleAmplifier = SerializableMeta.getObject(Integer.class, map, OMINOUS_BOTTLE_AMPLIFIER.BUKKIT, true); if (ominousBottleAmplifier != null) { - this.setAmplifier(ominousBottleAmplifier); + setAmplifier(ominousBottleAmplifier); } } @@ -43,23 +43,18 @@ public class CraftMetaOminousBottle extends CraftMetaItem implements OminousBott void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.hasAmplifier()) { - tag.put(CraftMetaOminousBottle.OMINOUS_BOTTLE_AMPLIFIER, this.ominousBottleAmplifier); + if (hasAmplifier()) { + tag.put(OMINOUS_BOTTLE_AMPLIFIER, new OminousBottleAmplifier(ominousBottleAmplifier)); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isBottleEmpty(); + return super.isEmpty() && isBottleEmpty(); } boolean isBottleEmpty() { - return !(this.hasAmplifier()); - } - - @Override - boolean applicableTo(Material type) { - return type == Material.OMINOUS_BOTTLE; + return !(hasAmplifier()); } @Override @@ -70,12 +65,12 @@ public CraftMetaOminousBottle clone() { @Override public boolean hasAmplifier() { - return this.ominousBottleAmplifier != null; + return ominousBottleAmplifier != null; } @Override public int getAmplifier() { - return this.ominousBottleAmplifier; + return ominousBottleAmplifier; } @Override @@ -88,8 +83,8 @@ public void setAmplifier(int amplifier) { int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasAmplifier()) { - hash = 61 * hash + this.ominousBottleAmplifier.hashCode(); + if (hasAmplifier()) { + hash = 61 * hash + ominousBottleAmplifier.hashCode(); } return original != hash ? CraftMetaOminousBottle.class.hashCode() ^ hash : hash; @@ -103,22 +98,22 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaOminousBottle) { CraftMetaOminousBottle that = (CraftMetaOminousBottle) meta; - return (this.hasAmplifier() ? that.hasAmplifier() && this.ominousBottleAmplifier.equals(that.ominousBottleAmplifier) : !that.hasAmplifier()); + return (hasAmplifier() ? that.hasAmplifier() && this.ominousBottleAmplifier.equals(that.ominousBottleAmplifier) : !that.hasAmplifier()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaOminousBottle || this.isBottleEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaOminousBottle || isBottleEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasAmplifier()) { - builder.put(CraftMetaOminousBottle.OMINOUS_BOTTLE_AMPLIFIER.BUKKIT, this.ominousBottleAmplifier); + if (hasAmplifier()) { + builder.put(OMINOUS_BOTTLE_AMPLIFIER.BUKKIT, ominousBottleAmplifier); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java index b73d6428..1aec60cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java @@ -3,22 +3,19 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; import net.minecraft.core.Holder; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.item.alchemy.Potion; +import net.minecraft.world.effect.MobEffect; import net.minecraft.world.item.alchemy.PotionContents; +import net.minecraft.world.item.alchemy.PotionRegistry; import org.bukkit.Color; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; import org.bukkit.craftbukkit.potion.CraftPotionType; @@ -32,22 +29,17 @@ @DelegateDeserialization(SerializableMeta.class) class CraftMetaPotion extends CraftMetaItem implements PotionMeta { - private static final Set POTION_MATERIALS = Sets.newHashSet( - Material.POTION, - Material.SPLASH_POTION, - Material.LINGERING_POTION, - Material.TIPPED_ARROW - ); - @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) static final ItemMetaKeyType POTION_CONTENTS = new ItemMetaKeyType<>(DataComponents.POTION_CONTENTS); static final ItemMetaKey POTION_EFFECTS = new ItemMetaKey("custom-effects"); static final ItemMetaKey POTION_COLOR = new ItemMetaKey("custom-color"); + static final ItemMetaKey CUSTOM_NAME = new ItemMetaKey("custom-name"); static final ItemMetaKey DEFAULT_POTION = new ItemMetaKey("potion-type"); private PotionType type; private List customEffects; private Color color; + private String customName; CraftMetaPotion(CraftMetaItem meta) { super(meta); @@ -56,6 +48,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { } this.type = potionMeta.type; this.color = potionMeta.color; + this.customName = potionMeta.customName; if (potionMeta.hasCustomEffects()) { this.customEffects = new ArrayList<>(potionMeta.customEffects); } @@ -63,25 +56,29 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { CraftMetaPotion(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaPotion.POTION_CONTENTS).ifPresent((potionContents) -> { + getOrEmpty(tag, POTION_CONTENTS).ifPresent((potionContents) -> { potionContents.potion().ifPresent((potion) -> { - this.type = CraftPotionType.minecraftHolderToBukkit(potion); + type = CraftPotionType.minecraftHolderToBukkit(potion); }); potionContents.customColor().ifPresent((customColor) -> { try { - this.color = Color.fromRGB(customColor); + color = Color.fromRGB(customColor); } catch (IllegalArgumentException ex) { // Invalid colour } }); - List list = potionContents.customEffects(); + potionContents.customName().ifPresent((name) -> { + customName = name; + }); + + List list = potionContents.customEffects(); int length = list.size(); - this.customEffects = new ArrayList<>(length); + customEffects = new ArrayList<>(length); for (int i = 0; i < length; i++) { - MobEffectInstance effect = list.get(i); + MobEffect effect = list.get(i); PotionEffectType type = CraftPotionEffectType.minecraftHolderToBukkit(effect.getEffect()); // SPIGOT-4047: Vanilla just disregards these if (type == null) { @@ -93,31 +90,36 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { boolean ambient = effect.isAmbient(); boolean particles = effect.isVisible(); boolean icon = effect.showIcon(); - this.customEffects.add(new PotionEffect(type, duration, amp, ambient, particles, icon)); + customEffects.add(new PotionEffect(type, duration, amp, ambient, particles, icon)); } }); } CraftMetaPotion(Map map) { super(map); - String typeString = SerializableMeta.getString(map, CraftMetaPotion.DEFAULT_POTION.BUKKIT, true); + String typeString = SerializableMeta.getString(map, DEFAULT_POTION.BUKKIT, true); if (typeString != null) { - this.type = CraftPotionType.stringToBukkit(typeString); + type = CraftPotionType.stringToBukkit(typeString); } - Color color = SerializableMeta.getObject(Color.class, map, CraftMetaPotion.POTION_COLOR.BUKKIT, true); + Color color = SerializableMeta.getObject(Color.class, map, POTION_COLOR.BUKKIT, true); if (color != null) { - this.setColor(color); + setColor(color); } - Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, CraftMetaPotion.POTION_EFFECTS.BUKKIT, true); + String name = SerializableMeta.getString(map, CUSTOM_NAME.BUKKIT, true); + if (name != null) { + setCustomName(name); + } + + Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, POTION_EFFECTS.BUKKIT, true); if (rawEffectList == null) { return; } for (Object obj : rawEffectList) { Preconditions.checkArgument(obj instanceof PotionEffect, "Object (%s) in effect list is not valid", obj.getClass()); - this.addCustomEffect((PotionEffect) obj, true); + addCustomEffect((PotionEffect) obj, true); } } @@ -125,37 +127,37 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - Optional> defaultPotion = (this.hasBasePotionType()) ? Optional.of(CraftPotionType.bukkitToMinecraftHolder(this.type)) : Optional.empty(); - Optional potionColor = (this.hasColor()) ? Optional.of(this.color.asRGB()) : Optional.empty(); + if (isPotionEmpty()) { + return; + } + + Optional> defaultPotion = (hasBasePotionType()) ? Optional.of(CraftPotionType.bukkitToMinecraftHolder(type)) : Optional.empty(); + Optional potionColor = (hasColor()) ? Optional.of(this.color.asRGB()) : Optional.empty(); + Optional customName = Optional.ofNullable(this.customName); - List effectList = new ArrayList<>(); - if (this.customEffects != null) { - for (PotionEffect effect : this.customEffects) { - effectList.add(new MobEffectInstance(CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles(), effect.hasIcon())); + List effectList = new ArrayList<>(); + if (customEffects != null) { + for (PotionEffect effect : customEffects) { + effectList.add(new MobEffect(CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles(), effect.hasIcon())); } } - tag.put(CraftMetaPotion.POTION_CONTENTS, new PotionContents(defaultPotion, potionColor, effectList)); + tag.put(POTION_CONTENTS, new PotionContents(defaultPotion, potionColor, effectList, customName)); } @Override boolean isEmpty() { - return super.isEmpty() && this.isPotionEmpty(); + return super.isEmpty() && isPotionEmpty(); } boolean isPotionEmpty() { - return (this.type == null) && !(this.hasCustomEffects() || this.hasColor()); - } - - @Override - boolean applicableTo(Material type) { - return CraftMetaPotion.POTION_MATERIALS.contains(type); + return (type == null) && !(hasCustomEffects() || hasColor() || hasCustomName()); } @Override public CraftMetaPotion clone() { CraftMetaPotion clone = (CraftMetaPotion) super.clone(); - clone.type = this.type; + clone.type = type; if (this.customEffects != null) { clone.customEffects = new ArrayList<>(this.customEffects); } @@ -174,28 +176,28 @@ public PotionData getBasePotionData() { @Override public void setBasePotionType(PotionType potionType) { - this.type = potionType; + type = potionType; } @Override public PotionType getBasePotionType() { - return this.type; + return type; } @Override public boolean hasBasePotionType() { - return this.type != null; + return type != null; } @Override public boolean hasCustomEffects() { - return this.customEffects != null; + return customEffects != null && !customEffects.isEmpty(); } @Override public List getCustomEffects() { - if (this.hasCustomEffects()) { - return ImmutableList.copyOf(this.customEffects); + if (hasCustomEffects()) { + return ImmutableList.copyOf(customEffects); } return ImmutableList.of(); } @@ -204,23 +206,23 @@ public List getCustomEffects() { public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { Preconditions.checkArgument(effect != null, "Potion effect cannot be null"); - int index = this.indexOfEffect(effect.getType()); + int index = indexOfEffect(effect.getType()); if (index != -1) { if (overwrite) { - PotionEffect old = this.customEffects.get(index); + PotionEffect old = customEffects.get(index); if (old.getAmplifier() == effect.getAmplifier() && old.getDuration() == effect.getDuration() && old.isAmbient() == effect.isAmbient()) { return false; } - this.customEffects.set(index, effect); + customEffects.set(index, effect); return true; } else { return false; } } else { - if (this.customEffects == null) { - this.customEffects = new ArrayList<>(); + if (customEffects == null) { + customEffects = new ArrayList<>(); } - this.customEffects.add(effect); + customEffects.add(effect); return true; } } @@ -229,12 +231,12 @@ public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { public boolean removeCustomEffect(PotionEffectType type) { Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); - if (!this.hasCustomEffects()) { + if (!hasCustomEffects()) { return false; } boolean changed = false; - Iterator iterator = this.customEffects.iterator(); + Iterator iterator = customEffects.iterator(); while (iterator.hasNext()) { PotionEffect effect = iterator.next(); if (type.equals(effect.getType())) { @@ -242,8 +244,8 @@ public boolean removeCustomEffect(PotionEffectType type) { changed = true; } } - if (this.customEffects.isEmpty()) { - this.customEffects = null; + if (customEffects.isEmpty()) { + customEffects = null; } return changed; } @@ -251,30 +253,30 @@ public boolean removeCustomEffect(PotionEffectType type) { @Override public boolean hasCustomEffect(PotionEffectType type) { Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); - return this.indexOfEffect(type) != -1; + return indexOfEffect(type) != -1; } @Override public boolean setMainEffect(PotionEffectType type) { Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); - int index = this.indexOfEffect(type); + int index = indexOfEffect(type); if (index == -1 || index == 0) { return false; } - PotionEffect old = this.customEffects.get(0); - this.customEffects.set(0, this.customEffects.get(index)); - this.customEffects.set(index, old); + PotionEffect old = customEffects.get(0); + customEffects.set(0, customEffects.get(index)); + customEffects.set(index, old); return true; } private int indexOfEffect(PotionEffectType type) { - if (!this.hasCustomEffects()) { + if (!hasCustomEffects()) { return -1; } - for (int i = 0; i < this.customEffects.size(); i++) { - if (this.customEffects.get(i).getType().equals(type)) { + for (int i = 0; i < customEffects.size(); i++) { + if (customEffects.get(i).getType().equals(type)) { return i; } } @@ -283,19 +285,19 @@ private int indexOfEffect(PotionEffectType type) { @Override public boolean clearCustomEffects() { - boolean changed = this.hasCustomEffects(); - this.customEffects = null; + boolean changed = hasCustomEffects(); + customEffects = null; return changed; } @Override public boolean hasColor() { - return this.color != null; + return color != null; } @Override public Color getColor() { - return this.color; + return color; } @Override @@ -303,18 +305,36 @@ public void setColor(Color color) { this.color = color; } + @Override + public boolean hasCustomName() { + return this.customName != null; + } + + @Override + public String getCustomName() { + return this.customName; + } + + @Override + public void setCustomName(String customName) { + this.customName = customName; + } + @Override int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.type != null) { - hash = 73 * hash + this.type.hashCode(); + if (type != null) { + hash = 73 * hash + type.hashCode(); } - if (this.hasColor()) { - hash = 73 * hash + this.color.hashCode(); + if (hasColor()) { + hash = 73 * hash + color.hashCode(); } - if (this.hasCustomEffects()) { - hash = 73 * hash + this.customEffects.hashCode(); + if (hasCustomName()) { + hash = 73 * hash + customName.hashCode(); + } + if (hasCustomEffects()) { + hash = 73 * hash + customEffects.hashCode(); } return original != hash ? CraftMetaPotion.class.hashCode() ^ hash : hash; } @@ -327,31 +347,36 @@ public boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaPotion) { CraftMetaPotion that = (CraftMetaPotion) meta; - return Objects.equals(this.type, that.type) + return Objects.equals(type, that.type) && (this.hasCustomEffects() ? that.hasCustomEffects() && this.customEffects.equals(that.customEffects) : !that.hasCustomEffects()) - && (this.hasColor() ? that.hasColor() && this.color.equals(that.color) : !that.hasColor()); + && (this.hasColor() ? that.hasColor() && this.color.equals(that.color) : !that.hasColor()) + && (this.hasCustomName() ? that.hasCustomName() && this.customName.equals(that.customName) : !that.hasCustomName()); } return true; } @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaPotion || this.isPotionEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaPotion || isPotionEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.type != null) { - builder.put(CraftMetaPotion.DEFAULT_POTION.BUKKIT, CraftPotionType.bukkitToString(this.type)); + if (type != null) { + builder.put(DEFAULT_POTION.BUKKIT, CraftPotionType.bukkitToString(type)); + } + + if (hasColor()) { + builder.put(POTION_COLOR.BUKKIT, getColor()); } - if (this.hasColor()) { - builder.put(CraftMetaPotion.POTION_COLOR.BUKKIT, this.getColor()); + if (hasCustomName()) { + builder.put(CUSTOM_NAME.BUKKIT, getCustomName()); } - if (this.hasCustomEffects()) { - builder.put(CraftMetaPotion.POTION_EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); + if (hasCustomEffects()) { + builder.put(POTION_EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaShield.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaShield.java index 3542c6e7..e87a1dd8 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaShield.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaShield.java @@ -9,6 +9,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.EnumColor; import net.minecraft.world.level.block.entity.BannerPatternLayers; import org.bukkit.DyeColor; import org.bukkit.Material; @@ -25,7 +26,7 @@ @DelegateDeserialization(SerializableMeta.class) public class CraftMetaShield extends CraftMetaItem implements ShieldMeta, BlockStateMeta { - static final ItemMetaKeyType BASE_COLOR = new ItemMetaKeyType<>(DataComponents.BASE_COLOR, "Base", "base-color"); + static final ItemMetaKeyType BASE_COLOR = new ItemMetaKeyType<>(DataComponents.BASE_COLOR, "Base", "base-color"); private Banner banner; @@ -44,19 +45,19 @@ public class CraftMetaShield extends CraftMetaItem implements ShieldMeta, BlockS CraftMetaShield(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaShield.BASE_COLOR).ifPresent((color) -> { - this.banner = CraftMetaShield.getBlockState(DyeColor.getByWoolData((byte) color.getId())); + getOrEmpty(tag, BASE_COLOR).ifPresent((color) -> { + banner = getBlockState(DyeColor.getByWoolData((byte) color.getId())); }); getOrEmpty(tag, CraftMetaBanner.PATTERNS).ifPresent((entityTag) -> { - List patterns = entityTag.layers(); + List patterns = entityTag.layers(); for (int i = 0; i < Math.min(patterns.size(), 20); i++) { - BannerPatternLayers.Layer p = patterns.get(i); + BannerPatternLayers.b p = patterns.get(i); DyeColor color = DyeColor.getByWoolData((byte) p.color().getId()); PatternType pattern = CraftPatternType.minecraftHolderToBukkit(p.pattern()); if (color != null && pattern != null) { - this.addPattern(new Pattern(color, pattern)); + addPattern(new Pattern(color, pattern)); } } }); @@ -65,9 +66,9 @@ public class CraftMetaShield extends CraftMetaItem implements ShieldMeta, BlockS CraftMetaShield(Map map) { super(map); - String baseColor = SerializableMeta.getString(map, CraftMetaShield.BASE_COLOR.BUKKIT, true); + String baseColor = SerializableMeta.getString(map, BASE_COLOR.BUKKIT, true); if (baseColor != null) { - this.banner = CraftMetaShield.getBlockState(DyeColor.valueOf(baseColor)); + banner = getBlockState(DyeColor.valueOf(baseColor)); } Iterable rawPatternList = SerializableMeta.getObject(Iterable.class, map, CraftMetaBanner.PATTERNS.BUKKIT, true); @@ -77,7 +78,7 @@ public class CraftMetaShield extends CraftMetaItem implements ShieldMeta, BlockS for (Object obj : rawPatternList) { Preconditions.checkArgument(obj instanceof Pattern, "Object (%s) in pattern list is not valid", obj.getClass()); - this.addPattern((Pattern) obj); + addPattern((Pattern) obj); } } @@ -85,14 +86,14 @@ public class CraftMetaShield extends CraftMetaItem implements ShieldMeta, BlockS void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.banner != null) { - tag.put(CraftMetaShield.BASE_COLOR, net.minecraft.world.item.DyeColor.byId(this.banner.getBaseColor().getWoolData())); + if (banner != null) { + tag.put(BASE_COLOR, EnumColor.byId(banner.getBaseColor().getWoolData())); - if (this.banner.numberOfPatterns() > 0) { - List newPatterns = new ArrayList<>(); + if (banner.numberOfPatterns() > 0) { + List newPatterns = new ArrayList<>(); - for (Pattern p : this.banner.getPatterns()) { - newPatterns.add(new BannerPatternLayers.Layer(CraftPatternType.bukkitToMinecraftHolder(p.getPattern()), net.minecraft.world.item.DyeColor.byId(p.getColor().getWoolData()))); + for (Pattern p : banner.getPatterns()) { + newPatterns.add(new BannerPatternLayers.b(CraftPatternType.bukkitToMinecraftHolder(p.getPattern()), EnumColor.byId(p.getColor().getWoolData()))); } tag.put(CraftMetaBanner.PATTERNS, new BannerPatternLayers(newPatterns)); @@ -102,94 +103,94 @@ void applyToItem(CraftMetaItem.Applicator tag) { @Override public List getPatterns() { - if (this.banner == null) { + if (banner == null) { return new ArrayList<>(); } - return this.banner.getPatterns(); + return banner.getPatterns(); } @Override public void setPatterns(List patterns) { - if (this.banner == null) { + if (banner == null) { if (patterns.isEmpty()) { return; } - this.banner = CraftMetaShield.getBlockState(null); + banner = getBlockState(null); } - this.banner.setPatterns(patterns); + banner.setPatterns(patterns); } @Override public void addPattern(Pattern pattern) { - if (this.banner == null) { - this.banner = CraftMetaShield.getBlockState(null); + if (banner == null) { + banner = getBlockState(null); } - this.banner.addPattern(pattern); + banner.addPattern(pattern); } @Override public Pattern getPattern(int i) { - if (this.banner == null) { + if (banner == null) { throw new IndexOutOfBoundsException(i); } - return this.banner.getPattern(i); + return banner.getPattern(i); } @Override public Pattern removePattern(int i) { - if (this.banner == null) { + if (banner == null) { throw new IndexOutOfBoundsException(i); } - return this.banner.removePattern(i); + return banner.removePattern(i); } @Override public void setPattern(int i, Pattern pattern) { - if (this.banner == null) { + if (banner == null) { throw new IndexOutOfBoundsException(i); } - this.banner.setPattern(i, pattern); + banner.setPattern(i, pattern); } @Override public int numberOfPatterns() { - if (this.banner == null) { + if (banner == null) { return 0; } - return this.banner.numberOfPatterns(); + return banner.numberOfPatterns(); } @Override public DyeColor getBaseColor() { - if (this.banner == null) { + if (banner == null) { return null; } - return this.banner.getBaseColor(); + return banner.getBaseColor(); } @Override public void setBaseColor(DyeColor baseColor) { if (baseColor == null) { - if (this.banner.numberOfPatterns() > 0) { - this.banner.setBaseColor(DyeColor.WHITE); + if (banner.numberOfPatterns() > 0) { + banner.setBaseColor(DyeColor.WHITE); } else { - this.banner = null; + banner = null; } } else { - if (this.banner == null) { - this.banner = CraftMetaShield.getBlockState(baseColor); + if (banner == null) { + banner = getBlockState(baseColor); } - this.banner.setBaseColor(baseColor); + banner.setBaseColor(baseColor); } } @@ -197,11 +198,11 @@ public void setBaseColor(DyeColor baseColor) { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.banner != null) { - builder.put(CraftMetaShield.BASE_COLOR.BUKKIT, this.banner.getBaseColor().toString()); + if (banner != null) { + builder.put(BASE_COLOR.BUKKIT, banner.getBaseColor().toString()); - if (this.banner.numberOfPatterns() > 0) { - builder.put(CraftMetaBanner.PATTERNS.BUKKIT, this.banner.getPatterns()); + if (banner.numberOfPatterns() > 0) { + builder.put(CraftMetaBanner.PATTERNS.BUKKIT, banner.getPatterns()); } } @@ -212,8 +213,8 @@ ImmutableMap.Builder serialize(ImmutableMap.Builder SKULL_MATERIALS = Sets.newHashSet( - Material.CREEPER_HEAD, - Material.CREEPER_WALL_HEAD, - Material.DRAGON_HEAD, - Material.DRAGON_WALL_HEAD, - Material.PIGLIN_HEAD, - Material.PIGLIN_WALL_HEAD, - Material.PLAYER_HEAD, - Material.PLAYER_WALL_HEAD, - Material.SKELETON_SKULL, - Material.SKELETON_WALL_SKULL, - Material.WITHER_SKELETON_SKULL, - Material.WITHER_SKELETON_WALL_SKULL, - Material.ZOMBIE_HEAD, - Material.ZOMBIE_WALL_HEAD - ); - @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) static final ItemMetaKeyType SKULL_PROFILE = new ItemMetaKeyType<>(DataComponents.PROFILE, "SkullProfile"); @@ -53,11 +33,11 @@ class CraftMetaSkull extends CraftMetaItem implements SkullMeta { @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) static final ItemMetaKey BLOCK_ENTITY_TAG = new ItemMetaKey("BlockEntityTag"); - static final ItemMetaKeyType NOTE_BLOCK_SOUND = new ItemMetaKeyType<>(DataComponents.NOTE_BLOCK_SOUND, "note_block_sound"); + static final ItemMetaKeyType NOTE_BLOCK_SOUND = new ItemMetaKeyType<>(DataComponents.NOTE_BLOCK_SOUND, "note_block_sound"); static final int MAX_OWNER_LENGTH = 16; private ResolvableProfile profile; - private ResourceLocation noteBlockSound; + private MinecraftKey noteBlockSound; CraftMetaSkull(CraftMetaItem meta) { super(meta); @@ -78,42 +58,42 @@ class CraftMetaSkull extends CraftMetaItem implements SkullMeta { CraftMetaSkull(Map map) { super(map); - if (this.profile == null) { - Object object = map.get(CraftMetaSkull.SKULL_OWNER.BUKKIT); + if (profile == null) { + Object object = map.get(SKULL_OWNER.BUKKIT); if (object instanceof PlayerProfile playerProfile) { - this.setOwnerProfile(playerProfile); + setOwnerProfile(playerProfile); } else { - this.setOwner(SerializableMeta.getString(map, CraftMetaSkull.SKULL_OWNER.BUKKIT, true)); + setOwner(SerializableMeta.getString(map, SKULL_OWNER.BUKKIT, true)); } } - if (this.noteBlockSound == null) { - Object object = map.get(CraftMetaSkull.NOTE_BLOCK_SOUND.BUKKIT); + if (noteBlockSound == null) { + Object object = map.get(NOTE_BLOCK_SOUND.BUKKIT); if (object != null) { - this.setNoteBlockSound(NamespacedKey.fromString(object.toString())); + setNoteBlockSound(NamespacedKey.fromString(object.toString())); } } } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaSkull.SKULL_PROFILE.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - CompoundTag skullTag = tag.getCompound(CraftMetaSkull.SKULL_PROFILE.NBT); + if (tag.contains(SKULL_PROFILE.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { + NBTTagCompound skullTag = tag.getCompound(SKULL_PROFILE.NBT); // convert type of stored Id from String to UUID for backwards compatibility if (skullTag.contains("Id", CraftMagicNumbers.NBT.TAG_STRING)) { UUID uuid = UUID.fromString(skullTag.getString("Id")); skullTag.putUUID("Id", uuid); } - ResolvableProfile.CODEC.parse(NbtOps.INSTANCE, skullTag).result().ifPresent(this::setProfile); + ResolvableProfile.CODEC.parse(DynamicOpsNBT.INSTANCE, skullTag).result().ifPresent(this::setProfile); } - if (tag.contains(CraftMetaSkull.BLOCK_ENTITY_TAG.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - CompoundTag nbtTagCompound = tag.getCompound(CraftMetaSkull.BLOCK_ENTITY_TAG.NBT).copy(); - if (nbtTagCompound.contains(CraftMetaSkull.NOTE_BLOCK_SOUND.NBT, 8)) { - this.noteBlockSound = ResourceLocation.tryParse(nbtTagCompound.getString(CraftMetaSkull.NOTE_BLOCK_SOUND.NBT)); + if (tag.contains(BLOCK_ENTITY_TAG.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { + NBTTagCompound nbtTagCompound = tag.getCompound(BLOCK_ENTITY_TAG.NBT).copy(); + if (nbtTagCompound.contains(NOTE_BLOCK_SOUND.NBT, 8)) { + this.noteBlockSound = MinecraftKey.tryParse(nbtTagCompound.getString(NOTE_BLOCK_SOUND.NBT)); } } } @@ -128,34 +108,29 @@ void applyToItem(CraftMetaItem.Applicator tag) { if (hasOwner()) { // SPIGOT-6558: Set initial textures - tag.put(CraftMetaSkull.SKULL_PROFILE, profile); + tag.put(SKULL_PROFILE, profile); // Fill in textures - PlayerProfile ownerProfile = new CraftPlayerProfile(this.profile); // getOwnerProfile may return null + PlayerProfile ownerProfile = new CraftPlayerProfile(profile); // getOwnerProfile may return null if (ownerProfile.getTextures().isEmpty()) { ownerProfile.update().thenAccept((filledProfile) -> { - this.setOwnerProfile(filledProfile); - tag.put(CraftMetaSkull.SKULL_PROFILE, profile); + setOwnerProfile(filledProfile); + tag.put(SKULL_PROFILE, profile); }); } } - if (this.noteBlockSound != null) { - tag.put(CraftMetaSkull.NOTE_BLOCK_SOUND, this.noteBlockSound); + if (noteBlockSound != null) { + tag.put(NOTE_BLOCK_SOUND, this.noteBlockSound); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isSkullEmpty(); + return super.isEmpty() && isSkullEmpty(); } boolean isSkullEmpty() { - return this.profile == null && this.noteBlockSound == null; - } - - @Override - boolean applicableTo(Material type) { - return CraftMetaSkull.SKULL_MATERIALS.contains(type); + return profile == null && noteBlockSound == null; } @Override @@ -165,7 +140,7 @@ public CraftMetaSkull clone() { @Override public boolean hasOwner() { - return this.profile != null; + return profile != null; } @Override @@ -175,8 +150,8 @@ public String getOwner() { @Override public OfflinePlayer getOwningPlayer() { - if (this.hasOwner()) { - if (profile.id().filter(u -> !u.equals(Util.NIL_UUID)).isPresent()) { + if (hasOwner()) { + if (profile.id().filter(u -> !u.equals(SystemUtils.NIL_UUID)).isPresent()) { return Bukkit.getOfflinePlayer(profile.id().get()); } @@ -190,14 +165,14 @@ public OfflinePlayer getOwningPlayer() { @Override public boolean setOwner(String name) { - if (name != null && name.length() > CraftMetaSkull.MAX_OWNER_LENGTH) { + if (name != null && name.length() > MAX_OWNER_LENGTH) { return false; } if (name == null) { - this.setProfile(null); + setProfile(null); } else { - this.setProfile(new ResolvableProfile(new GameProfile(Util.NIL_UUID, name))); + setProfile(new ResolvableProfile(new GameProfile(SystemUtils.NIL_UUID, name))); } return true; @@ -206,11 +181,11 @@ public boolean setOwner(String name) { @Override public boolean setOwningPlayer(OfflinePlayer owner) { if (owner == null) { - this.setProfile(null); + setProfile(null); } else if (owner instanceof CraftPlayer craftPlayer) { setProfile(new ResolvableProfile(craftPlayer.getProfile())); } else { - this.setProfile(new ResolvableProfile(new GameProfile(owner.getUniqueId(), (owner.getName() == null) ? "" : owner.getName()))); + setProfile(new ResolvableProfile(new GameProfile(owner.getUniqueId(), (owner.getName() == null) ? "" : owner.getName()))); } return true; @@ -218,11 +193,11 @@ public boolean setOwningPlayer(OfflinePlayer owner) { @Override public PlayerProfile getOwnerProfile() { - if (!this.hasOwner()) { + if (!hasOwner()) { return null; } - return new CraftPlayerProfile(this.profile); + return new CraftPlayerProfile(profile); } @Override @@ -252,11 +227,11 @@ public NamespacedKey getNoteBlockSound() { int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasOwner()) { - hash = 61 * hash + this.profile.hashCode(); + if (hasOwner()) { + hash = 61 * hash + profile.hashCode(); } if (this.noteBlockSound != null) { - hash = 61 * hash + this.noteBlockSound.hashCode(); + hash = 61 * hash + noteBlockSound.hashCode(); } return original != hash ? CraftMetaSkull.class.hashCode() ^ hash : hash; } @@ -274,19 +249,22 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaSkull || this.isSkullEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaSkull || isSkullEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); + if (this.hasOwner()) { - return builder.put(CraftMetaSkull.SKULL_OWNER.BUKKIT, new CraftPlayerProfile(this.profile)); + builder.put(SKULL_OWNER.BUKKIT, new CraftPlayerProfile(this.profile)); } + NamespacedKey namespacedKeyNB = this.getNoteBlockSound(); if (namespacedKeyNB != null) { - return builder.put(CraftMetaSkull.NOTE_BLOCK_SOUND.BUKKIT, namespacedKeyNB.toString()); + builder.put(NOTE_BLOCK_SOUND.BUKKIT, namespacedKeyNB.toString()); } + return builder; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java index a9c6f3bf..9c3b5414 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java @@ -2,116 +2,26 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.collect.Sets; import java.util.Map; -import java.util.Set; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.item.component.CustomData; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.entity.CraftEntitySnapshot; -import org.bukkit.craftbukkit.entity.CraftEntityType; -import org.bukkit.craftbukkit.util.CraftLegacy; import org.bukkit.entity.EntitySnapshot; import org.bukkit.entity.EntityType; import org.bukkit.inventory.meta.SpawnEggMeta; -import org.bukkit.material.MaterialData; @DelegateDeserialization(SerializableMeta.class) public class CraftMetaSpawnEgg extends CraftMetaItem implements SpawnEggMeta { - private static final Set SPAWN_EGG_MATERIALS = Sets.newHashSet( - Material.ARMADILLO_SPAWN_EGG, - Material.ALLAY_SPAWN_EGG, - Material.AXOLOTL_SPAWN_EGG, - Material.BAT_SPAWN_EGG, - Material.BEE_SPAWN_EGG, - Material.BLAZE_SPAWN_EGG, - Material.BOGGED_SPAWN_EGG, - Material.BREEZE_SPAWN_EGG, - Material.CAT_SPAWN_EGG, - Material.CAMEL_SPAWN_EGG, - Material.CAVE_SPIDER_SPAWN_EGG, - Material.CHICKEN_SPAWN_EGG, - Material.COD_SPAWN_EGG, - Material.COW_SPAWN_EGG, - Material.CREEPER_SPAWN_EGG, - Material.DOLPHIN_SPAWN_EGG, - Material.DONKEY_SPAWN_EGG, - Material.DROWNED_SPAWN_EGG, - Material.ELDER_GUARDIAN_SPAWN_EGG, - Material.ENDER_DRAGON_SPAWN_EGG, - Material.ENDERMAN_SPAWN_EGG, - Material.ENDERMITE_SPAWN_EGG, - Material.EVOKER_SPAWN_EGG, - Material.FOX_SPAWN_EGG, - Material.FROG_SPAWN_EGG, - Material.GHAST_SPAWN_EGG, - Material.GLOW_SQUID_SPAWN_EGG, - Material.GOAT_SPAWN_EGG, - Material.GUARDIAN_SPAWN_EGG, - Material.HOGLIN_SPAWN_EGG, - Material.HORSE_SPAWN_EGG, - Material.HUSK_SPAWN_EGG, - Material.IRON_GOLEM_SPAWN_EGG, - Material.LLAMA_SPAWN_EGG, - Material.MAGMA_CUBE_SPAWN_EGG, - Material.MOOSHROOM_SPAWN_EGG, - Material.MULE_SPAWN_EGG, - Material.OCELOT_SPAWN_EGG, - Material.PANDA_SPAWN_EGG, - Material.PARROT_SPAWN_EGG, - Material.PHANTOM_SPAWN_EGG, - Material.PIGLIN_BRUTE_SPAWN_EGG, - Material.PIGLIN_SPAWN_EGG, - Material.PIG_SPAWN_EGG, - Material.PILLAGER_SPAWN_EGG, - Material.POLAR_BEAR_SPAWN_EGG, - Material.PUFFERFISH_SPAWN_EGG, - Material.RABBIT_SPAWN_EGG, - Material.RAVAGER_SPAWN_EGG, - Material.SALMON_SPAWN_EGG, - Material.SHEEP_SPAWN_EGG, - Material.SHULKER_SPAWN_EGG, - Material.SILVERFISH_SPAWN_EGG, - Material.SKELETON_HORSE_SPAWN_EGG, - Material.SKELETON_SPAWN_EGG, - Material.SLIME_SPAWN_EGG, - Material.SNIFFER_SPAWN_EGG, - Material.SNOW_GOLEM_SPAWN_EGG, - Material.SPIDER_SPAWN_EGG, - Material.SQUID_SPAWN_EGG, - Material.STRAY_SPAWN_EGG, - Material.STRIDER_SPAWN_EGG, - Material.TADPOLE_SPAWN_EGG, - Material.TRADER_LLAMA_SPAWN_EGG, - Material.TROPICAL_FISH_SPAWN_EGG, - Material.TURTLE_SPAWN_EGG, - Material.VEX_SPAWN_EGG, - Material.VILLAGER_SPAWN_EGG, - Material.VINDICATOR_SPAWN_EGG, - Material.WARDEN_SPAWN_EGG, - Material.WANDERING_TRADER_SPAWN_EGG, - Material.WITCH_SPAWN_EGG, - Material.WITHER_SPAWN_EGG, - Material.WITHER_SKELETON_SPAWN_EGG, - Material.WOLF_SPAWN_EGG, - Material.ZOGLIN_SPAWN_EGG, - Material.ZOMBIE_HORSE_SPAWN_EGG, - Material.ZOMBIE_SPAWN_EGG, - Material.ZOMBIE_VILLAGER_SPAWN_EGG, - Material.ZOMBIFIED_PIGLIN_SPAWN_EGG - ); - static final ItemMetaKeyType ENTITY_TAG = new ItemMetaKeyType<>(DataComponents.ENTITY_DATA, "entity-tag"); @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) static final ItemMetaKey ENTITY_ID = new ItemMetaKey("id"); - private CompoundTag entityTag; + private NBTTagCompound entityTag; CraftMetaSpawnEgg(CraftMetaItem meta) { super(meta); @@ -126,8 +36,8 @@ public class CraftMetaSpawnEgg extends CraftMetaItem implements SpawnEggMeta { CraftMetaSpawnEgg(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaSpawnEgg.ENTITY_TAG).ifPresent((nbt) -> { - this.entityTag = nbt.copyTag(); + getOrEmpty(tag, ENTITY_TAG).ifPresent((nbt) -> { + entityTag = nbt.copyTag(); }); } @@ -136,14 +46,14 @@ public class CraftMetaSpawnEgg extends CraftMetaItem implements SpawnEggMeta { } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaSpawnEgg.ENTITY_TAG.NBT)) { - this.entityTag = tag.getCompound(CraftMetaSpawnEgg.ENTITY_TAG.NBT); + if (tag.contains(ENTITY_TAG.NBT)) { + entityTag = tag.getCompound(ENTITY_TAG.NBT); // Tag still has some other data, lets try our luck with a conversion - if (!this.entityTag.isEmpty()) { + if (!entityTag.isEmpty()) { // SPIGOT-4128: This is hopeless until we start versioning stacks. RIP data. // entityTag = (NBTTagCompound) MinecraftServer.getServer().dataConverterManager.update(DataConverterTypes.ENTITY, new Dynamic(DynamicOpsNBT.a, entityTag), -1, CraftMagicNumbers.DATA_VERSION).getValue(); } @@ -151,9 +61,9 @@ void deserializeInternal(CompoundTag tag, Object context) { } @Override - void serializeInternal(Map internalTags) { - if (this.entityTag != null && !this.entityTag.isEmpty()) { - internalTags.put(CraftMetaSpawnEgg.ENTITY_TAG.NBT, this.entityTag); + void serializeInternal(Map internalTags) { + if (entityTag != null && !entityTag.isEmpty()) { + internalTags.put(ENTITY_TAG.NBT, entityTag); } } @@ -161,19 +71,14 @@ void serializeInternal(Map internalTags) { void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.entityTag != null) { - tag.put(CraftMetaSpawnEgg.ENTITY_TAG, CustomData.of(this.entityTag)); + if (entityTag != null) { + tag.put(ENTITY_TAG, CustomData.of(entityTag)); } } - @Override - boolean applicableTo(Material type) { - return CraftMetaSpawnEgg.SPAWN_EGG_MATERIALS.contains(type); - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isSpawnEggEmpty(); + return super.isEmpty() && isSpawnEggEmpty(); } boolean isSpawnEggEmpty() { @@ -216,7 +121,7 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaSpawnEgg || this.isSpawnEggEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaSpawnEgg || isSpawnEggEmpty()); } @Override @@ -224,8 +129,8 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.entityTag != null) { - hash = 73 * hash + this.entityTag.hashCode(); + if (entityTag != null) { + hash = 73 * hash + entityTag.hashCode(); } return original != hash ? CraftMetaSpawnEgg.class.hashCode() ^ hash : hash; @@ -242,8 +147,8 @@ Builder serialize(Builder builder) { public CraftMetaSpawnEgg clone() { CraftMetaSpawnEgg clone = (CraftMetaSpawnEgg) super.clone(); - if (this.entityTag != null) { - clone.entityTag = this.entityTag.copy(); + if (entityTag != null) { + clone.entityTag = entityTag.copy(); } return clone; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java index 8fc3cd50..356c3d29 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java @@ -10,7 +10,6 @@ import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.component.SuspiciousStewEffects; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; import org.bukkit.inventory.meta.SuspiciousStewMeta; @@ -36,19 +35,19 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious CraftMetaSuspiciousStew(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaSuspiciousStew.EFFECTS).ifPresent((suspiciousStewEffects) -> { - List list = suspiciousStewEffects.effects(); + getOrEmpty(tag, EFFECTS).ifPresent((suspiciousStewEffects) -> { + List list = suspiciousStewEffects.effects(); int length = list.size(); - this.customEffects = new ArrayList<>(length); + customEffects = new ArrayList<>(length); for (int i = 0; i < length; i++) { - SuspiciousStewEffects.Entry effect = list.get(i); + SuspiciousStewEffects.a effect = list.get(i); PotionEffectType type = CraftPotionEffectType.minecraftHolderToBukkit(effect.effect()); if (type == null) { continue; } int duration = effect.duration(); - this.customEffects.add(new PotionEffect(type, duration, 0)); + customEffects.add(new PotionEffect(type, duration, 0)); } }); } @@ -56,14 +55,14 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious CraftMetaSuspiciousStew(Map map) { super(map); - Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, CraftMetaSuspiciousStew.EFFECTS.BUKKIT, true); + Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, EFFECTS.BUKKIT, true); if (rawEffectList == null) { return; } for (Object obj : rawEffectList) { Preconditions.checkArgument(obj instanceof PotionEffect, "Object (%s) in effect list is not valid", obj.getClass()); - this.addCustomEffect((PotionEffect) obj, true); + addCustomEffect((PotionEffect) obj, true); } } @@ -71,28 +70,23 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); - if (this.customEffects != null) { - List effectList = new ArrayList<>(); + if (customEffects != null) { + List effectList = new ArrayList<>(); - for (PotionEffect effect : this.customEffects) { - effectList.add(new net.minecraft.world.item.component.SuspiciousStewEffects.Entry(CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration())); + for (PotionEffect effect : customEffects) { + effectList.add(new net.minecraft.world.item.component.SuspiciousStewEffects.a(CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()), effect.getDuration())); } - tag.put(CraftMetaSuspiciousStew.EFFECTS, new SuspiciousStewEffects(effectList)); + tag.put(EFFECTS, new SuspiciousStewEffects(effectList)); } } @Override boolean isEmpty() { - return super.isEmpty() && this.isStewEmpty(); + return super.isEmpty() && isStewEmpty(); } boolean isStewEmpty() { - return !this.hasCustomEffects(); - } - - @Override - boolean applicableTo(Material type) { - return type == Material.SUSPICIOUS_STEW; + return !hasCustomEffects(); } @Override @@ -106,13 +100,13 @@ public CraftMetaSuspiciousStew clone() { @Override public boolean hasCustomEffects() { - return this.customEffects != null; + return customEffects != null; } @Override public List getCustomEffects() { - if (this.hasCustomEffects()) { - return ImmutableList.copyOf(this.customEffects); + if (hasCustomEffects()) { + return ImmutableList.copyOf(customEffects); } return ImmutableList.of(); } @@ -121,23 +115,23 @@ public List getCustomEffects() { public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { Preconditions.checkArgument(effect != null, "Potion effect cannot be null"); - int index = this.indexOfEffect(effect.getType()); + int index = indexOfEffect(effect.getType()); if (index != -1) { if (overwrite) { - PotionEffect old = this.customEffects.get(index); + PotionEffect old = customEffects.get(index); if (old.getDuration() == effect.getDuration()) { return false; } - this.customEffects.set(index, effect); + customEffects.set(index, effect); return true; } else { return false; } } else { - if (this.customEffects == null) { - this.customEffects = new ArrayList<>(); + if (customEffects == null) { + customEffects = new ArrayList<>(); } - this.customEffects.add(effect); + customEffects.add(effect); return true; } } @@ -146,12 +140,12 @@ public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { public boolean removeCustomEffect(PotionEffectType type) { Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); - if (!this.hasCustomEffects()) { + if (!hasCustomEffects()) { return false; } boolean changed = false; - Iterator iterator = this.customEffects.iterator(); + Iterator iterator = customEffects.iterator(); while (iterator.hasNext()) { PotionEffect effect = iterator.next(); if (type.equals(effect.getType())) { @@ -159,8 +153,8 @@ public boolean removeCustomEffect(PotionEffectType type) { changed = true; } } - if (this.customEffects.isEmpty()) { - this.customEffects = null; + if (customEffects.isEmpty()) { + customEffects = null; } return changed; } @@ -168,16 +162,16 @@ public boolean removeCustomEffect(PotionEffectType type) { @Override public boolean hasCustomEffect(PotionEffectType type) { Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); - return this.indexOfEffect(type) != -1; + return indexOfEffect(type) != -1; } private int indexOfEffect(PotionEffectType type) { - if (!this.hasCustomEffects()) { + if (!hasCustomEffects()) { return -1; } - for (int i = 0; i < this.customEffects.size(); i++) { - if (this.customEffects.get(i).getType().equals(type)) { + for (int i = 0; i < customEffects.size(); i++) { + if (customEffects.get(i).getType().equals(type)) { return i; } } @@ -186,8 +180,8 @@ private int indexOfEffect(PotionEffectType type) { @Override public boolean clearCustomEffects() { - boolean changed = this.hasCustomEffects(); - this.customEffects = null; + boolean changed = hasCustomEffects(); + customEffects = null; return changed; } @@ -195,8 +189,8 @@ public boolean clearCustomEffects() { int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasCustomEffects()) { - hash = 73 * hash + this.customEffects.hashCode(); + if (hasCustomEffects()) { + hash = 73 * hash + customEffects.hashCode(); } return original != hash ? CraftMetaSuspiciousStew.class.hashCode() ^ hash : hash; } @@ -214,15 +208,15 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaSuspiciousStew || this.isStewEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaSuspiciousStew || isStewEmpty()); } @Override Builder serialize(Builder builder) { super.serialize(builder); - if (this.hasCustomEffects()) { - builder.put(CraftMetaSuspiciousStew.EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); + if (hasCustomEffects()) { + builder.put(EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java index f6c0360e..09743e9c 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java @@ -4,11 +4,10 @@ import java.util.Map; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.item.component.CustomData; import org.bukkit.DyeColor; -import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.entity.CraftTropicalFish; import org.bukkit.craftbukkit.util.CraftMagicNumbers; @@ -23,8 +22,8 @@ class CraftMetaTropicalFishBucket extends CraftMetaItem implements TropicalFishB static final ItemMetaKeyType BUCKET_ENTITY_TAG = new ItemMetaKeyType<>(DataComponents.BUCKET_ENTITY_DATA, "bucket-entity-tag"); private Integer variant; - private CompoundTag entityTag; - private CompoundTag bucketEntityTag; + private NBTTagCompound entityTag; + private NBTTagCompound bucketEntityTag; CraftMetaTropicalFishBucket(CraftMetaItem meta) { super(meta); @@ -42,11 +41,11 @@ class CraftMetaTropicalFishBucket extends CraftMetaItem implements TropicalFishB CraftMetaTropicalFishBucket(DataComponentPatch tag) { super(tag); - getOrEmpty(tag, CraftMetaTropicalFishBucket.ENTITY_TAG).ifPresent((nbt) -> { - this.entityTag = nbt.copyTag(); + getOrEmpty(tag, ENTITY_TAG).ifPresent((nbt) -> { + entityTag = nbt.copyTag(); - if (this.entityTag.contains(CraftMetaTropicalFishBucket.VARIANT.NBT, CraftMagicNumbers.NBT.TAG_INT)) { - this.variant = this.entityTag.getInt(CraftMetaTropicalFishBucket.VARIANT.NBT); + if (entityTag.contains(VARIANT.NBT, CraftMagicNumbers.NBT.TAG_INT)) { + this.variant = entityTag.getInt(VARIANT.NBT); } }); getOrEmpty(tag, BUCKET_ENTITY_TAG).ifPresent((nbt) -> { @@ -61,18 +60,18 @@ class CraftMetaTropicalFishBucket extends CraftMetaItem implements TropicalFishB CraftMetaTropicalFishBucket(Map map) { super(map); - Integer variant = SerializableMeta.getObject(Integer.class, map, CraftMetaTropicalFishBucket.VARIANT.BUKKIT, true); + Integer variant = SerializableMeta.getObject(Integer.class, map, VARIANT.BUKKIT, true); if (variant != null) { this.variant = variant; } } @Override - void deserializeInternal(CompoundTag tag, Object context) { + void deserializeInternal(NBTTagCompound tag, Object context) { super.deserializeInternal(tag, context); - if (tag.contains(CraftMetaTropicalFishBucket.ENTITY_TAG.NBT)) { - this.entityTag = tag.getCompound(CraftMetaTropicalFishBucket.ENTITY_TAG.NBT); + if (tag.contains(ENTITY_TAG.NBT)) { + entityTag = tag.getCompound(ENTITY_TAG.NBT); } if (tag.contains(BUCKET_ENTITY_TAG.NBT)) { bucketEntityTag = tag.getCompound(BUCKET_ENTITY_TAG.NBT); @@ -80,9 +79,9 @@ void deserializeInternal(CompoundTag tag, Object context) { } @Override - void serializeInternal(Map internalTags) { - if (this.entityTag != null && !this.entityTag.isEmpty()) { - internalTags.put(CraftMetaTropicalFishBucket.ENTITY_TAG.NBT, this.entityTag); + void serializeInternal(Map internalTags) { + if (entityTag != null && !entityTag.isEmpty()) { + internalTags.put(ENTITY_TAG.NBT, entityTag); } if (bucketEntityTag != null && !bucketEntityTag.isEmpty()) { internalTags.put(BUCKET_ENTITY_TAG.NBT, bucketEntityTag); @@ -92,79 +91,75 @@ void serializeInternal(Map internalTags) { @Override void applyToItem(CraftMetaItem.Applicator tag) { super.applyToItem(tag); + if (entityTag != null) { tag.put(ENTITY_TAG, CustomData.of(entityTag)); } - CompoundTag bucketEntityTag = (this.bucketEntityTag != null) ? this.bucketEntityTag.copy() : null; - if (this.hasVariant()) { + NBTTagCompound bucketEntityTag = (this.bucketEntityTag != null) ? this.bucketEntityTag.copy() : null; + if (hasVariant()) { if (bucketEntityTag == null) { - bucketEntityTag = new CompoundTag(); + bucketEntityTag = new NBTTagCompound(); } - bucketEntityTag.putInt(CraftMetaTropicalFishBucket.VARIANT.NBT, this.variant); + bucketEntityTag.putInt(VARIANT.NBT, variant); } if (bucketEntityTag != null) { - tag.put(CraftMetaTropicalFishBucket.ENTITY_TAG, CustomData.of(bucketEntityTag)); + tag.put(BUCKET_ENTITY_TAG, CustomData.of(bucketEntityTag)); } } - @Override - boolean applicableTo(Material type) { - return type == Material.TROPICAL_FISH_BUCKET; - } - @Override boolean isEmpty() { - return super.isEmpty() && this.isBucketEmpty(); + return super.isEmpty() && isBucketEmpty(); } boolean isBucketEmpty() { - return !(this.hasVariant() || this.entityTag != null || bucketEntityTag != null); + return !(hasVariant() || entityTag != null || bucketEntityTag != null); } @Override public DyeColor getPatternColor() { - return CraftTropicalFish.getPatternColor(this.variant); + return CraftTropicalFish.getPatternColor(variant); } @Override public void setPatternColor(DyeColor color) { - if (this.variant == null) { - this.variant = 0; + if (variant == null) { + variant = 0; } - this.variant = CraftTropicalFish.getData(color, this.getPatternColor(), this.getPattern()); + variant = CraftTropicalFish.getData(color, getPatternColor(), getPattern()); } @Override public DyeColor getBodyColor() { - return CraftTropicalFish.getBodyColor(this.variant); + return CraftTropicalFish.getBodyColor(variant); } @Override public void setBodyColor(DyeColor color) { - if (this.variant == null) { - this.variant = 0; + if (variant == null) { + variant = 0; } - this.variant = CraftTropicalFish.getData(this.getPatternColor(), color, this.getPattern()); + variant = CraftTropicalFish.getData(getPatternColor(), color, getPattern()); } @Override public TropicalFish.Pattern getPattern() { - return CraftTropicalFish.getPattern(this.variant); + return CraftTropicalFish.getPattern(variant); } @Override public void setPattern(TropicalFish.Pattern pattern) { - if (this.variant == null) { - this.variant = 0; + if (variant == null) { + variant = 0; } - this.variant = CraftTropicalFish.getData(this.getPatternColor(), this.getBodyColor(), pattern); + variant = CraftTropicalFish.getData(getPatternColor(), getBodyColor(), pattern); } @Override public boolean hasVariant() { - return this.variant != null; + return variant != null; } @Override @@ -175,7 +170,7 @@ boolean equalsCommon(CraftMetaItem meta) { if (meta instanceof CraftMetaTropicalFishBucket) { CraftMetaTropicalFishBucket that = (CraftMetaTropicalFishBucket) meta; - return (this.hasVariant() ? that.hasVariant() && this.variant.equals(that.variant) : !that.hasVariant()) + return (hasVariant() ? that.hasVariant() && this.variant.equals(that.variant) : !that.hasVariant()) && (entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : that.entityTag == null) && (bucketEntityTag != null ? that.bucketEntityTag != null && this.bucketEntityTag.equals(that.bucketEntityTag) : that.bucketEntityTag == null); } @@ -184,7 +179,7 @@ boolean equalsCommon(CraftMetaItem meta) { @Override boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaTropicalFishBucket || this.isBucketEmpty()); + return super.notUncommon(meta) && (meta instanceof CraftMetaTropicalFishBucket || isBucketEmpty()); } @Override @@ -192,11 +187,11 @@ int applyHash() { final int original; int hash = original = super.applyHash(); - if (this.hasVariant()) { - hash = 61 * hash + this.variant; + if (hasVariant()) { + hash = 61 * hash + variant; } - if (this.entityTag != null) { - hash = 61 * hash + this.entityTag.hashCode(); + if (entityTag != null) { + hash = 61 * hash + entityTag.hashCode(); } if (bucketEntityTag != null) { hash = 61 * hash + bucketEntityTag.hashCode(); @@ -209,8 +204,8 @@ int applyHash() { public CraftMetaTropicalFishBucket clone() { CraftMetaTropicalFishBucket clone = (CraftMetaTropicalFishBucket) super.clone(); - if (this.entityTag != null) { - clone.entityTag = this.entityTag.copy(); + if (entityTag != null) { + clone.entityTag = entityTag.copy(); } if (bucketEntityTag != null) { clone.bucketEntityTag = bucketEntityTag.copy(); @@ -223,8 +218,8 @@ public CraftMetaTropicalFishBucket clone() { ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); - if (this.hasVariant()) { - builder.put(CraftMetaTropicalFishBucket.VARIANT.BUKKIT, this.variant); + if (hasVariant()) { + builder.put(VARIANT.BUKKIT, variant); } return builder; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java index 139dff90..f40fea0d 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java @@ -3,8 +3,15 @@ import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; -import net.minecraft.world.item.crafting.Ingredient; -import org.bukkit.inventory.ItemStack; +import java.util.Optional; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.crafting.IRecipe; +import net.minecraft.world.item.crafting.RecipeItemStack; +import org.bukkit.NamespacedKey; +import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.recipe.CookingBookCategory; @@ -14,47 +21,53 @@ public interface CraftRecipe extends Recipe { void addToCraftingManager(); - default Ingredient toNMS(RecipeChoice bukkit, boolean requireNotEmpty) { - Ingredient stack; + default Optional toNMSOptional(RecipeChoice bukkit, boolean requireNotEmpty) { + return (bukkit == null) ? Optional.empty() : Optional.of(toNMS(bukkit, requireNotEmpty)); + } + + default RecipeItemStack toNMS(RecipeChoice bukkit, boolean requireNotEmpty) { + RecipeItemStack stack; if (bukkit == null) { - stack = Ingredient.EMPTY; + stack = RecipeItemStack.of(); } else if (bukkit instanceof RecipeChoice.MaterialChoice) { - stack = new Ingredient(((RecipeChoice.MaterialChoice) bukkit).getChoices().stream().map((mat) -> new net.minecraft.world.item.crafting.Ingredient.ItemValue(CraftItemStack.asNMSCopy(new ItemStack(mat))))); + stack = RecipeItemStack.of(((RecipeChoice.MaterialChoice) bukkit).getChoices().stream().map((mat) -> CraftItemType.bukkitToMinecraft(mat))); } else if (bukkit instanceof RecipeChoice.ExactChoice) { - stack = new Ingredient(((RecipeChoice.ExactChoice) bukkit).getChoices().stream().map((mat) -> new net.minecraft.world.item.crafting.Ingredient.ItemValue(CraftItemStack.asNMSCopy(mat)))); - stack.exact = true; + stack = RecipeItemStack.ofStacks(((RecipeChoice.ExactChoice) bukkit).getChoices().stream().map((mat) -> CraftItemStack.asNMSCopy(mat)).toList()); } else { throw new IllegalArgumentException("Unknown recipe stack instance " + bukkit); } - stack.getItems(); + List> items = stack.items(); if (requireNotEmpty) { - Preconditions.checkArgument(stack.itemStacks.length != 0, "Recipe requires at least one non-air choice"); + Preconditions.checkArgument(!items.isEmpty(), "Recipe requires at least one non-air choice"); } return stack; } - public static RecipeChoice toBukkit(Ingredient list) { - list.getItems(); + public static RecipeChoice toBukkit(Optional list) { + return list.map(CraftRecipe::toBukkit).orElse(null); + } + + public static RecipeChoice toBukkit(RecipeItemStack list) { + List> items = list.items(); - if (list.itemStacks.length == 0) { + if (items.isEmpty()) { return null; } - if (list.exact) { - List choices = new ArrayList<>(list.itemStacks.length); - for (net.minecraft.world.item.ItemStack i : list.itemStacks) { + if (list.isExact()) { + List choices = new ArrayList<>(list.itemStacks().size()); + for (net.minecraft.world.item.ItemStack i : list.itemStacks()) { choices.add(CraftItemStack.asBukkitCopy(i)); } return new RecipeChoice.ExactChoice(choices); } else { - - List choices = new ArrayList<>(list.itemStacks.length); - for (net.minecraft.world.item.ItemStack i : list.itemStacks) { - choices.add(CraftItemType.minecraftToBukkit(i.getItem())); + List choices = new ArrayList<>(items.size()); + for (Holder i : items) { + choices.add(CraftItemType.minecraftToBukkit(i.value())); } return new RecipeChoice.MaterialChoice(choices); @@ -76,4 +89,8 @@ public static net.minecraft.world.item.crafting.CookingBookCategory getCategory( public static CookingBookCategory getCategory(net.minecraft.world.item.crafting.CookingBookCategory nms) { return CookingBookCategory.valueOf(nms.name()); } + + public static ResourceKey> toMinecraft(NamespacedKey key) { + return ResourceKey.create(Registries.RECIPE, CraftNamespacedKey.toMinecraft(key)); + } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java index d4ad8c00..bf3714e0 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java @@ -1,47 +1,47 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import org.bukkit.inventory.ItemStack; public class CraftResultInventory extends CraftInventory { - private final Container resultInventory; + private final IInventory resultInventory; - public CraftResultInventory(Container inventory, Container resultInventory) { + public CraftResultInventory(IInventory inventory, IInventory resultInventory) { super(inventory); this.resultInventory = resultInventory; } - public Container getResultInventory() { - return this.resultInventory; + public IInventory getResultInventory() { + return resultInventory; } - public Container getIngredientsInventory() { - return this.inventory; + public IInventory getIngredientsInventory() { + return inventory; } @Override public ItemStack getItem(int slot) { - if (slot < this.getIngredientsInventory().getContainerSize()) { - net.minecraft.world.item.ItemStack item = this.getIngredientsInventory().getItem(slot); + if (slot < getIngredientsInventory().getContainerSize()) { + net.minecraft.world.item.ItemStack item = getIngredientsInventory().getItem(slot); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } else { - net.minecraft.world.item.ItemStack item = this.getResultInventory().getItem(slot - this.getIngredientsInventory().getContainerSize()); + net.minecraft.world.item.ItemStack item = getResultInventory().getItem(slot - getIngredientsInventory().getContainerSize()); return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); } } @Override public void setItem(int index, ItemStack item) { - if (index < this.getIngredientsInventory().getContainerSize()) { - this.getIngredientsInventory().setItem(index, CraftItemStack.asNMSCopy(item)); + if (index < getIngredientsInventory().getContainerSize()) { + getIngredientsInventory().setItem(index, CraftItemStack.asNMSCopy(item)); } else { - this.getResultInventory().setItem((index - this.getIngredientsInventory().getContainerSize()), CraftItemStack.asNMSCopy(item)); + getResultInventory().setItem((index - getIngredientsInventory().getContainerSize()), CraftItemStack.asNMSCopy(item)); } } @Override public int getSize() { - return this.getResultInventory().getContainerSize() + this.getIngredientsInventory().getContainerSize(); + return getResultInventory().getContainerSize() + getIngredientsInventory().getContainerSize(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java index 12389d85..243118cd 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java @@ -3,27 +3,25 @@ import com.google.common.collect.Maps; import java.util.Map; import java.util.Objects; -import java.util.Optional; -import net.minecraft.core.NonNullList; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeItemStack; import net.minecraft.world.item.crafting.ShapedRecipePattern; +import net.minecraft.world.item.crafting.ShapedRecipes; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.ShapedRecipe; public class CraftShapedRecipe extends ShapedRecipe implements CraftRecipe { // TODO: Could eventually use this to add a matches() method or some such - private net.minecraft.world.item.crafting.ShapedRecipe recipe; + private ShapedRecipes recipe; public CraftShapedRecipe(NamespacedKey key, ItemStack result) { super(key, result); } - public CraftShapedRecipe(NamespacedKey key, ItemStack result, net.minecraft.world.item.crafting.ShapedRecipe recipe) { + public CraftShapedRecipe(NamespacedKey key, ItemStack result, ShapedRecipes recipe) { this(key, result); this.recipe = recipe; } @@ -52,14 +50,13 @@ public void addToCraftingManager() { Map ingred = this.getChoiceMap(); String[] shape = replaceUndefinedIngredientsWithEmpty(this.getShape(), ingred); ingred.values().removeIf(Objects::isNull); - Map data = Maps.transformValues(ingred, (bukkit) -> toNMS(bukkit, false)); + Map data = Maps.transformValues(ingred, (bukkit) -> toNMS(bukkit, false)); ShapedRecipePattern pattern = ShapedRecipePattern.of(data, shape); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.ShapedRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), pattern, CraftItemStack.asNMSCopy(this.getResult())))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new ShapedRecipes(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), pattern, CraftItemStack.asNMSCopy(this.getResult())))); } private static String[] replaceUndefinedIngredientsWithEmpty(String[] shape, Map ingredients) { - for (int i = 0; i < shape.length; i++) { String row = shape[i]; StringBuilder filteredRow = new StringBuilder(row.length()); @@ -70,6 +67,7 @@ private static String[] replaceUndefinedIngredientsWithEmpty(String[] shape, Map shape[i] = filteredRow.toString(); } + return shape; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java index 96d772eb..3cc08a64 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java @@ -1,25 +1,25 @@ package org.bukkit.craftbukkit.inventory; +import java.util.ArrayList; import java.util.List; -import net.minecraft.core.NonNullList; import net.minecraft.server.MinecraftServer; -import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeItemStack; +import net.minecraft.world.item.crafting.ShapelessRecipes; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.ShapelessRecipe; public class CraftShapelessRecipe extends ShapelessRecipe implements CraftRecipe { // TODO: Could eventually use this to add a matches() method or some such - private net.minecraft.world.item.crafting.ShapelessRecipe recipe; + private ShapelessRecipes recipe; public CraftShapelessRecipe(NamespacedKey key, ItemStack result) { super(key, result); } - public CraftShapelessRecipe(NamespacedKey key, ItemStack result, net.minecraft.world.item.crafting.ShapelessRecipe recipe) { + public CraftShapelessRecipe(NamespacedKey key, ItemStack result, ShapelessRecipes recipe) { this(key, result); this.recipe = recipe; } @@ -40,11 +40,11 @@ public static CraftShapelessRecipe fromBukkitRecipe(ShapelessRecipe recipe) { @Override public void addToCraftingManager() { List ingred = this.getChoiceList(); - NonNullList data = NonNullList.withSize(ingred.size(), Ingredient.EMPTY); + List data = new ArrayList<>(ingred.size()); for (int i = 0; i < ingred.size(); i++) { - data.set(i, this.toNMS(ingred.get(i), true)); + data.set(i, toNMS(ingred.get(i), true)); } - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.ShapelessRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), CraftItemStack.asNMSCopy(this.getResult()), data))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new ShapelessRecipes(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), CraftItemStack.asNMSCopy(this.getResult()), data))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTransformRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTransformRecipe.java index 8c381e27..2a518ac1 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTransformRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTransformRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.SmithingTransformRecipe; @@ -25,6 +24,6 @@ public static CraftSmithingTransformRecipe fromBukkitRecipe(SmithingTransformRec public void addToCraftingManager() { ItemStack result = this.getResult(); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.SmithingTransformRecipe(this.toNMS(this.getTemplate(), true), this.toNMS(this.getBase(), true), this.toNMS(this.getAddition(), true), CraftItemStack.asNMSCopy(result)))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.SmithingTransformRecipe(toNMSOptional(this.getTemplate(), false), toNMSOptional(this.getBase(), false), toNMSOptional(this.getAddition(), false), CraftItemStack.asNMSCopy(result)))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTrimRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTrimRecipe.java index 87f20a48..339dcbfc 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTrimRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmithingTrimRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.SmithingTrimRecipe; @@ -23,6 +22,6 @@ public static CraftSmithingTrimRecipe fromBukkitRecipe(SmithingTrimRecipe recipe @Override public void addToCraftingManager() { - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.SmithingTrimRecipe(this.toNMS(this.getTemplate(), true), this.toNMS(this.getBase(), true), this.toNMS(this.getAddition(), true)))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.SmithingTrimRecipe(toNMSOptional(this.getTemplate(), false), toNMSOptional(this.getBase(), false), toNMSOptional(this.getAddition(), false)))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java index 46ce3f27..69e3b325 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.SmokingRecipe; @@ -27,6 +26,6 @@ public static CraftSmokingRecipe fromBukkitRecipe(SmokingRecipe recipe) { public void addToCraftingManager() { ItemStack result = this.getResult(); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.SmokingRecipe(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), this.toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), this.getExperience(), this.getCookingTime()))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.RecipeSmoking(this.getGroup(), CraftRecipe.getCategory(this.getCategory()), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime()))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java index 78898e5e..1515c7b1 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java @@ -3,7 +3,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.StonecuttingRecipe; @@ -26,6 +25,6 @@ public static CraftStonecuttingRecipe fromBukkitRecipe(StonecuttingRecipe recipe public void addToCraftingManager() { ItemStack result = this.getResult(); - MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftNamespacedKey.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.StonecutterRecipe(this.getGroup(), this.toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result)))); + MinecraftServer.getServer().getRecipeManager().addRecipe(new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), new net.minecraft.world.item.crafting.RecipeStonecutting(this.getGroup(), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result)))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftTransmuteRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftTransmuteRecipe.java new file mode 100644 index 00000000..6af50aaa --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftTransmuteRecipe.java @@ -0,0 +1,40 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.core.Holder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.item.crafting.RecipeHolder; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.TransmuteRecipe; + +public class CraftTransmuteRecipe extends TransmuteRecipe implements CraftRecipe { + + public CraftTransmuteRecipe(NamespacedKey key, Material result, RecipeChoice input, RecipeChoice material) { + super(key, result, input, material); + } + + public static CraftTransmuteRecipe fromBukkitRecipe(TransmuteRecipe recipe) { + if (recipe instanceof CraftTransmuteRecipe) { + return (CraftTransmuteRecipe) recipe; + } + CraftTransmuteRecipe ret = new CraftTransmuteRecipe(recipe.getKey(), recipe.getResult().getType(), recipe.getInput(), recipe.getMaterial()); + ret.setGroup(recipe.getGroup()); + ret.setCategory(recipe.getCategory()); + return ret; + } + + @Override + public void addToCraftingManager() { + MinecraftServer.getServer().getRecipeManager().addRecipe( + new RecipeHolder<>(CraftRecipe.toMinecraft(this.getKey()), + new net.minecraft.world.item.crafting.TransmuteRecipe(this.getGroup(), + CraftRecipe.getCategory(this.getCategory()), + toNMS(this.getInput(), true), + toNMS(this.getMaterial(), true), + Holder.direct(CraftItemType.bukkitToMinecraft(this.getResult().getType())) + ) + ) + ); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java b/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java index 5b869361..10dec416 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java @@ -22,41 +22,41 @@ public class InventoryIterator implements ListIterator { @Override public boolean hasNext() { - return this.nextIndex < this.inventory.getSize(); + return nextIndex < inventory.getSize(); } @Override public ItemStack next() { - this.lastDirection = true; - return this.inventory.getItem(this.nextIndex++); + lastDirection = true; + return inventory.getItem(nextIndex++); } @Override public int nextIndex() { - return this.nextIndex; + return nextIndex; } @Override public boolean hasPrevious() { - return this.nextIndex > 0; + return nextIndex > 0; } @Override public ItemStack previous() { - this.lastDirection = false; - return this.inventory.getItem(--this.nextIndex); + lastDirection = false; + return inventory.getItem(--nextIndex); } @Override public int previousIndex() { - return this.nextIndex - 1; + return nextIndex - 1; } @Override public void set(ItemStack item) { - Preconditions.checkState(this.lastDirection != null, "No current item!"); - int i = this.lastDirection ? this.nextIndex - 1 : this.nextIndex; - this.inventory.setItem(i, item); + Preconditions.checkState(lastDirection != null, "No current item!"); + int i = lastDirection ? nextIndex - 1 : nextIndex; + inventory.setItem(i, item); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java b/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java index 78a2afa9..460b29e5 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java @@ -4,28 +4,28 @@ import java.util.Map; import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.item.crafting.Recipes; import org.bukkit.inventory.Recipe; public class RecipeIterator implements Iterator { - private final Iterator, RecipeHolder>> recipes; + private final Iterator, RecipeHolder>> recipes; public RecipeIterator() { - this.recipes = MinecraftServer.getServer().getRecipeManager().byType.entries().iterator(); + this.recipes = MinecraftServer.getServer().getRecipeManager().recipes.byType.entries().iterator(); } @Override public boolean hasNext() { - return this.recipes.hasNext(); + return recipes.hasNext(); } @Override public Recipe next() { - return this.recipes.next().getValue().toBukkitRecipe(); + return recipes.next().getValue().toBukkitRecipe(); } @Override public void remove() { - this.recipes.remove(); + recipes.remove(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java b/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java index 1ac1c43e..f5c94495 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java @@ -6,6 +6,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.NoSuchElementException; +import org.bukkit.block.Banner; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.inventory.meta.ItemMeta; @@ -30,6 +31,7 @@ public final class SerializableMeta implements ConfigurationSerializable { .put(CraftMetaColorableArmor.class, "COLORABLE_ARMOR") .put(CraftMetaMap.class, "MAP") .put(CraftMetaPotion.class, "POTION") + .put(CraftMetaShield.class, "SHIELD") .put(CraftMetaSpawnEgg.class, "SPAWN_EGG") .put(CraftMetaEnchantedBook.class, "ENCHANTED") .put(CraftMetaFirework.class, "FIREWORK") @@ -64,18 +66,24 @@ private SerializableMeta() { public static ItemMeta deserialize(Map map) throws Throwable { Preconditions.checkArgument(map != null, "Cannot deserialize null map"); - String type = SerializableMeta.getString(map, SerializableMeta.TYPE_FIELD, false); - Constructor constructor = SerializableMeta.constructorMap.get(type); + String type = getString(map, TYPE_FIELD, false); + Constructor constructor = constructorMap.get(type); if (constructor == null) { - throw new IllegalArgumentException(type + " is not a valid " + SerializableMeta.TYPE_FIELD); + throw new IllegalArgumentException(type + " is not a valid " + TYPE_FIELD); } try { - return constructor.newInstance(map); - } catch (final InstantiationException e) { - throw new AssertionError(e); - } catch (final IllegalAccessException e) { + CraftMetaItem meta = constructor.newInstance(map); + + // Convert Shield CraftMetaBlockState to CraftMetaShield + if (meta instanceof CraftMetaBlockState state && state.hasBlockState() && state.getBlockState() instanceof Banner) { + meta = new CraftMetaShield(meta); + meta.unhandledTags.clear(CraftMetaShield.BASE_COLOR.TYPE); + } + + return meta; + } catch (final InstantiationException | IllegalAccessException e) { throw new AssertionError(e); } catch (final InvocationTargetException e) { throw e.getCause(); @@ -88,11 +96,11 @@ public Map serialize() { } public static String getString(Map map, Object field, boolean nullable) { - return SerializableMeta.getObject(String.class, map, field, nullable); + return getObject(String.class, map, field, nullable); } public static boolean getBoolean(Map map, Object field) { - Boolean value = SerializableMeta.getObject(Boolean.class, map, field, true); + Boolean value = getObject(Boolean.class, map, field, true); return value != null && value; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftEquippableComponent.java b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftEquippableComponent.java new file mode 100644 index 00000000..f72ae515 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftEquippableComponent.java @@ -0,0 +1,239 @@ +package org.bukkit.craftbukkit.inventory.components; + +import com.google.common.base.Preconditions; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.sounds.SoundEffects; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.EnumItemSlot; +import net.minecraft.world.item.equipment.Equippable; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Sound; +import org.bukkit.Tag; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.craftbukkit.CraftEquipmentSlot; +import org.bukkit.craftbukkit.CraftSound; +import org.bukkit.craftbukkit.entity.CraftEntityType; +import org.bukkit.craftbukkit.inventory.SerializableMeta; +import org.bukkit.craftbukkit.tag.CraftEntityTag; +import org.bukkit.craftbukkit.util.CraftNamespacedKey; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.meta.components.EquippableComponent; + +@SerializableAs("Equippable") +public final class CraftEquippableComponent implements EquippableComponent { + + private Equippable handle; + + public CraftEquippableComponent(Equippable handle) { + this.handle = handle; + } + + public CraftEquippableComponent(CraftEquippableComponent craft) { + this.handle = craft.handle; + } + + public CraftEquippableComponent(Map map) { + EnumItemSlot slot = CraftEquipmentSlot.getNMS(EquipmentSlot.valueOf(SerializableMeta.getString(map, "slot", false))); + + Sound equipSound = null; + String snd = SerializableMeta.getString(map, "equip-sound", true); + if (snd != null) { + equipSound = Registry.SOUNDS.get(NamespacedKey.fromString(snd)); + } + + String model = SerializableMeta.getString(map, "model", true); + String cameraOverlay = SerializableMeta.getString(map, "camera-overlay", true); + + HolderSet> allowedEntities = null; + Object allowed = SerializableMeta.getObject(Object.class, map, "allowed-entities", true); + if (allowed != null) { + allowedEntities = CraftHolderUtil.parse(allowed, Registries.ENTITY_TYPE, BuiltInRegistries.ENTITY_TYPE); + } + + Boolean dispensable = SerializableMeta.getObject(Boolean.class, map, "dispensable", true); + Boolean swappable = SerializableMeta.getObject(Boolean.class, map, "swappable", true); + Boolean damageOnHurt = SerializableMeta.getObject(Boolean.class, map, "damage-on-hurt", true); + + this.handle = new Equippable(slot, + (equipSound != null) ? CraftSound.bukkitToMinecraftHolder(equipSound) : SoundEffects.ARMOR_EQUIP_GENERIC, + Optional.ofNullable(model).map(MinecraftKey::parse), + Optional.ofNullable(cameraOverlay).map(MinecraftKey::parse), + Optional.ofNullable(allowedEntities), + (dispensable != null) ? dispensable : true, + (swappable != null) ? swappable : true, + (damageOnHurt != null) ? damageOnHurt : true + ); + } + + @Override + public Map serialize() { + Map result = new LinkedHashMap<>(); + result.put("slot", getSlot().name()); + result.put("equip-sound", getEquipSound().getKey().toString()); + + NamespacedKey model = getModel(); + if (model != null) { + result.put("model", model.toString()); + } + + NamespacedKey cameraOverlay = getCameraOverlay(); + if (cameraOverlay != null) { + result.put("camera-overlay", cameraOverlay.toString()); + } + + Optional>> allowed = handle.allowedEntities(); + if (allowed.isPresent()) { + CraftHolderUtil.serialize(result, "allowed-entities", allowed.get()); + } + + result.put("dispensable", isDispensable()); + result.put("swappable", isSwappable()); + result.put("damage-on-hurt", isDamageOnHurt()); + + return result; + } + + public Equippable getHandle() { + return handle; + } + + @Override + public EquipmentSlot getSlot() { + return CraftEquipmentSlot.getSlot(handle.slot()); + } + + @Override + public void setSlot(EquipmentSlot slot) { + handle = new Equippable(CraftEquipmentSlot.getNMS(slot), handle.equipSound(), handle.model(), handle.cameraOverlay(), handle.allowedEntities(), handle.dispensable(), handle.swappable(), handle.damageOnHurt()); + } + + @Override + public Sound getEquipSound() { + return CraftSound.minecraftToBukkit(handle.equipSound().value()); + } + + @Override + public void setEquipSound(Sound sound) { + handle = new Equippable(handle.slot(), (sound != null) ? CraftSound.bukkitToMinecraftHolder(sound) : SoundEffects.ARMOR_EQUIP_GENERIC, handle.model(), handle.cameraOverlay(), handle.allowedEntities(), handle.dispensable(), handle.swappable(), handle.damageOnHurt()); + } + + @Override + public NamespacedKey getModel() { + return handle.model().map(CraftNamespacedKey::fromMinecraft).orElse(null); + } + + @Override + public void setModel(NamespacedKey key) { + handle = new Equippable(handle.slot(), handle.equipSound(), Optional.ofNullable(key).map(CraftNamespacedKey::toMinecraft), handle.cameraOverlay(), handle.allowedEntities(), handle.dispensable(), handle.swappable(), handle.damageOnHurt()); + } + + @Override + public NamespacedKey getCameraOverlay() { + return handle.cameraOverlay().map(CraftNamespacedKey::fromMinecraft).orElse(null); + } + + @Override + public void setCameraOverlay(NamespacedKey key) { + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), Optional.ofNullable(key).map(CraftNamespacedKey::toMinecraft), handle.allowedEntities(), handle.dispensable(), handle.swappable(), handle.damageOnHurt()); + } + + @Override + public Collection getAllowedEntities() { + return handle.allowedEntities().map(HolderSet::stream).map((stream) -> stream.map(Holder::value).map(CraftEntityType::minecraftToBukkit).collect(Collectors.toList())).orElse(null); + } + + @Override + public void setAllowedEntities(EntityType entities) { + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), handle.cameraOverlay(), + (entities != null) ? Optional.of(HolderSet.direct(CraftEntityType.bukkitToMinecraftHolder(entities))) : Optional.empty(), + handle.dispensable(), handle.swappable(), handle.damageOnHurt() + ); + } + + @Override + public void setAllowedEntities(Collection entities) { + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), handle.cameraOverlay(), + (entities != null) ? Optional.of(HolderSet.direct(entities.stream().map(CraftEntityType::bukkitToMinecraftHolder).collect(Collectors.toList()))) : Optional.empty(), + handle.dispensable(), handle.swappable(), handle.damageOnHurt() + ); + } + + @Override + public void setAllowedEntities(Tag tag) { + Preconditions.checkArgument(tag instanceof CraftEntityTag, "tag must be an entity tag"); + + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), handle.cameraOverlay(), + (tag != null) ? Optional.of(((CraftEntityTag) tag).getHandle()) : Optional.empty(), + handle.dispensable(), handle.swappable(), handle.damageOnHurt() + ); + } + + @Override + public boolean isDispensable() { + return handle.dispensable(); + } + + @Override + public void setDispensable(boolean dispensable) { + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), handle.cameraOverlay(), handle.allowedEntities(), dispensable, handle.swappable(), handle.damageOnHurt()); + } + + @Override + public boolean isSwappable() { + return handle.swappable(); + } + + @Override + public void setSwappable(boolean swappable) { + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), handle.cameraOverlay(), handle.allowedEntities(), handle.dispensable(), swappable, handle.damageOnHurt()); + } + + @Override + public boolean isDamageOnHurt() { + return handle.damageOnHurt(); + } + + @Override + public void setDamageOnHurt(boolean damage) { + handle = new Equippable(handle.slot(), handle.equipSound(), handle.model(), handle.cameraOverlay(), handle.allowedEntities(), handle.dispensable(), handle.swappable(), damage); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftEquippableComponent other = (CraftEquippableComponent) obj; + return Objects.equals(this.handle, other.handle); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 19 * hash + Objects.hashCode(this.handle); + return hash; + } + + @Override + public String toString() { + return "CraftEquippableComponent{" + "handle=" + handle + '}'; + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftFoodComponent.java b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftFoodComponent.java index 3fd12a9f..f121f46b 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftFoodComponent.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftFoodComponent.java @@ -1,29 +1,20 @@ package org.bukkit.craftbukkit.inventory.components; import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import java.util.ArrayList; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; -import net.minecraft.world.food.FoodProperties; +import net.minecraft.world.food.FoodInfo; import org.bukkit.configuration.serialization.SerializableAs; -import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.inventory.SerializableMeta; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.components.FoodComponent; -import org.bukkit.potion.PotionEffect; @SerializableAs("Food") public final class CraftFoodComponent implements FoodComponent { - private FoodProperties handle; + private FoodInfo handle; - public CraftFoodComponent(FoodProperties food) { + public CraftFoodComponent(FoodInfo food) { this.handle = food; } @@ -36,112 +27,52 @@ public CraftFoodComponent(Map map) { Float saturationModifier = SerializableMeta.getObject(Float.class, map, "saturation", false); Boolean canAlwaysEat = SerializableMeta.getBoolean(map, "can-always-eat"); - Float eatSeconds = SerializableMeta.getObject(Float.class, map, "eat-seconds", true); - if (eatSeconds == null) { - eatSeconds = 1.6f; - } - - ItemStack usingConvertsTo = SerializableMeta.getObject(ItemStack.class, map, "using-converts-to", true); - - ImmutableList.Builder effects = ImmutableList.builder(); - Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, "effects", true); - if (rawEffectList != null) { - for (Object obj : rawEffectList) { - Preconditions.checkArgument(obj instanceof FoodEffect, "Object (%s) in effect list is not valid", obj.getClass()); - effects.add(new CraftFoodEffect((FoodEffect) obj)); - } - } - - this.handle = new FoodProperties(nutrition, saturationModifier, canAlwaysEat, eatSeconds, Optional.ofNullable(usingConvertsTo).map(CraftItemStack::asNMSCopy), effects.build().stream().map(CraftFoodEffect::new).map(CraftFoodEffect::getHandle).toList()); + this.handle = new FoodInfo(nutrition, saturationModifier, canAlwaysEat); } @Override public Map serialize() { Map result = new LinkedHashMap<>(); - result.put("nutrition", this.getNutrition()); - result.put("saturation", this.getSaturation()); - result.put("can-always-eat", this.canAlwaysEat()); - result.put("eat-seconds", this.getEatSeconds()); - result.put("using-converts-to", getUsingConvertsTo()); - result.put("effects", this.getEffects()); + result.put("nutrition", getNutrition()); + result.put("saturation", getSaturation()); + result.put("can-always-eat", canAlwaysEat()); + return result; } - public FoodProperties getHandle() { - return this.handle; + public FoodInfo getHandle() { + return handle; } @Override public int getNutrition() { - return this.handle.nutrition(); + return handle.nutrition(); } @Override public void setNutrition(int nutrition) { Preconditions.checkArgument(nutrition >= 0, "Nutrition cannot be negative"); - this.handle = new FoodProperties(nutrition, this.handle.saturation(), this.handle.canAlwaysEat(), this.handle.eatSeconds(), this.handle.usingConvertsTo(), handle.effects()); + handle = new FoodInfo(nutrition, handle.saturation(), handle.canAlwaysEat()); } @Override public float getSaturation() { - return this.handle.saturation(); + return handle.saturation(); } @Override public void setSaturation(float saturation) { - this.handle = new FoodProperties(this.handle.nutrition(), saturation, this.handle.canAlwaysEat(), this.handle.eatSeconds(), this.handle.usingConvertsTo(), handle.effects()); + handle = new FoodInfo(handle.nutrition(), saturation, handle.canAlwaysEat()); } @Override public boolean canAlwaysEat() { - return this.handle.canAlwaysEat(); + return handle.canAlwaysEat(); } @Override public void setCanAlwaysEat(boolean canAlwaysEat) { - this.handle = new FoodProperties(this.handle.nutrition(), this.handle.saturation(), canAlwaysEat, this.handle.eatSeconds(), this.handle.usingConvertsTo(), handle.effects()); - } - - @Override - public float getEatSeconds() { - return this.handle.eatSeconds(); - } - - @Override - public void setEatSeconds(float eatSeconds) { - handle = new FoodProperties(handle.nutrition(), handle.saturation(), handle.canAlwaysEat(), eatSeconds, handle.usingConvertsTo(), handle.effects()); - } - - @Override - public ItemStack getUsingConvertsTo() { - return handle.usingConvertsTo().map(CraftItemStack::asBukkitCopy).orElse(null); - } - - @Override - public void setUsingConvertsTo(ItemStack item) { - handle = new FoodProperties(handle.nutrition(), handle.saturation(), handle.canAlwaysEat(), handle.eatSeconds(), Optional.ofNullable(item).map(CraftItemStack::asNMSCopy), handle.effects()); - } - - @Override - public List getEffects() { - return this.handle.effects().stream().map(CraftFoodEffect::new).collect(Collectors.toList()); - } - - @Override - public void setEffects(List effects) { - this.handle = new FoodProperties(this.handle.nutrition(), this.handle.saturation(), this.handle.canAlwaysEat(), this.handle.eatSeconds(), handle.usingConvertsTo(), effects.stream().map(CraftFoodEffect::new).map(CraftFoodEffect::getHandle).toList()); - } - - @Override - public FoodEffect addEffect(PotionEffect effect, float probability) { - List effects = new ArrayList<>(this.handle.effects()); - - FoodProperties.PossibleEffect newEffect = new net.minecraft.world.food.FoodProperties.PossibleEffect(CraftPotionUtil.fromBukkit(effect), probability); - effects.add(newEffect); - - this.handle = new FoodProperties(this.handle.nutrition(), this.handle.saturation(), this.handle.canAlwaysEat(), this.handle.eatSeconds(), handle.usingConvertsTo(), effects); - - return new CraftFoodEffect(newEffect); + handle = new FoodInfo(handle.nutrition(), handle.saturation(), canAlwaysEat); } @Override @@ -159,7 +90,7 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (this.getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final CraftFoodComponent other = (CraftFoodComponent) obj; @@ -168,91 +99,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return "CraftFoodComponent{" + "handle=" + this.handle + '}'; - } - - @SerializableAs("FoodEffect") - public static class CraftFoodEffect implements FoodEffect { - - private FoodProperties.PossibleEffect handle; - - public CraftFoodEffect(FoodProperties.PossibleEffect handle) { - this.handle = handle; - } - - public CraftFoodEffect(FoodEffect bukkit) { - this.handle = new net.minecraft.world.food.FoodProperties.PossibleEffect(CraftPotionUtil.fromBukkit(bukkit.getEffect()), bukkit.getProbability()); - } - - public CraftFoodEffect(Map map) { - PotionEffect effect = SerializableMeta.getObject(PotionEffect.class, map, "effect", false); - - Float probability = SerializableMeta.getObject(Float.class, map, "probability", true); - if (probability == null) { - probability = 1.0f; - } - - this.handle = new net.minecraft.world.food.FoodProperties.PossibleEffect(CraftPotionUtil.fromBukkit(effect), probability); - } - - @Override - public Map serialize() { - Map result = new LinkedHashMap<>(); - result.put("effect", this.getEffect()); - result.put("probability", this.getProbability()); - return result; - } - - public FoodProperties.PossibleEffect getHandle() { - return this.handle; - } - - @Override - public PotionEffect getEffect() { - return CraftPotionUtil.toBukkit(this.handle.effect()); - } - - @Override - public void setEffect(PotionEffect effect) { - this.handle = new net.minecraft.world.food.FoodProperties.PossibleEffect(CraftPotionUtil.fromBukkit(effect), this.handle.probability()); - } - - @Override - public float getProbability() { - return this.handle.probability(); - } - - @Override - public void setProbability(float probability) { - Preconditions.checkArgument(0 <= probability && probability <= 1, "Probability cannot be outside range [0,1]"); - this.handle = new net.minecraft.world.food.FoodProperties.PossibleEffect(this.handle.effect(), probability); - } - - @Override - public int hashCode() { - int hash = 5; - hash = 97 * hash + Objects.hashCode(this.handle); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (this.getClass() != obj.getClass()) { - return false; - } - final CraftFoodEffect other = (CraftFoodEffect) obj; - return Objects.equals(this.handle, other.handle); - } - - @Override - public String toString() { - return "CraftFoodEffect{" + "handle=" + this.handle + '}'; - } + return "CraftFoodComponent{" + "handle=" + handle + '}'; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftHolderUtil.java b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftHolderUtil.java new file mode 100644 index 00000000..0f1e5e74 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftHolderUtil.java @@ -0,0 +1,56 @@ +package org.bukkit.craftbukkit.inventory.components; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.IRegistry; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; + +final class CraftHolderUtil { + + private CraftHolderUtil() { + } + + public static void serialize(Map result, String key, HolderSet handle) { + handle.unwrap() + .ifLeft(tag -> result.put(key, "#" + tag.location().toString())) // Tag + .ifRight(list -> result.put(key, list.stream().map((entry) -> entry.unwrapKey().orElseThrow().location().toString()).toList())); // List + } + + public static HolderSet parse(Object parseObject, ResourceKey> registryKey, IRegistry registry) { + HolderSet holderSet = null; + + if (parseObject instanceof String parseString && parseString.startsWith("#")) { // Tag + parseString = parseString.substring(1); + MinecraftKey key = MinecraftKey.tryParse(parseString); + if (key != null) { + holderSet = registry.get(TagKey.create(registryKey, key)).orElse(null); + } + } else if (parseObject instanceof List parseList) { // List + List> holderList = new ArrayList<>(parseList.size()); + + for (Object entry : parseList) { + MinecraftKey key = MinecraftKey.tryParse(entry.toString()); + if (key == null) { + continue; + } + + registry.get(key).ifPresent(holderList::add); + } + + holderSet = HolderSet.direct(holderList); + } else { + throw new IllegalArgumentException("(" + parseObject + ") is not a valid String or List"); + } + + if (holderSet == null) { + holderSet = HolderSet.empty(); + } + + return holderSet; + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftJukeboxComponent.java b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftJukeboxComponent.java index 386e5c0d..78ac53c6 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftJukeboxComponent.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftJukeboxComponent.java @@ -7,8 +7,8 @@ import java.util.Optional; import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; +import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.EitherHolder; import net.minecraft.world.item.JukeboxPlayable; import org.bukkit.JukeboxSong; @@ -37,7 +37,7 @@ public CraftJukeboxComponent(Map map) { String song = SerializableMeta.getObject(String.class, map, "song", false); Boolean showTooltip = SerializableMeta.getObject(Boolean.class, map, "show-in-tooltip", true); - this.handle = new JukeboxPlayable(new EitherHolder<>(ResourceKey.create(Registries.JUKEBOX_SONG, ResourceLocation.parse(song))), (showTooltip != null) ? showTooltip : true); + this.handle = new JukeboxPlayable(new EitherHolder<>(ResourceKey.create(Registries.JUKEBOX_SONG, MinecraftKey.parse(song))), (showTooltip != null) ? showTooltip : true); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftToolComponent.java b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftToolComponent.java index 63c7b597..1484ac8e 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftToolComponent.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftToolComponent.java @@ -14,8 +14,6 @@ import net.minecraft.core.HolderSet; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; import net.minecraft.world.item.component.Tool; import net.minecraft.world.level.block.Block; import org.bukkit.Material; @@ -109,13 +107,13 @@ public ToolRule addRule(Material block, Float speed, Boolean correctForDrops) { Preconditions.checkArgument(block != null, "block must not be null"); Preconditions.checkArgument(block.isBlock(), "block must be a block type, given %s", block.getKey()); - Holder.Reference nmsBlock = CraftBlockType.bukkitToMinecraft(block).builtInRegistryHolder(); + Holder.c nmsBlock = CraftBlockType.bukkitToMinecraft(block).builtInRegistryHolder(); return addRule(HolderSet.direct(nmsBlock), speed, correctForDrops); } @Override public ToolRule addRule(Collection blocks, Float speed, Boolean correctForDrops) { - List> nmsBlocks = new ArrayList<>(blocks.size()); + List> nmsBlocks = new ArrayList<>(blocks.size()); for (Material material : blocks) { Preconditions.checkArgument(material.isBlock(), "blocks contains non-block type: %s", material.getKey()); @@ -132,9 +130,9 @@ public ToolRule addRule(Tag tag, Float speed, Boolean correctForDrops) } private ToolRule addRule(HolderSet blocks, Float speed, Boolean correctForDrops) { - Tool.Rule rule = new Tool.Rule(blocks, Optional.ofNullable(speed), Optional.ofNullable(correctForDrops)); + Tool.a rule = new Tool.a(blocks, Optional.ofNullable(speed), Optional.ofNullable(correctForDrops)); - List rules = new ArrayList<>(handle.rules().size() + 1); + List rules = new ArrayList<>(handle.rules().size() + 1); rules.addAll(handle.rules()); rules.add(rule); @@ -146,7 +144,7 @@ private ToolRule addRule(HolderSet blocks, Float speed, Boolean correctFo public boolean removeRule(ToolRule rule) { Preconditions.checkArgument(rule != null, "rule must not be null"); - List rules = new ArrayList<>(handle.rules()); + List rules = new ArrayList<>(handle.rules()); boolean removed = rules.remove(((CraftToolRule) rule).handle); handle = new Tool(rules, handle.defaultMiningSpeed(), handle.damagePerBlock()); @@ -183,60 +181,30 @@ public String toString() { @SerializableAs("ToolRule") public static class CraftToolRule implements ToolRule { - private Tool.Rule handle; + private Tool.a handle; - public CraftToolRule(Tool.Rule handle) { + public CraftToolRule(Tool.a handle) { this.handle = handle; } public CraftToolRule(ToolRule bukkit) { - Tool.Rule toCopy = ((CraftToolRule) bukkit).handle; - this.handle = new Tool.Rule(toCopy.blocks(), toCopy.speed(), toCopy.correctForDrops()); + Tool.a toCopy = ((CraftToolRule) bukkit).handle; + this.handle = new Tool.a(toCopy.blocks(), toCopy.speed(), toCopy.correctForDrops()); } public CraftToolRule(Map map) { Float speed = SerializableMeta.getObject(Float.class, map, "speed", true); Boolean correct = SerializableMeta.getObject(Boolean.class, map, "correct-for-drops", true); + HolderSet blocks = CraftHolderUtil.parse(SerializableMeta.getObject(Object.class, map, "blocks", false), Registries.BLOCK, BuiltInRegistries.BLOCK); - HolderSet blocks = null; - Object blocksObject = SerializableMeta.getObject(Object.class, map, "blocks", false); - if (blocksObject instanceof String blocksString && blocksString.startsWith("#")) { // Tag - blocksString = blocksString.substring(1); - ResourceLocation key = ResourceLocation.tryParse(blocksString); - if (key != null) { - blocks = BuiltInRegistries.BLOCK.getTag(TagKey.create(Registries.BLOCK, key)).orElse(null); - } - } else if (blocksObject instanceof List blocksList) { // List of blocks - List> blockHolders = new ArrayList<>(blocksList.size()); - - for (Object entry : blocksList) { - ResourceLocation key = ResourceLocation.tryParse(entry.toString()); - if (key == null) { - continue; - } - - BuiltInRegistries.BLOCK.getHolder(key).ifPresent(blockHolders::add); - } - - blocks = HolderSet.direct(blockHolders); - } else { - throw new IllegalArgumentException("blocks" + "(" + blocksObject + ") is not a valid String or List"); - } - - if (blocks == null) { - blocks = HolderSet.empty(); - } - - this.handle = new Tool.Rule(blocks, Optional.ofNullable(speed), Optional.ofNullable(correct)); + this.handle = new Tool.a(blocks, Optional.ofNullable(speed), Optional.ofNullable(correct)); } @Override public Map serialize() { Map result = new LinkedHashMap<>(); - handle.blocks().unwrap() - .ifLeft(key -> result.put("blocks", "#" + key.location().toString())) // Tag - .ifRight(blocks -> result.put("blocks", blocks.stream().map((block) -> block.unwrapKey().orElseThrow().location().toString()).toList())); // List of blocks + CraftHolderUtil.serialize(result, "blocks", handle.blocks()); Float speed = getSpeed(); if (speed != null) { @@ -251,7 +219,7 @@ public Map serialize() { return result; } - public Tool.Rule getHandle() { + public Tool.a getHandle() { return handle; } @@ -264,7 +232,7 @@ public Collection getBlocks() { public void setBlocks(Material block) { Preconditions.checkArgument(block != null, "block must not be null"); Preconditions.checkArgument(block.isBlock(), "block must be a block type, given %s", block.getKey()); - handle = new Tool.Rule(HolderSet.direct(CraftBlockType.bukkitToMinecraft(block).builtInRegistryHolder()), handle.speed(), handle.correctForDrops()); + handle = new Tool.a(HolderSet.direct(CraftBlockType.bukkitToMinecraft(block).builtInRegistryHolder()), handle.speed(), handle.correctForDrops()); } @Override @@ -274,13 +242,13 @@ public void setBlocks(Collection blocks) { Preconditions.checkArgument(material.isBlock(), "blocks contains non-block type: %s", material.getKey()); } - handle = new Tool.Rule(HolderSet.direct((List) blocks.stream().map(CraftBlockType::bukkitToMinecraft).map(Block::builtInRegistryHolder).collect(Collectors.toList())), handle.speed(), handle.correctForDrops()); + handle = new Tool.a(HolderSet.direct((List) blocks.stream().map(CraftBlockType::bukkitToMinecraft).map(Block::builtInRegistryHolder).collect(Collectors.toList())), handle.speed(), handle.correctForDrops()); } @Override public void setBlocks(Tag tag) { Preconditions.checkArgument(tag instanceof CraftBlockTag, "tag must be a block tag"); - handle = new Tool.Rule(((CraftBlockTag) tag).getHandle(), handle.speed(), handle.correctForDrops()); + handle = new Tool.a(((CraftBlockTag) tag).getHandle(), handle.speed(), handle.correctForDrops()); } @Override @@ -290,7 +258,7 @@ public Float getSpeed() { @Override public void setSpeed(Float speed) { - handle = new Tool.Rule(handle.blocks(), Optional.ofNullable(speed), handle.correctForDrops()); + handle = new Tool.a(handle.blocks(), Optional.ofNullable(speed), handle.correctForDrops()); } @Override @@ -300,7 +268,7 @@ public Boolean isCorrectForDrops() { @Override public void setCorrectForDrops(Boolean correct) { - handle = new Tool.Rule(handle.blocks(), handle.speed(), Optional.ofNullable(correct)); + handle = new Tool.a(handle.blocks(), handle.speed(), Optional.ofNullable(correct)); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftUseCooldownComponent.java b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftUseCooldownComponent.java new file mode 100644 index 00000000..a316eb62 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/inventory/components/CraftUseCooldownComponent.java @@ -0,0 +1,99 @@ +package org.bukkit.craftbukkit.inventory.components; + +import com.google.common.base.Preconditions; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.world.item.component.UseCooldown; +import org.bukkit.NamespacedKey; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.craftbukkit.inventory.SerializableMeta; +import org.bukkit.craftbukkit.util.CraftNamespacedKey; +import org.bukkit.inventory.meta.components.UseCooldownComponent; + +@SerializableAs("UseCooldown") +public final class CraftUseCooldownComponent implements UseCooldownComponent { + + private UseCooldown handle; + + public CraftUseCooldownComponent(UseCooldown cooldown) { + this.handle = cooldown; + } + + public CraftUseCooldownComponent(CraftUseCooldownComponent food) { + this.handle = food.handle; + } + + public CraftUseCooldownComponent(Map map) { + Float seconds = SerializableMeta.getObject(Float.class, map, "seconds", false); + String cooldownGroup = SerializableMeta.getString(map, "cooldown-group", true); + + this.handle = new UseCooldown(seconds, Optional.ofNullable(cooldownGroup).map(MinecraftKey::parse)); + } + + @Override + public Map serialize() { + Map result = new LinkedHashMap<>(); + result.put("seconds", getCooldownSeconds()); + if (getCooldownGroup() != null) { + result.put("cooldown-group", getCooldownGroup()); + } + + return result; + } + + public UseCooldown getHandle() { + return handle; + } + + @Override + public float getCooldownSeconds() { + return handle.seconds(); + } + + @Override + public void setCooldownSeconds(float eatSeconds) { + Preconditions.checkArgument(eatSeconds >= 0, "eatSeconds cannot be less than 0"); + + handle = new UseCooldown(eatSeconds, handle.cooldownGroup()); + } + + @Override + public NamespacedKey getCooldownGroup() { + return handle.cooldownGroup().map(CraftNamespacedKey::fromMinecraft).orElse(null); + } + + @Override + public void setCooldownGroup(NamespacedKey song) { + handle = new UseCooldown(handle.seconds(), Optional.ofNullable(song).map(CraftNamespacedKey::toMinecraft)); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 73 * hash + Objects.hashCode(this.handle); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftUseCooldownComponent other = (CraftUseCooldownComponent) obj; + return Objects.equals(this.handle, other.handle); + } + + @Override + public String toString() { + return "CraftUseCooldownComponent{" + "handle=" + handle + '}'; + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java index 4e1ec43a..8e1c1e9b 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java @@ -26,7 +26,7 @@ public Class getPrimitiveType() { @NotNull @Override public Class getComplexType() { - return this.deprecated.getComplexType(); + return deprecated.getComplexType(); } @NotNull diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java index 9496478c..3ef217b0 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java @@ -23,38 +23,38 @@ public DeprecatedCustomTagContainer(PersistentDataContainer wrapped) { @Override public void setCustomTag(NamespacedKey key, ItemTagType type, Z value) { if (Objects.equals(CustomItemTagContainer.class, type.getPrimitiveType())) { - this.wrapped.set(key, new DeprecatedContainerTagType<>((ItemTagType) type), value); + wrapped.set(key, new DeprecatedContainerTagType<>((ItemTagType) type), value); } else { - this.wrapped.set(key, new DeprecatedItemTagType<>(type), value); + wrapped.set(key, new DeprecatedItemTagType<>(type), value); } } @Override public boolean hasCustomTag(NamespacedKey key, ItemTagType type) { if (Objects.equals(CustomItemTagContainer.class, type.getPrimitiveType())) { - return this.wrapped.has(key, new DeprecatedContainerTagType<>((ItemTagType) type)); + return wrapped.has(key, new DeprecatedContainerTagType<>((ItemTagType) type)); } else { - return this.wrapped.has(key, new DeprecatedItemTagType<>(type)); + return wrapped.has(key, new DeprecatedItemTagType<>(type)); } } @Override public Z getCustomTag(NamespacedKey key, ItemTagType type) { if (Objects.equals(CustomItemTagContainer.class, type.getPrimitiveType())) { - return this.wrapped.get(key, new DeprecatedContainerTagType<>((ItemTagType) type)); + return wrapped.get(key, new DeprecatedContainerTagType<>((ItemTagType) type)); } else { - return this.wrapped.get(key, new DeprecatedItemTagType<>(type)); + return wrapped.get(key, new DeprecatedItemTagType<>(type)); } } @Override public void removeCustomTag(NamespacedKey key) { - this.wrapped.remove(key); + wrapped.remove(key); } @Override public boolean isEmpty() { - return this.wrapped.isEmpty(); + return wrapped.isEmpty(); } @Override @@ -63,6 +63,6 @@ public ItemTagAdapterContext getAdapterContext() { } public PersistentDataContainer getWrapped() { - return this.wrapped; + return wrapped; } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java index fd614f47..e8bb75e9 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java @@ -19,6 +19,6 @@ public DeprecatedItemAdapterContext(PersistentDataAdapterContext context) { */ @Override public CustomItemTagContainer newTagContainer() { - return new DeprecatedCustomTagContainer(this.context.newPersistentDataContainer()); + return new DeprecatedCustomTagContainer(context.newPersistentDataContainer()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java index fe718fc4..372a0cfd 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java @@ -16,13 +16,13 @@ public DeprecatedItemTagType(ItemTagType deprecated) { @NotNull @Override public Class

    getPrimitiveType() { - return this.deprecated.getPrimitiveType(); + return deprecated.getPrimitiveType(); } @NotNull @Override public Class getComplexType() { - return this.deprecated.getComplexType(); + return deprecated.getComplexType(); } @NotNull diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java index 8952e552..b7944a5c 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.contents.TranslatableContents; import org.bukkit.NamespacedKey; @@ -11,26 +12,26 @@ import org.bukkit.inventory.meta.trim.TrimMaterial; import org.jetbrains.annotations.NotNull; -public class CraftTrimMaterial implements TrimMaterial, Handleable { +public class CraftTrimMaterial implements TrimMaterial, Handleable { - public static TrimMaterial minecraftToBukkit(net.minecraft.world.item.armortrim.TrimMaterial minecraft) { + public static TrimMaterial minecraftToBukkit(net.minecraft.world.item.equipment.trim.TrimMaterial minecraft) { return CraftRegistry.minecraftToBukkit(minecraft, Registries.TRIM_MATERIAL, Registry.TRIM_MATERIAL); } - public static TrimMaterial minecraftHolderToBukkit(Holder minecraft) { - return CraftTrimMaterial.minecraftToBukkit(minecraft.value()); + public static TrimMaterial minecraftHolderToBukkit(Holder minecraft) { + return minecraftToBukkit(minecraft.value()); } - public static net.minecraft.world.item.armortrim.TrimMaterial bukkitToMinecraft(TrimMaterial bukkit) { + public static net.minecraft.world.item.equipment.trim.TrimMaterial bukkitToMinecraft(TrimMaterial bukkit) { return CraftRegistry.bukkitToMinecraft(bukkit); } - public static Holder bukkitToMinecraftHolder(TrimMaterial bukkit) { + public static Holder bukkitToMinecraftHolder(TrimMaterial bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.TRIM_MATERIAL); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.TRIM_MATERIAL); - if (registry.wrapAsHolder(CraftTrimMaterial.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -39,27 +40,27 @@ public static Holder bukkitToMi } private final NamespacedKey key; - private final net.minecraft.world.item.armortrim.TrimMaterial handle; + private final net.minecraft.world.item.equipment.trim.TrimMaterial handle; - public CraftTrimMaterial(NamespacedKey key, net.minecraft.world.item.armortrim.TrimMaterial handle) { + public CraftTrimMaterial(NamespacedKey key, net.minecraft.world.item.equipment.trim.TrimMaterial handle) { this.key = key; this.handle = handle; } @Override - public net.minecraft.world.item.armortrim.TrimMaterial getHandle() { - return this.handle; + public net.minecraft.world.item.equipment.trim.TrimMaterial getHandle() { + return handle; } @Override @NotNull public NamespacedKey getKey() { - return this.key; + return key; } @NotNull @Override public String getTranslationKey() { - return ((TranslatableContents) this.handle.description().getContents()).getKey(); + return ((TranslatableContents) handle.description().getContents()).getKey(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java index 0a6df5fd..2d9fc520 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.contents.TranslatableContents; import org.bukkit.NamespacedKey; @@ -11,26 +12,26 @@ import org.bukkit.inventory.meta.trim.TrimPattern; import org.jetbrains.annotations.NotNull; -public class CraftTrimPattern implements TrimPattern, Handleable { +public class CraftTrimPattern implements TrimPattern, Handleable { - public static TrimPattern minecraftToBukkit(net.minecraft.world.item.armortrim.TrimPattern minecraft) { + public static TrimPattern minecraftToBukkit(net.minecraft.world.item.equipment.trim.TrimPattern minecraft) { return CraftRegistry.minecraftToBukkit(minecraft, Registries.TRIM_PATTERN, Registry.TRIM_PATTERN); } - public static TrimPattern minecraftHolderToBukkit(Holder minecraft) { - return CraftTrimPattern.minecraftToBukkit(minecraft.value()); + public static TrimPattern minecraftHolderToBukkit(Holder minecraft) { + return minecraftToBukkit(minecraft.value()); } - public static net.minecraft.world.item.armortrim.TrimPattern bukkitToMinecraft(TrimPattern bukkit) { + public static net.minecraft.world.item.equipment.trim.TrimPattern bukkitToMinecraft(TrimPattern bukkit) { return CraftRegistry.bukkitToMinecraft(bukkit); } - public static Holder bukkitToMinecraftHolder(TrimPattern bukkit) { + public static Holder bukkitToMinecraftHolder(TrimPattern bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.TRIM_PATTERN); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.TRIM_PATTERN); - if (registry.wrapAsHolder(CraftTrimPattern.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -39,27 +40,27 @@ public static Holder bukkitToMin } private final NamespacedKey key; - private final net.minecraft.world.item.armortrim.TrimPattern handle; + private final net.minecraft.world.item.equipment.trim.TrimPattern handle; - public CraftTrimPattern(NamespacedKey key, net.minecraft.world.item.armortrim.TrimPattern handle) { + public CraftTrimPattern(NamespacedKey key, net.minecraft.world.item.equipment.trim.TrimPattern handle) { this.key = key; this.handle = handle; } @Override - public net.minecraft.world.item.armortrim.TrimPattern getHandle() { - return this.handle; + public net.minecraft.world.item.equipment.trim.TrimPattern getHandle() { + return handle; } @Override @NotNull public NamespacedKey getKey() { - return this.key; + return key; } @NotNull @Override public String getTranslationKey() { - return ((TranslatableContents) this.handle.description().getContents()).getKey(); + return ((TranslatableContents) handle.description().getContents()).getKey(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java index ec8ef47e..52cdf39c 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java @@ -14,47 +14,47 @@ public final class CraftInventoryCreator { private final Map converterMap = new HashMap<>(); private CraftInventoryCreator() { - this.converterMap.put(InventoryType.CHEST, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.DISPENSER, new CraftTileInventoryConverter.Dispenser()); - this.converterMap.put(InventoryType.DROPPER, new CraftTileInventoryConverter.Dropper()); - this.converterMap.put(InventoryType.FURNACE, new CraftTileInventoryConverter.Furnace()); - this.converterMap.put(InventoryType.WORKBENCH, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.ENCHANTING, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.BREWING, new CraftTileInventoryConverter.BrewingStand()); - this.converterMap.put(InventoryType.PLAYER, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.MERCHANT, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.ENDER_CHEST, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.ANVIL, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.SMITHING, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.BEACON, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.HOPPER, new CraftTileInventoryConverter.Hopper()); - this.converterMap.put(InventoryType.SHULKER_BOX, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.BARREL, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.BLAST_FURNACE, new CraftTileInventoryConverter.BlastFurnace()); - this.converterMap.put(InventoryType.LECTERN, new CraftTileInventoryConverter.Lectern()); - this.converterMap.put(InventoryType.SMOKER, new CraftTileInventoryConverter.Smoker()); - this.converterMap.put(InventoryType.LOOM, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.CARTOGRAPHY, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.GRINDSTONE, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.STONECUTTER, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.SMITHING_NEW, this.DEFAULT_CONVERTER); - this.converterMap.put(InventoryType.CRAFTER, new CraftTileInventoryConverter.Crafter()); + converterMap.put(InventoryType.CHEST, DEFAULT_CONVERTER); + converterMap.put(InventoryType.DISPENSER, new CraftTileInventoryConverter.Dispenser()); + converterMap.put(InventoryType.DROPPER, new CraftTileInventoryConverter.Dropper()); + converterMap.put(InventoryType.FURNACE, new CraftTileInventoryConverter.Furnace()); + converterMap.put(InventoryType.WORKBENCH, DEFAULT_CONVERTER); + converterMap.put(InventoryType.ENCHANTING, DEFAULT_CONVERTER); + converterMap.put(InventoryType.BREWING, new CraftTileInventoryConverter.BrewingStand()); + converterMap.put(InventoryType.PLAYER, DEFAULT_CONVERTER); + converterMap.put(InventoryType.MERCHANT, DEFAULT_CONVERTER); + converterMap.put(InventoryType.ENDER_CHEST, DEFAULT_CONVERTER); + converterMap.put(InventoryType.ANVIL, DEFAULT_CONVERTER); + converterMap.put(InventoryType.SMITHING, DEFAULT_CONVERTER); + converterMap.put(InventoryType.BEACON, DEFAULT_CONVERTER); + converterMap.put(InventoryType.HOPPER, new CraftTileInventoryConverter.Hopper()); + converterMap.put(InventoryType.SHULKER_BOX, DEFAULT_CONVERTER); + converterMap.put(InventoryType.BARREL, DEFAULT_CONVERTER); + converterMap.put(InventoryType.BLAST_FURNACE, new CraftTileInventoryConverter.BlastFurnace()); + converterMap.put(InventoryType.LECTERN, new CraftTileInventoryConverter.Lectern()); + converterMap.put(InventoryType.SMOKER, new CraftTileInventoryConverter.Smoker()); + converterMap.put(InventoryType.LOOM, DEFAULT_CONVERTER); + converterMap.put(InventoryType.CARTOGRAPHY, DEFAULT_CONVERTER); + converterMap.put(InventoryType.GRINDSTONE, DEFAULT_CONVERTER); + converterMap.put(InventoryType.STONECUTTER, DEFAULT_CONVERTER); + converterMap.put(InventoryType.SMITHING_NEW, DEFAULT_CONVERTER); + converterMap.put(InventoryType.CRAFTER, new CraftTileInventoryConverter.Crafter()); } public Inventory createInventory(InventoryHolder holder, InventoryType type) { - return this.converterMap.get(type).createInventory(holder, type); + return converterMap.get(type).createInventory(holder, type); } public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { - return this.converterMap.get(type).createInventory(holder, type, title); + return converterMap.get(type).createInventory(holder, type, title); } public Inventory createInventory(InventoryHolder holder, int size) { - return this.DEFAULT_CONVERTER.createInventory(holder, size); + return DEFAULT_CONVERTER.createInventory(holder, size); } public Inventory createInventory(InventoryHolder holder, int size, String title) { - return this.DEFAULT_CONVERTER.createInventory(holder, size, title); + return DEFAULT_CONVERTER.createInventory(holder, size, title); } public interface InventoryConverter { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenuBuilder.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenuBuilder.java index da075d52..a3938166 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenuBuilder.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenuBuilder.java @@ -1,38 +1,38 @@ package org.bukkit.craftbukkit.inventory.util; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.ContainerLevelAccess; -import net.minecraft.world.inventory.MenuType; +import net.minecraft.server.level.EntityPlayer; +import net.minecraft.world.ITileInventory; +import net.minecraft.world.entity.player.PlayerInventory; +import net.minecraft.world.inventory.Container; +import net.minecraft.world.inventory.ContainerAccess; +import net.minecraft.world.inventory.Containers; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.IBlockData; public interface CraftMenuBuilder { - AbstractContainerMenu build(ServerPlayer player, MenuType type); + Container build(EntityPlayer player, Containers type); static CraftMenuBuilder worldAccess(LocationBoundContainerBuilder builder) { - return (ServerPlayer player, MenuType type) -> { - return builder.build(player.nextContainerCounterInt(), player.getInventory(), ContainerLevelAccess.create(player.level(), player.blockPosition())); + return (EntityPlayer player, Containers type) -> { + return builder.build(player.nextContainerCounter(), player.getInventory(), ContainerAccess.create(player.level(), player.blockPosition())); }; } static CraftMenuBuilder tileEntity(TileEntityObjectBuilder objectBuilder, Block block) { - return (ServerPlayer player, MenuType type) -> { - return objectBuilder.build(player.blockPosition(), block.defaultBlockState()).createMenu(player.nextContainerCounterInt(), player.getInventory(), player); + return (EntityPlayer player, Containers type) -> { + return objectBuilder.build(player.blockPosition(), block.defaultBlockState()).createMenu(player.nextContainerCounter(), player.getInventory(), player); }; } interface TileEntityObjectBuilder { - MenuProvider build(BlockPos blockPosition, BlockState blockData); + ITileInventory build(BlockPos blockPosition, IBlockData blockData); } interface LocationBoundContainerBuilder { - AbstractContainerMenu build(int syncId, Inventory inventory, ContainerLevelAccess access); + Container build(int syncId, PlayerInventory inventory, ContainerAccess access); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenus.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenus.java index adadc6d0..e63d3f3e 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenus.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftMenus.java @@ -1,12 +1,25 @@ package org.bukkit.craftbukkit.inventory.util; import static org.bukkit.craftbukkit.inventory.util.CraftMenuBuilder.*; - - -import net.minecraft.network.chat.Component; -import net.minecraft.world.SimpleMenuProvider; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.world.TileInventory; +import net.minecraft.world.inventory.ContainerAnvil; +import net.minecraft.world.inventory.ContainerCartography; +import net.minecraft.world.inventory.ContainerEnchantTable; +import net.minecraft.world.inventory.ContainerGrindstone; +import net.minecraft.world.inventory.ContainerSmithing; +import net.minecraft.world.inventory.ContainerStonecutter; +import net.minecraft.world.inventory.ContainerWorkbench; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.CrafterBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityBeacon; +import net.minecraft.world.level.block.entity.TileEntityBlastFurnace; +import net.minecraft.world.level.block.entity.TileEntityBrewingStand; +import net.minecraft.world.level.block.entity.TileEntityDispenser; +import net.minecraft.world.level.block.entity.TileEntityFurnaceFurnace; +import net.minecraft.world.level.block.entity.TileEntityHopper; +import net.minecraft.world.level.block.entity.TileEntityLectern; +import net.minecraft.world.level.block.entity.TileEntitySmoker; import org.bukkit.craftbukkit.inventory.CraftMenuType; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.MenuType; @@ -20,61 +33,59 @@ import org.bukkit.inventory.view.LoomView; import org.bukkit.inventory.view.MerchantView; import org.bukkit.inventory.view.StonecutterView; -import net.minecraft.world.level.block.entity.*; -import net.minecraft.world.inventory.*; public final class CraftMenus { public record MenuTypeData(Class viewClass, CraftMenuBuilder menuBuilder) { } - private static final CraftMenuBuilder STANDARD = (player, menuType) -> menuType.create(player.nextContainerCounterInt(), player.getInventory()); + private static final CraftMenuBuilder STANDARD = (player, menuType) -> menuType.create(player.nextContainerCounter(), player.getInventory()); public static MenuTypeData getMenuTypeData(CraftMenuType menuType) { // this isn't ideal as both dispenser and dropper are 3x3, InventoryType can't currently handle generic 3x3s with size 9 // this needs to be removed when inventory creation is overhauled if (menuType == MenuType.GENERIC_3X3) { - return asType(new MenuTypeData<>(InventoryView.class, tileEntity(DispenserBlockEntity::new, Blocks.DISPENSER))); + return asType(new MenuTypeData<>(InventoryView.class, tileEntity(TileEntityDispenser::new, Blocks.DISPENSER))); } if (menuType == MenuType.CRAFTER_3X3) { return asType(new MenuTypeData<>(CrafterView.class, tileEntity(CrafterBlockEntity::new, Blocks.CRAFTER))); } if (menuType == MenuType.ANVIL) { - return asType(new MenuTypeData<>(AnvilView.class, worldAccess(AnvilMenu::new))); + return asType(new MenuTypeData<>(AnvilView.class, worldAccess(ContainerAnvil::new))); } if (menuType == MenuType.BEACON) { - return asType(new MenuTypeData<>(BeaconView.class, tileEntity(BeaconBlockEntity::new, Blocks.BEACON))); + return asType(new MenuTypeData<>(BeaconView.class, tileEntity(TileEntityBeacon::new, Blocks.BEACON))); } if (menuType == MenuType.BLAST_FURNACE) { - return asType(new MenuTypeData<>(FurnaceView.class, tileEntity(BlastFurnaceBlockEntity::new, Blocks.BLAST_FURNACE))); + return asType(new MenuTypeData<>(FurnaceView.class, tileEntity(TileEntityBlastFurnace::new, Blocks.BLAST_FURNACE))); } if (menuType == MenuType.BREWING_STAND) { - return asType(new MenuTypeData<>(BrewingStandView.class, tileEntity(BrewingStandBlockEntity::new, Blocks.BREWING_STAND))); + return asType(new MenuTypeData<>(BrewingStandView.class, tileEntity(TileEntityBrewingStand::new, Blocks.BREWING_STAND))); } if (menuType == MenuType.CRAFTING) { - return asType(new MenuTypeData<>(InventoryView.class, worldAccess(CraftingMenu::new))); + return asType(new MenuTypeData<>(InventoryView.class, worldAccess(ContainerWorkbench::new))); } if (menuType == MenuType.ENCHANTMENT) { return asType(new MenuTypeData<>(EnchantmentView.class, (player, type) -> { - return new SimpleMenuProvider((syncId, inventory, human) -> { - return worldAccess(EnchantmentMenu::new).build(player, type); - }, Component.empty()).createMenu(player.nextContainerCounterInt(), player.getInventory(), player); + return new TileInventory((syncId, inventory, human) -> { + return worldAccess(ContainerEnchantTable::new).build(player, type); + }, IChatBaseComponent.empty()).createMenu(player.nextContainerCounter(), player.getInventory(), player); })); } if (menuType == MenuType.FURNACE) { - return asType(new MenuTypeData<>(FurnaceView.class, tileEntity(FurnaceBlockEntity::new, Blocks.FURNACE))); + return asType(new MenuTypeData<>(FurnaceView.class, tileEntity(TileEntityFurnaceFurnace::new, Blocks.FURNACE))); } if (menuType == MenuType.GRINDSTONE) { - return asType(new MenuTypeData<>(InventoryView.class, worldAccess(GrindstoneMenu::new))); + return asType(new MenuTypeData<>(InventoryView.class, worldAccess(ContainerGrindstone::new))); } // We really don't need to be creating a tile entity for hopper but currently InventoryType doesn't have capacity // to understand otherwise if (menuType == MenuType.HOPPER) { - return asType(new MenuTypeData<>(InventoryView.class, tileEntity(HopperBlockEntity::new, Blocks.HOPPER))); + return asType(new MenuTypeData<>(InventoryView.class, tileEntity(TileEntityHopper::new, Blocks.HOPPER))); } // We also don't need to create a tile entity for lectern, but again InventoryType isn't smart enough to know any better if (menuType == MenuType.LECTERN) { - return asType(new MenuTypeData<>(LecternView.class, tileEntity(LecternBlockEntity::new, Blocks.LECTERN))); + return asType(new MenuTypeData<>(LecternView.class, tileEntity(TileEntityLectern::new, Blocks.LECTERN))); } if (menuType == MenuType.LOOM) { return asType(new MenuTypeData<>(LoomView.class, STANDARD)); @@ -83,16 +94,16 @@ public static MenuTypeData getMenuTypeData(CraftMen return asType(new MenuTypeData<>(MerchantView.class, STANDARD)); } if (menuType == MenuType.SMITHING) { - return asType(new MenuTypeData<>(InventoryView.class, worldAccess(SmithingMenu::new))); + return asType(new MenuTypeData<>(InventoryView.class, worldAccess(ContainerSmithing::new))); } if (menuType == MenuType.SMOKER) { - return asType(new MenuTypeData<>(FurnaceView.class, tileEntity(SmokerBlockEntity::new, Blocks.SMOKER))); + return asType(new MenuTypeData<>(FurnaceView.class, tileEntity(TileEntitySmoker::new, Blocks.SMOKER))); } if (menuType == MenuType.CARTOGRAPHY_TABLE) { - return asType(new MenuTypeData<>(InventoryView.class, worldAccess(CartographyTableMenu::new))); + return asType(new MenuTypeData<>(InventoryView.class, worldAccess(ContainerCartography::new))); } if (menuType == MenuType.STONECUTTER) { - return asType(new MenuTypeData<>(StonecutterView.class, worldAccess(StonecutterMenu::new))); + return asType(new MenuTypeData<>(StonecutterView.class, worldAccess(ContainerStonecutter::new))); } return asType(new MenuTypeData<>(InventoryView.class, STANDARD)); diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java index 11d23b3a..d84faa27 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java @@ -1,19 +1,19 @@ package org.bukkit.craftbukkit.inventory.util; import net.minecraft.core.BlockPos; -import net.minecraft.world.Container; +import net.minecraft.world.IInventory; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; -import net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity; -import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; import net.minecraft.world.level.block.entity.CrafterBlockEntity; -import net.minecraft.world.level.block.entity.DispenserBlockEntity; -import net.minecraft.world.level.block.entity.DropperBlockEntity; -import net.minecraft.world.level.block.entity.FurnaceBlockEntity; -import net.minecraft.world.level.block.entity.HopperBlockEntity; -import net.minecraft.world.level.block.entity.LecternBlockEntity; -import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; -import net.minecraft.world.level.block.entity.SmokerBlockEntity; +import net.minecraft.world.level.block.entity.TileEntityBlastFurnace; +import net.minecraft.world.level.block.entity.TileEntityBrewingStand; +import net.minecraft.world.level.block.entity.TileEntityDispenser; +import net.minecraft.world.level.block.entity.TileEntityDropper; +import net.minecraft.world.level.block.entity.TileEntityFurnace; +import net.minecraft.world.level.block.entity.TileEntityFurnaceFurnace; +import net.minecraft.world.level.block.entity.TileEntityHopper; +import net.minecraft.world.level.block.entity.TileEntityLectern; +import net.minecraft.world.level.block.entity.TileEntityLootable; +import net.minecraft.world.level.block.entity.TileEntitySmoker; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.craftbukkit.inventory.CraftInventoryBrewer; import org.bukkit.craftbukkit.inventory.CraftInventoryFurnace; @@ -24,67 +24,67 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreator.InventoryConverter { - public abstract Container getTileEntity(); + public abstract IInventory getTileEntity(); @Override public Inventory createInventory(InventoryHolder holder, InventoryType type) { - return this.getInventory(this.getTileEntity()); + return getInventory(getTileEntity()); } @Override public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { - Container te = this.getTileEntity(); - if (te instanceof RandomizableContainerBlockEntity) { - ((RandomizableContainerBlockEntity) te).name = CraftChatMessage.fromStringOrNull(title); + IInventory te = getTileEntity(); + if (te instanceof TileEntityLootable) { + ((TileEntityLootable) te).name = CraftChatMessage.fromStringOrNull(title); } - return this.getInventory(te); + return getInventory(te); } - public Inventory getInventory(Container tileEntity) { + public Inventory getInventory(IInventory tileEntity) { return new CraftInventory(tileEntity); } public static class Furnace extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - AbstractFurnaceBlockEntity furnace = new FurnaceBlockEntity(BlockPos.ZERO, Blocks.FURNACE.defaultBlockState()); // TODO: customize this if required + public IInventory getTileEntity() { + TileEntityFurnace furnace = new TileEntityFurnaceFurnace(BlockPos.ZERO, Blocks.FURNACE.defaultBlockState()); // TODO: customize this if required return furnace; } @Override public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { - Container tileEntity = this.getTileEntity(); - ((AbstractFurnaceBlockEntity) tileEntity).name = CraftChatMessage.fromStringOrNull(title); - return this.getInventory(tileEntity); + IInventory tileEntity = getTileEntity(); + ((TileEntityFurnace) tileEntity).name = CraftChatMessage.fromStringOrNull(title); + return getInventory(tileEntity); } @Override - public Inventory getInventory(Container tileEntity) { - return new CraftInventoryFurnace((AbstractFurnaceBlockEntity) tileEntity); + public Inventory getInventory(IInventory tileEntity) { + return new CraftInventoryFurnace((TileEntityFurnace) tileEntity); } } public static class BrewingStand extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new BrewingStandBlockEntity(BlockPos.ZERO, Blocks.BREWING_STAND.defaultBlockState()); + public IInventory getTileEntity() { + return new TileEntityBrewingStand(BlockPos.ZERO, Blocks.BREWING_STAND.defaultBlockState()); } @Override public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { // BrewingStand does not extend TileEntityLootable - Container tileEntity = this.getTileEntity(); - if (tileEntity instanceof BrewingStandBlockEntity) { - ((BrewingStandBlockEntity) tileEntity).name = CraftChatMessage.fromStringOrNull(title); + IInventory tileEntity = getTileEntity(); + if (tileEntity instanceof TileEntityBrewingStand) { + ((TileEntityBrewingStand) tileEntity).name = CraftChatMessage.fromStringOrNull(title); } - return this.getInventory(tileEntity); + return getInventory(tileEntity); } @Override - public Inventory getInventory(Container tileEntity) { + public Inventory getInventory(IInventory tileEntity) { return new CraftInventoryBrewer(tileEntity); } } @@ -92,55 +92,55 @@ public Inventory getInventory(Container tileEntity) { public static class Dispenser extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new DispenserBlockEntity(BlockPos.ZERO, Blocks.DISPENSER.defaultBlockState()); + public IInventory getTileEntity() { + return new TileEntityDispenser(BlockPos.ZERO, Blocks.DISPENSER.defaultBlockState()); } } public static class Dropper extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new DropperBlockEntity(BlockPos.ZERO, Blocks.DROPPER.defaultBlockState()); + public IInventory getTileEntity() { + return new TileEntityDropper(BlockPos.ZERO, Blocks.DROPPER.defaultBlockState()); } } public static class Hopper extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new HopperBlockEntity(BlockPos.ZERO, Blocks.HOPPER.defaultBlockState()); + public IInventory getTileEntity() { + return new TileEntityHopper(BlockPos.ZERO, Blocks.HOPPER.defaultBlockState()); } } public static class BlastFurnace extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new BlastFurnaceBlockEntity(BlockPos.ZERO, Blocks.BLAST_FURNACE.defaultBlockState()); + public IInventory getTileEntity() { + return new TileEntityBlastFurnace(BlockPos.ZERO, Blocks.BLAST_FURNACE.defaultBlockState()); } } public static class Lectern extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new LecternBlockEntity(BlockPos.ZERO, Blocks.LECTERN.defaultBlockState()).bookAccess; + public IInventory getTileEntity() { + return new TileEntityLectern(BlockPos.ZERO, Blocks.LECTERN.defaultBlockState()).bookAccess; } } public static class Smoker extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { - return new SmokerBlockEntity(BlockPos.ZERO, Blocks.SMOKER.defaultBlockState()); + public IInventory getTileEntity() { + return new TileEntitySmoker(BlockPos.ZERO, Blocks.SMOKER.defaultBlockState()); } } public static class Crafter extends CraftTileInventoryConverter { @Override - public Container getTileEntity() { + public IInventory getTileEntity() { return new CrafterBlockEntity(BlockPos.ZERO, Blocks.CRAFTER.defaultBlockState()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftAnvilView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftAnvilView.java index e2d8d69c..447437f2 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftAnvilView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftAnvilView.java @@ -1,66 +1,66 @@ package org.bukkit.craftbukkit.inventory.view; -import net.minecraft.world.inventory.AnvilMenu; +import net.minecraft.world.inventory.ContainerAnvil; import org.bukkit.craftbukkit.inventory.CraftInventoryAnvil; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.view.AnvilView; import org.jetbrains.annotations.Nullable; -public class CraftAnvilView extends CraftInventoryView implements AnvilView { +public class CraftAnvilView extends CraftInventoryView implements AnvilView { - public CraftAnvilView(final HumanEntity player, final Inventory viewing, final AnvilMenu container) { + public CraftAnvilView(final HumanEntity player, final AnvilInventory viewing, final ContainerAnvil container) { super(player, viewing, container); } @Nullable @Override public String getRenameText() { - return this.container.itemName; + return container.itemName; } @Override public int getRepairItemCountCost() { - return this.container.repairItemCountCost; + return container.repairItemCountCost; } @Override public int getRepairCost() { - return this.container.getCost(); + return container.getCost(); } @Override public int getMaximumRepairCost() { - return this.container.maximumRepairCost; + return container.maximumRepairCost; } @Override public void setRepairItemCountCost(final int cost) { - this.container.repairItemCountCost = cost; + container.repairItemCountCost = cost; } @Override public void setRepairCost(final int cost) { - this.container.cost.set(cost); + container.cost.set(cost); } @Override public void setMaximumRepairCost(final int cost) { - this.container.maximumRepairCost = cost; + container.maximumRepairCost = cost; } public void updateFromLegacy(CraftInventoryAnvil legacy) { if (legacy.isRepairCostSet()) { - this.setRepairCost(legacy.getRepairCost()); + setRepairCost(legacy.getRepairCost()); } if (legacy.isRepairCostAmountSet()) { - this.setRepairItemCountCost(legacy.getRepairCostAmount()); + setRepairItemCountCost(legacy.getRepairCostAmount()); } if (legacy.isMaximumRepairCostSet()) { - this.setMaximumRepairCost(legacy.getMaximumRepairCost()); + setMaximumRepairCost(legacy.getMaximumRepairCost()); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBeaconView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBeaconView.java index 9326fa75..bd6e24a2 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBeaconView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBeaconView.java @@ -1,45 +1,45 @@ package org.bukkit.craftbukkit.inventory.view; -import net.minecraft.world.inventory.BeaconMenu; -import net.minecraft.world.level.block.entity.BeaconBlockEntity; +import net.minecraft.world.inventory.ContainerBeacon; +import net.minecraft.world.level.block.entity.TileEntityBeacon; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.BeaconInventory; import org.bukkit.inventory.view.BeaconView; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.Nullable; -public class CraftBeaconView extends CraftInventoryView implements BeaconView { +public class CraftBeaconView extends CraftInventoryView implements BeaconView { - public CraftBeaconView(final HumanEntity player, final Inventory viewing, final BeaconMenu container) { + public CraftBeaconView(final HumanEntity player, final BeaconInventory viewing, final ContainerBeacon container) { super(player, viewing, container); } @Override public int getTier() { - return this.container.getLevels(); + return container.getLevels(); } @Nullable @Override public PotionEffectType getPrimaryEffect() { - return this.container.getPrimaryEffect() != null ? CraftPotionEffectType.minecraftHolderToBukkit(this.container.getPrimaryEffect()) : null; + return container.getPrimaryEffect() != null ? CraftPotionEffectType.minecraftHolderToBukkit(container.getPrimaryEffect()) : null; } @Nullable @Override public PotionEffectType getSecondaryEffect() { - return this.container.getSecondaryEffect() != null ? CraftPotionEffectType.minecraftHolderToBukkit(this.container.getSecondaryEffect()) : null; + return container.getSecondaryEffect() != null ? CraftPotionEffectType.minecraftHolderToBukkit(container.getSecondaryEffect()) : null; } @Override public void setPrimaryEffect(@Nullable final PotionEffectType effectType) { - this.container.setData(BeaconBlockEntity.DATA_PRIMARY, BeaconMenu.encodeEffect(CraftPotionEffectType.bukkitToMinecraftHolder(effectType))); + container.setData(TileEntityBeacon.DATA_PRIMARY, ContainerBeacon.encodeEffect((effectType == null) ? null : CraftPotionEffectType.bukkitToMinecraftHolder(effectType))); } @Override public void setSecondaryEffect(@Nullable final PotionEffectType effectType) { - this.container.setData(BeaconBlockEntity.DATA_SECONDARY, BeaconMenu.encodeEffect(CraftPotionEffectType.bukkitToMinecraftHolder(effectType))); + container.setData(TileEntityBeacon.DATA_SECONDARY, ContainerBeacon.encodeEffect((effectType == null) ? null : CraftPotionEffectType.bukkitToMinecraftHolder(effectType))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBrewingStandView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBrewingStandView.java index c92e5122..db00f945 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBrewingStandView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftBrewingStandView.java @@ -1,38 +1,38 @@ package org.bukkit.craftbukkit.inventory.view; import com.google.common.base.Preconditions; -import net.minecraft.world.inventory.BrewingStandMenu; -import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; +import net.minecraft.world.inventory.ContainerBrewingStand; +import net.minecraft.world.level.block.entity.TileEntityBrewingStand; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.BrewerInventory; import org.bukkit.inventory.view.BrewingStandView; -public class CraftBrewingStandView extends CraftInventoryView implements BrewingStandView { +public class CraftBrewingStandView extends CraftInventoryView implements BrewingStandView { - public CraftBrewingStandView(final HumanEntity player, final Inventory viewing, final BrewingStandMenu container) { + public CraftBrewingStandView(final HumanEntity player, final BrewerInventory viewing, final ContainerBrewingStand container) { super(player, viewing, container); } @Override public int getFuelLevel() { - return this.container.getFuel(); + return container.getFuel(); } @Override public int getBrewingTicks() { - return this.container.getBrewingTicks(); + return container.getBrewingTicks(); } @Override public void setFuelLevel(final int fuelLevel) { Preconditions.checkArgument(fuelLevel > 0, "The given fuel level must be greater than 0"); - this.container.setData(BrewingStandBlockEntity.DATA_FUEL_USES, fuelLevel); + container.setData(TileEntityBrewingStand.DATA_FUEL_USES, fuelLevel); } @Override public void setBrewingTicks(final int brewingTicks) { Preconditions.checkArgument(brewingTicks > 0, "The given brewing ticks must be greater than 0"); - this.container.setData(BrewingStandBlockEntity.DATA_BREW_TIME, brewingTicks); + container.setData(TileEntityBrewingStand.DATA_BREW_TIME, brewingTicks); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftCrafterView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftCrafterView.java index 6dcea638..d80860cc 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftCrafterView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftCrafterView.java @@ -4,29 +4,29 @@ import net.minecraft.world.inventory.CrafterMenu; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.CrafterInventory; import org.bukkit.inventory.view.CrafterView; -public class CraftCrafterView extends CraftInventoryView implements CrafterView { +public class CraftCrafterView extends CraftInventoryView implements CrafterView { - public CraftCrafterView(final HumanEntity player, final Inventory viewing, final CrafterMenu container) { + public CraftCrafterView(final HumanEntity player, final CrafterInventory viewing, final CrafterMenu container) { super(player, viewing, container); } @Override public boolean isSlotDisabled(final int slot) { - return this.container.isSlotDisabled(slot); + return container.isSlotDisabled(slot); } @Override public boolean isPowered() { - return this.container.isPowered(); + return container.isPowered(); } @Override public void setSlotDisabled(final int slot, final boolean disabled) { Preconditions.checkArgument(slot >= 0 && slot < 9, "Invalid slot index %s for Crafter", slot); - this.container.setSlotState(slot, !disabled); + container.setSlotState(slot, !disabled); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftEnchantmentView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftEnchantmentView.java index 259a21ff..2cc217e3 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftEnchantmentView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftEnchantmentView.java @@ -2,38 +2,38 @@ import com.google.common.base.Preconditions; import net.minecraft.core.Holder; -import net.minecraft.core.IdMap; +import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; -import net.minecraft.world.inventory.EnchantmentMenu; +import net.minecraft.world.inventory.ContainerEnchantTable; import net.minecraft.world.item.enchantment.Enchantment; import org.bukkit.craftbukkit.CraftRegistry; import org.bukkit.craftbukkit.enchantments.CraftEnchantment; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.enchantments.EnchantmentOffer; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.EnchantingInventory; import org.bukkit.inventory.view.EnchantmentView; import org.jetbrains.annotations.NotNull; -public class CraftEnchantmentView extends CraftInventoryView implements EnchantmentView { +public class CraftEnchantmentView extends CraftInventoryView implements EnchantmentView { - public CraftEnchantmentView(final HumanEntity player, final Inventory viewing, final EnchantmentMenu container) { + public CraftEnchantmentView(final HumanEntity player, final EnchantingInventory viewing, final ContainerEnchantTable container) { super(player, viewing, container); } @Override public int getEnchantmentSeed() { - return this.container.getEnchantmentSeed(); + return container.getEnchantmentSeed(); } @NotNull @Override public EnchantmentOffer[] getOffers() { - IdMap> registry = CraftRegistry.getMinecraftRegistry().registryOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); + Registry> registry = CraftRegistry.getMinecraftRegistry().lookupOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); EnchantmentOffer[] offers = new EnchantmentOffer[3]; for (int i = 0; i < 3; i++) { - org.bukkit.enchantments.Enchantment enchantment = (this.container.enchantClue[i] >= 0) ? CraftEnchantment.minecraftHolderToBukkit(registry.byId(this.container.enchantClue[i])) : null; - offers[i] = (enchantment != null) ? new EnchantmentOffer(enchantment, this.container.levelClue[i], this.container.costs[i]) : null; + org.bukkit.enchantments.Enchantment enchantment = (container.enchantClue[i] >= 0) ? CraftEnchantment.minecraftHolderToBukkit(registry.byId(container.enchantClue[i])) : null; + offers[i] = (enchantment != null) ? new EnchantmentOffer(enchantment, container.levelClue[i], container.costs[i]) : null; } return offers; } @@ -41,19 +41,19 @@ public EnchantmentOffer[] getOffers() { @Override public void setOffers(@NotNull final EnchantmentOffer[] offers) { Preconditions.checkArgument(offers.length != 3, "There must be 3 offers given"); - IdMap> registry = CraftRegistry.getMinecraftRegistry().registryOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); + Registry> registry = CraftRegistry.getMinecraftRegistry().lookupOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); for (int i = 0; i < offers.length; i++) { final EnchantmentOffer offer = offers[i]; if (offer == null) { - this.container.enchantClue[i] = -1; - this.container.levelClue[i] = -1; - this.container.costs[i] = 0; + container.enchantClue[i] = -1; + container.levelClue[i] = -1; + container.costs[i] = 0; continue; } - this.container.enchantClue[i] = registry.getIdOrThrow(CraftEnchantment.bukkitToMinecraftHolder(offer.getEnchantment())); - this.container.levelClue[i] = offer.getEnchantmentLevel(); - this.container.costs[i] = offer.getCost(); + container.enchantClue[i] = registry.getIdOrThrow(CraftEnchantment.bukkitToMinecraftHolder(offer.getEnchantment())); + container.levelClue[i] = offer.getEnchantmentLevel(); + container.costs[i] = offer.getCost(); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftFurnaceView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftFurnaceView.java index 0cf4fe88..cd134533 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftFurnaceView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftFurnaceView.java @@ -1,42 +1,42 @@ package org.bukkit.craftbukkit.inventory.view; -import net.minecraft.world.inventory.AbstractFurnaceMenu; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.inventory.ContainerFurnace; +import net.minecraft.world.level.block.entity.TileEntityFurnace; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.FurnaceInventory; import org.bukkit.inventory.view.FurnaceView; -public class CraftFurnaceView extends CraftInventoryView implements FurnaceView { +public class CraftFurnaceView extends CraftInventoryView implements FurnaceView { - public CraftFurnaceView(final HumanEntity player, final Inventory viewing, final AbstractFurnaceMenu container) { + public CraftFurnaceView(final HumanEntity player, final FurnaceInventory viewing, final ContainerFurnace container) { super(player, viewing, container); } @Override public float getCookTime() { - return this.container.getBurnProgress(); + return container.getBurnProgress(); } @Override public float getBurnTime() { - return this.container.getLitProgress(); + return container.getLitProgress(); } @Override public boolean isBurning() { - return this.container.isLit(); + return container.isLit(); } @Override public void setCookTime(final int cookProgress, final int cookDuration) { - this.container.setData(AbstractFurnaceBlockEntity.DATA_COOKING_PROGRESS, cookProgress); - this.container.setData(AbstractFurnaceBlockEntity.DATA_COOKING_TOTAL_TIME, cookDuration); + container.setData(TileEntityFurnace.DATA_COOKING_PROGRESS, cookProgress); + container.setData(TileEntityFurnace.DATA_COOKING_TOTAL_TIME, cookDuration); } @Override public void setBurnTime(final int burnProgress, final int burnDuration) { - this.container.setData(AbstractFurnaceBlockEntity.DATA_LIT_TIME, burnProgress); - this.container.setData(AbstractFurnaceBlockEntity.DATA_LIT_DURATION, burnDuration); + container.setData(TileEntityFurnace.DATA_LIT_TIME, burnProgress); + container.setData(TileEntityFurnace.DATA_LIT_DURATION, burnDuration); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLecternView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLecternView.java index b49f84ca..14e2a625 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLecternView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLecternView.java @@ -1,27 +1,27 @@ package org.bukkit.craftbukkit.inventory.view; import com.google.common.base.Preconditions; -import net.minecraft.world.inventory.LecternMenu; -import net.minecraft.world.level.block.entity.LecternBlockEntity; +import net.minecraft.world.inventory.ContainerLectern; +import net.minecraft.world.level.block.entity.TileEntityLectern; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.LecternInventory; import org.bukkit.inventory.view.LecternView; -public class CraftLecternView extends CraftInventoryView implements LecternView { +public class CraftLecternView extends CraftInventoryView implements LecternView { - public CraftLecternView(final HumanEntity player, final Inventory viewing, final LecternMenu container) { + public CraftLecternView(final HumanEntity player, final LecternInventory viewing, final ContainerLectern container) { super(player, viewing, container); } @Override public int getPage() { - return this.container.getPage(); + return container.getPage(); } @Override public void setPage(final int page) { Preconditions.checkArgument(page >= 0, "The minimum page is 0"); - this.container.setData(LecternBlockEntity.DATA_PAGE, page); + container.setData(TileEntityLectern.DATA_PAGE, page); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLoomView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLoomView.java index df0121eb..8f0740cb 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLoomView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftLoomView.java @@ -3,26 +3,26 @@ import java.util.ArrayList; import java.util.List; import net.minecraft.core.Holder; -import net.minecraft.world.inventory.LoomMenu; -import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.inventory.ContainerLoom; +import net.minecraft.world.level.block.entity.EnumBannerPatternType; import org.bukkit.block.banner.PatternType; import org.bukkit.craftbukkit.block.banner.CraftPatternType; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.LoomInventory; import org.bukkit.inventory.view.LoomView; -public class CraftLoomView extends CraftInventoryView implements LoomView { +public class CraftLoomView extends CraftInventoryView implements LoomView { - public CraftLoomView(final HumanEntity player, final Inventory viewing, final LoomMenu container) { + public CraftLoomView(final HumanEntity player, final LoomInventory viewing, final ContainerLoom container) { super(player, viewing, container); } @Override public List getSelectablePatterns() { - final List> selectablePatterns = this.container.getSelectablePatterns(); + final List> selectablePatterns = container.getSelectablePatterns(); final List patternTypes = new ArrayList<>(selectablePatterns.size()); - for (final Holder selectablePattern : selectablePatterns) { + for (final Holder selectablePattern : selectablePatterns) { patternTypes.add(CraftPatternType.minecraftHolderToBukkit(selectablePattern)); } return patternTypes; @@ -30,6 +30,6 @@ public List getSelectablePatterns() { @Override public int getSelectedPatternIndex() { - return this.container.getSelectedBannerPatternIndex(); + return container.getSelectedBannerPatternIndex(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftMerchantView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftMerchantView.java index 791daf73..39b70795 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftMerchantView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftMerchantView.java @@ -1,18 +1,19 @@ package org.bukkit.craftbukkit.inventory.view; -import net.minecraft.world.inventory.MerchantMenu; +import net.minecraft.world.inventory.ContainerMerchant; +import net.minecraft.world.item.trading.IMerchant; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Merchant; +import org.bukkit.inventory.MerchantInventory; import org.bukkit.inventory.view.MerchantView; import org.jetbrains.annotations.NotNull; -public class CraftMerchantView extends CraftInventoryView implements MerchantView { +public class CraftMerchantView extends CraftInventoryView implements MerchantView { - private final net.minecraft.world.item.trading.Merchant trader; + private final IMerchant trader; - public CraftMerchantView(final HumanEntity player, final Inventory viewing, final MerchantMenu container, final net.minecraft.world.item.trading.Merchant trader) { + public CraftMerchantView(final HumanEntity player, final MerchantInventory viewing, final ContainerMerchant container, final IMerchant trader) { super(player, viewing, container); this.trader = trader; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftStonecutterView.java b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftStonecutterView.java index 994c74df..19cb5bc1 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftStonecutterView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/view/CraftStonecutterView.java @@ -2,39 +2,40 @@ import java.util.ArrayList; import java.util.List; -import net.minecraft.world.inventory.StonecutterMenu; +import net.minecraft.world.inventory.ContainerStonecutter; import net.minecraft.world.item.crafting.RecipeHolder; -import net.minecraft.world.item.crafting.StonecutterRecipe; +import net.minecraft.world.item.crafting.RecipeStonecutting; +import net.minecraft.world.item.crafting.SelectableRecipe; import org.bukkit.craftbukkit.inventory.CraftInventoryView; import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.StonecutterInventory; import org.bukkit.inventory.StonecuttingRecipe; import org.bukkit.inventory.view.StonecutterView; import org.jetbrains.annotations.NotNull; -public class CraftStonecutterView extends CraftInventoryView implements StonecutterView { +public class CraftStonecutterView extends CraftInventoryView implements StonecutterView { - public CraftStonecutterView(final HumanEntity player, final Inventory viewing, final StonecutterMenu container) { + public CraftStonecutterView(final HumanEntity player, final StonecutterInventory viewing, final ContainerStonecutter container) { super(player, viewing, container); } @Override public int getSelectedRecipeIndex() { - return this.container.getSelectedRecipeIndex(); + return container.getSelectedRecipeIndex(); } @NotNull @Override public List getRecipes() { final List recipes = new ArrayList<>(); - for (final RecipeHolder recipe : this.container.getRecipes()) { - recipes.add((StonecuttingRecipe) recipe.toBukkitRecipe()); + for (final SelectableRecipe.a recipe : container.getVisibleRecipes().entries()) { + recipe.recipe().recipe().map(RecipeHolder::toBukkitRecipe).ifPresent((bukkit) -> recipes.add((StonecuttingRecipe) bukkit)); } return recipes; } @Override public int getRecipeAmount() { - return this.container.getNumRecipes(); + return container.getNumberOfVisibleRecipes(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java b/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java index b2812cc8..536db5de 100644 --- a/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java +++ b/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java @@ -10,23 +10,23 @@ import java.util.Set; import net.minecraft.SharedConstants; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.Tag; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.Bootstrap; +import net.minecraft.nbt.DynamicOpsNBT; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.server.DispenserRegistry; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.datafix.DataFixers; -import net.minecraft.util.datafix.fixes.BlockStateData; -import net.minecraft.util.datafix.fixes.ItemIdFix; -import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.DataConverterRegistry; +import net.minecraft.util.datafix.fixes.DataConverterFlattenData; +import net.minecraft.util.datafix.fixes.DataConverterMaterialId; +import net.minecraft.util.datafix.fixes.DataConverterTypes; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.block.state.BlockStateList; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.block.state.properties.IBlockState; import org.bukkit.Material; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.entity.EntityType; @@ -49,8 +49,8 @@ public final class CraftLegacy { private static final Set whitelistedStates = new HashSet<>(Arrays.asList("explode", "check_decay", "decayable", "facing")); private static final Map materialToItem = new HashMap<>(16384); private static final Map itemToMaterial = new HashMap<>(1024); - private static final Map materialToData = new HashMap<>(4096); - private static final Map dataToMaterial = new HashMap<>(4096); + private static final Map materialToData = new HashMap<>(4096); + private static final Map dataToMaterial = new HashMap<>(4096); private static final Map materialToBlock = new HashMap<>(4096); private static final Map blockToMaterial = new HashMap<>(1024); @@ -63,11 +63,11 @@ public static Material toLegacy(Material material) { return material; } - return CraftLegacy.toLegacyData(material).getItemType(); + return toLegacyData(material).getItemType(); } public static MaterialData toLegacyData(Material material) { - return CraftLegacy.toLegacyData(material, false); + return toLegacyData(material, false); } public static MaterialData toLegacyData(Material material, boolean itemPriority) { @@ -76,44 +76,44 @@ public static MaterialData toLegacyData(Material material, boolean itemPriority) if (itemPriority) { Item item = CraftMagicNumbers.getItem(material); - mappedData = CraftLegacy.itemToMaterial.get(item); + mappedData = itemToMaterial.get(item); } if (mappedData == null && material.isBlock()) { Block block = CraftMagicNumbers.getBlock(material); - BlockState blockData = block.defaultBlockState(); + IBlockData blockData = block.defaultBlockState(); // Try exact match first - mappedData = CraftLegacy.dataToMaterial.get(blockData); + mappedData = dataToMaterial.get(blockData); // Fallback to any block if (mappedData == null) { - mappedData = CraftLegacy.blockToMaterial.get(block); + mappedData = blockToMaterial.get(block); // Fallback to matching item if (mappedData == null) { - mappedData = CraftLegacy.itemToMaterial.get(block.asItem()); + mappedData = itemToMaterial.get(block.asItem()); } } } else if (!itemPriority) { Item item = CraftMagicNumbers.getItem(material); - mappedData = CraftLegacy.itemToMaterial.get(item); + mappedData = itemToMaterial.get(item); } return (mappedData == null) ? new MaterialData(Material.LEGACY_AIR) : mappedData; } - public static BlockState fromLegacyData(Material material, byte data) { + public static IBlockData fromLegacyData(Material material, byte data) { Preconditions.checkArgument(material.isLegacy(), "fromLegacyData on modern Material"); MaterialData materialData = new MaterialData(material, data); // Try exact match first - BlockState converted = CraftLegacy.materialToData.get(materialData); + IBlockData converted = materialToData.get(materialData); if (converted != null) { return converted; } // Fallback to any block - Block convertedBlock = CraftLegacy.materialToBlock.get(materialData); + Block convertedBlock = materialToBlock.get(materialData); if (convertedBlock != null) { return convertedBlock.defaultBlockState(); } @@ -128,7 +128,7 @@ public static Item fromLegacyData(Material material, short data) { MaterialData materialData = new MaterialData(material, (byte) data); // First try matching item - Item convertedItem = CraftLegacy.materialToItem.get(materialData); + Item convertedItem = materialToItem.get(materialData); if (convertedItem != null) { return convertedItem; } @@ -136,13 +136,13 @@ public static Item fromLegacyData(Material material, short data) { // Fallback to matching block if (material.isBlock()) { // Try exact match first - BlockState converted = CraftLegacy.materialToData.get(materialData); + IBlockData converted = materialToData.get(materialData); if (converted != null) { return converted.getBlock().asItem(); } // Fallback to any block - Block convertedBlock = CraftLegacy.materialToBlock.get(materialData); + Block convertedBlock = materialToBlock.get(materialData); if (convertedBlock != null) { return convertedBlock.asItem(); } @@ -152,22 +152,22 @@ public static Item fromLegacyData(Material material, short data) { return Items.AIR; } - public static byte toLegacyData(BlockState blockData) { - return CraftLegacy.toLegacy(blockData).getData(); + public static byte toLegacyData(IBlockData blockData) { + return toLegacy(blockData).getData(); } - public static Material toLegacyMaterial(BlockState blockData) { - return CraftLegacy.toLegacy(blockData).getItemType(); + public static Material toLegacyMaterial(IBlockData blockData) { + return toLegacy(blockData).getItemType(); } - public static MaterialData toLegacy(BlockState blockData) { + public static MaterialData toLegacy(IBlockData blockData) { MaterialData mappedData; // Try exact match first - mappedData = CraftLegacy.dataToMaterial.get(blockData); + mappedData = dataToMaterial.get(blockData); // Fallback to any block if (mappedData == null) { - mappedData = CraftLegacy.blockToMaterial.get(blockData.getBlock()); + mappedData = blockToMaterial.get(blockData.getBlock()); } return (mappedData == null) ? new MaterialData(Material.LEGACY_AIR) : mappedData; @@ -178,11 +178,11 @@ public static Material fromLegacy(Material material) { return material; } - return CraftLegacy.fromLegacy(new MaterialData(material)); + return fromLegacy(new MaterialData(material)); } public static Material fromLegacy(MaterialData materialData) { - return CraftLegacy.fromLegacy(materialData, false); + return fromLegacy(materialData, false); } public static Material fromLegacy(MaterialData materialData, boolean itemPriority) { @@ -195,7 +195,7 @@ public static Material fromLegacy(MaterialData materialData, boolean itemPriorit // Try item first if (itemPriority) { - Item item = CraftLegacy.materialToItem.get(materialData); + Item item = materialToItem.get(materialData); if (item != null) { mappedData = CraftMagicNumbers.getMaterial(item); } @@ -203,14 +203,14 @@ public static Material fromLegacy(MaterialData materialData, boolean itemPriorit if (mappedData == null) { // Try exact match first - BlockState iblock = CraftLegacy.materialToData.get(materialData); + IBlockData iblock = materialToData.get(materialData); if (iblock != null) { mappedData = CraftMagicNumbers.getMaterial(iblock.getBlock()); } // Fallback to any block if (mappedData == null) { - Block block = CraftLegacy.materialToBlock.get(materialData); + Block block = materialToBlock.get(materialData); if (block != null) { mappedData = CraftMagicNumbers.getMaterial(block); } @@ -219,7 +219,7 @@ public static Material fromLegacy(MaterialData materialData, boolean itemPriorit // Fallback to matching item if (!itemPriority && mappedData == null) { - Item item = CraftLegacy.materialToItem.get(materialData); + Item item = materialToItem.get(materialData); if (item != null) { mappedData = CraftMagicNumbers.getMaterial(item); } @@ -256,7 +256,7 @@ public static String name(Material material) { } public static String toString(Material material) { - return CraftLegacy.name(material); + return name(material); } public static void init() { @@ -323,7 +323,7 @@ public static void init() { SPAWN_EGGS.put((byte) EntityType.ZOMBIE_VILLAGER.getTypeId(), Material.ZOMBIE_VILLAGER_SPAWN_EGG); SharedConstants.tryDetectVersion(); - Bootstrap.bootStrap(); + DispenserRegistry.bootStrap(); for (Material material : Material.values()) { if (!material.isLegacy()) { @@ -331,29 +331,29 @@ public static void init() { } // Handle blocks - if (material.isBlock()) { + if (isBlock(material)) { // Use custom method instead of Material#isBlock since it relies on this being already run for (byte data = 0; data < 16; data++) { MaterialData matData = new MaterialData(material, data); - Dynamic blockTag = BlockStateData.getTag(material.getId() << 4 | data); - blockTag = DataFixers.getDataFixer().update(References.BLOCK_STATE, blockTag, 100, CraftMagicNumbers.INSTANCE.getDataVersion()); + Dynamic blockTag = DataConverterFlattenData.getTag(material.getId() << 4 | data); + blockTag = DataConverterRegistry.getDataFixer().update(DataConverterTypes.BLOCK_STATE, blockTag, 100, CraftMagicNumbers.INSTANCE.getDataVersion()); // TODO: better skull conversion, chests if (blockTag.get("Name").asString("").contains("%%FILTER_ME%%")) { continue; } String name = blockTag.get("Name").asString(""); - Block block = BuiltInRegistries.BLOCK.get(ResourceLocation.parse(name)); + Block block = BuiltInRegistries.BLOCK.getValue(MinecraftKey.parse(name)); if (block == null) { continue; } - BlockState blockData = block.defaultBlockState(); - StateDefinition states = block.getStateDefinition(); + IBlockData blockData = block.defaultBlockState(); + BlockStateList states = block.getStateDefinition(); - Optional propMap = blockTag.getElement("Properties").result(); + Optional propMap = blockTag.getElement("Properties").result(); if (propMap.isPresent()) { - CompoundTag properties = propMap.get(); + NBTTagCompound properties = propMap.get(); for (String dataKey : properties.getAllKeys()) { - Property state = states.getProperty(dataKey); + IBlockState state = states.getProperty(dataKey); if (state == null) { Preconditions.checkArgument(whitelistedStates.contains(dataKey), "No state for %s", dataKey); @@ -397,17 +397,17 @@ public static void init() { continue; } // Skip non item stacks for now (18w19b) - if (ItemIdFix.getItem(material.getId()) == null) { + if (DataConverterMaterialId.getItem(material.getId()) == null) { continue; } MaterialData matData = new MaterialData(material, data); - CompoundTag stack = new CompoundTag(); + NBTTagCompound stack = new NBTTagCompound(); stack.putInt("id", material.getId()); stack.putShort("Damage", data); - Dynamic converted = DataFixers.getDataFixer().update(References.ITEM_STACK, new Dynamic(NbtOps.INSTANCE, stack), -1, CraftMagicNumbers.INSTANCE.getDataVersion()); + Dynamic converted = DataConverterRegistry.getDataFixer().update(DataConverterTypes.ITEM_STACK, new Dynamic(DynamicOpsNBT.INSTANCE, stack), -1, CraftMagicNumbers.INSTANCE.getDataVersion()); String newId = converted.get("id").asString(""); // Recover spawn eggs with invalid data @@ -416,7 +416,7 @@ public static void init() { } // Preconditions.checkState(newId.contains("minecraft:"), "Unknown new material for " + matData); - Item newMaterial = BuiltInRegistries.ITEM.get(ResourceLocation.parse(newId)); + Item newMaterial = BuiltInRegistries.ITEM.getValue(MinecraftKey.parse(newId)); if (newMaterial == Items.AIR) { continue; @@ -438,6 +438,12 @@ public static void init() { } } + private static boolean isBlock(Material material) { + // From Material#isBlock before the rewrite to ItemType / BlockType + // Git hash: 42f6cdf4c5dcdd52a27543403dcd17fb60311621 + return 0 <= material.getId() && material.getId() < 256; + } + public static void main(String[] args) { System.err.println(""); } diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/FieldRename.java b/src/main/java/org/bukkit/craftbukkit/legacy/FieldRename.java index 117f72db..f52f1f33 100644 --- a/src/main/java/org/bukkit/craftbukkit/legacy/FieldRename.java +++ b/src/main/java/org/bukkit/craftbukkit/legacy/FieldRename.java @@ -175,6 +175,8 @@ public static Biome valueOf_Biome(String name) { .change("SNOWMAN", "SNOW_GOLEM") .change("FISHING_HOOK", "FISHING_BOBBER") .change("LIGHTNING", "LIGHTNING_BOLT") + .change("BOAT", "OAK_BOAT") + .change("CHEST_BOAT", "OAK_CHEST_BOAT") .withKeyRename() .change("XP_ORB", "EXPERIENCE_ORB") .change("EYE_OF_ENDER_SIGNAL", "EYE_OF_ENDER") diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RequirePluginVersionData.java b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RequirePluginVersionData.java index 8f344e50..5cc95b2a 100644 --- a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RequirePluginVersionData.java +++ b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RequirePluginVersionData.java @@ -7,7 +7,7 @@ public record RequirePluginVersionData(ApiVersion minInclusive, ApiVersion maxIn public static RequirePluginVersionData create(RequirePluginVersion requirePluginVersion) { if (!requirePluginVersion.value().isBlank()) { if (!requirePluginVersion.minInclusive().isBlank() || !requirePluginVersion.maxInclusive().isBlank()) { - throw new RuntimeException("When setting value, min inclusive and max inclusive data is not allowed."); + throw new IllegalArgumentException("When setting value, min inclusive and max inclusive data is not allowed."); } return new RequirePluginVersionData(ApiVersion.getOrCreateVersion(requirePluginVersion.value()), ApiVersion.getOrCreateVersion(requirePluginVersion.value())); @@ -23,6 +23,12 @@ public static RequirePluginVersionData create(RequirePluginVersion requirePlugin maxInclusive = ApiVersion.getOrCreateVersion(requirePluginVersion.maxInclusive()); } + if (minInclusive != null && maxInclusive != null) { + if (minInclusive.isNewerThan(maxInclusive)) { + throw new IllegalArgumentException("Min inclusive cannot be newer than max inclusive."); + } + } + return new RequirePluginVersionData(minInclusive, maxInclusive); } diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/Reroute.java b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/Reroute.java new file mode 100644 index 00000000..1f828c37 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/Reroute.java @@ -0,0 +1,120 @@ +package org.bukkit.craftbukkit.legacy.reroute; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import org.bukkit.craftbukkit.util.ApiVersion; +import org.bukkit.craftbukkit.util.ClassTraverser; +import org.jetbrains.annotations.VisibleForTesting; +import org.objectweb.asm.Type; + +public class Reroute { + + @VisibleForTesting + final Map rerouteDataMap; + + Reroute(Map rerouteDataMap) { + this.rerouteDataMap = rerouteDataMap; + } + + /* + This method looks (and probably is) overengineered, but it gives the most flexible when it comes to remapping normal methods to static one. + The problem with normal owner and desc replacement is that child classes have them as an owner, instead there parents for there parents methods + + For example, if we have following two interfaces org.bukkit.BlockData and org.bukkit.Orientable extents BlockData + and BlockData has the method org.bukkit.Material getType which we want to reroute to the static method + org.bukkit.Material org.bukkit.craftbukkit.legacy.EnumEvil#getType(org.bukkit.BlockData) + + If we now call BlockData#getType we get as the owner org/bukkit/BlockData and as desc ()Lorg/bukkit/Material; + Which we can nicely reroute by checking if the owner is BlockData and the name getType + The problem, starts if we use Orientable#getType no we get as owner org/bukkit/Orientable and as desc ()Lorg/bukkit/Material; + Now we can now longer safely say to which getType method we need to reroute (assume there are multiple getType methods from different classes, + which are not related to BlockData), simple using the owner class will not work, since would reroute to + EnumEvil#getType(org.bukkit.Orientable) which is not EnumEvil#getType(org.bukkit.BlockData) and will throw a method not found error + at runtime. + + Meaning we would need to add checks for each subclass, which would be pur insanity. + + To solve this, we go through each super class and interfaces (and their super class and interfaces etc.) and try to get an owner + which matches with one of our replacement methods. Based on how inheritance works in java, this method should be safe to use. + + As a site note: This method could also be used for the other method reroute, e.g. legacy method rerouting, where only the replacement + method needs to be written, and this method figures out the rest, which could reduce the size and complexity of the Commodore class. + The question then becomes one about performance (since this is not the most performance way) and convenience. + But since it is only applied for each class and method call once when they get first loaded, it should not be that bad. + (Although some load time testing could be done) + */ + public boolean apply(ApiVersion pluginVersion, String owner, String name, String desc, boolean staticCall, Consumer consumer) { + RerouteDataHolder rerouteData = rerouteDataMap.get(desc + name); + if (rerouteData == null) { + return false; + } + + Type ownerType = Type.getObjectType(owner); + RerouteMethodData data = rerouteData.get(ownerType); + + if (staticCall && data == null) { + return false; + } + + if (data != null) { + if (data.requiredPluginVersion() != null && !data.requiredPluginVersion().test(pluginVersion)) { + return false; + } + + consumer.accept(data); + return true; + } + + Class ownerClass; + try { + ownerClass = Class.forName(ownerType.getClassName(), false, Reroute.class.getClassLoader()); + } catch (ClassNotFoundException e) { + return false; + } + + ClassTraverser it = new ClassTraverser(ownerClass); + while (it.hasNext()) { + Class clazz = it.next(); + + data = rerouteData.get(Type.getType(clazz)); + + if (data == null) { + continue; + } + + if (data.requiredPluginVersion() != null && !data.requiredPluginVersion().test(pluginVersion)) { + return false; + } + + consumer.accept(data); + return true; + } + + return false; + } + + static class RerouteDataHolder { + + @VisibleForTesting + final Map rerouteMethodDataMap = new HashMap<>(); + + public RerouteMethodData get(Class clazz) { + return rerouteMethodDataMap.get(Type.getInternalName(clazz)); + } + + private RerouteMethodData get(Type owner) { + return rerouteMethodDataMap.get(owner.getInternalName()); + } + + void add(RerouteMethodData value) { + RerouteMethodData rerouteMethodData = get(value.sourceOwner()); + + if (rerouteMethodData != null) { + throw new IllegalStateException("Reroute method data already exists: " + rerouteMethodData); + } + + rerouteMethodDataMap.put(value.sourceOwner().getInternalName(), value); + } + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteBuilder.java b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteBuilder.java index c4ff44ae..435672a3 100644 --- a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteBuilder.java +++ b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteBuilder.java @@ -1,53 +1,69 @@ package org.bukkit.craftbukkit.legacy.reroute; import com.google.common.base.Preconditions; +import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Predicate; import org.bukkit.craftbukkit.util.ApiVersion; import org.objectweb.asm.Type; public class RerouteBuilder { - public static Map buildFromClass(Class clazz) { - Preconditions.checkArgument(!clazz.isInterface(), "Interface Classes are currently not supported"); + private final List> classes = new ArrayList<>(); + private final Predicate compatibilityPresent; - Map result = new HashMap<>(); + private RerouteBuilder(Predicate compatibilityPresent) { + this.compatibilityPresent = compatibilityPresent; + } - for (Method method : clazz.getDeclaredMethods()) { - if (method.isBridge()) { - continue; - } + public static RerouteBuilder create(Predicate compatibilityPresent) { + return new RerouteBuilder(compatibilityPresent); + } - if (method.isSynthetic()) { - continue; - } + public RerouteBuilder forClass(Class clazz) { + classes.add(clazz); + return this; + } - if (!Modifier.isPublic(method.getModifiers())) { - continue; - } + public Reroute build() { + Map rerouteDataHolderMap = new HashMap<>(); - if (!Modifier.isStatic(method.getModifiers())) { + for (Class clazz : classes) { + List data = buildFromClass(clazz, compatibilityPresent); + data.forEach(value -> rerouteDataHolderMap.computeIfAbsent(value.methodKey(), v -> new Reroute.RerouteDataHolder()).add(value)); + } + + return new Reroute(rerouteDataHolderMap); + } + + private static List buildFromClass(Class clazz, Predicate compatibilityPresent) { + Preconditions.checkArgument(!clazz.isInterface(), "Interface Classes are currently not supported"); + + List result = new ArrayList<>(); + boolean shouldInclude = shouldInclude(getRequireCompatibility(clazz), true, compatibilityPresent); + + for (Method method : clazz.getDeclaredMethods()) { + if (!isMethodValid(method)) { continue; } - if (method.isAnnotationPresent(DoNotReroute.class)) { + if (!shouldInclude(getRequireCompatibility(method), shouldInclude, compatibilityPresent)) { continue; } - RerouteMethodData rerouteMethodData = buildFromMethod(method); - result.put(rerouteMethodData.source(), rerouteMethodData); + result.add(buildFromMethod(method)); } - return Collections.unmodifiableMap(result); + return result; } - public static RerouteMethodData buildFromMethod(Method method) { + private static RerouteMethodData buildFromMethod(Method method) { RerouteReturn rerouteReturn = new RerouteReturn(Type.getReturnType(method)); List arguments = new ArrayList<>(); List sourceArguments = new ArrayList<>(); @@ -113,7 +129,10 @@ public static RerouteMethodData buildFromMethod(Method method) { if (rerouteStatic != null) { sourceOwner = Type.getObjectType(rerouteStatic.value()); } else { - RerouteArgument argument = sourceArguments.get(0); + if (sourceArguments.isEmpty()) { + throw new RuntimeException("Source argument list is empty, no owner class found"); + } + RerouteArgument argument = sourceArguments.getFirst(); sourceOwner = argument.sourceType(); sourceArguments.remove(argument); } @@ -135,23 +154,12 @@ public static RerouteMethodData buildFromMethod(Method method) { methodName = method.getName(); } - String methodKey = sourceOwner.getInternalName() - + " " - + sourceDesc.getDescriptor() - + " " - + methodName; + String methodKey = sourceDesc.getDescriptor() + methodName; Type targetType = Type.getType(method); boolean inBukkit = !method.isAnnotationPresent(NotInBukkit.class) && !method.getDeclaringClass().isAnnotationPresent(NotInBukkit.class); - String requiredCompatibility = null; - if (method.isAnnotationPresent(RequireCompatibility.class)) { - requiredCompatibility = method.getAnnotation(RequireCompatibility.class).value(); - } else if (method.getDeclaringClass().isAnnotationPresent(RequireCompatibility.class)) { - requiredCompatibility = method.getDeclaringClass().getAnnotation(RequireCompatibility.class).value(); - } - RequirePluginVersionData requiredPluginVersion = null; if (method.isAnnotationPresent(RequirePluginVersion.class)) { requiredPluginVersion = RequirePluginVersionData.create(method.getAnnotation(RequirePluginVersion.class)); @@ -159,6 +167,47 @@ public static RerouteMethodData buildFromMethod(Method method) { requiredPluginVersion = RequirePluginVersionData.create(method.getDeclaringClass().getAnnotation(RequirePluginVersion.class)); } - return new RerouteMethodData(methodKey, sourceDesc, sourceOwner, methodName, rerouteStatic != null, targetType, Type.getInternalName(method.getDeclaringClass()), method.getName(), arguments, rerouteReturn, inBukkit, requiredCompatibility, requiredPluginVersion); + return new RerouteMethodData(methodKey, sourceDesc, sourceOwner, methodName, rerouteStatic != null, targetType, Type.getInternalName(method.getDeclaringClass()), method.getName(), arguments, rerouteReturn, inBukkit, requiredPluginVersion); + } + + private static boolean isMethodValid(Method method) { + if (method.isBridge()) { + return false; + } + + if (method.isSynthetic()) { + return false; + } + + if (!Modifier.isPublic(method.getModifiers())) { + return false; + } + + if (!Modifier.isStatic(method.getModifiers())) { + return false; + } + + if (method.isAnnotationPresent(DoNotReroute.class)) { + return false; + } + + return true; + } + + private static String getRequireCompatibility(AnnotatedElement element) { + RequireCompatibility annotation = element.getAnnotation(RequireCompatibility.class); + if (annotation == null) { + return null; + } + + return annotation.value(); + } + + private static boolean shouldInclude(String string, boolean parent, Predicate compatibilityPresent) { + if (string == null) { + return parent; + } + + return compatibilityPresent.test(string); } } diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteMethodData.java b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteMethodData.java index 6b6bf143..cf94b805 100644 --- a/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteMethodData.java +++ b/src/main/java/org/bukkit/craftbukkit/legacy/reroute/RerouteMethodData.java @@ -4,8 +4,8 @@ import org.jetbrains.annotations.Nullable; import org.objectweb.asm.Type; -public record RerouteMethodData(String source, Type sourceDesc, Type sourceOwner, String sourceName, +public record RerouteMethodData(String methodKey, Type sourceDesc, Type sourceOwner, String sourceName, boolean staticReroute, Type targetType, String targetOwner, String targetName, List arguments, RerouteReturn rerouteReturn, boolean isInBukkit, - @Nullable String requiredCompatibility, @Nullable RequirePluginVersionData requiredPluginVersion) { + @Nullable RequirePluginVersionData requiredPluginVersion) { } diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java index ff59f759..5cb1d4c2 100644 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java +++ b/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java @@ -19,17 +19,17 @@ public class CraftMapCanvas implements MapCanvas { protected CraftMapCanvas(CraftMapView mapView) { this.mapView = mapView; - Arrays.fill(this.buffer, (byte) -1); + Arrays.fill(buffer, (byte) -1); } @Override public CraftMapView getMapView() { - return this.mapView; + return mapView; } @Override public MapCursorCollection getCursors() { - return this.cursors; + return cursors; } @Override @@ -39,12 +39,12 @@ public void setCursors(MapCursorCollection cursors) { @Override public void setPixelColor(int x, int y, Color color) { - this.setPixel(x, y, (color == null) ? -1 : MapPalette.matchColor(color)); + setPixel(x, y, (color == null) ? -1 : MapPalette.matchColor(color)); } @Override public Color getPixelColor(int x, int y) { - byte pixel = this.getPixel(x, y); + byte pixel = getPixel(x, y); if (pixel == -1) { return null; } @@ -54,16 +54,16 @@ public Color getPixelColor(int x, int y) { @Override public Color getBasePixelColor(int x, int y) { - return MapPalette.getColor(this.getBasePixel(x, y)); + return MapPalette.getColor(getBasePixel(x, y)); } @Override public void setPixel(int x, int y, byte color) { if (x < 0 || y < 0 || x >= 128 || y >= 128) return; - if (this.buffer[y * 128 + x] != color) { - this.buffer[y * 128 + x] = color; - this.mapView.worldMap.setColorsDirty(x, y); + if (buffer[y * 128 + x] != color) { + buffer[y * 128 + x] = color; + mapView.worldMap.setColorsDirty(x, y); } } @@ -71,14 +71,14 @@ public void setPixel(int x, int y, byte color) { public byte getPixel(int x, int y) { if (x < 0 || y < 0 || x >= 128 || y >= 128) return 0; - return this.buffer[y * 128 + x]; + return buffer[y * 128 + x]; } @Override public byte getBasePixel(int x, int y) { if (x < 0 || y < 0 || x >= 128 || y >= 128) return 0; - return this.base[y * 128 + x]; + return base[y * 128 + x]; } protected void setBase(byte[] base) { @@ -86,7 +86,7 @@ protected void setBase(byte[] base) { } protected byte[] getBuffer() { - return this.buffer; + return buffer; } @Override @@ -94,7 +94,7 @@ public void drawImage(int x, int y, Image image) { byte[] bytes = MapPalette.imageToBytes(image); for (int x2 = 0; x2 < image.getWidth(null); ++x2) { for (int y2 = 0; y2 < image.getHeight(null); ++y2) { - this.setPixel(x + x2, y + y2, bytes[y2 * image.getWidth(null) + x2]); + setPixel(x + x2, y + y2, bytes[y2 * image.getWidth(null) + x2]); } } } @@ -126,7 +126,7 @@ public void drawText(int x, int y, MapFont font, String text) { for (int r = 0; r < font.getHeight(); ++r) { for (int c = 0; c < sprite.getWidth(); ++c) { if (sprite.get(r, c)) { - this.setPixel(x + c, y + r, color); + setPixel(x + c, y + r, color); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapColorCache.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapColorCache.java index 8149b9c5..9482c0ea 100644 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapColorCache.java +++ b/src/main/java/org/bukkit/craftbukkit/map/CraftMapColorCache.java @@ -15,7 +15,7 @@ import java.util.logging.Logger; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import net.minecraft.Util; +import net.minecraft.SystemUtils; import org.bukkit.map.MapPalette; public class CraftMapColorCache implements MapPalette.MapColorCache { @@ -37,7 +37,7 @@ public static void main(String[] args) { craftMapColorCache.buildCache(); try { byte[] hash = MessageDigest.getInstance("MD5").digest(craftMapColorCache.cache); - System.out.println("MD5_CACHE_HASH: " + CraftMapColorCache.bytesToString(hash)); + System.out.println("MD5_CACHE_HASH: " + bytesToString(hash)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } @@ -58,16 +58,16 @@ public static String bytesToString(byte[] bytes) { } public CompletableFuture initCache() { - Preconditions.checkState(!this.cached && !this.running.getAndSet(true), "Cache is already build or is currently being build"); + Preconditions.checkState(!cached && !running.getAndSet(true), "Cache is already build or is currently being build"); - this.cache = new byte[256 * 256 * 256]; // Red, Green and Blue have each a range from 0 to 255 each mean we need space for 256 * 256 * 256 values - if (CraftMapColorCache.CACHE_FILE.exists()) { + cache = new byte[256 * 256 * 256]; // Red, Green and Blue have each a range from 0 to 255 each mean we need space for 256 * 256 * 256 values + if (CACHE_FILE.exists()) { byte[] fileContent; - try (InputStream inputStream = new InflaterInputStream(new FileInputStream(CraftMapColorCache.CACHE_FILE))) { + try (InputStream inputStream = new InflaterInputStream(new FileInputStream(CACHE_FILE))) { fileContent = inputStream.readAllBytes(); } catch (IOException e) { - this.logger.warning("Error while reading map color cache"); + logger.warning("Error while reading map color cache"); e.printStackTrace(); return CompletableFuture.completedFuture(null); } @@ -76,22 +76,22 @@ public CompletableFuture initCache() { try { hash = MessageDigest.getInstance("MD5").digest(fileContent); } catch (NoSuchAlgorithmException e) { - this.logger.warning("Error while hashing map color cache"); + logger.warning("Error while hashing map color cache"); e.printStackTrace(); return CompletableFuture.completedFuture(null); } - if (!CraftMapColorCache.MD5_CACHE_HASH.equals(CraftMapColorCache.bytesToString(hash))) { - this.logger.info("Map color cache hash invalid, rebuilding cache in the background"); - return this.buildAndSaveCache(); + if (!MD5_CACHE_HASH.equals(bytesToString(hash))) { + logger.info("Map color cache hash invalid, rebuilding cache in the background"); + return buildAndSaveCache(); } else { - System.arraycopy(fileContent, 0, this.cache, 0, fileContent.length); + System.arraycopy(fileContent, 0, cache, 0, fileContent.length); } - this.cached = true; + cached = true; } else { - this.logger.info("Map color cache not found, building it in the background"); - return this.buildAndSaveCache(); + logger.info("Map color cache not found, building it in the background"); + return buildAndSaveCache(); } return CompletableFuture.completedFuture(null); @@ -102,7 +102,7 @@ private void buildCache() { for (int g = 0; g < 256; g++) { for (int b = 0; b < 256; b++) { Color color = new Color(r, g, b); - this.cache[this.toInt(color)] = MapPalette.matchColor(color); + cache[toInt(color)] = MapPalette.matchColor(color); } } } @@ -110,34 +110,34 @@ private void buildCache() { private CompletableFuture buildAndSaveCache() { return CompletableFuture.runAsync(() -> { - this.buildCache(); + buildCache(); - if (!CraftMapColorCache.CACHE_FILE.exists()) { + if (!CACHE_FILE.exists()) { try { - if (!CraftMapColorCache.CACHE_FILE.createNewFile()) { - this.cached = true; + if (!CACHE_FILE.createNewFile()) { + cached = true; return; } } catch (IOException e) { - this.logger.warning("Error while building map color cache"); + logger.warning("Error while building map color cache"); e.printStackTrace(); - this.cached = true; + cached = true; return; } } - try (OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(CraftMapColorCache.CACHE_FILE))) { - outputStream.write(this.cache); + try (OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(CACHE_FILE))) { + outputStream.write(cache); } catch (IOException e) { - this.logger.warning("Error while building map color cache"); + logger.warning("Error while building map color cache"); e.printStackTrace(); - this.cached = true; + cached = true; return; } - this.cached = true; - this.logger.info("Map color cache build successfully"); - }, Util.backgroundExecutor()); + cached = true; + logger.info("Map color cache build successfully"); + }, SystemUtils.backgroundExecutor()); } private int toInt(Color color) { @@ -146,13 +146,13 @@ private int toInt(Color color) { @Override public boolean isCached() { - return this.cached || (!this.running.get() && this.initCache().isDone()); + return cached || (!running.get() && initCache().isDone()); } @Override public byte matchColor(Color color) { - Preconditions.checkState(this.isCached(), "Cache not build jet"); + Preconditions.checkState(isCached(), "Cache not build jet"); - return this.cache[this.toInt(color)]; + return cache[toInt(color)]; } } diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapCursor.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapCursor.java index 695965be..d55fb016 100644 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapCursor.java +++ b/src/main/java/org/bukkit/craftbukkit/map/CraftMapCursor.java @@ -1,6 +1,5 @@ package org.bukkit.craftbukkit.map; -import com.google.common.base.Preconditions; import java.util.Locale; import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; @@ -8,7 +7,6 @@ import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.craftbukkit.CraftRegistry; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.craftbukkit.util.Handleable; import org.bukkit.map.MapCursor; @@ -23,7 +21,7 @@ public static MapCursor.Type minecraftToBukkit(MapDecorationType minecraft) { } public static MapCursor.Type minecraftHolderToBukkit(Holder minecraft) { - return CraftType.minecraftToBukkit(minecraft.value()); + return minecraftToBukkit(minecraft.value()); } public static MapDecorationType bukkitToMinecraft(MapCursor.Type bukkit) { @@ -51,38 +49,38 @@ public CraftType(NamespacedKey key, MapDecorationType mapDecorationType) { } else { this.name = key.toString(); } - this.ordinal = CraftType.count++; + this.ordinal = count++; } @Override public MapDecorationType getHandle() { - return this.mapDecorationType; + return mapDecorationType; } @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override public int compareTo(MapCursor.Type type) { - return this.ordinal - type.ordinal(); + return ordinal - type.ordinal(); } @Override public String name() { - return this.name; + return name; } @Override public int ordinal() { - return this.ordinal; + return ordinal; } @Override public String toString() { // For backwards compatibility - return this.name(); + return name(); } @Override @@ -95,17 +93,17 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((MapCursor.Type) other).getKey()); + return getKey().equals(((MapCursor.Type) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } @Override public byte getValue() { - return (byte) CraftRegistry.getMinecraftRegistry(Registries.MAP_DECORATION_TYPE).getId(this.getHandle()); + return (byte) CraftRegistry.getMinecraftRegistry(Registries.MAP_DECORATION_TYPE).getId(getHandle()); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java index 9efd33cc..34d4926c 100644 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java +++ b/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.map; -import net.minecraft.world.level.saveddata.maps.MapDecoration; -import net.minecraft.world.level.saveddata.maps.MapItemSavedData; +import net.minecraft.world.level.saveddata.maps.MapIcon; +import net.minecraft.world.level.saveddata.maps.WorldMap; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.entity.Player; @@ -13,9 +13,9 @@ public class CraftMapRenderer extends MapRenderer { - private final MapItemSavedData worldMap; + private final WorldMap worldMap; - public CraftMapRenderer(CraftMapView mapView, MapItemSavedData worldMap) { + public CraftMapRenderer(CraftMapView mapView, WorldMap worldMap) { super(false); this.worldMap = worldMap; } @@ -25,7 +25,7 @@ public void render(MapView map, MapCanvas canvas, Player player) { // Map for (int x = 0; x < 128; ++x) { for (int y = 0; y < 128; ++y) { - canvas.setPixel(x, y, this.worldMap.colors[y * 128 + x]); + canvas.setPixel(x, y, worldMap.colors[y * 128 + x]); } } @@ -35,14 +35,14 @@ public void render(MapView map, MapCanvas canvas, Player player) { cursors.removeCursor(cursors.getCursor(0)); } - for (String key : this.worldMap.decorations.keySet()) { + for (String key : worldMap.decorations.keySet()) { // If this cursor is for a player check visibility with vanish system Player other = Bukkit.getPlayerExact((String) key); if (other != null && !player.canSee(other)) { continue; } - MapDecoration decoration = this.worldMap.decorations.get(key); + MapIcon decoration = worldMap.decorations.get(key); cursors.addCursor(new MapCursor(decoration.x(), decoration.y(), (byte) (decoration.rot() & 15), CraftMapCursor.CraftType.minecraftHolderToBukkit(decoration.type()), true, CraftChatMessage.fromComponent(decoration.name().orElse(null)))); } } diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java index a15cdf64..ab8e203c 100644 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java +++ b/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java @@ -8,8 +8,8 @@ import java.util.logging.Level; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.saveddata.maps.MapItemSavedData; +import net.minecraft.server.level.WorldServer; +import net.minecraft.world.level.saveddata.maps.WorldMap; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.craftbukkit.CraftWorld; @@ -22,100 +22,100 @@ public final class CraftMapView implements MapView { private final Map renderCache = new HashMap(); private final List renderers = new ArrayList(); private final Map> canvases = new HashMap>(); - protected final MapItemSavedData worldMap; + protected final WorldMap worldMap; - public CraftMapView(MapItemSavedData worldMap) { + public CraftMapView(WorldMap worldMap) { this.worldMap = worldMap; - this.addRenderer(new CraftMapRenderer(this, worldMap)); + addRenderer(new CraftMapRenderer(this, worldMap)); } @Override public int getId() { - return this.worldMap.id.id(); + return worldMap.id.id(); } @Override public boolean isVirtual() { - return this.renderers.size() > 0 && !(this.renderers.get(0) instanceof CraftMapRenderer); + return renderers.size() > 0 && !(renderers.get(0) instanceof CraftMapRenderer); } @Override public Scale getScale() { - return Scale.valueOf(this.worldMap.scale); + return Scale.valueOf(worldMap.scale); } @Override public void setScale(Scale scale) { - this.worldMap.scale = scale.getValue(); + worldMap.scale = scale.getValue(); } @Override public World getWorld() { - ResourceKey dimension = this.worldMap.dimension; - ServerLevel world = MinecraftServer.getServer().getLevel(dimension); + ResourceKey dimension = worldMap.dimension; + WorldServer world = MinecraftServer.getServer().getLevel(dimension); if (world != null) { return world.getWorld(); } - if (this.worldMap.uniqueId != null) { - return Bukkit.getServer().getWorld(this.worldMap.uniqueId); + if (worldMap.uniqueId != null) { + return Bukkit.getServer().getWorld(worldMap.uniqueId); } return null; } @Override public void setWorld(World world) { - this.worldMap.dimension = ((CraftWorld) world).getHandle().dimension(); - this.worldMap.uniqueId = world.getUID(); + worldMap.dimension = ((CraftWorld) world).getHandle().dimension(); + worldMap.uniqueId = world.getUID(); } @Override public int getCenterX() { - return this.worldMap.centerX; + return worldMap.centerX; } @Override public int getCenterZ() { - return this.worldMap.centerZ; + return worldMap.centerZ; } @Override public void setCenterX(int x) { - this.worldMap.centerX = x; + worldMap.centerX = x; } @Override public void setCenterZ(int z) { - this.worldMap.centerZ = z; + worldMap.centerZ = z; } @Override public List getRenderers() { - return new ArrayList(this.renderers); + return new ArrayList(renderers); } @Override public void addRenderer(MapRenderer renderer) { - if (!this.renderers.contains(renderer)) { - this.renderers.add(renderer); - this.canvases.put(renderer, new HashMap()); + if (!renderers.contains(renderer)) { + renderers.add(renderer); + canvases.put(renderer, new HashMap()); renderer.initialize(this); } } @Override public boolean removeRenderer(MapRenderer renderer) { - if (this.renderers.contains(renderer)) { - this.renderers.remove(renderer); - for (Map.Entry entry : this.canvases.get(renderer).entrySet()) { + if (renderers.contains(renderer)) { + renderers.remove(renderer); + for (Map.Entry entry : canvases.get(renderer).entrySet()) { for (int x = 0; x < 128; ++x) { for (int y = 0; y < 128; ++y) { entry.getValue().setPixel(x, y, (byte) -1); } } } - this.canvases.remove(renderer); + canvases.remove(renderer); return true; } else { return false; @@ -123,33 +123,33 @@ public boolean removeRenderer(MapRenderer renderer) { } private boolean isContextual() { - for (MapRenderer renderer : this.renderers) { + for (MapRenderer renderer : renderers) { if (renderer.isContextual()) return true; } return false; } public RenderData render(CraftPlayer player) { - boolean context = this.isContextual(); - RenderData render = this.renderCache.get(context ? player : null); + boolean context = isContextual(); + RenderData render = renderCache.get(context ? player : null); if (render == null) { render = new RenderData(); - this.renderCache.put(context ? player : null, render); + renderCache.put(context ? player : null, render); } - if (context && this.renderCache.containsKey(null)) { - this.renderCache.remove(null); + if (context && renderCache.containsKey(null)) { + renderCache.remove(null); } Arrays.fill(render.buffer, (byte) 0); render.cursors.clear(); - for (MapRenderer renderer : this.renderers) { - CraftMapCanvas canvas = this.canvases.get(renderer).get(renderer.isContextual() ? player : null); + for (MapRenderer renderer : renderers) { + CraftMapCanvas canvas = canvases.get(renderer).get(renderer.isContextual() ? player : null); if (canvas == null) { canvas = new CraftMapCanvas(this); - this.canvases.get(renderer).put(renderer.isContextual() ? player : null, canvas); + canvases.get(renderer).put(renderer.isContextual() ? player : null, canvas); } canvas.setBase(render.buffer); @@ -176,31 +176,31 @@ public RenderData render(CraftPlayer player) { @Override public boolean isTrackingPosition() { - return this.worldMap.trackingPosition; + return worldMap.trackingPosition; } @Override public void setTrackingPosition(boolean trackingPosition) { - this.worldMap.trackingPosition = trackingPosition; + worldMap.trackingPosition = trackingPosition; } @Override public boolean isUnlimitedTracking() { - return this.worldMap.unlimitedTracking; + return worldMap.unlimitedTracking; } @Override public void setUnlimitedTracking(boolean unlimited) { - this.worldMap.unlimitedTracking = unlimited; + worldMap.unlimitedTracking = unlimited; } @Override public boolean isLocked() { - return this.worldMap.locked; + return worldMap.locked; } @Override public void setLocked(boolean locked) { - this.worldMap.locked = locked; + worldMap.locked = locked; } } diff --git a/src/main/java/org/bukkit/craftbukkit/map/RenderData.java b/src/main/java/org/bukkit/craftbukkit/map/RenderData.java index 503a31b4..256a1317 100644 --- a/src/main/java/org/bukkit/craftbukkit/map/RenderData.java +++ b/src/main/java/org/bukkit/craftbukkit/map/RenderData.java @@ -5,7 +5,7 @@ public class RenderData { - public byte[] buffer; + public final byte[] buffer; public final ArrayList cursors; public RenderData() { diff --git a/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java b/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java index 140058d1..ae2c85db 100644 --- a/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java +++ b/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java @@ -43,7 +43,7 @@ protected String disambiguate(Block block, String metadataKey) { */ @Override public List getMetadata(Block block, String metadataKey) { - Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", this.owningWorld.getName()); + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); return super.getMetadata(block, metadataKey); } @@ -54,7 +54,7 @@ public List getMetadata(Block block, String metadataKey) { */ @Override public boolean hasMetadata(Block block, String metadataKey) { - Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", this.owningWorld.getName()); + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); return super.hasMetadata(block, metadataKey); } @@ -65,7 +65,7 @@ public boolean hasMetadata(Block block, String metadataKey) { */ @Override public void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) { - Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", this.owningWorld.getName()); + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); super.removeMetadata(block, metadataKey, owningPlugin); } @@ -76,7 +76,7 @@ public void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) */ @Override public void setMetadata(Block block, String metadataKey, MetadataValue newMetadataValue) { - Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", this.owningWorld.getName()); + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); super.setMetadata(block, metadataKey, newMetadataValue); } } diff --git a/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPack.java b/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPack.java index 9525a7d4..daaf004f 100644 --- a/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPack.java +++ b/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPack.java @@ -3,10 +3,10 @@ import java.io.IOException; import java.util.Set; import java.util.stream.Collectors; -import net.minecraft.server.packs.PackResources; -import net.minecraft.server.packs.metadata.pack.PackMetadataSection; -import net.minecraft.server.packs.repository.Pack; +import net.minecraft.server.packs.IResourcePack; +import net.minecraft.server.packs.metadata.pack.ResourcePackInfo; import net.minecraft.server.packs.repository.PackSource; +import net.minecraft.server.packs.repository.ResourcePackLoader; import net.minecraft.util.InclusiveRange; import org.bukkit.Bukkit; import org.bukkit.FeatureFlag; @@ -18,24 +18,24 @@ public class CraftDataPack implements DataPack { - private final Pack handle; - private final PackMetadataSection resourcePackInfo; + private final ResourcePackLoader handle; + private final ResourcePackInfo resourcePackInfo; - public CraftDataPack(Pack handler) { + public CraftDataPack(ResourcePackLoader handler) { this.handle = handler; - try (PackResources iresourcepack = this.handle.resources.openPrimary(this.handle.location())) { - this.resourcePackInfo = iresourcepack.getMetadataSection(PackMetadataSection.TYPE); + try (IResourcePack iresourcepack = this.handle.resources.openPrimary(this.handle.location())) { + this.resourcePackInfo = iresourcepack.getMetadataSection(ResourcePackInfo.TYPE); } catch (IOException e) { // This is already called in NMS then if in NMS not happen is secure this not throw here throw new RuntimeException(e); } } - public Pack getHandle() { + public ResourcePackLoader getHandle() { return this.handle; } public String getRawId() { - return this.getHandle().getId(); + return getHandle().getId(); } @Override @@ -65,7 +65,7 @@ public int getMaxSupportedPackFormat() { @Override public boolean isRequired() { - return this.getHandle().isRequired(); + return getHandle().isRequired(); } @Override @@ -79,7 +79,7 @@ public Compatibility getCompatibility() { @Override public boolean isEnabled() { - return ((CraftServer) Bukkit.getServer()).getServer().getPackRepository().getSelectedIds().contains(this.getRawId()); + return ((CraftServer) Bukkit.getServer()).getServer().getPackRepository().getSelectedIds().contains(getRawId()); } @Override @@ -103,12 +103,12 @@ public Set getRequestedFeatures() { @Override public NamespacedKey getKey() { - return NamespacedKey.fromString(this.getRawId()); + return NamespacedKey.fromString(getRawId()); } @Override public String toString() { - String requestedFeatures = this.getRequestedFeatures().stream().map(featureFlag -> featureFlag.getKey().toString()).collect(Collectors.joining(",")); + String requestedFeatures = getRequestedFeatures().stream().map(featureFlag -> featureFlag.getKey().toString()).collect(Collectors.joining(",")); return "CraftDataPack{rawId=" + this.getRawId() + ",id=" + this.getKey() + ",title=" + this.getTitle() + ",description=" + this.getDescription() + ",packformat=" + this.getPackFormat() + ",minSupportedPackFormat=" + this.getMinSupportedPackFormat() + ",maxSupportedPackFormat=" + this.getMaxSupportedPackFormat() + ",compatibility=" + this.getCompatibility() + ",source=" + this.getSource() + ",enabled=" + this.isEnabled() + ",requestedFeatures=[" + requestedFeatures + "]}"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPackManager.java b/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPackManager.java index 48c68c98..77e3f54c 100644 --- a/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPackManager.java +++ b/src/main/java/org/bukkit/craftbukkit/packs/CraftDataPackManager.java @@ -4,8 +4,9 @@ import java.util.Collection; import java.util.Objects; import java.util.stream.Collectors; -import net.minecraft.server.packs.repository.Pack; -import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.ResourcePackLoader; +import net.minecraft.server.packs.repository.ResourcePackRepository; +import net.minecraft.world.entity.EntityTypes; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.World; @@ -21,13 +22,13 @@ public class CraftDataPackManager implements DataPackManager { - private final PackRepository handle; + private final ResourcePackRepository handle; - public CraftDataPackManager(PackRepository resourcePackRepository) { + public CraftDataPackManager(ResourcePackRepository resourcePackRepository) { this.handle = resourcePackRepository; } - public PackRepository getHandle() { + public ResourcePackRepository getHandle() { return this.handle; } @@ -36,7 +37,7 @@ public Collection getDataPacks() { // Based in the command for datapacks need reload for get the updated list of datapacks this.getHandle().reload(); - Collection availablePacks = this.getHandle().getAvailablePacks(); + Collection availablePacks = this.getHandle().getAvailablePacks(); return availablePacks.stream().map(CraftDataPack::new).collect(Collectors.toUnmodifiableList()); } @@ -52,8 +53,8 @@ public Collection getEnabledDataPacks(World world) { Preconditions.checkArgument(world != null, "world cannot be null"); CraftWorld craftWorld = ((CraftWorld) world); - return craftWorld.getHandle().K.getDataConfiguration().dataPacks().getEnabled().stream().map(packName -> { - Pack resourcePackLoader = this.getHandle().getPack(packName); + return craftWorld.getHandle().serverLevelData.getDataConfiguration().dataPacks().getEnabled().stream().map(packName -> { + ResourcePackLoader resourcePackLoader = this.getHandle().getPack(packName); if (resourcePackLoader != null) { return new CraftDataPack(resourcePackLoader); } @@ -66,8 +67,8 @@ public Collection getDisabledDataPacks(World world) { Preconditions.checkArgument(world != null, "world cannot be null"); CraftWorld craftWorld = ((CraftWorld) world); - return craftWorld.getHandle().K.getDataConfiguration().dataPacks().getDisabled().stream().map(packName -> { - Pack resourcePackLoader = this.getHandle().getPack(packName); + return craftWorld.getHandle().serverLevelData.getDataConfiguration().dataPacks().getDisabled().stream().map(packName -> { + ResourcePackLoader resourcePackLoader = this.getHandle().getPack(packName); if (resourcePackLoader != null) { return new CraftDataPack(resourcePackLoader); } @@ -115,7 +116,7 @@ public boolean isEnabledByFeature(EntityType entityType, World world) { Preconditions.checkArgument(entityType != EntityType.UNKNOWN, "EntityType.UNKNOWN its not allowed here"); CraftWorld craftWorld = ((CraftWorld) world); - net.minecraft.world.entity.EntityType nmsEntity = CraftEntityType.bukkitToMinecraft(entityType); + EntityTypes nmsEntity = CraftEntityType.bukkitToMinecraft(entityType); return nmsEntity.isEnabled(craftWorld.getHandle().enabledFeatures()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java index dbb9a5b2..af31f754 100644 --- a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java @@ -7,8 +7,8 @@ import java.util.Map.Entry; import java.util.Objects; import java.util.Set; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import org.bukkit.NamespacedKey; import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer; import org.bukkit.persistence.PersistentDataAdapterContext; @@ -18,11 +18,11 @@ public class CraftPersistentDataContainer implements PersistentDataContainer { - private final Map customDataTags = new HashMap<>(); + private final Map customDataTags = new HashMap<>(); private final CraftPersistentDataTypeRegistry registry; private final CraftPersistentDataAdapterContext adapterContext; - public CraftPersistentDataContainer(Map customTags, CraftPersistentDataTypeRegistry registry) { + public CraftPersistentDataContainer(Map customTags, CraftPersistentDataTypeRegistry registry) { this(registry); this.customDataTags.putAll(customTags); } @@ -39,7 +39,7 @@ public void set(@NotNull NamespacedKey key, @NotNull PersistentDataType boolean has(@NotNull NamespacedKey key, @NotNull PersistentDataTyp Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null"); Preconditions.checkArgument(type != null, "The provided type cannot be null"); - Tag value = this.customDataTags.get(key.toString()); + NBTBase value = this.customDataTags.get(key.toString()); if (value == null) { return false; } @@ -65,12 +65,12 @@ public Z get(@NotNull NamespacedKey key, @NotNull PersistentDataType myRawMap = this.getRaw(); - Map theirRawMap = ((CraftPersistentDataContainer) obj).getRaw(); + Map myRawMap = this.getRaw(); + Map theirRawMap = ((CraftPersistentDataContainer) obj).getRaw(); return Objects.equals(myRawMap, theirRawMap); } - public CompoundTag toTagCompound() { - CompoundTag tag = new CompoundTag(); - for (Entry entry : this.customDataTags.entrySet()) { + public NBTTagCompound toTagCompound() { + NBTTagCompound tag = new NBTTagCompound(); + for (Entry entry : this.customDataTags.entrySet()) { tag.put(entry.getKey(), entry.getValue()); } return tag; } - public void put(String key, Tag base) { + public void put(String key, NBTBase base) { this.customDataTags.put(key, base); } - public void putAll(Map map) { + public void putAll(Map map) { this.customDataTags.putAll(map); } - public void putAll(CompoundTag compound) { + public void putAll(NBTTagCompound compound) { for (String key : compound.getAllKeys()) { this.customDataTags.put(key, compound.get(key)); } } - public Map getRaw() { + public Map getRaw() { return this.customDataTags; } @@ -175,6 +175,6 @@ public int hashCode() { } public String serialize() { - return CraftNBTTagConfigSerializer.serialize(this.toTagCompound()); + return CraftNBTTagConfigSerializer.serialize(toTagCompound()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java index 71dc4a22..a1b7442f 100644 --- a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java +++ b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java @@ -12,19 +12,19 @@ import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; -import net.minecraft.nbt.ByteArrayTag; -import net.minecraft.nbt.ByteTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.FloatTag; -import net.minecraft.nbt.IntArrayTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.LongArrayTag; -import net.minecraft.nbt.LongTag; -import net.minecraft.nbt.ShortTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagByte; +import net.minecraft.nbt.NBTTagByteArray; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagDouble; +import net.minecraft.nbt.NBTTagFloat; +import net.minecraft.nbt.NBTTagInt; +import net.minecraft.nbt.NBTTagIntArray; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagLong; +import net.minecraft.nbt.NBTTagLongArray; +import net.minecraft.nbt.NBTTagShort; +import net.minecraft.nbt.NBTTagString; import org.bukkit.persistence.ListPersistentDataType; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; @@ -33,11 +33,11 @@ /** * The craft persistent data type registry, at its core, is responsible for the * conversion process between a {@link PersistentDataType} and a respective - * {@link Tag} instance. + * {@link NBTBase} instance. *

    * It does so by creating {@link TagAdapter} instances that are capable of * mappings the supported "primitive types" of {@link PersistentDataType}s to - * their respective {@link Tag} instances. + * their respective {@link NBTBase} instances. *

    * To accomplish this, the class makes heavy use of raw arguments. Their * validity is enforced by the mapping of class to {@link TagAdapter} @@ -50,39 +50,39 @@ public final class CraftPersistentDataTypeRegistry { /** * A tag adapter is a closely related type to a specific implementation of - * the {@link Tag} interface. It exists to convert from and to the - * respective value of a {@link Tag} to a "primitive type" for later + * the {@link NBTBase} interface. It exists to convert from and to the + * respective value of a {@link NBTBase} to a "primitive type" for later * usage in {@link PersistentDataType}. * * @param primitiveType the class of the primitive type, e.g. * {@link String}. * @param nbtBaseType the class of the tag implementation that is used to - * store this primitive type, e.g {@link StringTag}. + * store this primitive type, e.g {@link NBTTagString}. * @param nmsTypeByte the byte identifier of the tag as defined by - * {@link Tag#getId()}. + * {@link NBTBase#getId()}. * @param builder a bi function that is responsible for mapping a "primitive - * type" and its respective {@link PersistentDataType} to a {@link Tag}. + * type" and its respective {@link PersistentDataType} to a {@link NBTBase}. * @param extractor a bi function that is responsible for extracting a - * "primitive type" from a {@link Tag} given a + * "primitive type" from a {@link NBTBase} given a * {@link PersistentDataType}. * @param matcher a bi predicate that is responsible for computing if the - * passed {@link Tag} holds a value that the {@link PersistentDataType} + * passed {@link NBTBase} holds a value that the {@link PersistentDataType} * can extract. * @param

    the generic type of the primitive the persistent data type * expects. - * @param the generic type of the concrete {@link Tag} + * @param the generic type of the concrete {@link NBTBase} * implementation that the primitive type is mapped into. */ - private record TagAdapter( + private record TagAdapter( Class

    primitiveType, Class nbtBaseType, byte nmsTypeByte, BiFunction, P, T> builder, BiFunction, T, P> extractor, - BiPredicate, Tag> matcher) { + BiPredicate, NBTBase> matcher) { /** - * Extract the primitive value from the {@link Tag}. + * Extract the primitive value from the {@link NBTBase}. * * @param base the base to extract from * @return the value stored inside the tag @@ -90,7 +90,7 @@ private record TagAdapter( * the defined base type and therefore is not applicable to the * extractor function. */ - private P extract(final PersistentDataType dataType, final Tag base) { + private P extract(final PersistentDataType dataType, final NBTBase base) { Preconditions.checkArgument(this.nbtBaseType.isInstance(base), "The provided NBTBase was of the type %s. Expected type %s", base.getClass().getSimpleName(), this.nbtBaseType.getSimpleName()); return this.extractor.apply(dataType, this.nbtBaseType.cast(base)); } @@ -111,12 +111,12 @@ private T build(final PersistentDataType dataType, final Object value) { /** * Computes if the provided persistent data type's primitive type is a - * representation of the {@link Tag}. + * representation of the {@link NBTBase}. * * @param base the base tag instance to check against * @return if the tag was an instance of the set type */ - private boolean isInstance(final PersistentDataType persistentDataType, final Tag base) { + private boolean isInstance(final PersistentDataType persistentDataType, final NBTBase base) { return this.matcher.test(persistentDataType, base); } } @@ -140,63 +140,63 @@ private TagAdapter createAdapter(Class type) { // Primitives if (Objects.equals(Byte.class, type)) { return this.createAdapter( - Byte.class, ByteTag.class, Tag.TAG_BYTE, - ByteTag::valueOf, ByteTag::getAsByte + Byte.class, NBTTagByte.class, NBTBase.TAG_BYTE, + NBTTagByte::valueOf, NBTTagByte::getAsByte ); } if (Objects.equals(Short.class, type)) { return this.createAdapter( - Short.class, ShortTag.class, Tag.TAG_SHORT, ShortTag::valueOf, ShortTag::getAsShort + Short.class, NBTTagShort.class, NBTBase.TAG_SHORT, NBTTagShort::valueOf, NBTTagShort::getAsShort ); } if (Objects.equals(Integer.class, type)) { return this.createAdapter( - Integer.class, IntTag.class, Tag.TAG_INT, IntTag::valueOf, IntTag::getAsInt + Integer.class, NBTTagInt.class, NBTBase.TAG_INT, NBTTagInt::valueOf, NBTTagInt::getAsInt ); } if (Objects.equals(Long.class, type)) { return this.createAdapter( - Long.class, LongTag.class, Tag.TAG_LONG, LongTag::valueOf, LongTag::getAsLong + Long.class, NBTTagLong.class, NBTBase.TAG_LONG, NBTTagLong::valueOf, NBTTagLong::getAsLong ); } if (Objects.equals(Float.class, type)) { return this.createAdapter( - Float.class, FloatTag.class, Tag.TAG_FLOAT, - FloatTag::valueOf, FloatTag::getAsFloat + Float.class, NBTTagFloat.class, NBTBase.TAG_FLOAT, + NBTTagFloat::valueOf, NBTTagFloat::getAsFloat ); } if (Objects.equals(Double.class, type)) { return this.createAdapter( - Double.class, DoubleTag.class, Tag.TAG_DOUBLE, - DoubleTag::valueOf, DoubleTag::getAsDouble + Double.class, NBTTagDouble.class, NBTBase.TAG_DOUBLE, + NBTTagDouble::valueOf, NBTTagDouble::getAsDouble ); } if (Objects.equals(String.class, type)) { return this.createAdapter( - String.class, StringTag.class, Tag.TAG_STRING, - StringTag::valueOf, StringTag::getAsString + String.class, NBTTagString.class, NBTBase.TAG_STRING, + NBTTagString::valueOf, NBTTagString::getAsString ); } // Primitive non-list arrays if (Objects.equals(byte[].class, type)) { return this.createAdapter( - byte[].class, ByteArrayTag.class, Tag.TAG_BYTE_ARRAY, - array -> new ByteArrayTag(Arrays.copyOf(array, array.length)), + byte[].class, NBTTagByteArray.class, NBTBase.TAG_BYTE_ARRAY, + array -> new NBTTagByteArray(Arrays.copyOf(array, array.length)), n -> Arrays.copyOf(n.getAsByteArray(), n.size()) ); } if (Objects.equals(int[].class, type)) { return this.createAdapter( - int[].class, IntArrayTag.class, Tag.TAG_INT_ARRAY, - array -> new IntArrayTag(Arrays.copyOf(array, array.length)), + int[].class, NBTTagIntArray.class, NBTBase.TAG_INT_ARRAY, + array -> new NBTTagIntArray(Arrays.copyOf(array, array.length)), n -> Arrays.copyOf(n.getAsIntArray(), n.size()) ); } if (Objects.equals(long[].class, type)) { return this.createAdapter( - long[].class, LongArrayTag.class, Tag.TAG_LONG_ARRAY, - array -> new LongArrayTag(Arrays.copyOf(array, array.length)), + long[].class, NBTTagLongArray.class, NBTBase.TAG_LONG_ARRAY, + array -> new NBTTagLongArray(Arrays.copyOf(array, array.length)), n -> Arrays.copyOf(n.getAsLongArray(), n.size()) ); } @@ -204,9 +204,9 @@ private TagAdapter createAdapter(Class type) { // Previously "emulated" compound lists, now useless as a proper list type exists. if (Objects.equals(PersistentDataContainer[].class, type)) { return this.createAdapter( - PersistentDataContainer[].class, ListTag.class, Tag.TAG_LIST, + PersistentDataContainer[].class, NBTTagList.class, NBTBase.TAG_LIST, (containerArray) -> { - final ListTag list = new ListTag(); + final NBTTagList list = new NBTTagList(); for (final PersistentDataContainer persistentDataContainer : containerArray) { list.add(((CraftPersistentDataContainer) persistentDataContainer).toTagCompound()); } @@ -216,7 +216,7 @@ private TagAdapter createAdapter(Class type) { final PersistentDataContainer[] containerArray = new CraftPersistentDataContainer[tag.size()]; for (int i = 0; i < tag.size(); i++) { final CraftPersistentDataContainer container = new CraftPersistentDataContainer(this); - final CompoundTag compound = tag.getCompound(i); + final NBTTagCompound compound = tag.getCompound(i); for (final String key : compound.getAllKeys()) { container.put(key, compound.get(key)); } @@ -232,7 +232,7 @@ private TagAdapter createAdapter(Class type) { // as defined in TagAdapter#build. if (Objects.equals(PersistentDataContainer.class, type)) { return this.createAdapter( - CraftPersistentDataContainer.class, CompoundTag.class, Tag.TAG_COMPOUND, + CraftPersistentDataContainer.class, NBTTagCompound.class, NBTBase.TAG_COMPOUND, CraftPersistentDataContainer::toTagCompound, tag -> { final CraftPersistentDataContainer container = new CraftPersistentDataContainer(this); @@ -244,10 +244,10 @@ private TagAdapter createAdapter(Class type) { } if (Objects.equals(List.class, type)) { - return this.createAdapter( + return createAdapter( List.class, - net.minecraft.nbt.ListTag.class, - Tag.TAG_LIST, + net.minecraft.nbt.NBTTagList.class, + NBTBase.TAG_LIST, this::constructList, this::extractList, this::matchesListTag @@ -258,11 +258,11 @@ private TagAdapter createAdapter(Class type) { } // Plain constructor helper method. - private TagAdapter createAdapter( + private TagAdapter createAdapter( final Class primitiveType, final Class nbtBaseType, final byte nmsTypeByte, final Function builder, final Function extractor ) { - return this.createAdapter( + return createAdapter( primitiveType, nbtBaseType, nmsTypeByte, @@ -273,11 +273,11 @@ private TagAdapter createAdapter( } // Plain constructor helper method. - private TagAdapter createAdapter( + private TagAdapter createAdapter( final Class primitiveType, final Class nbtBaseType, final byte nmsTypeByte, final BiFunction, T, Z> builder, final BiFunction, Z, T> extractor, - final BiPredicate, Tag> matcher + final BiPredicate, NBTBase> matcher ) { return new TagAdapter<>(primitiveType, nbtBaseType, nmsTypeByte, builder, extractor, matcher); } @@ -292,7 +292,7 @@ private TagAdapter createAdapter( * @throws IllegalArgumentException if no suitable tag type adapter for this * type was found. */ - public Tag wrap(final PersistentDataType type, final T value) { + public NBTBase wrap(final PersistentDataType type, final T value) { return this.getOrCreateAdapter(type).build(type, value); } @@ -306,7 +306,7 @@ public Tag wrap(final PersistentDataType type, final T value) { * @throws IllegalArgumentException if no suitable tag type adapter for this * type was found. */ - public boolean isInstanceOf(final PersistentDataType type, final Tag base) { + public boolean isInstanceOf(final PersistentDataType type, final NBTBase base) { return this.getOrCreateAdapter(type).isInstance(type, base); } @@ -323,8 +323,8 @@ public boolean isInstanceOf(final PersistentDataType type, final Tag b * persistent data type. */ @NotNull - private TagAdapter getOrCreateAdapter(@NotNull final PersistentDataType type) { - return this.adapters.computeIfAbsent(type.getPrimitiveType(), this.CREATE_ADAPTER); + private TagAdapter getOrCreateAdapter(@NotNull final PersistentDataType type) { + return this.adapters.computeIfAbsent(type.getPrimitiveType(), CREATE_ADAPTER); } /** @@ -342,7 +342,7 @@ private TagAdapter getOrCreateAdapter(@NotNull final Pe * @throws IllegalArgumentException if no suitable tag type adapter for this * type was found. */ - public T extract(final PersistentDataType type, final Tag tag) throws ClassCastException, IllegalArgumentException { + public T extract(final PersistentDataType type, final NBTBase tag) throws ClassCastException, IllegalArgumentException { final Class primitiveType = type.getPrimitiveType(); final TagAdapter adapter = this.getOrCreateAdapter(type); Preconditions.checkArgument(adapter.isInstance(type, tag), "The found tag instance (%s) cannot store %s", tag.getClass().getSimpleName(), primitiveType.getSimpleName()); @@ -353,30 +353,30 @@ public T extract(final PersistentDataType type, final T } /** - * Constructs a {@link ListTag} from a {@link List} instance by using the + * Constructs a {@link NBTTagList} from a {@link List} instance by using the * passed persistent data type. * * @param type the persistent data type of the list. * @param list the list or primitive values. * @param

    the generic type of the primitive values in the list. - * @return the constructed {@link ListTag}. + * @return the constructed {@link NBTTagList}. */ - private > ListTag constructList(@NotNull final PersistentDataType type, @NotNull final List

    list) { + private > NBTTagList constructList(@NotNull final PersistentDataType type, @NotNull final List

    list) { Preconditions.checkArgument(type instanceof ListPersistentDataType, "The passed list cannot be written to the PDC with a %s (expected a list data type)", type.getClass().getSimpleName()); final ListPersistentDataType listPersistentDataType = (ListPersistentDataType) type; - final TagAdapter elementAdapter = this.getOrCreateAdapter(listPersistentDataType.elementType()); + final TagAdapter elementAdapter = this.getOrCreateAdapter(listPersistentDataType.elementType()); - final List values = Lists.newArrayListWithCapacity(list.size()); + final List values = Lists.newArrayListWithCapacity(list.size()); for (final P primitiveValue : list) { values.add(this.wrap(listPersistentDataType.elementType(), primitiveValue)); } - return new ListTag(values, values.isEmpty() ? ListTag.TAG_END : elementAdapter.nmsTypeByte()); + return new NBTTagList(values, values.isEmpty() ? NBTTagList.TAG_END : elementAdapter.nmsTypeByte()); } /** - * Extracts a {@link List} from a {@link ListTag} and a respective + * Extracts a {@link List} from a {@link NBTTagList} and a respective * {@link PersistentDataType}. * * @param type the persistent data type of the list. @@ -389,12 +389,12 @@ private > ListTag constructList(@NotNull final PersistentDa * extract a {@link List}. */ private

    List

    extractList(@NotNull final PersistentDataType type, - @NotNull final ListTag listTag) { + @NotNull final NBTTagList listTag) { Preconditions.checkArgument(type instanceof ListPersistentDataType, "The found list tag cannot be read with a %s (expected a list data type)", type.getClass().getSimpleName()); final ListPersistentDataType listPersistentDataType = (ListPersistentDataType) type; final List

    output = new ObjectArrayList<>(listTag.size()); - for (final Tag tag : listTag) { + for (final NBTBase tag : listTag) { output.add(this.extract(listPersistentDataType.elementType(), tag)); } @@ -402,7 +402,7 @@ private

    List

    extractList(@NotNull final PersistentDataType type, } /** - * Computes if the passed {@link Tag} is a {@link ListTag} and it, + * Computes if the passed {@link NBTBase} is a {@link NBTTagList} and it, * including its elements, can be read/written via the passed * {@link PersistentDataType}. *

    @@ -416,17 +416,17 @@ private

    List

    extractList(@NotNull final PersistentDataType type, * @param tag the tag that is to be checked if it matches the data type. * @return whether the passed tag can be read/written via the passed type. */ - private boolean matchesListTag(final PersistentDataType type, final Tag tag) { + private boolean matchesListTag(final PersistentDataType type, final NBTBase tag) { if ((!(type instanceof final ListPersistentDataType listPersistentDataType))) { return false; } - if (!(tag instanceof final ListTag listTag)) { + if (!(tag instanceof final NBTTagList listTag)) { return false; } final byte elementType = listTag.getElementType(); final TagAdapter elementAdapter = this.getOrCreateAdapter(listPersistentDataType.elementType()); - return elementAdapter.nmsTypeByte() == elementType || elementType == ListTag.TAG_END; + return elementAdapter.nmsTypeByte() == elementType || elementType == NBTTagList.TAG_END; } } diff --git a/src/main/java/org/bukkit/craftbukkit/persistence/DirtyCraftPersistentDataContainer.java b/src/main/java/org/bukkit/craftbukkit/persistence/DirtyCraftPersistentDataContainer.java index fc3a34b5..fe837dca 100644 --- a/src/main/java/org/bukkit/craftbukkit/persistence/DirtyCraftPersistentDataContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/persistence/DirtyCraftPersistentDataContainer.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.persistence; import java.util.Map; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; import org.bukkit.NamespacedKey; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; @@ -15,7 +15,7 @@ public final class DirtyCraftPersistentDataContainer extends CraftPersistentData private boolean dirty; - public DirtyCraftPersistentDataContainer(Map customTags, CraftPersistentDataTypeRegistry registry) { + public DirtyCraftPersistentDataContainer(Map customTags, CraftPersistentDataTypeRegistry registry) { super(customTags, registry); } @@ -44,19 +44,19 @@ public void remove(@NotNull NamespacedKey key) { } @Override - public void put(String key, Tag base) { + public void put(String key, NBTBase base) { super.put(key, base); this.dirty(true); } @Override - public void putAll(CompoundTag compound) { + public void putAll(NBTTagCompound compound) { super.putAll(compound); this.dirty(true); } @Override - public void putAll(Map map) { + public void putAll(Map map) { super.putAll(map); this.dirty(true); } diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java index 416c8064..eb57e49a 100644 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java +++ b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java @@ -2,7 +2,7 @@ import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; -import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.effect.MobEffectList; import org.bukkit.Color; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -13,43 +13,43 @@ import org.bukkit.potion.PotionEffectTypeCategory; import org.jetbrains.annotations.NotNull; -public class CraftPotionEffectType extends PotionEffectType implements Handleable { +public class CraftPotionEffectType extends PotionEffectType implements Handleable { - public static PotionEffectType minecraftHolderToBukkit(Holder minecraft) { - return CraftPotionEffectType.minecraftToBukkit(minecraft.value()); + public static PotionEffectType minecraftHolderToBukkit(Holder minecraft) { + return minecraftToBukkit(minecraft.value()); } - public static PotionEffectType minecraftToBukkit(MobEffect minecraft) { + public static PotionEffectType minecraftToBukkit(MobEffectList minecraft) { return CraftRegistry.minecraftToBukkit(minecraft, Registries.MOB_EFFECT, Registry.EFFECT); } - public static MobEffect bukkitToMinecraft(PotionEffectType bukkit) { + public static MobEffectList bukkitToMinecraft(PotionEffectType bukkit) { return CraftRegistry.bukkitToMinecraft(bukkit); } - public static Holder bukkitToMinecraftHolder(PotionEffectType bukkit) { + public static Holder bukkitToMinecraftHolder(PotionEffectType bukkit) { return CraftRegistry.bukkitToMinecraftHolder(bukkit, Registries.MOB_EFFECT); } private final NamespacedKey key; - private final MobEffect handle; + private final MobEffectList handle; private final int id; - public CraftPotionEffectType(NamespacedKey key, MobEffect handle) { + public CraftPotionEffectType(NamespacedKey key, MobEffectList handle) { this.key = key; this.handle = handle; this.id = CraftRegistry.getMinecraftRegistry(Registries.MOB_EFFECT).getId(handle) + 1; } @Override - public MobEffect getHandle() { - return this.handle; + public MobEffectList getHandle() { + return handle; } @NotNull @Override public NamespacedKey getKey() { - return this.key; + return key; } @Override @@ -59,12 +59,12 @@ public double getDurationModifier() { @Override public int getId() { - return this.id; + return id; } @Override public String getName() { - return switch (this.getId()) { + return switch (getId()) { case 1 -> "SPEED"; case 2 -> "SLOW"; case 3 -> "FAST_DIGGING"; @@ -98,19 +98,19 @@ public String getName() { case 31 -> "BAD_OMEN"; case 32 -> "HERO_OF_THE_VILLAGE"; case 33 -> "DARKNESS"; - default -> this.getKey().toString(); + default -> getKey().toString(); }; } @NotNull @Override public PotionEffect createEffect(int duration, int amplifier) { - return new PotionEffect(this, this.isInstant() ? 1 : (int) (duration * this.getDurationModifier()), amplifier); + return new PotionEffect(this, isInstant() ? 1 : (int) (duration * getDurationModifier()), amplifier); } @Override public boolean isInstant() { - return this.handle.isInstantenous(); + return handle.isInstantenous(); } @Override @@ -120,13 +120,13 @@ public PotionEffectTypeCategory getCategory() { @Override public Color getColor() { - return Color.fromRGB(this.handle.getColor()); + return Color.fromRGB(handle.getColor()); } @NotNull @Override public String getTranslationKey() { - return this.handle.getDescriptionId(); + return handle.getDescriptionId(); } @Override @@ -139,16 +139,16 @@ public boolean equals(Object other) { return false; } - return this.getKey().equals(((PotionEffectType) other).getKey()); + return getKey().equals(((PotionEffectType) other).getKey()); } @Override public int hashCode() { - return this.getKey().hashCode(); + return getKey().hashCode(); } @Override public String toString() { - return "CraftPotionEffectType[" + this.getKey() + "]"; + return "CraftPotionEffectType[" + getKey() + "]"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectTypeCategory.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectTypeCategory.java index f9df871b..b5377db7 100644 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectTypeCategory.java +++ b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectTypeCategory.java @@ -1,18 +1,18 @@ package org.bukkit.craftbukkit.potion; import com.google.common.base.Preconditions; -import net.minecraft.world.effect.MobEffectCategory; +import net.minecraft.world.effect.MobEffectInfo; import org.bukkit.potion.PotionEffectTypeCategory; public final class CraftPotionEffectTypeCategory { - public static PotionEffectTypeCategory minecraftToBukkit(MobEffectCategory minecraft) { + public static PotionEffectTypeCategory minecraftToBukkit(MobEffectInfo minecraft) { Preconditions.checkArgument(minecraft != null); return PotionEffectTypeCategory.valueOf(minecraft.name()); } - public static MobEffectCategory bukkitToMinecraft(PotionEffectTypeCategory bukkit) { + public static MobEffectInfo bukkitToMinecraft(PotionEffectTypeCategory bukkit) { Preconditions.checkArgument(bukkit != null); - return MobEffectCategory.valueOf(bukkit.name()); + return MobEffectInfo.valueOf(bukkit.name()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionType.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionType.java index 82a50b06..29621d8e 100644 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionType.java +++ b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionType.java @@ -6,8 +6,9 @@ import java.util.Locale; import java.util.function.Supplier; import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; import net.minecraft.core.registries.Registries; -import net.minecraft.world.item.alchemy.Potion; +import net.minecraft.world.item.alchemy.PotionRegistry; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.craftbukkit.CraftRegistry; @@ -20,14 +21,14 @@ public class CraftPotionType implements PotionType.InternalPotionData { - public static PotionType minecraftHolderToBukkit(Holder minecraft) { - return CraftPotionType.minecraftToBukkit(minecraft.value()); + public static PotionType minecraftHolderToBukkit(Holder minecraft) { + return minecraftToBukkit(minecraft.value()); } - public static PotionType minecraftToBukkit(Potion minecraft) { + public static PotionType minecraftToBukkit(PotionRegistry minecraft) { Preconditions.checkArgument(minecraft != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.POTION); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.POTION); PotionType bukkit = Registry.POTION.get(CraftNamespacedKey.fromMinecraft(registry.getResourceKey(minecraft).orElseThrow().location())); Preconditions.checkArgument(bukkit != null); @@ -35,19 +36,19 @@ public static PotionType minecraftToBukkit(Potion minecraft) { return bukkit; } - public static Potion bukkitToMinecraft(PotionType bukkit) { + public static PotionRegistry bukkitToMinecraft(PotionType bukkit) { Preconditions.checkArgument(bukkit != null); return CraftRegistry.getMinecraftRegistry(Registries.POTION) .getOptional(CraftNamespacedKey.toMinecraft(bukkit.getKey())).orElseThrow(); } - public static Holder bukkitToMinecraftHolder(PotionType bukkit) { + public static Holder bukkitToMinecraftHolder(PotionType bukkit) { Preconditions.checkArgument(bukkit != null); - net.minecraft.core.Registry registry = CraftRegistry.getMinecraftRegistry(Registries.POTION); + IRegistry registry = CraftRegistry.getMinecraftRegistry(Registries.POTION); - if (registry.wrapAsHolder(CraftPotionType.bukkitToMinecraft(bukkit)) instanceof Holder.Reference holder) { + if (registry.wrapAsHolder(bukkitToMinecraft(bukkit)) instanceof Holder.c holder) { return holder; } @@ -75,48 +76,48 @@ public static PotionType stringToBukkit(String string) { } private final NamespacedKey key; - private final Potion potion; + private final PotionRegistry potion; private final Supplier> potionEffects; private final Supplier upgradeable; private final Supplier extendable; private final Supplier maxLevel; - public CraftPotionType(NamespacedKey key, Potion potion) { + public CraftPotionType(NamespacedKey key, PotionRegistry potion) { this.key = key; this.potion = potion; this.potionEffects = Suppliers.memoize(() -> potion.getEffects().stream().map(CraftPotionUtil::toBukkit).toList()); this.upgradeable = Suppliers.memoize(() -> Registry.POTION.get(new NamespacedKey(key.getNamespace(), "strong_" + key.getKey())) != null); this.extendable = Suppliers.memoize(() -> Registry.POTION.get(new NamespacedKey(key.getNamespace(), "long_" + key.getKey())) != null); - this.maxLevel = Suppliers.memoize(() -> this.isUpgradeable() ? 2 : 1); + this.maxLevel = Suppliers.memoize(() -> isUpgradeable() ? 2 : 1); } @Override public PotionEffectType getEffectType() { - return this.getPotionEffects().isEmpty() ? null : this.getPotionEffects().get(0).getType(); + return getPotionEffects().isEmpty() ? null : getPotionEffects().get(0).getType(); } @Override public List getPotionEffects() { - return this.potionEffects.get(); + return potionEffects.get(); } @Override public boolean isInstant() { - return this.potion.hasInstantEffects(); + return potion.hasInstantEffects(); } @Override public boolean isUpgradeable() { - return this.upgradeable.get(); + return upgradeable.get(); } @Override public boolean isExtendable() { - return this.extendable.get(); + return extendable.get(); } @Override public int getMaxLevel() { - return this.maxLevel.get(); + return maxLevel.get(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java index d96863c3..986e7fd6 100644 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java +++ b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java @@ -3,11 +3,9 @@ import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; -import java.util.HashMap; -import java.util.Map; import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffectList; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; @@ -15,8 +13,6 @@ public class CraftPotionUtil { - public static Map mods = new HashMap<>(); // Mohist - private static final BiMap upgradeable = ImmutableBiMap.builder() .put(PotionType.LEAPING, PotionType.STRONG_LEAPING) .put(PotionType.SWIFTNESS, PotionType.STRONG_SWIFTNESS) @@ -80,12 +76,12 @@ public static PotionData toBukkit(PotionType type) { return new PotionData(type, false, false); } - public static MobEffectInstance fromBukkit(PotionEffect effect) { - Holder type = CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()); - return new MobEffectInstance(type, effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()); + public static MobEffect fromBukkit(PotionEffect effect) { + Holder type = CraftPotionEffectType.bukkitToMinecraftHolder(effect.getType()); + return new MobEffect(type, effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()); } - public static PotionEffect toBukkit(MobEffectInstance effect) { + public static PotionEffect toBukkit(MobEffect effect) { PotionEffectType type = CraftPotionEffectType.minecraftHolderToBukkit(effect.getEffect()); int amp = effect.getAmplifier(); int duration = effect.getDuration(); @@ -94,7 +90,7 @@ public static PotionEffect toBukkit(MobEffectInstance effect) { return new PotionEffect(type, duration, amp, ambient, particles); } - public static boolean equals(Holder mobEffect, PotionEffectType type) { + public static boolean equals(Holder mobEffect, PotionEffectType type) { PotionEffectType typeV = CraftPotionEffectType.minecraftHolderToBukkit(mobEffect); return typeV.equals(type); } diff --git a/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java b/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java index 59983673..9c518881 100644 --- a/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java +++ b/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java @@ -18,7 +18,7 @@ import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.Util; +import net.minecraft.SystemUtils; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.world.item.component.ResolvableProfile; import org.apache.commons.lang.StringUtils; @@ -75,6 +75,7 @@ public CraftPlayerProfile(UUID uniqueId, String name) { this(uniqueId, name, true); } + // The ResolvableProfile used in Components can have just the properties then need ignore all checks internally @ApiStatus.Internal public CraftPlayerProfile(@Nonnull ResolvableProfile resolvableProfile) { this(resolvableProfile.id().orElse(null), resolvableProfile.name().orElse(null), false); @@ -96,7 +97,7 @@ private CraftPlayerProfile(@Nonnull CraftPlayerProfile other) { @Override public UUID getUniqueId() { - return (Objects.equals(uniqueId, Util.NIL_UUID)) ? null : uniqueId; + return (Objects.equals(uniqueId, SystemUtils.NIL_UUID)) ? null : uniqueId; } @Override @@ -106,28 +107,28 @@ public String getName() { @Nullable Property getProperty(String propertyName) { - return Iterables.getFirst(this.properties.get(propertyName), null); + return Iterables.getFirst(properties.get(propertyName), null); } void setProperty(String propertyName, @Nullable Property property) { // Assert: (property == null) || property.getName().equals(propertyName) - this.removeProperty(propertyName); + removeProperty(propertyName); if (property != null) { - this.properties.put(property.name(), property); + properties.put(property.name(), property); } } void removeProperty(String propertyName) { - this.properties.removeAll(propertyName); + properties.removeAll(propertyName); } void rebuildDirtyProperties() { - this.textures.rebuildPropertyIfDirty(); + textures.rebuildPropertyIfDirty(); } @Override public CraftPlayerTextures getTextures() { - return this.textures; + return textures; } @Override @@ -141,12 +142,12 @@ public void setTextures(@Nullable PlayerTextures textures) { @Override public boolean isComplete() { - return (this.getUniqueId() != null) && (this.getName() != null) && !this.textures.isEmpty(); + return (getUniqueId() != null) && (getName() != null) && !textures.isEmpty(); } @Override public CompletableFuture update() { - return CompletableFuture.supplyAsync(this::getUpdatedProfile, Util.backgroundExecutor()); + return CompletableFuture.supplyAsync(this::getUpdatedProfile, SystemUtils.backgroundExecutor()); } private CraftPlayerProfile getUpdatedProfile() { @@ -154,12 +155,12 @@ private CraftPlayerProfile getUpdatedProfile() { GameProfile profile = this.buildGameProfile(); // If missing, look up the uuid by name: - if (profile.getId().equals(Util.NIL_UUID)) { + if (profile.getId().equals(SystemUtils.NIL_UUID)) { profile = server.getProfileCache().get(profile.getName()).orElse(profile); } // Look up properties such as the textures: - if (!profile.getId().equals(Util.NIL_UUID)) { + if (!profile.getId().equals(SystemUtils.NIL_UUID)) { ProfileResult newProfile = server.getSessionService().fetchProfile(profile.getId(), true); if (newProfile != null) { profile = newProfile.profile(); @@ -181,22 +182,22 @@ public ResolvableProfile buildResolvableProfile() { // built GameProfiles don't affect the use of this profile in other contexts. @Nonnull public GameProfile buildGameProfile() { - this.rebuildDirtyProperties(); - GameProfile profile = new GameProfile(this.uniqueId, this.name); - profile.getProperties().putAll(this.properties); + rebuildDirtyProperties(); + GameProfile profile = new GameProfile(uniqueId, name); + profile.getProperties().putAll(properties); return profile; } @Override public String toString() { - this.rebuildDirtyProperties(); + rebuildDirtyProperties(); StringBuilder builder = new StringBuilder(); builder.append("CraftPlayerProfile [uniqueId="); - builder.append(this.uniqueId); + builder.append(uniqueId); builder.append(", name="); - builder.append(this.name); + builder.append(name); builder.append(", properties="); - builder.append(CraftPlayerProfile.toString(this.properties)); + builder.append(toString(properties)); builder.append("]"); return builder.toString(); } @@ -217,12 +218,12 @@ private static String toString(@Nonnull PropertyMap propertyMap) { public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof CraftPlayerProfile other)) return false; - if (!Objects.equals(this.uniqueId, other.uniqueId)) return false; - if (!Objects.equals(this.name, other.name)) return false; + if (!Objects.equals(uniqueId, other.uniqueId)) return false; + if (!Objects.equals(name, other.name)) return false; - this.rebuildDirtyProperties(); + rebuildDirtyProperties(); other.rebuildDirtyProperties(); - if (!CraftPlayerProfile.equals(this.properties, other.properties)) return false; + if (!equals(properties, other.properties)) return false; return true; } @@ -245,11 +246,11 @@ private static boolean equals(@Nonnull PropertyMap propertyMap, @Nonnull Propert @Override public int hashCode() { - this.rebuildDirtyProperties(); + rebuildDirtyProperties(); int result = 1; - result = 31 * result + Objects.hashCode(this.uniqueId); - result = 31 * result + Objects.hashCode(this.name); - result = 31 * result + CraftPlayerProfile.hashCode(this.properties); + result = 31 * result + Objects.hashCode(uniqueId); + result = 31 * result + Objects.hashCode(name); + result = 31 * result + hashCode(properties); return result; } @@ -273,9 +274,9 @@ public Map serialize() { map.put("uniqueId", this.uniqueId.toString()); } if (this.name != null) { - map.put("name", this.getName()); + map.put("name", getName()); } - this.rebuildDirtyProperties(); + rebuildDirtyProperties(); if (!this.properties.isEmpty()) { List propertiesData = new ArrayList<>(); this.properties.forEach((propertyName, property) -> propertiesData.add(CraftProfileProperty.serialize(property))); diff --git a/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerTextures.java b/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerTextures.java index 78e9e79b..76262ad5 100644 --- a/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerTextures.java +++ b/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerTextures.java @@ -24,8 +24,8 @@ private static void validateTextureUrl(@Nullable URL url) { // Null represents an unset texture and is therefore valid. if (url == null) return; - Preconditions.checkArgument(url.getHost().equals(CraftPlayerTextures.MINECRAFT_HOST), "Expected host '%s' but got '%s'", CraftPlayerTextures.MINECRAFT_HOST, url.getHost()); - Preconditions.checkArgument(url.getPath().startsWith(CraftPlayerTextures.MINECRAFT_PATH), "Expected path starting with '%s' but got '%s", CraftPlayerTextures.MINECRAFT_PATH, url.getPath()); + Preconditions.checkArgument(url.getHost().equals(MINECRAFT_HOST), "Expected host '%s' but got '%s'", MINECRAFT_HOST, url.getHost()); + Preconditions.checkArgument(url.getPath().startsWith(MINECRAFT_PATH), "Expected path starting with '%s' but got '%s", MINECRAFT_PATH, url.getPath()); } @Nullable @@ -75,33 +75,33 @@ void copyFrom(@Nonnull PlayerTextures other) { if (other == this) return; Preconditions.checkArgument(other instanceof CraftPlayerTextures, "Expecting CraftPlayerTextures, got %s", other.getClass().getName()); CraftPlayerTextures otherTextures = (CraftPlayerTextures) other; - this.clear(); + clear(); Property texturesProperty = otherTextures.getProperty(); - this.profile.setProperty(CraftPlayerTextures.PROPERTY_NAME, texturesProperty); + profile.setProperty(PROPERTY_NAME, texturesProperty); if (texturesProperty != null - && (!Objects.equals(this.profile.getUniqueId(), otherTextures.profile.getUniqueId()) - || !Objects.equals(this.profile.getName(), otherTextures.profile.getName()))) { + && (!Objects.equals(profile.getUniqueId(), otherTextures.profile.getUniqueId()) + || !Objects.equals(profile.getName(), otherTextures.profile.getName()))) { // We might need to rebuild the textures property for this profile: // TODO Only rebuild if the textures property actually stores an incompatible profileId/playerName? - this.ensureLoaded(); - this.markDirty(); - this.rebuildPropertyIfDirty(); + ensureLoaded(); + markDirty(); + rebuildPropertyIfDirty(); } } private void ensureLoaded() { - if (this.loaded) return; - this.loaded = true; + if (loaded) return; + loaded = true; - Property property = this.getProperty(); + Property property = getProperty(); if (property == null) return; - this.data = CraftProfileProperty.decodePropertyValue(property.value()); - if (this.data != null) { - JsonObject texturesMap = JsonHelper.getObjectOrNull(this.data, "textures"); - this.loadSkin(texturesMap); - this.loadCape(texturesMap); - this.loadTimestamp(); + data = CraftProfileProperty.decodePropertyValue(property.value()); + if (data != null) { + JsonObject texturesMap = JsonHelper.getObjectOrNull(data, "textures"); + loadSkin(texturesMap); + loadCape(texturesMap); + loadTimestamp(); } } @@ -111,12 +111,12 @@ private void loadSkin(@Nullable JsonObject texturesMap) { if (texture == null) return; String skinUrlString = JsonHelper.getStringOrNull(texture, "url"); - this.skin = CraftPlayerTextures.parseUrl(skinUrlString); - this.skinModel = CraftPlayerTextures.loadSkinModel(texture); + this.skin = parseUrl(skinUrlString); + this.skinModel = loadSkinModel(texture); // Special case: If a skin is present, but no skin model, we use the default classic skin model. - if (this.skinModel == null && this.skin != null) { - this.skinModel = SkinModel.CLASSIC; + if (skinModel == null && skin != null) { + skinModel = SkinModel.CLASSIC; } } @@ -127,7 +127,7 @@ private static SkinModel loadSkinModel(@Nullable JsonObject texture) { if (metadata == null) return null; String skinModelName = JsonHelper.getStringOrNull(metadata, "model"); - return CraftPlayerTextures.parseSkinModel(skinModelName); + return parseSkinModel(skinModelName); } private void loadCape(@Nullable JsonObject texturesMap) { @@ -136,12 +136,12 @@ private void loadCape(@Nullable JsonObject texturesMap) { if (texture == null) return; String skinUrlString = JsonHelper.getStringOrNull(texture, "url"); - this.cape = CraftPlayerTextures.parseUrl(skinUrlString); + this.cape = parseUrl(skinUrlString); } private void loadTimestamp() { - if (this.data == null) return; - JsonPrimitive timestamp = JsonHelper.getPrimitiveOrNull(this.data, "timestamp"); + if (data == null) return; + JsonPrimitive timestamp = JsonHelper.getPrimitiveOrNull(data, "timestamp"); if (timestamp == null) return; try { @@ -151,100 +151,100 @@ private void loadTimestamp() { } private void markDirty() { - this.dirty = true; + dirty = true; // Clear any cached but no longer valid data: - this.data = null; - this.timestamp = 0L; + data = null; + timestamp = 0L; } @Override public boolean isEmpty() { - this.ensureLoaded(); - return (this.skin == null) && (this.cape == null); + ensureLoaded(); + return (skin == null) && (cape == null); } @Override public void clear() { - this.profile.removeProperty(CraftPlayerTextures.PROPERTY_NAME); - this.loaded = false; - this.data = null; - this.timestamp = 0L; - this.skin = null; - this.skinModel = SkinModel.CLASSIC; - this.cape = null; - this.dirty = false; + profile.removeProperty(PROPERTY_NAME); + loaded = false; + data = null; + timestamp = 0L; + skin = null; + skinModel = SkinModel.CLASSIC; + cape = null; + dirty = false; } @Override public URL getSkin() { - this.ensureLoaded(); - return this.skin; + ensureLoaded(); + return skin; } @Override public void setSkin(URL skinUrl) { - this.setSkin(skinUrl, SkinModel.CLASSIC); + setSkin(skinUrl, SkinModel.CLASSIC); } @Override public void setSkin(URL skinUrl, SkinModel skinModel) { - CraftPlayerTextures.validateTextureUrl(skinUrl); + validateTextureUrl(skinUrl); if (skinModel == null) skinModel = SkinModel.CLASSIC; // This also loads the textures if necessary: - if (Objects.equals(this.getSkin(), skinUrl) && Objects.equals(this.getSkinModel(), skinModel)) return; + if (Objects.equals(getSkin(), skinUrl) && Objects.equals(getSkinModel(), skinModel)) return; this.skin = skinUrl; this.skinModel = (skinUrl != null) ? skinModel : SkinModel.CLASSIC; - this.markDirty(); + markDirty(); } @Override public SkinModel getSkinModel() { - this.ensureLoaded(); - return this.skinModel; + ensureLoaded(); + return skinModel; } @Override public URL getCape() { - this.ensureLoaded(); - return this.cape; + ensureLoaded(); + return cape; } @Override public void setCape(URL capeUrl) { - CraftPlayerTextures.validateTextureUrl(capeUrl); + validateTextureUrl(capeUrl); // This also loads the textures if necessary: - if (Objects.equals(this.getCape(), capeUrl)) return; + if (Objects.equals(getCape(), capeUrl)) return; this.cape = capeUrl; - this.markDirty(); + markDirty(); } @Override public long getTimestamp() { - this.ensureLoaded(); - return this.timestamp; + ensureLoaded(); + return timestamp; } @Override public boolean isSigned() { - if (this.dirty) return false; - Property property = this.getProperty(); + if (dirty) return false; + Property property = getProperty(); return property != null && CraftProfileProperty.hasValidSignature(property); } @Nullable Property getProperty() { - this.rebuildPropertyIfDirty(); - return this.profile.getProperty(CraftPlayerTextures.PROPERTY_NAME); + rebuildPropertyIfDirty(); + return profile.getProperty(PROPERTY_NAME); } void rebuildPropertyIfDirty() { - if (!this.dirty) return; + if (!dirty) return; // Assert: loaded - this.dirty = false; + dirty = false; - if (this.isEmpty()) { - this.profile.removeProperty(CraftPlayerTextures.PROPERTY_NAME); + if (isEmpty()) { + profile.removeProperty(PROPERTY_NAME); return; } @@ -256,23 +256,23 @@ void rebuildPropertyIfDirty() { // The order of Json object elements is important. JsonObject propertyData = new JsonObject(); - if (this.skin != null) { + if (skin != null) { JsonObject texturesMap = JsonHelper.getOrCreateObject(propertyData, "textures"); JsonObject skinTexture = JsonHelper.getOrCreateObject(texturesMap, MinecraftProfileTexture.Type.SKIN.name()); - skinTexture.addProperty("url", this.skin.toExternalForm()); + skinTexture.addProperty("url", skin.toExternalForm()); // Special case: If the skin model is classic (i.e. default), omit it. // Assert: skinModel != null - if (this.skinModel != SkinModel.CLASSIC) { + if (skinModel != SkinModel.CLASSIC) { JsonObject metadata = JsonHelper.getOrCreateObject(skinTexture, "metadata"); - metadata.addProperty("model", this.skinModel.name().toLowerCase(Locale.ROOT)); + metadata.addProperty("model", skinModel.name().toLowerCase(Locale.ROOT)); } } - if (this.cape != null) { + if (cape != null) { JsonObject texturesMap = JsonHelper.getOrCreateObject(propertyData, "textures"); JsonObject skinTexture = JsonHelper.getOrCreateObject(texturesMap, MinecraftProfileTexture.Type.CAPE.name()); - skinTexture.addProperty("url", this.cape.toExternalForm()); + skinTexture.addProperty("url", cape.toExternalForm()); } this.data = propertyData; @@ -280,28 +280,28 @@ void rebuildPropertyIfDirty() { // We use the compact formatter here since this is more likely to match the output of existing popular tools // that also create profiles with custom textures: String encodedTexturesData = CraftProfileProperty.encodePropertyValue(propertyData, CraftProfileProperty.JsonFormatter.COMPACT); - Property property = new Property(CraftPlayerTextures.PROPERTY_NAME, encodedTexturesData); - this.profile.setProperty(CraftPlayerTextures.PROPERTY_NAME, property); + Property property = new Property(PROPERTY_NAME, encodedTexturesData); + profile.setProperty(PROPERTY_NAME, property); } private JsonObject getData() { - this.ensureLoaded(); - this.rebuildPropertyIfDirty(); - return this.data; + ensureLoaded(); + rebuildPropertyIfDirty(); + return data; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("CraftPlayerTextures [data="); - builder.append(this.getData()); + builder.append(getData()); builder.append("]"); return builder.toString(); } @Override public int hashCode() { - Property property = this.getProperty(); + Property property = getProperty(); return (property == null) ? 0 : CraftProfileProperty.hashCode(property); } @@ -310,7 +310,7 @@ public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof CraftPlayerTextures)) return false; CraftPlayerTextures other = (CraftPlayerTextures) obj; - Property property = this.getProperty(); + Property property = getProperty(); Property otherProperty = other.getProperty(); return CraftProfileProperty.equals(property, otherProperty); } diff --git a/src/main/java/org/bukkit/craftbukkit/profile/CraftProfileProperty.java b/src/main/java/org/bukkit/craftbukkit/profile/CraftProfileProperty.java index 63a13192..2268abcc 100644 --- a/src/main/java/org/bukkit/craftbukkit/profile/CraftProfileProperty.java +++ b/src/main/java/org/bukkit/craftbukkit/profile/CraftProfileProperty.java @@ -36,7 +36,7 @@ public interface JsonFormatter { @Override public String format(JsonElement jsonElement) { - return this.gson.toJson(jsonElement); + return gson.toJson(jsonElement); } }; @@ -54,7 +54,7 @@ public String format(JsonElement jsonElement) { } public static boolean hasValidSignature(@Nonnull Property property) { - return property.hasSignature() && CraftProfileProperty.PUBLIC_KEYS.keys(ServicesKeyType.PROFILE_PROPERTY).stream().anyMatch((key) -> key.validateProperty(property)); + return property.hasSignature() && PUBLIC_KEYS.keys(ServicesKeyType.PROFILE_PROPERTY).stream().anyMatch((key) -> key.validateProperty(property)); } @Nullable @@ -68,7 +68,7 @@ private static String decodeBase64(@Nonnull String encoded) { @Nullable public static JsonObject decodePropertyValue(@Nonnull String encodedPropertyValue) { - String json = CraftProfileProperty.decodeBase64(encodedPropertyValue); + String json = decodeBase64(encodedPropertyValue); if (json == null) return null; try { JsonElement jsonElement = JsonParser.parseString(json); diff --git a/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java b/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java index 8b570445..aedca773 100644 --- a/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java +++ b/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java @@ -1,142 +1,143 @@ package org.bukkit.craftbukkit.projectiles; import com.google.common.base.Preconditions; -import net.minecraft.core.Direction; -import net.minecraft.core.Position; -import net.minecraft.core.dispenser.BlockSource; -import net.minecraft.server.level.ServerLevel; +import net.minecraft.core.EnumDirection; +import net.minecraft.core.IPosition; +import net.minecraft.core.dispenser.SourceBlock; +import net.minecraft.server.level.WorldServer; import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; -import net.minecraft.world.entity.projectile.ThrowableProjectile; -import net.minecraft.world.entity.projectile.ThrownEgg; -import net.minecraft.world.entity.projectile.ThrownEnderpearl; -import net.minecraft.world.entity.projectile.ThrownExperienceBottle; -import net.minecraft.world.level.block.DispenserBlock; -import net.minecraft.world.level.block.entity.DispenserBlockEntity; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.projectile.EntityArrow; +import net.minecraft.world.entity.projectile.EntityFireball; +import net.minecraft.world.entity.projectile.IProjectile; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.ProjectileItem; +import net.minecraft.world.level.block.BlockDispenser; +import net.minecraft.world.level.block.entity.TileEntityDispenser; +import net.minecraft.world.phys.Vec3D; import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.Arrow; +import org.bukkit.entity.AbstractWindCharge; +import org.bukkit.entity.BreezeWindCharge; +import org.bukkit.entity.DragonFireball; import org.bukkit.entity.Egg; import org.bukkit.entity.EnderPearl; import org.bukkit.entity.Fireball; +import org.bukkit.entity.Firework; +import org.bukkit.entity.LargeFireball; import org.bukkit.entity.LingeringPotion; import org.bukkit.entity.Projectile; -import org.bukkit.entity.SmallFireball; import org.bukkit.entity.Snowball; import org.bukkit.entity.SpectralArrow; import org.bukkit.entity.ThrownExpBottle; import org.bukkit.entity.ThrownPotion; import org.bukkit.entity.TippedArrow; import org.bukkit.entity.WitherSkull; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionType; import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.util.Vector; public class CraftBlockProjectileSource implements BlockProjectileSource { - private final DispenserBlockEntity dispenserBlock; + private final TileEntityDispenser dispenserBlock; - public CraftBlockProjectileSource(DispenserBlockEntity dispenserBlock) { + public CraftBlockProjectileSource(TileEntityDispenser dispenserBlock) { this.dispenserBlock = dispenserBlock; } @Override public Block getBlock() { - return this.dispenserBlock.getLevel().getWorld().getBlockAt(this.dispenserBlock.getBlockPos().getX(), this.dispenserBlock.getBlockPos().getY(), this.dispenserBlock.getBlockPos().getZ()); + return dispenserBlock.getLevel().getWorld().getBlockAt(dispenserBlock.getBlockPos().getX(), dispenserBlock.getBlockPos().getY(), dispenserBlock.getBlockPos().getZ()); } @Override public T launchProjectile(Class projectile) { - return this.launchProjectile(projectile, null); + return launchProjectile(projectile, null); } @Override public T launchProjectile(Class projectile, Vector velocity) { - Preconditions.checkArgument(this.getBlock().getType() == Material.DISPENSER, "Block is no longer dispenser"); + Preconditions.checkArgument(getBlock().getType() == Material.DISPENSER, "Block is no longer dispenser"); // Copied from BlockDispenser.dispense() - BlockSource sourceblock = new BlockSource((ServerLevel) this.dispenserBlock.getLevel(), this.dispenserBlock.getBlockPos(), this.dispenserBlock.getBlockState(), this.dispenserBlock); + SourceBlock sourceblock = new SourceBlock((WorldServer) dispenserBlock.getLevel(), dispenserBlock.getBlockPos(), dispenserBlock.getBlockState(), dispenserBlock); // Copied from DispenseBehaviorProjectile - Position iposition = DispenserBlock.getDispensePosition(sourceblock); - Direction enumdirection = (Direction) sourceblock.state().getValue(DispenserBlock.FACING); - net.minecraft.world.level.Level world = this.dispenserBlock.getLevel(); - net.minecraft.world.entity.Entity launch = null; + EnumDirection enumdirection = (EnumDirection) sourceblock.state().getValue(BlockDispenser.FACING); + net.minecraft.world.level.World world = dispenserBlock.getLevel(); + net.minecraft.world.item.Item item = null; if (Snowball.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.Snowball(world, iposition.x(), iposition.y(), iposition.z()); + item = Items.SNOWBALL; } else if (Egg.class.isAssignableFrom(projectile)) { - launch = new ThrownEgg(world, iposition.x(), iposition.y(), iposition.z()); + item = Items.EGG; } else if (EnderPearl.class.isAssignableFrom(projectile)) { - launch = new ThrownEnderpearl(world, null); - launch.setPos(iposition.x(), iposition.y(), iposition.z()); + item = Items.ENDER_PEARL; } else if (ThrownExpBottle.class.isAssignableFrom(projectile)) { - launch = new ThrownExperienceBottle(world, iposition.x(), iposition.y(), iposition.z()); + item = Items.EXPERIENCE_BOTTLE; } else if (ThrownPotion.class.isAssignableFrom(projectile)) { if (LingeringPotion.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.ThrownPotion(world, iposition.x(), iposition.y(), iposition.z()); - ((net.minecraft.world.entity.projectile.ThrownPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); + item = Items.LINGERING_POTION; } else { - launch = new net.minecraft.world.entity.projectile.ThrownPotion(world, iposition.x(), iposition.y(), iposition.z()); - ((net.minecraft.world.entity.projectile.ThrownPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.SPLASH_POTION, 1))); + item = Items.SPLASH_POTION; } } else if (AbstractArrow.class.isAssignableFrom(projectile)) { if (TippedArrow.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.Arrow(world, iposition.x(), iposition.y(), iposition.z(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.ARROW), null); - ((Arrow) launch.getBukkitEntity()).setBasePotionType(PotionType.WATER); + item = Items.TIPPED_ARROW; } else if (SpectralArrow.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.SpectralArrow(world, iposition.x(), iposition.y(), iposition.z(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.SPECTRAL_ARROW), null); + item = Items.SPECTRAL_ARROW; } else { - launch = new net.minecraft.world.entity.projectile.Arrow(world, iposition.x(), iposition.y(), iposition.z(), new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.ARROW), null); + item = Items.ARROW; } - ((net.minecraft.world.entity.projectile.AbstractArrow) launch).pickup = net.minecraft.world.entity.projectile.AbstractArrow.Pickup.ALLOWED; - ((net.minecraft.world.entity.projectile.AbstractArrow) launch).projectileSource = this; } else if (Fireball.class.isAssignableFrom(projectile)) { - double d0 = iposition.x() + (double) ((float) enumdirection.getStepX() * 0.3F); - double d1 = iposition.y() + (double) ((float) enumdirection.getStepY() * 0.3F); - double d2 = iposition.z() + (double) ((float) enumdirection.getStepZ() * 0.3F); - RandomSource random = world.random; - double d3 = random.nextGaussian() * 0.05D + (double) enumdirection.getStepX(); - double d4 = random.nextGaussian() * 0.05D + (double) enumdirection.getStepY(); - double d5 = random.nextGaussian() * 0.05D + (double) enumdirection.getStepZ(); - - if (SmallFireball.class.isAssignableFrom(projectile)) { - launch = new net.minecraft.world.entity.projectile.SmallFireball(world, null, new Vec3(d0, d1, d2)); - } else if (WitherSkull.class.isAssignableFrom(projectile)) { - launch = EntityType.WITHER_SKULL.create(world); - launch.setPos(d0, d1, d2); - - ((AbstractHurtingProjectile) launch).assignDirectionalMovement(new Vec3(d3, d4, d5), 0.1D); + if (AbstractWindCharge.class.isAssignableFrom(projectile)) { + item = Items.WIND_CHARGE; } else { - launch = EntityType.FIREBALL.create(world); - launch.setPos(d0, d1, d2); - - ((AbstractHurtingProjectile) launch).assignDirectionalMovement(new Vec3(d3, d4, d5), 0.1D); + item = Items.FIRE_CHARGE; } - - ((AbstractHurtingProjectile) launch).projectileSource = this; + } else if (Firework.class.isAssignableFrom(projectile)) { + item = Items.FIREWORK_ROCKET; } - Preconditions.checkArgument(launch != null, "Projectile not supported"); + Preconditions.checkArgument(item instanceof ProjectileItem, "Projectile not supported"); + + ItemStack itemstack = new ItemStack(item); + ProjectileItem projectileItem = (ProjectileItem) item; + ProjectileItem.a dispenseConfig = projectileItem.createDispenseConfig(); + + IPosition iposition = dispenseConfig.positionFunction().getDispensePosition(sourceblock, enumdirection); + IProjectile launch = projectileItem.asProjectile(world, iposition, itemstack, enumdirection); - if (launch instanceof net.minecraft.world.entity.projectile.Projectile) { - if (launch instanceof ThrowableProjectile) { - ((ThrowableProjectile) launch).projectileSource = this; + if (Fireball.class.isAssignableFrom(projectile)) { + EntityFireball customFireball = null; + if (WitherSkull.class.isAssignableFrom(projectile)) { + launch = customFireball = EntityTypes.WITHER_SKULL.create(world, EntitySpawnReason.TRIGGERED); + } else if (DragonFireball.class.isAssignableFrom(projectile)) { + launch = EntityTypes.DRAGON_FIREBALL.create(world, EntitySpawnReason.TRIGGERED); + } else if (BreezeWindCharge.class.isAssignableFrom(projectile)) { + launch = customFireball = EntityTypes.BREEZE_WIND_CHARGE.create(world, EntitySpawnReason.TRIGGERED); + } else if (LargeFireball.class.isAssignableFrom(projectile)) { + launch = customFireball = EntityTypes.FIREBALL.create(world, EntitySpawnReason.TRIGGERED); } - // Values from DispenseBehaviorProjectile - float a = 6.0F; - float b = 1.1F; - if (launch instanceof net.minecraft.world.entity.projectile.ThrownPotion || launch instanceof ThrownExpBottle) { - // Values from respective DispenseBehavior classes - a *= 0.5F; - b *= 1.25F; + + if (customFireball != null) { + customFireball.setPos(iposition.x(), iposition.y(), iposition.z()); + + // Values from ItemFireball + RandomSource randomsource = world.getRandom(); + double d0 = randomsource.triangle((double) enumdirection.getStepX(), 0.11485000000000001D); + double d1 = randomsource.triangle((double) enumdirection.getStepY(), 0.11485000000000001D); + double d2 = randomsource.triangle((double) enumdirection.getStepZ(), 0.11485000000000001D); + Vec3D vec3d = new Vec3D(d0, d1, d2); + customFireball.assignDirectionalMovement(vec3d, 0.1D); } - // Copied from DispenseBehaviorProjectile - ((net.minecraft.world.entity.projectile.Projectile) launch).shoot((double) enumdirection.getStepX(), (double) ((float) enumdirection.getStepY() + 0.1F), (double) enumdirection.getStepZ(), b, a); } + if (launch instanceof EntityArrow arrow) { + arrow.pickup = EntityArrow.PickupStatus.ALLOWED; + } + launch.projectileSource = this; + projectileItem.shoot(launch, (double) enumdirection.getStepX(), (double) enumdirection.getStepY(), (double) enumdirection.getStepZ(), dispenseConfig.power(), dispenseConfig.uncertainty()); + if (velocity != null) { ((T) launch.getBukkitEntity()).setVelocity(velocity); } diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java index 365b7e7c..fd32d145 100644 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java +++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java @@ -25,13 +25,13 @@ public boolean isSync() { @Override public void run() { final Thread thread = Thread.currentThread(); - synchronized (this.workers) { - if (this.getPeriod() == CraftTask.CANCEL) { + synchronized (workers) { + if (getPeriod() == CraftTask.CANCEL) { // Never continue running after cancelled. // Checking this with the lock is important! return; } - this.workers.add( + workers.add( new BukkitWorker() { @Override public Thread getThread() { @@ -54,16 +54,16 @@ public Plugin getOwner() { super.run(); } catch (final Throwable t) { thrown = t; - this.getOwner().getLogger().log( + getOwner().getLogger().log( Level.WARNING, String.format( "Plugin %s generated an exception while executing task %s", - this.getOwner().getDescription().getFullName(), - this.getTaskId()), + getOwner().getDescription().getFullName(), + getTaskId()), thrown); } finally { // Cleanup is important for any async task, otherwise ghost tasks are everywhere - synchronized (this.workers) { + synchronized (workers) { try { final Iterator workers = this.workers.iterator(); boolean removed = false; @@ -79,15 +79,15 @@ public Plugin getOwner() { String.format( "Unable to remove worker %s on task %s for %s", thread.getName(), - this.getTaskId(), - this.getOwner().getDescription().getFullName()), + getTaskId(), + getOwner().getDescription().getFullName()), thrown); // We don't want to lose the original exception, if any } } finally { - if (this.getPeriod() < 0 && this.workers.isEmpty()) { + if (getPeriod() < 0 && workers.isEmpty()) { // At this spot, we know we are the final async task being executed! // Because we have the lock, nothing else is running or will run because delay < 0 - this.runners.remove(this.getTaskId()); + runners.remove(getTaskId()); } } } @@ -95,16 +95,16 @@ public Plugin getOwner() { } LinkedList getWorkers() { - return this.workers; + return workers; } @Override boolean cancel0() { - synchronized (this.workers) { + synchronized (workers) { // Synchronizing here prevents race condition for a completing task - this.setPeriod(CraftTask.CANCEL); - if (this.workers.isEmpty()) { - this.runners.remove(this.getTaskId()); + setPeriod(CraftTask.CANCEL); + if (workers.isEmpty()) { + runners.remove(getTaskId()); } } return true; diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java index c587adad..1e20385f 100644 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java +++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java @@ -21,10 +21,10 @@ class CraftFuture extends CraftTask implements Future { @Override public synchronized boolean cancel(final boolean mayInterruptIfRunning) { - if (this.getPeriod() != CraftTask.NO_REPEATING) { + if (getPeriod() != CraftTask.NO_REPEATING) { return false; } - this.setPeriod(CraftTask.CANCEL); + setPeriod(CraftTask.CANCEL); return true; } @@ -37,7 +37,7 @@ public boolean isDone() { @Override public T get() throws CancellationException, InterruptedException, ExecutionException { try { - return this.get(0, TimeUnit.MILLISECONDS); + return get(0, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { throw new Error(e); } @@ -67,10 +67,10 @@ public synchronized T get(long timeout, final TimeUnit unit) throws InterruptedE throw new CancellationException(); } if (period == CraftTask.DONE_FOR_FUTURE) { - if (this.exception == null) { - return this.value; + if (exception == null) { + return value; } - throw new ExecutionException(this.exception); + throw new ExecutionException(exception); } throw new IllegalStateException("Expected " + CraftTask.NO_REPEATING + " to " + CraftTask.DONE_FOR_FUTURE + ", got " + period); } @@ -79,18 +79,18 @@ public synchronized T get(long timeout, final TimeUnit unit) throws InterruptedE @Override public void run() { synchronized (this) { - if (this.getPeriod() == CraftTask.CANCEL) { + if (getPeriod() == CraftTask.CANCEL) { return; } - this.setPeriod(CraftTask.PROCESS_FOR_FUTURE); + setPeriod(CraftTask.PROCESS_FOR_FUTURE); } try { - this.value = this.callable.call(); + value = callable.call(); } catch (final Exception e) { - this.exception = e; + exception = e; } finally { synchronized (this) { - this.setPeriod(CraftTask.DONE_FOR_FUTURE); + setPeriod(CraftTask.DONE_FOR_FUTURE); this.notifyAll(); } } @@ -98,11 +98,11 @@ public void run() { @Override synchronized boolean cancel0() { - if (this.getPeriod() != CraftTask.NO_REPEATING) { + if (getPeriod() != CraftTask.NO_REPEATING) { return false; } - this.setPeriod(CraftTask.CANCEL); - this.notifyAll(); + setPeriod(CraftTask.CANCEL); + notifyAll(); return true; } } diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java index 905adf97..e504fbb0 100644 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java +++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java @@ -54,14 +54,14 @@ public class CraftScheduler implements BukkitScheduler { private static final IntUnaryOperator INCREMENT_IDS = previous -> { // We reached the end, go back to the start! if (previous == Integer.MAX_VALUE) { - return CraftScheduler.START_ID; + return START_ID; } return previous + 1; }; /** * Counter for IDs. Order doesn't matter, only uniqueness. */ - private final AtomicInteger ids = new AtomicInteger(CraftScheduler.START_ID); + private final AtomicInteger ids = new AtomicInteger(START_ID); /** * Current head of linked-list. This reference is always stale, {@link CraftTask#next} is the live reference. */ @@ -69,7 +69,7 @@ public class CraftScheduler implements BukkitScheduler { /** * Tail of a linked-list. AtomicReference only matters when adding to queue */ - private final AtomicReference tail = new AtomicReference(this.head); + private final AtomicReference tail = new AtomicReference(head); /** * Main thread logic only */ @@ -103,7 +103,7 @@ StringBuilder debugTo(StringBuilder string) { return string; } }; - private CraftAsyncDebugger debugTail = this.debugHead; + private CraftAsyncDebugger debugTail = debugHead; private static final int RECENT_TICKS; static { @@ -117,12 +117,12 @@ public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable task) { @Override public BukkitTask runTask(Plugin plugin, Runnable runnable) { - return this.runTaskLater(plugin, runnable, 0L); + return runTaskLater(plugin, runnable, 0L); } @Override public void runTask(Plugin plugin, Consumer task) throws IllegalArgumentException { - this.runTaskLater(plugin, task, 0L); + runTaskLater(plugin, task, 0L); } @Deprecated @@ -133,12 +133,12 @@ public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable task) { @Override public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable runnable) { - return this.runTaskLaterAsynchronously(plugin, runnable, 0L); + return runTaskLaterAsynchronously(plugin, runnable, 0L); } @Override public void runTaskAsynchronously(Plugin plugin, Consumer task) throws IllegalArgumentException { - this.runTaskLaterAsynchronously(plugin, task, 0L); + runTaskLaterAsynchronously(plugin, task, 0L); } @Override @@ -148,12 +148,12 @@ public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable task, fin @Override public BukkitTask runTaskLater(Plugin plugin, Runnable runnable, long delay) { - return this.runTaskTimer(plugin, runnable, delay, CraftTask.NO_REPEATING); + return runTaskTimer(plugin, runnable, delay, CraftTask.NO_REPEATING); } @Override public void runTaskLater(Plugin plugin, Consumer task, long delay) throws IllegalArgumentException { - this.runTaskTimer(plugin, task, delay, CraftTask.NO_REPEATING); + runTaskTimer(plugin, task, delay, CraftTask.NO_REPEATING); } @Deprecated @@ -164,36 +164,36 @@ public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable task, fi @Override public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable runnable, long delay) { - return this.runTaskTimerAsynchronously(plugin, runnable, delay, CraftTask.NO_REPEATING); + return runTaskTimerAsynchronously(plugin, runnable, delay, CraftTask.NO_REPEATING); } @Override public void runTaskLaterAsynchronously(Plugin plugin, Consumer task, long delay) throws IllegalArgumentException { - this.runTaskTimerAsynchronously(plugin, task, delay, CraftTask.NO_REPEATING); + runTaskTimerAsynchronously(plugin, task, delay, CraftTask.NO_REPEATING); } @Override public void runTaskTimerAsynchronously(Plugin plugin, Consumer task, long delay, long period) throws IllegalArgumentException { - this.runTaskTimerAsynchronously(plugin, (Object) task, delay, CraftTask.NO_REPEATING); + runTaskTimerAsynchronously(plugin, (Object) task, delay, CraftTask.NO_REPEATING); } @Override public int scheduleSyncRepeatingTask(final Plugin plugin, final Runnable runnable, long delay, long period) { - return this.runTaskTimer(plugin, runnable, delay, period).getTaskId(); + return runTaskTimer(plugin, runnable, delay, period).getTaskId(); } @Override public BukkitTask runTaskTimer(Plugin plugin, Runnable runnable, long delay, long period) { - return this.runTaskTimer(plugin, (Object) runnable, delay, period); + return runTaskTimer(plugin, (Object) runnable, delay, period); } @Override public void runTaskTimer(Plugin plugin, Consumer task, long delay, long period) throws IllegalArgumentException { - this.runTaskTimer(plugin, (Object) task, delay, period); + runTaskTimer(plugin, (Object) task, delay, period); } public BukkitTask runTaskTimer(Plugin plugin, Object runnable, long delay, long period) { - CraftScheduler.validate(plugin, runnable); + validate(plugin, runnable); if (delay < 0L) { delay = 0; } @@ -202,22 +202,22 @@ public BukkitTask runTaskTimer(Plugin plugin, Object runnable, long delay, long } else if (period < CraftTask.NO_REPEATING) { period = CraftTask.NO_REPEATING; } - return this.handle(new CraftTask(plugin, runnable, this.nextId(), period), delay); + return handle(new CraftTask(plugin, runnable, nextId(), period), delay); } @Deprecated @Override public int scheduleAsyncRepeatingTask(final Plugin plugin, final Runnable runnable, long delay, long period) { - return this.runTaskTimerAsynchronously(plugin, runnable, delay, period).getTaskId(); + return runTaskTimerAsynchronously(plugin, runnable, delay, period).getTaskId(); } @Override public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable runnable, long delay, long period) { - return this.runTaskTimerAsynchronously(plugin, (Object) runnable, delay, period); + return runTaskTimerAsynchronously(plugin, (Object) runnable, delay, period); } public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Object runnable, long delay, long period) { - CraftScheduler.validate(plugin, runnable); + validate(plugin, runnable); if (delay < 0L) { delay = 0; } @@ -226,14 +226,14 @@ public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Object runnable, lon } else if (period < CraftTask.NO_REPEATING) { period = CraftTask.NO_REPEATING; } - return this.handle(new CraftAsyncTask(this.runners, plugin, runnable, this.nextId(), period), delay); + return handle(new CraftAsyncTask(runners, plugin, runnable, nextId(), period), delay); } @Override public Future callSyncMethod(final Plugin plugin, final Callable task) { - CraftScheduler.validate(plugin, task); - final CraftFuture future = new CraftFuture(task, plugin, this.nextId()); - this.handle(future, 0L); + validate(plugin, task); + final CraftFuture future = new CraftFuture(task, plugin, nextId()); + handle(future, 0L); return future; } @@ -242,7 +242,7 @@ public void cancelTask(final int taskId) { if (taskId <= 0) { return; } - CraftTask task = this.runners.get(taskId); + CraftTask task = runners.get(taskId); if (task != null) { task.cancel0(); } @@ -250,8 +250,8 @@ public void cancelTask(final int taskId) { new Runnable() { @Override public void run() { - if (!this.check(CraftScheduler.this.temp)) { - this.check(CraftScheduler.this.pending); + if (!check(CraftScheduler.this.temp)) { + check(CraftScheduler.this.pending); } } private boolean check(final Iterable collection) { @@ -262,7 +262,7 @@ private boolean check(final Iterable collection) { task.cancel0(); tasks.remove(); if (task.isSync()) { - CraftScheduler.this.runners.remove(taskId); + runners.remove(taskId); } return true; } @@ -270,8 +270,8 @@ private boolean check(final Iterable collection) { return false; } }); - this.handle(task, 0L); - for (CraftTask taskPending = this.head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { + handle(task, 0L); + for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { if (taskPending == task) { return; } @@ -288,8 +288,8 @@ public void cancelTasks(final Plugin plugin) { new Runnable() { @Override public void run() { - this.check(CraftScheduler.this.pending); - this.check(CraftScheduler.this.temp); + check(CraftScheduler.this.pending); + check(CraftScheduler.this.temp); } void check(final Iterable collection) { final Iterator tasks = collection.iterator(); @@ -299,14 +299,14 @@ void check(final Iterable collection) { task.cancel0(); tasks.remove(); if (task.isSync()) { - CraftScheduler.this.runners.remove(task.getTaskId()); + runners.remove(task.getTaskId()); } } } } }); - this.handle(task, 0L); - for (CraftTask taskPending = this.head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { + handle(task, 0L); + for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { if (taskPending == task) { break; } @@ -314,7 +314,7 @@ void check(final Iterable collection) { taskPending.cancel0(); } } - for (CraftTask runner : this.runners.values()) { + for (CraftTask runner : runners.values()) { if (runner.getOwner().equals(plugin)) { runner.cancel0(); } @@ -323,12 +323,12 @@ void check(final Iterable collection) { @Override public boolean isCurrentlyRunning(final int taskId) { - final CraftTask task = this.runners.get(taskId); + final CraftTask task = runners.get(taskId); if (task == null) { return false; } if (task.isSync()) { - return (task == this.currentTask); + return (task == currentTask); } final CraftAsyncTask asyncTask = (CraftAsyncTask) task; synchronized (asyncTask.getWorkers()) { @@ -341,19 +341,19 @@ public boolean isQueued(final int taskId) { if (taskId <= 0) { return false; } - for (CraftTask task = this.head.getNext(); task != null; task = task.getNext()) { + for (CraftTask task = head.getNext(); task != null; task = task.getNext()) { if (task.getTaskId() == taskId) { return task.getPeriod() >= CraftTask.NO_REPEATING; // The task will run } } - CraftTask task = this.runners.get(taskId); + CraftTask task = runners.get(taskId); return task != null && task.getPeriod() >= CraftTask.NO_REPEATING; } @Override public List getActiveWorkers() { final ArrayList workers = new ArrayList(); - for (final CraftTask taskObj : this.runners.values()) { + for (final CraftTask taskObj : runners.values()) { // Iterator will be a best-effort (may fail to grab very new values) if called from an async thread if (taskObj.isSync()) { continue; @@ -370,7 +370,7 @@ public List getActiveWorkers() { @Override public List getPendingTasks() { final ArrayList truePending = new ArrayList(); - for (CraftTask task = this.head.getNext(); task != null; task = task.getNext()) { + for (CraftTask task = head.getNext(); task != null; task = task.getNext()) { if (task.getTaskId() != -1) { // -1 is special code truePending.add(task); @@ -378,7 +378,7 @@ public List getPendingTasks() { } final ArrayList pending = new ArrayList(); - for (CraftTask task : this.runners.values()) { + for (CraftTask task : runners.values()) { if (task.getPeriod() >= CraftTask.NO_REPEATING) { pending.add(task); } @@ -395,25 +395,23 @@ public List getPendingTasks() { /** * This method is designed to never block or wait for locks; an immediate execution of all current tasks. */ - public void mainThreadHeartbeat(final int currentTick) { - this.currentTick = currentTick; + public void mainThreadHeartbeat() { + this.currentTick++; final List temp = this.temp; - this.parsePending(); - while (this.isReady(currentTick)) { - final CraftTask task = this.pending.remove(); + parsePending(); + while (isReady(currentTick)) { + final CraftTask task = pending.remove(); if (task.getPeriod() < CraftTask.NO_REPEATING) { if (task.isSync()) { - this.runners.remove(task.getTaskId(), task); + runners.remove(task.getTaskId(), task); } - this.parsePending(); + parsePending(); continue; } if (task.isSync()) { - this.currentTask = task; + currentTask = task; try { - task.timings.startTiming(); // Spigot task.run(); - task.timings.stopTiming(); // Spigot } catch (final Throwable throwable) { task.getOwner().getLogger().log( Level.WARNING, @@ -423,12 +421,12 @@ public void mainThreadHeartbeat(final int currentTick) { task.getOwner().getDescription().getFullName()), throwable); } finally { - this.currentTask = null; + currentTask = null; } - this.parsePending(); + parsePending(); } else { - this.debugTail = this.debugTail.setNext(new CraftAsyncDebugger(currentTick + CraftScheduler.RECENT_TICKS, task.getOwner(), task.getTaskClass())); - this.executor.execute(task); + debugTail = debugTail.setNext(new CraftAsyncDebugger(currentTick + RECENT_TICKS, task.getOwner(), task.getTaskClass())); + executor.execute(task); // We don't need to parse pending // (async tasks must live with race-conditions if they attempt to cancel between these few lines of code) } @@ -437,12 +435,12 @@ public void mainThreadHeartbeat(final int currentTick) { task.setNextRun(currentTick + period); temp.add(task); } else if (task.isSync()) { - this.runners.remove(task.getTaskId()); + runners.remove(task.getTaskId()); } } - this.pending.addAll(temp); + pending.addAll(temp); temp.clear(); - this.debugHead = this.debugHead.getNextHead(currentTick); + debugHead = debugHead.getNextHead(currentTick); } private void addTask(final CraftTask task) { @@ -455,8 +453,8 @@ private void addTask(final CraftTask task) { } private CraftTask handle(final CraftTask task, final long delay) { - task.setNextRun(this.currentTick + delay); - this.addTask(task); + task.setNextRun(currentTick + delay); + addTask(task); return task; } @@ -469,11 +467,11 @@ private static void validate(final Plugin plugin, final Object task) { } private int nextId() { - Preconditions.checkArgument(this.runners.size() < Integer.MAX_VALUE, "There are already %s tasks scheduled! Cannot schedule more", Integer.MAX_VALUE); + Preconditions.checkArgument(runners.size() < Integer.MAX_VALUE, "There are already %s tasks scheduled! Cannot schedule more", Integer.MAX_VALUE); int id; do { - id = this.ids.updateAndGet(CraftScheduler.INCREMENT_IDS); - } while (this.runners.containsKey(id)); // Avoid generating duplicate IDs + id = ids.updateAndGet(INCREMENT_IDS); + } while (runners.containsKey(id)); // Avoid generating duplicate IDs return id; } @@ -485,8 +483,8 @@ private void parsePending() { if (task.getTaskId() == -1) { task.run(); } else if (task.getPeriod() >= CraftTask.NO_REPEATING) { - this.pending.add(task); - this.runners.put(task.getTaskId(), task); + pending.add(task); + runners.put(task.getTaskId(), task); } } // We split this because of the way things are ordered for all of the async calls in CraftScheduler @@ -499,14 +497,14 @@ private void parsePending() { } private boolean isReady(final int currentTick) { - return !this.pending.isEmpty() && this.pending.peek().getNextRun() <= currentTick; + return !pending.isEmpty() && pending.peek().getNextRun() <= currentTick; } @Override public String toString() { - int debugTick = this.currentTick; - StringBuilder string = new StringBuilder("Recent tasks from ").append(debugTick - CraftScheduler.RECENT_TICKS).append('-').append(debugTick).append('{'); - this.debugHead.debugTo(string); + int debugTick = currentTick; + StringBuilder string = new StringBuilder("Recent tasks from ").append(debugTick - RECENT_TICKS).append('-').append(debugTick).append('{'); + debugHead.debugTo(string); return string.append('}').toString(); } diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java index e4d1eb4a..c885bc74 100644 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java +++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java @@ -5,10 +5,7 @@ import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; -import org.bukkit.craftbukkit.SpigotTimings; // Spigot -import org.spigotmc.CustomTimingsHandler; // Spigot - -public class CraftTask implements BukkitTask, Runnable { // Spigot +class CraftTask implements BukkitTask, Runnable { private volatile CraftTask next = null; public static final int ERROR = 0; @@ -32,7 +29,6 @@ public class CraftTask implements BukkitTask, Runnable { // Spigot private final int id; private final long createdAt = System.nanoTime(); - final CustomTimingsHandler timings; // Spigot CraftTask() { this(null, null, CraftTask.NO_REPEATING, CraftTask.NO_REPEATING); } @@ -58,17 +54,16 @@ public class CraftTask implements BukkitTask, Runnable { // Spigot } this.id = id; this.period = period; - this.timings = this.isSync() ? SpigotTimings.getPluginTaskTimings(this, period) : null; // Spigot } @Override public final int getTaskId() { - return this.id; + return id; } @Override public final Plugin getOwner() { - return this.plugin; + return plugin; } @Override @@ -78,19 +73,19 @@ public boolean isSync() { @Override public void run() { - if (this.rTask != null) { - this.rTask.run(); + if (rTask != null) { + rTask.run(); } else { - this.cTask.accept(this); + cTask.accept(this); } } long getCreatedAt() { - return this.createdAt; + return createdAt; } long getPeriod() { - return this.period; + return period; } void setPeriod(long period) { @@ -98,7 +93,7 @@ void setPeriod(long period) { } long getNextRun() { - return this.nextRun; + return nextRun; } void setNextRun(long nextRun) { @@ -106,7 +101,7 @@ void setNextRun(long nextRun) { } CraftTask getNext() { - return this.next; + return next; } void setNext(CraftTask next) { @@ -114,17 +109,17 @@ void setNext(CraftTask next) { } Class getTaskClass() { - return (this.rTask != null) ? this.rTask.getClass() : ((this.cTask != null) ? this.cTask.getClass() : null); + return (rTask != null) ? rTask.getClass() : ((cTask != null) ? cTask.getClass() : null); } @Override public boolean isCancelled() { - return (this.period == CraftTask.CANCEL); + return (period == CraftTask.CANCEL); } @Override public void cancel() { - Bukkit.getScheduler().cancelTask(this.id); + Bukkit.getScheduler().cancelTask(id); } /** @@ -133,13 +128,7 @@ public void cancel() { * @return false if it is a craft future task that has already begun execution, true otherwise */ boolean cancel0() { - this.setPeriod(CraftTask.CANCEL); + setPeriod(CraftTask.CANCEL); return true; } - - // Spigot start - public String getTaskName() { - return (this.getTaskClass() == null) ? "Unknown" : this.getTaskClass().getName(); - } - // Spigot end } diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java index 441e2122..4bb9e8ae 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java @@ -2,8 +2,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; -import net.minecraft.world.scores.Objective; -import net.minecraft.world.scores.criteria.ObjectiveCriteria; +import net.minecraft.world.scores.ScoreboardObjective; +import net.minecraft.world.scores.criteria.IScoreboardCriteria; import org.bukkit.scoreboard.Criteria; import org.bukkit.scoreboard.RenderType; @@ -14,9 +14,9 @@ public final class CraftCriteria implements Criteria { static { ImmutableMap.Builder defaults = ImmutableMap.builder(); - for (Map.Entry entry : ObjectiveCriteria.CRITERIA_CACHE.entrySet()) { + for (Map.Entry entry : IScoreboardCriteria.CRITERIA_CACHE.entrySet()) { String name = entry.getKey(); - ObjectiveCriteria criteria = entry.getValue(); + IScoreboardCriteria criteria = entry.getValue(); defaults.put(name, new CraftCriteria(criteria)); } @@ -25,45 +25,45 @@ public final class CraftCriteria implements Criteria { DUMMY = DEFAULTS.get("dummy"); } - final ObjectiveCriteria criteria; + final IScoreboardCriteria criteria; final String bukkitName; private CraftCriteria(String bukkitName) { this.bukkitName = bukkitName; - this.criteria = CraftCriteria.DUMMY.criteria; + this.criteria = DUMMY.criteria; } - private CraftCriteria(ObjectiveCriteria criteria) { + private CraftCriteria(IScoreboardCriteria criteria) { this.criteria = criteria; this.bukkitName = criteria.getName(); } @Override public String getName() { - return this.bukkitName; + return bukkitName; } @Override public boolean isReadOnly() { - return this.criteria.isReadOnly(); + return criteria.isReadOnly(); } @Override public RenderType getDefaultRenderType() { - return RenderType.values()[this.criteria.getDefaultRenderType().ordinal()]; + return RenderType.values()[criteria.getDefaultRenderType().ordinal()]; } - static CraftCriteria getFromNMS(Objective objective) { - return CraftCriteria.DEFAULTS.get(objective.getCriteria().getName()); + static CraftCriteria getFromNMS(ScoreboardObjective objective) { + return DEFAULTS.get(objective.getCriteria().getName()); } public static CraftCriteria getFromBukkit(String name) { - CraftCriteria criteria = CraftCriteria.DEFAULTS.get(name); + CraftCriteria criteria = DEFAULTS.get(name); if (criteria != null) { return criteria; } - return ObjectiveCriteria.byName(name).map(CraftCriteria::new).orElseGet(() -> new CraftCriteria(name)); + return IScoreboardCriteria.byName(name).map(CraftCriteria::new).orElseGet(() -> new CraftCriteria(name)); } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java index 5c987c7d..214c210a 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java @@ -2,6 +2,7 @@ import com.google.common.base.Preconditions; import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.ScoreboardObjective; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.scoreboard.Criteria; @@ -11,67 +12,67 @@ import org.bukkit.scoreboard.Score; final class CraftObjective extends CraftScoreboardComponent implements Objective { - private final net.minecraft.world.scores.Objective objective; + private final ScoreboardObjective objective; private final CraftCriteria criteria; - CraftObjective(CraftScoreboard scoreboard, net.minecraft.world.scores.Objective objective) { + CraftObjective(CraftScoreboard scoreboard, ScoreboardObjective objective) { super(scoreboard); this.objective = objective; this.criteria = CraftCriteria.getFromNMS(objective); } - net.minecraft.world.scores.Objective getHandle() { - return this.objective; + ScoreboardObjective getHandle() { + return objective; } @Override public String getName() { - this.checkState(); + checkState(); - return this.objective.getName(); + return objective.getName(); } @Override public String getDisplayName() { - this.checkState(); + checkState(); - return CraftChatMessage.fromComponent(this.objective.getDisplayName()); + return CraftChatMessage.fromComponent(objective.getDisplayName()); } @Override public void setDisplayName(String displayName) { Preconditions.checkArgument(displayName != null, "Display name cannot be null"); - this.checkState(); + checkState(); - this.objective.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable + objective.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable } @Override public String getCriteria() { - this.checkState(); + checkState(); - return this.criteria.bukkitName; + return criteria.bukkitName; } @Override public Criteria getTrackedCriteria() { - this.checkState(); + checkState(); - return this.criteria; + return criteria; } @Override public boolean isModifiable() { - this.checkState(); + checkState(); - return !this.criteria.criteria.isReadOnly(); + return !criteria.criteria.isReadOnly(); } @Override public void setDisplaySlot(DisplaySlot slot) { - CraftScoreboard scoreboard = this.checkState(); + CraftScoreboard scoreboard = checkState(); Scoreboard board = scoreboard.board; - net.minecraft.world.scores.Objective objective = this.objective; + ScoreboardObjective objective = this.objective; for (net.minecraft.world.scores.DisplaySlot i : net.minecraft.world.scores.DisplaySlot.values()) { if (board.getDisplayObjective(i) == objective) { @@ -80,15 +81,15 @@ public void setDisplaySlot(DisplaySlot slot) { } if (slot != null) { net.minecraft.world.scores.DisplaySlot slotNumber = CraftScoreboardTranslations.fromBukkitSlot(slot); - board.setDisplayObjective(slotNumber, this.getHandle()); + board.setDisplayObjective(slotNumber, getHandle()); } } @Override public DisplaySlot getDisplaySlot() { - CraftScoreboard scoreboard = this.checkState(); + CraftScoreboard scoreboard = checkState(); Scoreboard board = scoreboard.board; - net.minecraft.world.scores.Objective objective = this.objective; + ScoreboardObjective objective = this.objective; for (net.minecraft.world.scores.DisplaySlot i : net.minecraft.world.scores.DisplaySlot.values()) { if (board.getDisplayObjective(i) == objective) { @@ -101,21 +102,21 @@ public DisplaySlot getDisplaySlot() { @Override public void setRenderType(RenderType renderType) { Preconditions.checkArgument(renderType != null, "RenderType cannot be null"); - this.checkState(); + checkState(); this.objective.setRenderType(CraftScoreboardTranslations.fromBukkitRender(renderType)); } @Override public RenderType getRenderType() { - this.checkState(); + checkState(); return CraftScoreboardTranslations.toBukkitRender(this.objective.getRenderType()); } @Override public Score getScore(OfflinePlayer player) { - this.checkState(); + checkState(); return new CraftScore(this, CraftScoreboard.getScoreHolder(player)); } @@ -124,23 +125,23 @@ public Score getScore(OfflinePlayer player) { public Score getScore(String entry) { Preconditions.checkArgument(entry != null, "Entry cannot be null"); Preconditions.checkArgument(entry.length() <= Short.MAX_VALUE, "Score '" + entry + "' is longer than the limit of 32767 characters"); - this.checkState(); + checkState(); return new CraftScore(this, CraftScoreboard.getScoreHolder(entry)); } @Override public void unregister() { - CraftScoreboard scoreboard = this.checkState(); + CraftScoreboard scoreboard = checkState(); - scoreboard.board.removeObjective(this.objective); + scoreboard.board.removeObjective(objective); } @Override CraftScoreboard checkState() { - Preconditions.checkState(this.getScoreboard().board.getObjective(this.objective.getName()) != null, "Unregistered scoreboard component"); + Preconditions.checkState(getScoreboard().board.getObjective(objective.getName()) != null, "Unregistered scoreboard component"); - return this.getScoreboard(); + return getScoreboard(); } @Override @@ -155,7 +156,7 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (this.getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final CraftObjective other = (CraftObjective) obj; diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java index 29e24461..2c11f70d 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java @@ -25,24 +25,24 @@ final class CraftScore implements Score { @Override public OfflinePlayer getPlayer() { - return Bukkit.getOfflinePlayer(this.entry.getScoreboardName()); + return Bukkit.getOfflinePlayer(entry.getScoreboardName()); } @Override public String getEntry() { - return this.entry.getScoreboardName(); + return entry.getScoreboardName(); } @Override public Objective getObjective() { - return this.objective; + return objective; } @Override public int getScore() { - Scoreboard board = this.objective.checkState().board; + Scoreboard board = objective.checkState().board; - ReadOnlyScoreInfo score = board.getPlayerScoreInfo(this.entry, this.objective.getHandle()); + ReadOnlyScoreInfo score = board.getPlayerScoreInfo(entry, objective.getHandle()); if (score != null) { // Lazy return score.value(); } @@ -52,18 +52,18 @@ public int getScore() { @Override public void setScore(int score) { - this.objective.checkState().board.getOrCreatePlayerScore(this.entry, this.objective.getHandle()).set(score); + objective.checkState().board.getOrCreatePlayerScore(entry, objective.getHandle()).set(score); } @Override public boolean isScoreSet() { - Scoreboard board = this.objective.checkState().board; + Scoreboard board = objective.checkState().board; - return board.getPlayerScoreInfo(this.entry, this.objective.getHandle()) != null; + return board.getPlayerScoreInfo(entry, objective.getHandle()) != null; } @Override public CraftScoreboard getScoreboard() { - return this.objective.getScoreboard(); + return objective.getScoreboard(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java index d9f8a0c8..9f4f67b0 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java @@ -4,9 +4,10 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import net.minecraft.world.scores.PlayerTeam; import net.minecraft.world.scores.ScoreHolder; import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.ScoreboardObjective; +import net.minecraft.world.scores.ScoreboardTeam; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.entity.CraftPlayer; @@ -27,22 +28,22 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public CraftObjective registerNewObjective(String name, String criteria) { - return this.registerNewObjective(name, criteria, name); + return registerNewObjective(name, criteria, name); } @Override public CraftObjective registerNewObjective(String name, String criteria, String displayName) { - return this.registerNewObjective(name, CraftCriteria.getFromBukkit(criteria), displayName, RenderType.INTEGER); + return registerNewObjective(name, CraftCriteria.getFromBukkit(criteria), displayName, RenderType.INTEGER); } @Override public CraftObjective registerNewObjective(String name, String criteria, String displayName, RenderType renderType) { - return this.registerNewObjective(name, CraftCriteria.getFromBukkit(criteria), displayName, renderType); + return registerNewObjective(name, CraftCriteria.getFromBukkit(criteria), displayName, renderType); } @Override public CraftObjective registerNewObjective(String name, Criteria criteria, String displayName) { - return this.registerNewObjective(name, criteria, displayName, RenderType.INTEGER); + return registerNewObjective(name, criteria, displayName, RenderType.INTEGER); } @Override @@ -52,16 +53,16 @@ public CraftObjective registerNewObjective(String name, Criteria criteria, Strin Preconditions.checkArgument(displayName != null, "Display name cannot be null"); Preconditions.checkArgument(renderType != null, "RenderType cannot be null"); Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "The name '%s' is longer than the limit of 32767 characters (%s)", name, name.length()); - Preconditions.checkArgument(this.board.getObjective(name) == null, "An objective of name '%s' already exists", name); + Preconditions.checkArgument(board.getObjective(name) == null, "An objective of name '%s' already exists", name); - net.minecraft.world.scores.Objective objective = this.board.addObjective(name, ((CraftCriteria) criteria).criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType), true, null); + ScoreboardObjective objective = board.addObjective(name, ((CraftCriteria) criteria).criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType), true, null); return new CraftObjective(this, objective); } @Override public Objective getObjective(String name) { Preconditions.checkArgument(name != null, "Objective name cannot be null"); - net.minecraft.world.scores.Objective nms = this.board.getObjective(name); + ScoreboardObjective nms = board.getObjective(name); return nms == null ? null : new CraftObjective(this, nms); } @@ -70,7 +71,7 @@ public ImmutableSet getObjectivesByCriteria(String criteria) { Preconditions.checkArgument(criteria != null, "Criteria name cannot be null"); ImmutableSet.Builder objectives = ImmutableSet.builder(); - for (net.minecraft.world.scores.Objective netObjective : this.board.getObjectives()) { + for (ScoreboardObjective netObjective : this.board.getObjectives()) { CraftObjective objective = new CraftObjective(this, netObjective); if (objective.getCriteria().equals(criteria)) { objectives.add(objective); @@ -84,7 +85,7 @@ public ImmutableSet getObjectivesByCriteria(Criteria criteria) { Preconditions.checkArgument(criteria != null, "Criteria cannot be null"); ImmutableSet.Builder objectives = ImmutableSet.builder(); - for (net.minecraft.world.scores.Objective netObjective : this.board.getObjectives()) { + for (ScoreboardObjective netObjective : board.getObjectives()) { CraftObjective objective = new CraftObjective(this, netObjective); if (objective.getTrackedCriteria().equals(criteria)) { objectives.add(objective); @@ -96,13 +97,13 @@ public ImmutableSet getObjectivesByCriteria(Criteria criteria) { @Override public ImmutableSet getObjectives() { - return ImmutableSet.copyOf(Iterables.transform(this.board.getObjectives(), (Function) input -> new CraftObjective(CraftScoreboard.this, input))); + return ImmutableSet.copyOf(Iterables.transform(this.board.getObjectives(), (Function) input -> new CraftObjective(CraftScoreboard.this, input))); } @Override public Objective getObjective(DisplaySlot slot) { Preconditions.checkArgument(slot != null, "Display slot cannot be null"); - net.minecraft.world.scores.Objective objective = this.board.getDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot)); + ScoreboardObjective objective = board.getDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot)); if (objective == null) { return null; } @@ -111,19 +112,19 @@ public Objective getObjective(DisplaySlot slot) { @Override public ImmutableSet getScores(OfflinePlayer player) { - return this.getScores(CraftScoreboard.getScoreHolder(player)); + return getScores(getScoreHolder(player)); } @Override public ImmutableSet getScores(String entry) { - return this.getScores(CraftScoreboard.getScoreHolder(entry)); + return getScores(getScoreHolder(entry)); } private ImmutableSet getScores(ScoreHolder entry) { Preconditions.checkArgument(entry != null, "Entry cannot be null"); ImmutableSet.Builder scores = ImmutableSet.builder(); - for (net.minecraft.world.scores.Objective objective : this.board.getObjectives()) { + for (ScoreboardObjective objective : this.board.getObjectives()) { scores.add(new CraftScore(new CraftObjective(this, objective), entry)); } return scores.build(); @@ -131,19 +132,19 @@ private ImmutableSet getScores(ScoreHolder entry) { @Override public void resetScores(OfflinePlayer player) { - this.resetScores(CraftScoreboard.getScoreHolder(player)); + resetScores(getScoreHolder(player)); } @Override public void resetScores(String entry) { - this.resetScores(CraftScoreboard.getScoreHolder(entry)); + resetScores(getScoreHolder(entry)); } private void resetScores(ScoreHolder entry) { Preconditions.checkArgument(entry != null, "Entry cannot be null"); - for (net.minecraft.world.scores.Objective objective : this.board.getObjectives()) { - this.board.resetSinglePlayerScore(entry, objective); + for (ScoreboardObjective objective : this.board.getObjectives()) { + board.resetSinglePlayerScore(entry, objective); } } @@ -151,7 +152,7 @@ private void resetScores(ScoreHolder entry) { public Team getPlayerTeam(OfflinePlayer player) { Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); - PlayerTeam team = this.board.getPlayersTeam(player.getName()); + ScoreboardTeam team = board.getPlayersTeam(player.getName()); return team == null ? null : new CraftTeam(this, team); } @@ -159,7 +160,7 @@ public Team getPlayerTeam(OfflinePlayer player) { public Team getEntryTeam(String entry) { Preconditions.checkArgument(entry != null, "Entry cannot be null"); - PlayerTeam team = this.board.getPlayersTeam(entry); + ScoreboardTeam team = board.getPlayersTeam(entry); return team == null ? null : new CraftTeam(this, team); } @@ -167,28 +168,28 @@ public Team getEntryTeam(String entry) { public Team getTeam(String teamName) { Preconditions.checkArgument(teamName != null, "Team name cannot be null"); - PlayerTeam team = this.board.getPlayerTeam(teamName); + ScoreboardTeam team = board.getPlayerTeam(teamName); return team == null ? null : new CraftTeam(this, team); } @Override public ImmutableSet getTeams() { - return ImmutableSet.copyOf(Iterables.transform(this.board.getPlayerTeams(), (Function) input -> new CraftTeam(CraftScoreboard.this, input))); + return ImmutableSet.copyOf(Iterables.transform(this.board.getPlayerTeams(), (Function) input -> new CraftTeam(CraftScoreboard.this, input))); } @Override public Team registerNewTeam(String name) { Preconditions.checkArgument(name != null, "Team name cannot be null"); Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "Team name '%s' is longer than the limit of 32767 characters (%s)", name, name.length()); - Preconditions.checkArgument(this.board.getPlayerTeam(name) == null, "Team name '%s' is already in use", name); + Preconditions.checkArgument(board.getPlayerTeam(name) == null, "Team name '%s' is already in use", name); - return new CraftTeam(this, this.board.addPlayerTeam(name)); + return new CraftTeam(this, board.addPlayerTeam(name)); } @Override public ImmutableSet getPlayers() { ImmutableSet.Builder players = ImmutableSet.builder(); - for (ScoreHolder playerName : this.board.getTrackedPlayers()) { + for (ScoreHolder playerName : board.getTrackedPlayers()) { players.add(Bukkit.getOfflinePlayer(playerName.getScoreboardName())); } return players.build(); @@ -197,7 +198,7 @@ public ImmutableSet getPlayers() { @Override public ImmutableSet getEntries() { ImmutableSet.Builder entries = ImmutableSet.builder(); - for (ScoreHolder entry : this.board.getTrackedPlayers()) { + for (ScoreHolder entry : board.getTrackedPlayers()) { entries.add(entry.getScoreboardName()); } return entries.build(); @@ -206,12 +207,12 @@ public ImmutableSet getEntries() { @Override public void clearSlot(DisplaySlot slot) { Preconditions.checkArgument(slot != null, "Slot cannot be null"); - this.board.setDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot), null); + board.setDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot), null); } // CraftBukkit method public Scoreboard getHandle() { - return this.board; + return board; } static ScoreHolder getScoreHolder(String entry) { @@ -224,7 +225,7 @@ static ScoreHolder getScoreHolder(OfflinePlayer player) { if (player instanceof CraftPlayer craft) { return craft.getHandle(); } else { - return CraftScoreboard.getScoreHolder(player.getName()); + return getScoreHolder(player.getName()); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java index fd88bfe0..5a5f03e0 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java @@ -10,7 +10,7 @@ abstract class CraftScoreboardComponent { abstract CraftScoreboard checkState(); public CraftScoreboard getScoreboard() { - return this.scoreboard; + return scoreboard; } abstract void unregister(); diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java index 40e348ca..726887ec 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java @@ -7,17 +7,17 @@ import java.util.Iterator; import java.util.Map; import java.util.function.Consumer; -import net.minecraft.network.protocol.game.ClientboundSetObjectivePacket; -import net.minecraft.network.protocol.game.ClientboundSetPlayerTeamPacket; +import net.minecraft.network.protocol.game.PacketPlayOutScoreboardObjective; +import net.minecraft.network.protocol.game.PacketPlayOutScoreboardTeam; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerScoreboard; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.scores.Objective; -import net.minecraft.world.scores.PlayerTeam; +import net.minecraft.server.ScoreboardServer; +import net.minecraft.server.level.EntityPlayer; import net.minecraft.world.scores.ScoreAccess; import net.minecraft.world.scores.ScoreHolder; import net.minecraft.world.scores.Scoreboard; -import net.minecraft.world.scores.criteria.ObjectiveCriteria; +import net.minecraft.world.scores.ScoreboardObjective; +import net.minecraft.world.scores.ScoreboardTeam; +import net.minecraft.world.scores.criteria.IScoreboardCriteria; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.util.WeakCollection; import org.bukkit.scoreboard.ScoreboardManager; @@ -29,28 +29,27 @@ public final class CraftScoreboardManager implements ScoreboardManager { private final Map playerBoards = new HashMap<>(); public CraftScoreboardManager(MinecraftServer minecraftserver, net.minecraft.world.scores.Scoreboard scoreboardServer) { - this.mainScoreboard = new CraftScoreboard(scoreboardServer); - this.server = minecraftserver; - this.scoreboards.add(this.mainScoreboard); + mainScoreboard = new CraftScoreboard(scoreboardServer); + server = minecraftserver; + scoreboards.add(mainScoreboard); } @Override public CraftScoreboard getMainScoreboard() { - return this.mainScoreboard; + return mainScoreboard; } @Override public CraftScoreboard getNewScoreboard() { - org.spigotmc.AsyncCatcher.catchOp("scoreboard creation"); // Spigot - CraftScoreboard scoreboard = new CraftScoreboard(new ServerScoreboard(this.server)); - this.scoreboards.add(scoreboard); + CraftScoreboard scoreboard = new CraftScoreboard(new ScoreboardServer(server)); + scoreboards.add(scoreboard); return scoreboard; } // CraftBukkit method public CraftScoreboard getPlayerBoard(CraftPlayer player) { - CraftScoreboard board = this.playerBoards.get(player); - return board == null ? this.getMainScoreboard() : board; + CraftScoreboard board = playerBoards.get(player); + return board == null ? getMainScoreboard() : board; } // CraftBukkit method @@ -58,26 +57,26 @@ public void setPlayerBoard(CraftPlayer player, org.bukkit.scoreboard.Scoreboard Preconditions.checkArgument(bukkitScoreboard instanceof CraftScoreboard, "Cannot set player scoreboard to an unregistered Scoreboard"); CraftScoreboard scoreboard = (CraftScoreboard) bukkitScoreboard; - net.minecraft.world.scores.Scoreboard oldboard = this.getPlayerBoard(player).getHandle(); + net.minecraft.world.scores.Scoreboard oldboard = getPlayerBoard(player).getHandle(); net.minecraft.world.scores.Scoreboard newboard = scoreboard.getHandle(); - ServerPlayer entityplayer = player.getHandle(); + EntityPlayer entityplayer = player.getHandle(); if (oldboard == newboard) { return; } - if (scoreboard == this.mainScoreboard) { - this.playerBoards.remove(player); + if (scoreboard == mainScoreboard) { + playerBoards.remove(player); } else { - this.playerBoards.put(player, scoreboard); + playerBoards.put(player, scoreboard); } // Old objective tracking - HashSet removed = new HashSet<>(); + HashSet removed = new HashSet<>(); for (int i = 0; i < 3; ++i) { - Objective scoreboardobjective = oldboard.getDisplayObjective(net.minecraft.world.scores.DisplaySlot.BY_ID.apply(i)); + ScoreboardObjective scoreboardobjective = oldboard.getDisplayObjective(net.minecraft.world.scores.DisplaySlot.BY_ID.apply(i)); if (scoreboardobjective != null && !removed.contains(scoreboardobjective)) { - entityplayer.connection.send(new ClientboundSetObjectivePacket(scoreboardobjective, 1)); + entityplayer.connection.send(new PacketPlayOutScoreboardObjective(scoreboardobjective, 1)); removed.add(scoreboardobjective); } } @@ -85,22 +84,22 @@ public void setPlayerBoard(CraftPlayer player, org.bukkit.scoreboard.Scoreboard // Old team tracking Iterator iterator = oldboard.getPlayerTeams().iterator(); while (iterator.hasNext()) { - PlayerTeam scoreboardteam = (PlayerTeam) iterator.next(); - entityplayer.connection.send(ClientboundSetPlayerTeamPacket.createRemovePacket(scoreboardteam)); + ScoreboardTeam scoreboardteam = (ScoreboardTeam) iterator.next(); + entityplayer.connection.send(PacketPlayOutScoreboardTeam.createRemovePacket(scoreboardteam)); } // The above is the reverse of the below method. - this.server.getPlayerList().updateEntireScoreboard((ServerScoreboard) newboard, player.getHandle()); + server.getPlayerList().updateEntireScoreboard((ScoreboardServer) newboard, player.getHandle()); } // CraftBukkit method public void removePlayer(CraftPlayer player) { - this.playerBoards.remove(player); + playerBoards.remove(player); } // CraftBukkit method - public void forAllObjectives(ObjectiveCriteria criteria, ScoreHolder holder, Consumer consumer) { - for (CraftScoreboard scoreboard : this.scoreboards) { + public void forAllObjectives(IScoreboardCriteria criteria, ScoreHolder holder, Consumer consumer) { + for (CraftScoreboard scoreboard : scoreboards) { Scoreboard board = scoreboard.board; board.forAllObjectives(criteria, holder, (score) -> consumer.accept(score)); } diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java index 98b31f19..9cfc3e88 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.scoreboard; import com.google.common.collect.ImmutableBiMap; -import net.minecraft.world.scores.criteria.ObjectiveCriteria; +import net.minecraft.world.scores.criteria.IScoreboardCriteria; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.RenderType; @@ -32,18 +32,18 @@ final class CraftScoreboardTranslations { private CraftScoreboardTranslations() {} static DisplaySlot toBukkitSlot(net.minecraft.world.scores.DisplaySlot minecraft) { - return CraftScoreboardTranslations.SLOTS.inverse().get(minecraft.getSerializedName()); + return SLOTS.inverse().get(minecraft.getSerializedName()); } static net.minecraft.world.scores.DisplaySlot fromBukkitSlot(DisplaySlot slot) { - return net.minecraft.world.scores.DisplaySlot.CODEC.byName(CraftScoreboardTranslations.SLOTS.get(slot)); + return net.minecraft.world.scores.DisplaySlot.CODEC.byName(SLOTS.get(slot)); } - static RenderType toBukkitRender(ObjectiveCriteria.RenderType display) { + static RenderType toBukkitRender(IScoreboardCriteria.EnumScoreboardHealthDisplay display) { return RenderType.valueOf(display.name()); } - static ObjectiveCriteria.RenderType fromBukkitRender(RenderType render) { - return ObjectiveCriteria.RenderType.valueOf(render.name()); + static IScoreboardCriteria.EnumScoreboardHealthDisplay fromBukkitRender(RenderType render) { + return IScoreboardCriteria.EnumScoreboardHealthDisplay.valueOf(render.name()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java index 4d586e13..dbfbb957 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java @@ -3,8 +3,9 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import java.util.Set; -import net.minecraft.world.scores.PlayerTeam; -import net.minecraft.world.scores.Team.Visibility; +import net.minecraft.world.scores.ScoreboardTeam; +import net.minecraft.world.scores.ScoreboardTeamBase; +import net.minecraft.world.scores.ScoreboardTeamBase.EnumNameTagVisibility; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; @@ -13,128 +14,128 @@ import org.bukkit.scoreboard.Team; final class CraftTeam extends CraftScoreboardComponent implements Team { - private final PlayerTeam team; + private final ScoreboardTeam team; - CraftTeam(CraftScoreboard scoreboard, PlayerTeam team) { + CraftTeam(CraftScoreboard scoreboard, ScoreboardTeam team) { super(scoreboard); this.team = team; } @Override public String getName() { - this.checkState(); + checkState(); - return this.team.getName(); + return team.getName(); } @Override public String getDisplayName() { - this.checkState(); + checkState(); - return CraftChatMessage.fromComponent(this.team.getDisplayName()); + return CraftChatMessage.fromComponent(team.getDisplayName()); } @Override public void setDisplayName(String displayName) { Preconditions.checkArgument(displayName != null, "Display name cannot be null"); - this.checkState(); + checkState(); - this.team.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable + team.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable } @Override public String getPrefix() { - this.checkState(); + checkState(); - return CraftChatMessage.fromComponent(this.team.getPlayerPrefix()); + return CraftChatMessage.fromComponent(team.getPlayerPrefix()); } @Override public void setPrefix(String prefix) { Preconditions.checkArgument(prefix != null, "Prefix cannot be null"); - this.checkState(); + checkState(); - this.team.setPlayerPrefix(CraftChatMessage.fromStringOrNull(prefix)); + team.setPlayerPrefix(CraftChatMessage.fromStringOrNull(prefix)); } @Override public String getSuffix() { - this.checkState(); + checkState(); - return CraftChatMessage.fromComponent(this.team.getPlayerSuffix()); + return CraftChatMessage.fromComponent(team.getPlayerSuffix()); } @Override public void setSuffix(String suffix) { Preconditions.checkArgument(suffix != null, "Suffix cannot be null"); - this.checkState(); + checkState(); - this.team.setPlayerSuffix(CraftChatMessage.fromStringOrNull(suffix)); + team.setPlayerSuffix(CraftChatMessage.fromStringOrNull(suffix)); } @Override public ChatColor getColor() { - this.checkState(); + checkState(); - return CraftChatMessage.getColor(this.team.getColor()); + return CraftChatMessage.getColor(team.getColor()); } @Override public void setColor(ChatColor color) { Preconditions.checkArgument(color != null, "Color cannot be null"); - this.checkState(); + checkState(); - this.team.setColor(CraftChatMessage.getColor(color)); + team.setColor(CraftChatMessage.getColor(color)); } @Override public boolean allowFriendlyFire() { - this.checkState(); + checkState(); - return this.team.isAllowFriendlyFire(); + return team.isAllowFriendlyFire(); } @Override public void setAllowFriendlyFire(boolean enabled) { - this.checkState(); + checkState(); - this.team.setAllowFriendlyFire(enabled); + team.setAllowFriendlyFire(enabled); } @Override public boolean canSeeFriendlyInvisibles() { - this.checkState(); + checkState(); - return this.team.canSeeFriendlyInvisibles(); + return team.canSeeFriendlyInvisibles(); } @Override public void setCanSeeFriendlyInvisibles(boolean enabled) { - this.checkState(); + checkState(); - this.team.setSeeFriendlyInvisibles(enabled); + team.setSeeFriendlyInvisibles(enabled); } @Override public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException { - this.checkState(); + checkState(); - return CraftTeam.notchToBukkit(this.team.getNameTagVisibility()); + return notchToBukkit(team.getNameTagVisibility()); } @Override public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException { - this.checkState(); + checkState(); - this.team.setNameTagVisibility(CraftTeam.bukkitToNotch(visibility)); + team.setNameTagVisibility(bukkitToNotch(visibility)); } @Override public Set getPlayers() { - this.checkState(); + checkState(); ImmutableSet.Builder players = ImmutableSet.builder(); - for (String playerName : this.team.getPlayers()) { + for (String playerName : team.getPlayers()) { players.add(Bukkit.getOfflinePlayer(playerName)); } return players.build(); @@ -142,10 +143,10 @@ public Set getPlayers() { @Override public Set getEntries() { - this.checkState(); + checkState(); ImmutableSet.Builder entries = ImmutableSet.builder(); - for (String playerName : this.team.getPlayers()) { + for (String playerName : team.getPlayers()) { entries.add(playerName); } return entries.build(); @@ -153,76 +154,76 @@ public Set getEntries() { @Override public int getSize() { - this.checkState(); + checkState(); - return this.team.getPlayers().size(); + return team.getPlayers().size(); } @Override public void addPlayer(OfflinePlayer player) { Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); - this.addEntry(player.getName()); + addEntry(player.getName()); } @Override public void addEntry(String entry) { Preconditions.checkArgument(entry != null, "Entry cannot be null"); - CraftScoreboard scoreboard = this.checkState(); + CraftScoreboard scoreboard = checkState(); - scoreboard.board.addPlayerToTeam(entry, this.team); + scoreboard.board.addPlayerToTeam(entry, team); } @Override public boolean removePlayer(OfflinePlayer player) { Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); - return this.removeEntry(player.getName()); + return removeEntry(player.getName()); } @Override public boolean removeEntry(String entry) { Preconditions.checkArgument(entry != null, "Entry cannot be null"); - CraftScoreboard scoreboard = this.checkState(); + CraftScoreboard scoreboard = checkState(); - if (!this.team.getPlayers().contains(entry)) { + if (!team.getPlayers().contains(entry)) { return false; } - scoreboard.board.removePlayerFromTeam(entry, this.team); + scoreboard.board.removePlayerFromTeam(entry, team); return true; } @Override public boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); - return this.hasEntry(player.getName()); + return hasEntry(player.getName()); } @Override public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException { Preconditions.checkArgument(entry != null, "Entry cannot be null"); - this.checkState(); + checkState(); - return this.team.getPlayers().contains(entry); + return team.getPlayers().contains(entry); } @Override public void unregister() { - CraftScoreboard scoreboard = this.checkState(); + CraftScoreboard scoreboard = checkState(); - scoreboard.board.removePlayerTeam(this.team); + scoreboard.board.removePlayerTeam(team); } @Override public OptionStatus getOption(Option option) { - this.checkState(); + checkState(); switch (option) { case NAME_TAG_VISIBILITY: - return OptionStatus.values()[this.team.getNameTagVisibility().ordinal()]; + return OptionStatus.values()[team.getNameTagVisibility().ordinal()]; case DEATH_MESSAGE_VISIBILITY: - return OptionStatus.values()[this.team.getDeathMessageVisibility().ordinal()]; + return OptionStatus.values()[team.getDeathMessageVisibility().ordinal()]; case COLLISION_RULE: - return OptionStatus.values()[this.team.getCollisionRule().ordinal()]; + return OptionStatus.values()[team.getCollisionRule().ordinal()]; default: throw new IllegalArgumentException("Unrecognised option " + option); } @@ -230,39 +231,39 @@ public OptionStatus getOption(Option option) { @Override public void setOption(Option option, OptionStatus status) { - this.checkState(); + checkState(); switch (option) { case NAME_TAG_VISIBILITY: - this.team.setNameTagVisibility(Visibility.values()[status.ordinal()]); + team.setNameTagVisibility(EnumNameTagVisibility.values()[status.ordinal()]); break; case DEATH_MESSAGE_VISIBILITY: - this.team.setDeathMessageVisibility(Visibility.values()[status.ordinal()]); + team.setDeathMessageVisibility(EnumNameTagVisibility.values()[status.ordinal()]); break; case COLLISION_RULE: - this.team.setCollisionRule(net.minecraft.world.scores.Team.CollisionRule.values()[status.ordinal()]); + team.setCollisionRule(ScoreboardTeamBase.EnumTeamPush.values()[status.ordinal()]); break; default: throw new IllegalArgumentException("Unrecognised option " + option); } } - public static Visibility bukkitToNotch(NameTagVisibility visibility) { + public static EnumNameTagVisibility bukkitToNotch(NameTagVisibility visibility) { switch (visibility) { case ALWAYS: - return Visibility.ALWAYS; + return EnumNameTagVisibility.ALWAYS; case NEVER: - return Visibility.NEVER; + return EnumNameTagVisibility.NEVER; case HIDE_FOR_OTHER_TEAMS: - return Visibility.HIDE_FOR_OTHER_TEAMS; + return EnumNameTagVisibility.HIDE_FOR_OTHER_TEAMS; case HIDE_FOR_OWN_TEAM: - return Visibility.HIDE_FOR_OWN_TEAM; + return EnumNameTagVisibility.HIDE_FOR_OWN_TEAM; default: throw new IllegalArgumentException("Unknown visibility level " + visibility); } } - public static NameTagVisibility notchToBukkit(Visibility visibility) { + public static NameTagVisibility notchToBukkit(EnumNameTagVisibility visibility) { switch (visibility) { case ALWAYS: return NameTagVisibility.ALWAYS; @@ -279,9 +280,9 @@ public static NameTagVisibility notchToBukkit(Visibility visibility) { @Override CraftScoreboard checkState() { - Preconditions.checkState(this.getScoreboard().board.getPlayerTeam(this.team.getName()) != null, "Unregistered scoreboard component"); + Preconditions.checkState(getScoreboard().board.getPlayerTeam(team.getName()) != null, "Unregistered scoreboard component"); - return this.getScoreboard(); + return getScoreboard(); } @Override @@ -296,7 +297,7 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (this.getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final CraftTeam other = (CraftTeam) obj; diff --git a/src/main/java/org/bukkit/craftbukkit/structure/CraftPalette.java b/src/main/java/org/bukkit/craftbukkit/structure/CraftPalette.java index 26c7d0d3..0bb840fd 100644 --- a/src/main/java/org/bukkit/craftbukkit/structure/CraftPalette.java +++ b/src/main/java/org/bukkit/craftbukkit/structure/CraftPalette.java @@ -2,18 +2,18 @@ import java.util.ArrayList; import java.util.List; -import net.minecraft.core.RegistryAccess; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure; import org.bukkit.block.BlockState; import org.bukkit.craftbukkit.block.CraftBlockStates; import org.bukkit.structure.Palette; public class CraftPalette implements Palette { - private final StructureTemplate.Palette palette; - private final RegistryAccess registry; + private final DefinedStructure.b palette; + private final IRegistryCustom registry; - public CraftPalette(StructureTemplate.Palette palette, RegistryAccess registry) { + public CraftPalette(DefinedStructure.b palette, IRegistryCustom registry) { this.palette = palette; this.registry = registry; } @@ -21,14 +21,14 @@ public CraftPalette(StructureTemplate.Palette palette, RegistryAccess registry) @Override public List getBlocks() { List blocks = new ArrayList<>(); - for (StructureTemplate.StructureBlockInfo blockInfo : this.palette.blocks()) { - blocks.add(CraftBlockStates.getBlockState(this.registry, blockInfo.pos(), blockInfo.state(), blockInfo.nbt())); + for (DefinedStructure.BlockInfo blockInfo : palette.blocks()) { + blocks.add(CraftBlockStates.getBlockState(registry, blockInfo.pos(), blockInfo.state(), blockInfo.nbt())); } return blocks; } @Override public int getBlockCount() { - return this.palette.blocks().size(); + return palette.blocks().size(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java b/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java index d317bdb4..fa258958 100644 --- a/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java +++ b/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java @@ -8,16 +8,18 @@ import java.util.Random; import java.util.stream.Collectors; import net.minecraft.core.BlockPos; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.IRegistryCustom; import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.level.ChunkCoordIntPair; +import net.minecraft.world.level.GeneratorAccessSeed; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.levelgen.structure.templatesystem.BlockRotProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.world.level.block.EnumBlockMirror; +import net.minecraft.world.level.block.EnumBlockRotation; +import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure; +import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureInfo; +import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureProcessorRotation; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.RegionAccessor; @@ -41,17 +43,17 @@ public class CraftStructure implements Structure { - private final StructureTemplate structure; - private final RegistryAccess registry; + private final DefinedStructure structure; + private final IRegistryCustom registry; - public CraftStructure(StructureTemplate structure, RegistryAccess registry) { + public CraftStructure(DefinedStructure structure, IRegistryCustom registry) { this.structure = structure; this.registry = registry; } @Override public void place(Location location, boolean includeEntities, StructureRotation structureRotation, Mirror mirror, int palette, float integrity, Random random) { - this.place(location, includeEntities, structureRotation, mirror, palette, integrity, random, Collections.emptyList(), Collections.emptyList()); + place(location, includeEntities, structureRotation, mirror, palette, integrity, random, Collections.emptyList(), Collections.emptyList()); } @Override @@ -62,12 +64,12 @@ public void place(Location location, boolean includeEntities, StructureRotation Preconditions.checkArgument(world != null, "The World of Location cannot be null"); BlockVector blockVector = new BlockVector(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - this.place(world, blockVector, includeEntities, structureRotation, mirror, palette, integrity, random, blockTransformers, entityTransformers); + place(world, blockVector, includeEntities, structureRotation, mirror, palette, integrity, random, blockTransformers, entityTransformers); } @Override public void place(RegionAccessor regionAccessor, BlockVector location, boolean includeEntities, StructureRotation structureRotation, Mirror mirror, int palette, float integrity, Random random) { - this.place(regionAccessor, location, includeEntities, structureRotation, mirror, palette, integrity, random, Collections.emptyList(), Collections.emptyList()); + place(regionAccessor, location, includeEntities, structureRotation, mirror, palette, integrity, random, Collections.emptyList(), Collections.emptyList()); } @Override @@ -81,22 +83,22 @@ public void place(RegionAccessor regionAccessor, BlockVector location, boolean i Preconditions.checkArgument(integrity >= 0F && integrity <= 1F, "Integrity value (%S) must be between 0 and 1 inclusive", integrity); RandomSource randomSource = new RandomSourceWrapper(random); - StructurePlaceSettings definedstructureinfo = new StructurePlaceSettings() - .setMirror(net.minecraft.world.level.block.Mirror.valueOf(mirror.name())) - .setRotation(Rotation.valueOf(structureRotation.name())) + DefinedStructureInfo definedstructureinfo = new DefinedStructureInfo() + .setMirror(EnumBlockMirror.valueOf(mirror.name())) + .setRotation(EnumBlockRotation.valueOf(structureRotation.name())) .setIgnoreEntities(!includeEntities) - .addProcessor(new BlockRotProcessor(integrity)) + .addProcessor(new DefinedStructureProcessorRotation(integrity)) .setRandom(randomSource); definedstructureinfo.palette = palette; - BlockPos blockPosition = CraftBlockVector.toBlockPosition(location); - WorldGenLevel handle = ((CraftRegionAccessor) regionAccessor).getHandle(); + BlockPos blockPosition = CraftBlockVector.toBlockPos(location); + GeneratorAccessSeed handle = ((CraftRegionAccessor) regionAccessor).getHandle(); TransformerGeneratorAccess access = new TransformerGeneratorAccess(); access.setHandle(handle); - access.setStructureTransformer(new CraftStructureTransformer(handle, new ChunkPos(blockPosition), blockTransformers, entityTransformers)); + access.setStructureTransformer(new CraftStructureTransformer(handle, new ChunkCoordIntPair(blockPosition), blockTransformers, entityTransformers)); - this.structure.placeInWorld(access, blockPosition, blockPosition, definedstructureinfo, randomSource, 2); + structure.placeInWorld(access, blockPosition, blockPosition, definedstructureinfo, randomSource, 2); access.getStructureTransformer().discard(); } @@ -109,7 +111,7 @@ public void fill(Location corner1, Location corner2, boolean includeEntities) { Location origin = new Location(world, Math.min(corner1.getBlockX(), corner2.getBlockX()), Math.min(corner1.getBlockY(), corner2.getBlockY()), Math.min(corner1.getBlockZ(), corner2.getBlockZ())); BlockVector size = new BlockVector(Math.abs(corner1.getBlockX() - corner2.getBlockX()), Math.abs(corner1.getBlockY() - corner2.getBlockY()), Math.abs(corner1.getBlockZ() - corner2.getBlockZ())); - this.fill(origin, size, includeEntities); + fill(origin, size, includeEntities); } @Override @@ -120,19 +122,19 @@ public void fill(Location origin, BlockVector size, boolean includeEntities) { Preconditions.checkArgument(size != null, "BlockVector size cannot be null"); Preconditions.checkArgument(size.getBlockX() >= 1 && size.getBlockY() >= 1 && size.getBlockZ() >= 1, "Size must be at least 1x1x1 but was %sx%sx%s", size.getBlockX(), size.getBlockY(), size.getBlockZ()); - this.structure.fillFromWorld(((CraftWorld) world).getHandle(), CraftLocation.toBlockPosition(origin), CraftBlockVector.toBlockPosition(size), includeEntities, Blocks.STRUCTURE_VOID); + structure.fillFromWorld(((CraftWorld) world).getHandle(), CraftLocation.toBlockPos(origin), CraftBlockVector.toBlockPos(size), includeEntities, Blocks.STRUCTURE_VOID); } @Override public BlockVector getSize() { - return CraftBlockVector.toBukkit(this.structure.getSize()); + return CraftBlockVector.toBukkit(structure.getSize()); } @Override public List getEntities() { List entities = new ArrayList<>(); - for (StructureTemplate.StructureEntityInfo entity : this.structure.entityInfoList) { - EntityType.create(entity.nbt, ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle()).ifPresent(dummyEntity -> { + for (DefinedStructure.EntityInfo entity : structure.entityInfoList) { + EntityTypes.create(entity.nbt, ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle(), EntitySpawnReason.STRUCTURE).ifPresent(dummyEntity -> { dummyEntity.setPos(entity.pos.x, entity.pos.y, entity.pos.z); entities.add(dummyEntity.getBukkitEntity()); }); @@ -142,25 +144,25 @@ public List getEntities() { @Override public int getEntityCount() { - return this.structure.entityInfoList.size(); + return structure.entityInfoList.size(); } @Override public List getPalettes() { - return this.structure.palettes.stream().map((palette) -> new CraftPalette(palette, this.registry)).collect(Collectors.toList()); + return structure.palettes.stream().map((palette) -> new CraftPalette(palette, registry)).collect(Collectors.toList()); } @Override public int getPaletteCount() { - return this.structure.palettes.size(); + return structure.palettes.size(); } @Override public PersistentDataContainer getPersistentDataContainer() { - return this.getHandle().persistentDataContainer; + return getHandle().persistentDataContainer; } - public StructureTemplate getHandle() { - return this.structure; + public DefinedStructure getHandle() { + return structure; } } diff --git a/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java b/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java index 35b31ff1..10fbddfe 100644 --- a/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java +++ b/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java @@ -13,11 +13,11 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.nbt.NBTCompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.resources.MinecraftKey; +import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.bukkit.NamespacedKey; import org.bukkit.craftbukkit.util.CraftNamespacedKey; @@ -27,9 +27,9 @@ public class CraftStructureManager implements StructureManager { private final StructureTemplateManager structureManager; - private final RegistryAccess registry; + private final IRegistryCustom registry; - public CraftStructureManager(StructureTemplateManager structureManager, RegistryAccess registry) { + public CraftStructureManager(StructureTemplateManager structureManager, IRegistryCustom registry) { this.structureManager = structureManager; this.registry = registry; } @@ -37,8 +37,8 @@ public CraftStructureManager(StructureTemplateManager structureManager, Registry @Override public Map getStructures() { Map cachedStructures = new HashMap<>(); - for (Map.Entry> entry : this.structureManager.structureRepository.entrySet()) { - entry.getValue().ifPresent(definedStructure -> cachedStructures.put(CraftNamespacedKey.fromMinecraft(entry.getKey()), new CraftStructure(definedStructure, this.registry))); + for (Map.Entry> entry : structureManager.structureRepository.entrySet()) { + entry.getValue().ifPresent(definedStructure -> cachedStructures.put(CraftNamespacedKey.fromMinecraft(entry.getKey()), new CraftStructure(definedStructure, registry))); } return Collections.unmodifiableMap(cachedStructures); } @@ -47,39 +47,39 @@ public Map getStructures() { public Structure getStructure(NamespacedKey structureKey) { Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); - final Optional definedStructure = this.structureManager.structureRepository.get(CraftNamespacedKey.toMinecraft(structureKey)); + final Optional definedStructure = structureManager.structureRepository.get(CraftNamespacedKey.toMinecraft(structureKey)); if (definedStructure == null) { return null; } - return definedStructure.map((s) -> new CraftStructure(s, this.registry)).orElse(null); + return definedStructure.map((s) -> new CraftStructure(s, registry)).orElse(null); } @Override public Structure loadStructure(NamespacedKey structureKey, boolean register) { - ResourceLocation minecraftKey = this.createAndValidateMinecraftStructureKey(structureKey); + MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); - Optional structure = this.structureManager.structureRepository.get(minecraftKey); + Optional structure = structureManager.structureRepository.get(minecraftKey); structure = structure == null ? Optional.empty() : structure; - structure = structure.isPresent() ? structure : this.structureManager.loadFromGenerated(minecraftKey); - structure = structure.isPresent() ? structure : this.structureManager.loadFromResource(minecraftKey); + structure = structure.isPresent() ? structure : structureManager.loadFromGenerated(minecraftKey); + structure = structure.isPresent() ? structure : structureManager.loadFromResource(minecraftKey); if (register) { - this.structureManager.structureRepository.put(minecraftKey, structure); + structureManager.structureRepository.put(minecraftKey, structure); } - return structure.map((s) -> new CraftStructure(s, this.registry)).orElse(null); + return structure.map((s) -> new CraftStructure(s, registry)).orElse(null); } @Override public Structure loadStructure(NamespacedKey structureKey) { - return this.loadStructure(structureKey, true); + return loadStructure(structureKey, true); } @Override public void saveStructure(NamespacedKey structureKey) { - ResourceLocation minecraftKey = this.createAndValidateMinecraftStructureKey(structureKey); + MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); - this.structureManager.save(minecraftKey); + structureManager.save(minecraftKey); } @Override @@ -87,51 +87,51 @@ public void saveStructure(NamespacedKey structureKey, Structure structure) throw Preconditions.checkArgument(structureKey != null, "NamespacedKey structure cannot be null"); Preconditions.checkArgument(structure != null, "Structure cannot be null"); - File structureFile = this.getStructureFile(structureKey); + File structureFile = getStructureFile(structureKey); Files.createDirectories(structureFile.toPath().getParent()); - this.saveStructure(structureFile, structure); + saveStructure(structureFile, structure); } @Override public Structure registerStructure(NamespacedKey structureKey, Structure structure) { Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); Preconditions.checkArgument(structure != null, "Structure cannot be null"); - ResourceLocation minecraftKey = this.createAndValidateMinecraftStructureKey(structureKey); + MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); - final Optional optionalDefinedStructure = Optional.of(((CraftStructure) structure).getHandle()); - final Optional previousStructure = this.structureManager.structureRepository.put(minecraftKey, optionalDefinedStructure); - return previousStructure == null ? null : previousStructure.map((s) -> new CraftStructure(s, this.registry)).orElse(null); + final Optional optionalDefinedStructure = Optional.of(((CraftStructure) structure).getHandle()); + final Optional previousStructure = structureManager.structureRepository.put(minecraftKey, optionalDefinedStructure); + return previousStructure == null ? null : previousStructure.map((s) -> new CraftStructure(s, registry)).orElse(null); } @Override public Structure unregisterStructure(NamespacedKey structureKey) { Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); - ResourceLocation minecraftKey = this.createAndValidateMinecraftStructureKey(structureKey); + MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); - final Optional previousStructure = this.structureManager.structureRepository.remove(minecraftKey); - return previousStructure == null ? null : previousStructure.map((s) -> new CraftStructure(s, this.registry)).orElse(null); + final Optional previousStructure = structureManager.structureRepository.remove(minecraftKey); + return previousStructure == null ? null : previousStructure.map((s) -> new CraftStructure(s, registry)).orElse(null); } @Override public void deleteStructure(NamespacedKey structureKey) throws IOException { - this.deleteStructure(structureKey, true); + deleteStructure(structureKey, true); } @Override public void deleteStructure(NamespacedKey structureKey, boolean unregister) throws IOException { - ResourceLocation key = CraftNamespacedKey.toMinecraft(structureKey); + MinecraftKey key = CraftNamespacedKey.toMinecraft(structureKey); if (unregister) { - this.structureManager.structureRepository.remove(key); + structureManager.structureRepository.remove(key); } - Path path = this.structureManager.createAndValidatePathToGeneratedStructure(key, ".nbt"); + Path path = structureManager.createAndValidatePathToGeneratedStructure(key, ".nbt"); Files.deleteIfExists(path); } @Override public File getStructureFile(NamespacedKey structureKey) { - ResourceLocation minecraftKey = this.createAndValidateMinecraftStructureKey(structureKey); - return this.structureManager.createAndValidatePathToGeneratedStructure(minecraftKey, ".nbt").toFile(); + MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); + return structureManager.createAndValidatePathToGeneratedStructure(minecraftKey, ".nbt").toFile(); } @Override @@ -139,14 +139,14 @@ public Structure loadStructure(File file) throws IOException { Preconditions.checkArgument(file != null, "File cannot be null"); FileInputStream fileinputstream = new FileInputStream(file); - return this.loadStructure(fileinputstream); + return loadStructure(fileinputstream); } @Override public Structure loadStructure(InputStream inputStream) throws IOException { Preconditions.checkArgument(inputStream != null, "inputStream cannot be null"); - return new CraftStructure(this.structureManager.readStructure(inputStream), this.registry); + return new CraftStructure(structureManager.readStructure(inputStream), registry); } @Override @@ -155,7 +155,7 @@ public void saveStructure(File file, Structure structure) throws IOException { Preconditions.checkArgument(structure != null, "structure cannot be null"); FileOutputStream fileoutputstream = new FileOutputStream(file); - this.saveStructure(fileoutputstream, structure); + saveStructure(fileoutputstream, structure); } @Override @@ -163,19 +163,19 @@ public void saveStructure(OutputStream outputStream, Structure structure) throws Preconditions.checkArgument(outputStream != null, "outputStream cannot be null"); Preconditions.checkArgument(structure != null, "structure cannot be null"); - CompoundTag nbttagcompound = ((CraftStructure) structure).getHandle().save(new CompoundTag()); - NbtIo.writeCompressed(nbttagcompound, outputStream); + NBTTagCompound nbttagcompound = ((CraftStructure) structure).getHandle().save(new NBTTagCompound()); + NBTCompressedStreamTools.writeCompressed(nbttagcompound, outputStream); } @Override public Structure createStructure() { - return new CraftStructure(new StructureTemplate(), this.registry); + return new CraftStructure(new DefinedStructure(), registry); } - private ResourceLocation createAndValidateMinecraftStructureKey(NamespacedKey structureKey) { + private MinecraftKey createAndValidateMinecraftStructureKey(NamespacedKey structureKey) { Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); - ResourceLocation minecraftkey = CraftNamespacedKey.toMinecraft(structureKey); + MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(structureKey); Preconditions.checkArgument(!minecraftkey.getPath().contains("//"), "Resource key for Structures can not contain \"//\""); return minecraftkey; } @@ -183,6 +183,6 @@ private ResourceLocation createAndValidateMinecraftStructureKey(NamespacedKey st @Override public Structure copy(Structure structure) { Preconditions.checkArgument(structure != null, "Structure cannot be null"); - return new CraftStructure(this.structureManager.readStructure(((CraftStructure) structure).getHandle().save(new CompoundTag())), this.registry); + return new CraftStructure(structureManager.readStructure(((CraftStructure) structure).getHandle().save(new NBTTagCompound())), registry); } } diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java index d66bc8ce..4a92417e 100644 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java +++ b/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java @@ -2,7 +2,7 @@ import java.util.Set; import java.util.stream.Collectors; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; import net.minecraft.tags.TagKey; import net.minecraft.world.level.block.Block; import org.bukkit.Material; @@ -10,7 +10,7 @@ public class CraftBlockTag extends CraftTag { - public CraftBlockTag(Registry registry, TagKey tag) { + public CraftBlockTag(IRegistry registry, TagKey tag) { super(registry, tag); } @@ -23,11 +23,11 @@ public boolean isTagged(Material item) { return false; } - return block.builtInRegistryHolder().is(this.tag); + return block.builtInRegistryHolder().is(tag); } @Override public Set getValues() { - return this.getHandle().stream().map((block) -> CraftBlockType.minecraftToBukkit(block.value())).collect(Collectors.toUnmodifiableSet()); + return getHandle().stream().map((block) -> CraftBlockType.minecraftToBukkit(block.value())).collect(Collectors.toUnmodifiableSet()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftDamageTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftDamageTag.java new file mode 100644 index 00000000..12a26608 --- /dev/null +++ b/src/main/java/org/bukkit/craftbukkit/tag/CraftDamageTag.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.tag; + +import java.util.Set; +import java.util.stream.Collectors; +import net.minecraft.core.Holder; +import net.minecraft.core.IRegistry; +import net.minecraft.tags.TagKey; +import org.bukkit.craftbukkit.damage.CraftDamageType; +import org.bukkit.damage.DamageType; + +public class CraftDamageTag extends CraftTag { + + public CraftDamageTag(IRegistry registry, TagKey tag) { + super(registry, tag); + } + + @Override + public boolean isTagged(DamageType type) { + return CraftDamageType.bukkitToMinecraftHolder(type).is(tag); + } + + @Override + public Set getValues() { + return getHandle().stream().map(Holder::value).map(CraftDamageType::minecraftToBukkit).collect(Collectors.toUnmodifiableSet()); + } +} diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftEntityTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftEntityTag.java index 4270b771..85ec0c5c 100644 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftEntityTag.java +++ b/src/main/java/org/bukkit/craftbukkit/tag/CraftEntityTag.java @@ -3,24 +3,25 @@ import java.util.Set; import java.util.stream.Collectors; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; import net.minecraft.tags.TagKey; +import net.minecraft.world.entity.EntityTypes; import org.bukkit.craftbukkit.entity.CraftEntityType; import org.bukkit.entity.EntityType; -public class CraftEntityTag extends CraftTag, EntityType> { +public class CraftEntityTag extends CraftTag, EntityType> { - public CraftEntityTag(Registry> registry, TagKey> tag) { + public CraftEntityTag(IRegistry> registry, TagKey> tag) { super(registry, tag); } @Override public boolean isTagged(EntityType entity) { - return CraftEntityType.bukkitToMinecraft(entity).is(this.tag); + return CraftEntityType.bukkitToMinecraft(entity).is(tag); } @Override public Set getValues() { - return this.getHandle().stream().map(Holder::value).map(CraftEntityType::minecraftToBukkit).collect(Collectors.toUnmodifiableSet()); + return getHandle().stream().map(Holder::value).map(CraftEntityType::minecraftToBukkit).collect(Collectors.toUnmodifiableSet()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftFluidTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftFluidTag.java index 7f9a38f6..efb03e84 100644 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftFluidTag.java +++ b/src/main/java/org/bukkit/craftbukkit/tag/CraftFluidTag.java @@ -3,24 +3,25 @@ import java.util.Set; import java.util.stream.Collectors; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; import net.minecraft.tags.TagKey; +import net.minecraft.world.level.material.FluidType; import org.bukkit.Fluid; import org.bukkit.craftbukkit.CraftFluid; -public class CraftFluidTag extends CraftTag { +public class CraftFluidTag extends CraftTag { - public CraftFluidTag(Registry registry, TagKey tag) { + public CraftFluidTag(IRegistry registry, TagKey tag) { super(registry, tag); } @Override public boolean isTagged(Fluid fluid) { - return CraftFluid.bukkitToMinecraft(fluid).is(this.tag); + return CraftFluid.bukkitToMinecraft(fluid).is(tag); } @Override public Set getValues() { - return this.getHandle().stream().map(Holder::value).map(CraftFluid::minecraftToBukkit).collect(Collectors.toUnmodifiableSet()); + return getHandle().stream().map(Holder::value).map(CraftFluid::minecraftToBukkit).collect(Collectors.toUnmodifiableSet()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java index d9f608a0..cbf2f019 100644 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java +++ b/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java @@ -2,7 +2,7 @@ import java.util.Set; import java.util.stream.Collectors; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import org.bukkit.Material; @@ -10,7 +10,7 @@ public class CraftItemTag extends CraftTag { - public CraftItemTag(Registry registry, TagKey tag) { + public CraftItemTag(IRegistry registry, TagKey tag) { super(registry, tag); } @@ -23,11 +23,11 @@ public boolean isTagged(Material item) { return false; } - return minecraft.builtInRegistryHolder().is(this.tag); + return minecraft.builtInRegistryHolder().is(tag); } @Override public Set getValues() { - return this.getHandle().stream().map((item) -> CraftItemType.minecraftToBukkit(item.value())).collect(Collectors.toUnmodifiableSet()); + return getHandle().stream().map((item) -> CraftItemType.minecraftToBukkit(item.value())).collect(Collectors.toUnmodifiableSet()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java index b3a11f06..0f26ded9 100644 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java +++ b/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java @@ -1,7 +1,8 @@ package org.bukkit.craftbukkit.tag; +import java.util.Objects; import net.minecraft.core.HolderSet; -import net.minecraft.core.Registry; +import net.minecraft.core.IRegistry; import net.minecraft.tags.TagKey; import org.bukkit.Keyed; import org.bukkit.NamespacedKey; @@ -10,23 +11,49 @@ public abstract class CraftTag implements Tag { - protected final Registry registry; + protected final IRegistry registry; protected final TagKey tag; // private HolderSet.Named handle; - public CraftTag(Registry registry, TagKey tag) { + public CraftTag(IRegistry registry, TagKey tag) { this.registry = registry; this.tag = tag; - this.handle = registry.getTag(this.tag).orElseThrow(); + this.handle = registry.get(this.tag).orElseThrow(); } public HolderSet.Named getHandle() { - return this.handle; + return handle; } @Override public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(this.tag.location()); + return CraftNamespacedKey.fromMinecraft(tag.location()); + } + + @Override + public int hashCode() { + int hash = 3; + hash = 59 * hash + Objects.hashCode(this.registry); + hash = 59 * hash + Objects.hashCode(this.tag); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof CraftTag other)) { + return false; + } + + return Objects.equals(this.registry, other.registry) && Objects.equals(this.tag, other.tag); + } + + @Override + public String toString() { + return "CraftTag{" + this.tag + '}'; } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/ApiVersion.java b/src/main/java/org/bukkit/craftbukkit/util/ApiVersion.java index 4ffcdcbd..7f2c0bfd 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/ApiVersion.java +++ b/src/main/java/org/bukkit/craftbukkit/util/ApiVersion.java @@ -16,7 +16,7 @@ public final class ApiVersion implements Comparable, Serializable { static { versions = new HashMap<>(); - CURRENT = getOrCreateVersion("1.21.1"); + CURRENT = getOrCreateVersion("1.21.2"); FLATTENING = getOrCreateVersion("1.13"); FIELD_NAME_PARITY = getOrCreateVersion("1.20.5"); NONE = getOrCreateVersion("none"); @@ -43,10 +43,10 @@ private ApiVersion(int major, int minor, int patch) { public static ApiVersion getOrCreateVersion(String versionString) { if (versionString == null || versionString.trim().isEmpty() || versionString.equalsIgnoreCase("none")) { - return ApiVersion.versions.computeIfAbsent("none", s -> new ApiVersion()); + return versions.computeIfAbsent("none", s -> new ApiVersion()); } - ApiVersion version = ApiVersion.versions.get(versionString); + ApiVersion version = versions.get(versionString); if (version != null) { return version; @@ -58,18 +58,18 @@ public static ApiVersion getOrCreateVersion(String versionString) { throw new IllegalArgumentException(String.format("API version string should be of format \"major.minor.patch\" or \"major.minor\", where \"major\", \"minor\" and \"patch\" are numbers. For example \"1.18.2\" or \"1.13\", but got '%s' instead.", versionString)); } - int major = ApiVersion.parseNumber(versionParts[0]); - int minor = ApiVersion.parseNumber(versionParts[1]); + int major = parseNumber(versionParts[0]); + int minor = parseNumber(versionParts[1]); int patch; if (versionParts.length == 3) { - patch = ApiVersion.parseNumber(versionParts[2]); + patch = parseNumber(versionParts[2]); } else { patch = 0; } - versionString = ApiVersion.toVersionString(major, minor, patch); - return ApiVersion.versions.computeIfAbsent(versionString, s -> new ApiVersion(major, minor, patch)); + versionString = toVersionString(major, minor, patch); + return versions.computeIfAbsent(versionString, s -> new ApiVersion(major, minor, patch)); } private static int parseNumber(String number) { @@ -82,46 +82,46 @@ private static String toVersionString(int major, int minor, int patch) { @Override public int compareTo(@NotNull ApiVersion other) { - int result = Integer.compare(this.major, other.major); + int result = Integer.compare(major, other.major); if (result == 0) { - result = Integer.compare(this.minor, other.minor); + result = Integer.compare(minor, other.minor); } if (result == 0) { - result = Integer.compare(this.patch, other.patch); + result = Integer.compare(patch, other.patch); } return result; } public String getVersionString() { - if (this.none) { + if (none) { return "none"; } - return ApiVersion.toVersionString(this.major, this.minor, this.patch); + return toVersionString(major, minor, patch); } public boolean isNewerThan(ApiVersion apiVersion) { - return this.compareTo(apiVersion) > 0; + return compareTo(apiVersion) > 0; } public boolean isOlderThan(ApiVersion apiVersion) { - return this.compareTo(apiVersion) < 0; + return compareTo(apiVersion) < 0; } public boolean isNewerThanOrSameAs(ApiVersion apiVersion) { - return this.compareTo(apiVersion) >= 0; + return compareTo(apiVersion) >= 0; } public boolean isOlderThanOrSameAs(ApiVersion apiVersion) { - return this.compareTo(apiVersion) <= 0; + return compareTo(apiVersion) <= 0; } @Override public String toString() { - return this.getVersionString(); + return getVersionString(); } private static final long serialVersionUID = 0L; diff --git a/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java b/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java index ffe6881d..c889db2c 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java +++ b/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java @@ -8,85 +8,86 @@ import java.util.Set; import java.util.function.Predicate; import net.minecraft.core.BlockPos; -import net.minecraft.core.RegistryAccess; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.EntityBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.storage.LevelData; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.server.level.WorldServer; +import net.minecraft.world.level.GeneratorAccess; +import net.minecraft.world.level.block.ITileEntity; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.dimension.DimensionManager; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.storage.WorldData; import org.bukkit.block.BlockState; import org.bukkit.craftbukkit.block.CraftBlock; import org.bukkit.craftbukkit.block.CraftBlockEntityState; import org.bukkit.craftbukkit.block.CraftBlockState; public class BlockStateListPopulator extends DummyGeneratorAccess { - private final LevelAccessor world; - private final Map dataMap = new HashMap<>(); - private final Map entityMap = new HashMap<>(); + private final GeneratorAccess world; + private final Map dataMap = new HashMap<>(); + private final Map entityMap = new HashMap<>(); private final LinkedHashMap list; - public BlockStateListPopulator(LevelAccessor world) { + public BlockStateListPopulator(GeneratorAccess world) { this(world, new LinkedHashMap<>()); } - private BlockStateListPopulator(LevelAccessor world, LinkedHashMap list) { + private BlockStateListPopulator(GeneratorAccess world, LinkedHashMap list) { this.world = world; this.list = list; } @Override - public net.minecraft.world.level.block.state.BlockState getBlockState(BlockPos pos) { - net.minecraft.world.level.block.state.BlockState blockData = this.dataMap.get(pos); - return (blockData != null) ? blockData : this.world.getBlockState(pos); + public IBlockData getBlockState(BlockPos bp) { + IBlockData blockData = dataMap.get(bp); + return (blockData != null) ? blockData : world.getBlockState(bp); } @Override - public FluidState getFluidState(BlockPos pos) { - net.minecraft.world.level.block.state.BlockState blockData = this.dataMap.get(pos); - return (blockData != null) ? blockData.getFluidState() : this.world.getFluidState(pos); + public Fluid getFluidState(BlockPos bp) { + IBlockData blockData = dataMap.get(bp); + return (blockData != null) ? blockData.getFluidState() : world.getFluidState(bp); } @Override - public BlockEntity getBlockEntity(BlockPos pos) { + public TileEntity getBlockEntity(BlockPos blockposition) { // The contains is important to check for null values - if (this.entityMap.containsKey(pos)) { - return this.entityMap.get(pos); + if (entityMap.containsKey(blockposition)) { + return entityMap.get(blockposition); } - return this.world.getBlockEntity(pos); + return world.getBlockEntity(blockposition); } @Override - public boolean setBlock(BlockPos pos, net.minecraft.world.level.block.state.BlockState state, int flags) { - pos = pos.immutable(); + public boolean setBlock(BlockPos position, IBlockData data, int flag) { + position = position.immutable(); // remove first to keep insertion order - this.list.remove(pos); + list.remove(position); - this.dataMap.put(pos, state); - if (state.hasBlockEntity()) { - this.entityMap.put(pos, ((EntityBlock) state.getBlock()).newBlockEntity(pos, state)); + dataMap.put(position, data); + if (data.hasBlockEntity()) { + entityMap.put(position, ((ITileEntity) data.getBlock()).newBlockEntity(position, data)); } else { - this.entityMap.put(pos, null); + entityMap.put(position, null); } // use 'this' to ensure that the block state is the correct TileState - CraftBlockState state1 = (CraftBlockState) CraftBlock.at(this, pos).getState(); - state1.setFlag(flags); + CraftBlockState state = (CraftBlockState) CraftBlock.at(this, position).getState(); + state.setFlag(flag); // set world handle to ensure that updated calls are done to the world and not to this populator - state1.setWorldHandle(this.world); - this.list.put(pos, state1); + state.setWorldHandle(world); + list.put(position, state); return true; } @Override - public ServerLevel getMinecraftWorld() { - return this.world.getMinecraftWorld(); + public WorldServer getMinecraftWorld() { + return world.getMinecraftWorld(); } public void refreshTiles() { - for (CraftBlockState state : this.list.values()) { + for (CraftBlockState state : list.values()) { if (state instanceof CraftBlockEntityState) { ((CraftBlockEntityState) state).refreshSnapshot(); } @@ -94,62 +95,62 @@ public void refreshTiles() { } public void updateList() { - for (BlockState state : this.list.values()) { + for (BlockState state : list.values()) { state.update(true); } } public Set getBlocks() { - return this.list.keySet(); + return list.keySet(); } public List getList() { - return new ArrayList<>(this.list.values()); + return new ArrayList<>(list.values()); } - public LevelAccessor getWorld() { - return this.world; + public GeneratorAccess getWorld() { + return world; } // For tree generation @Override - public int getMinBuildHeight() { - return this.getWorld().getMinBuildHeight(); + public int getMinY() { + return getWorld().getMinY(); } @Override public int getHeight() { - return this.getWorld().getHeight(); + return getWorld().getHeight(); } @Override - public boolean isStateAtPosition(BlockPos pos, Predicate state) { - return state.test(this.getBlockState(pos)); + public boolean isStateAtPosition(BlockPos blockposition, Predicate predicate) { + return predicate.test(getBlockState(blockposition)); } @Override - public boolean isFluidAtPosition(BlockPos pos, Predicate state) { - return this.world.isFluidAtPosition(pos, state); + public boolean isFluidAtPosition(BlockPos bp, Predicate prdct) { + return world.isFluidAtPosition(bp, prdct); } @Override - public DimensionType dimensionType() { - return this.world.dimensionType(); + public DimensionManager dimensionType() { + return world.dimensionType(); } @Override - public RegistryAccess registryAccess() { - return this.world.registryAccess(); + public IRegistryCustom registryAccess() { + return world.registryAccess(); } // Needed when a tree generates in water @Override - public LevelData getLevelData() { - return this.world.getLevelData(); + public WorldData getLevelData() { + return world.getLevelData(); } @Override public long nextSubTickCount() { - return this.world.nextSubTickCount(); + return world.nextSubTickCount(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/ClassTraverser.java b/src/main/java/org/bukkit/craftbukkit/util/ClassTraverser.java index 600d7415..2e118c41 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/ClassTraverser.java +++ b/src/main/java/org/bukkit/craftbukkit/util/ClassTraverser.java @@ -18,28 +18,28 @@ public ClassTraverser(Class next) { @Override public boolean hasNext() { - return this.next != null; + return next != null; } @Override public Class next() { - Class clazz = this.next; + Class clazz = next; - this.visit.add(this.next); + visit.add(next); Set> classes = Sets.newHashSet(clazz.getInterfaces()); classes.add(clazz.getSuperclass()); classes.remove(null); // Super class can be null, remove it if this is the case - classes.removeAll(this.visit); - this.toVisit.addAll(classes); + classes.removeAll(visit); + toVisit.addAll(classes); - if (this.toVisit.isEmpty()) { - this.next = null; + if (toVisit.isEmpty()) { + next = null; return clazz; } - this.next = this.toVisit.iterator().next(); - this.toVisit.remove(this.next); + next = toVisit.iterator().next(); + toVisit.remove(next); return clazz; } diff --git a/src/main/java/org/bukkit/craftbukkit/util/Commodore.java b/src/main/java/org/bukkit/craftbukkit/util/Commodore.java index f68c54e4..7d1feb48 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/Commodore.java +++ b/src/main/java/org/bukkit/craftbukkit/util/Commodore.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.util; +import com.google.common.base.Predicates; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.io.ByteStreams; @@ -16,6 +17,7 @@ import java.util.Map; import java.util.Set; import java.util.function.Consumer; +import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -28,6 +30,7 @@ import org.bukkit.craftbukkit.legacy.MaterialRerouting; import org.bukkit.craftbukkit.legacy.MethodRerouting; import org.bukkit.craftbukkit.legacy.enums.EnumEvil; +import org.bukkit.craftbukkit.legacy.reroute.Reroute; import org.bukkit.craftbukkit.legacy.reroute.RerouteArgument; import org.bukkit.craftbukkit.legacy.reroute.RerouteBuilder; import org.bukkit.craftbukkit.legacy.reroute.RerouteMethodData; @@ -87,18 +90,38 @@ public class Commodore { "org/bukkit/block/banner/PatternType", "NOP" ); - private static Map createReroutes(Class clazz) { - Map reroutes = RerouteBuilder.buildFromClass(clazz); - REROUTES.add(reroutes); - return reroutes; + private final List reroutes = new ArrayList<>(); // only for testing + private Reroute materialReroute; + private Reroute reroute; + + public Commodore() { + } + + public Commodore(Predicate compatibilityPresent) { + updateReroute(compatibilityPresent); + } + + public void updateReroute(Predicate compatibilityPresent) { + materialReroute = RerouteBuilder + .create(compatibilityPresent) + .forClass(MaterialRerouting.class) + .build(); + reroute = RerouteBuilder + .create(compatibilityPresent) + .forClass(FieldRename.class) + .forClass(MethodRerouting.class) + .forClass(EnumEvil.class) + .build(); + + reroutes.clear(); + reroutes.add(materialReroute); + reroutes.add(reroute); } @VisibleForTesting - public static final List> REROUTES = new ArrayList<>(); // Only used for testing - private static final Map FIELD_RENAME_METHOD_REROUTE = createReroutes(FieldRename.class); - private static final Map MATERIAL_METHOD_REROUTE = createReroutes(MaterialRerouting.class); - private static final Map METHOD_REROUTE = createReroutes(MethodRerouting.class); - private static final Map ENUM_METHOD_REROUTE = createReroutes(EnumEvil.class); + public List getReroutes() { + return reroutes; + } public static void main(String[] args) { OptionParser parser = new OptionParser(); @@ -110,6 +133,8 @@ public static void main(String[] args) { File input = options.valueOf(inputFlag); File output = options.valueOf(outputFlag); + Commodore commodore = new Commodore(Predicates.alwaysTrue()); + if (input.isDirectory()) { if (!output.isDirectory()) { System.err.println("If input directory specified, output directory required too"); @@ -118,15 +143,15 @@ public static void main(String[] args) { for (File in : input.listFiles()) { if (in.getName().endsWith(".jar")) { - convert(in, new File(output, in.getName())); + convert(in, new File(output, in.getName()), commodore); } } } else { - convert(input, output); + convert(input, output, commodore); } } - private static void convert(File in, File out) { + private static void convert(File in, File out, Commodore commodore) { System.out.println("Attempting to convert " + in + " to " + out); try { @@ -144,7 +169,7 @@ private static void convert(File in, File out) { byte[] b = ByteStreams.toByteArray(is); if (entry.getName().endsWith(".class")) { - b = convert(b, "dummy", ApiVersion.NONE, Collections.emptySet()); + b = commodore.convert(b, "dummy", ApiVersion.NONE, Collections.emptySet()); entry = new JarEntry(entry.getName()); } @@ -162,11 +187,11 @@ private static void convert(File in, File out) { } } - public static byte[] convert(byte[] b, final String pluginName, final ApiVersion pluginVersion, final Set activeCompatibilities) { + public byte[] convert(byte[] b, final String pluginName, final ApiVersion pluginVersion, final Set activeCompatibilities) { final boolean modern = pluginVersion.isNewerThanOrSameAs(ApiVersion.FLATTENING); final boolean enumCompatibility = pluginVersion.isOlderThanOrSameAs(ApiVersion.getOrCreateVersion("1.20.6")) && activeCompatibilities.contains("enum-compatibility-mode"); ClassReader cr = new ClassReader(b); - ClassWriter cw = new ClassWriter(0); // TODO 2024-06-22: Open PR to ASM to included interface in handle hash + ClassWriter cw = new ClassWriter(cr, 0); List methodEnumSignatures = getMethodSignatures(b); Multimap enumLessToEnum = HashMultimap.create(); @@ -329,10 +354,7 @@ public void visitFieldInsn(int opcode, String owner, String name, String desc) { } private void handleMethod(MethodPrinter visitor, int opcode, String owner, String name, String desc, boolean itf, Type samMethodType, Type instantiatedMethodType) { - if (checkReroute(visitor, FIELD_RENAME_METHOD_REROUTE, opcode, owner, name, desc, samMethodType, instantiatedMethodType)) { - return; - } - if (checkReroute(visitor, METHOD_REROUTE, opcode, owner, name, desc, samMethodType, instantiatedMethodType)) { + if (checkReroute(visitor, reroute, opcode, owner, name, desc, samMethodType, instantiatedMethodType)) { return; } @@ -353,10 +375,6 @@ private void handleMethod(MethodPrinter visitor, int opcode, String owner, Strin } } - if (checkReroute(visitor, ENUM_METHOD_REROUTE, opcode, owner, name, desc, samMethodType, instantiatedMethodType)) { - return; - } - // SPIGOT-4496 if (owner.equals("org/bukkit/map/MapView") && name.equals("getId") && desc.equals("()S")) { // Should be same size on stack so just call other method @@ -448,15 +466,15 @@ private void handleMethod(MethodPrinter visitor, int opcode, String owner, Strin } // TODO 2024-05-21: Move this up, when material gets fully replaced with ItemType and BlockType - if (owner.startsWith("org/bukkit") && checkReroute(visitor, MATERIAL_METHOD_REROUTE, opcode, owner, name, desc, samMethodType, instantiatedMethodType)) { + if (owner.startsWith("org/bukkit") && checkReroute(visitor, materialReroute, opcode, owner, name, desc, samMethodType, instantiatedMethodType)) { return; } visitor.visit(opcode, owner, name, desc, itf, samMethodType, instantiatedMethodType); } - private boolean checkReroute(MethodPrinter visitor, Map rerouteMethodDataMap, int opcode, String owner, String name, String desc, Type samMethodType, Type instantiatedMethodType) { - return rerouteMethods(activeCompatibilities, pluginVersion, rerouteMethodDataMap, opcode == Opcodes.INVOKESTATIC || opcode == Opcodes.H_INVOKESTATIC, owner, name, desc, data -> { + private boolean checkReroute(MethodPrinter visitor, Reroute reroute, int opcode, String owner, String name, String desc, Type samMethodType, Type instantiatedMethodType) { + return rerouteMethods(pluginVersion, reroute, opcode == Opcodes.INVOKESTATIC || opcode == Opcodes.H_INVOKESTATIC, owner, name, desc, data -> { visitor.visit(Opcodes.INVOKESTATIC, className, buildMethodName(data), buildMethodDesc(data), isInterface, samMethodType, instantiatedMethodType); rerouteMethodData.add(data); }); @@ -599,69 +617,8 @@ public AnnotationVisitor visitAnnotation(String name, String descriptor) { }; } - /* - This method looks (and probably is) overengineered, but it gives the most flexible when it comes to remapping normal methods to static one. - The problem with normal owner and desc replacement is that child classes have them as an owner, instead there parents for there parents methods - - For example, if we have following two interfaces org.bukkit.BlockData and org.bukkit.Orientable extents BlockData - and BlockData has the method org.bukkit.Material getType which we want to reroute to the static method - org.bukkit.Material org.bukkit.craftbukkit.legacy.EnumEvil#getType(org.bukkit.BlockData) - - If we now call BlockData#getType we get as the owner org/bukkit/BlockData and as desc ()Lorg/bukkit/Material; - Which we can nicely reroute by checking if the owner is BlockData and the name getType - The problem, starts if we use Orientable#getType no we get as owner org/bukkit/Orientable and as desc ()Lorg/bukkit/Material; - Now we can now longer safely say to which getType method we need to reroute (assume there are multiple getType methods from different classes, - which are not related to BlockData), simple using the owner class will not work, since would reroute to - EnumEvil#getType(org.bukkit.Orientable) which is not EnumEvil#getType(org.bukkit.BlockData) and will throw a method not found error - at runtime. - - Meaning we would need to add checks for each subclass, which would be pur insanity. - - To solve this, we go through each super class and interfaces (and their super class and interfaces etc.) and try to get an owner - which matches with one of our replacement methods. Based on how inheritance works in java, this method should be safe to use. - - As a site note: This method could also be used for the other method reroute, e.g. legacy method rerouting, where only the replacement - method needs to be written, and this method figures out the rest, which could reduce the size and complexity of the Commodore class. - The question then becomes one about performance (since this is not the most performance way) and convenience. - But since it is only applied for each class and method call once when they get first loaded, it should not be that bad. - (Although some load time testing could be done) - */ - public static boolean rerouteMethods(Set activeCompatibilities, ApiVersion pluginVersion, Map rerouteMethodDataMap, boolean staticCall, String owner, String name, String desc, Consumer consumer) { - Type ownerType = Type.getObjectType(owner); - Class ownerClass; - try { - ownerClass = Class.forName(ownerType.getClassName()); - } catch (ClassNotFoundException e) { - return false; - } - - ClassTraverser it = new ClassTraverser(ownerClass); - while (it.hasNext()) { - Class clazz = it.next(); - - String methodKey = Type.getInternalName(clazz) + " " + desc + " " + name; - - RerouteMethodData data = rerouteMethodDataMap.get(methodKey); - if (data == null) { - if (staticCall) { - return false; - } - continue; - } - - if (data.requiredCompatibility() != null && !activeCompatibilities.contains(data.requiredCompatibility())) { - return false; - } - - if (data.requiredPluginVersion() != null && !data.requiredPluginVersion().test(pluginVersion)) { - return false; - } - - consumer.accept(data); - return true; - } - - return false; + public static boolean rerouteMethods(ApiVersion pluginVersion, Reroute reroute, boolean staticCall, String owner, String name, String desc, Consumer consumer) { + return reroute.apply(pluginVersion, owner, name, desc, staticCall, consumer); } private static List getMethodSignatures(byte[] clazz) { diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftBiomeSearchResult.java b/src/main/java/org/bukkit/craftbukkit/util/CraftBiomeSearchResult.java index 2c82b228..fede3daf 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftBiomeSearchResult.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftBiomeSearchResult.java @@ -15,10 +15,10 @@ public CraftBiomeSearchResult(Biome biome, Location location) { } public Biome getBiome() { - return this.biome; + return biome; } public Location getLocation() { - return this.location; + return location; } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftBlockVector.java b/src/main/java/org/bukkit/craftbukkit/util/CraftBlockVector.java index 001d2edb..b316fbf6 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftBlockVector.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftBlockVector.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.util; +import net.minecraft.core.BaseBlockPos; import net.minecraft.core.BlockPos; -import net.minecraft.core.Vec3i; import org.bukkit.util.BlockVector; public final class CraftBlockVector { @@ -9,11 +9,11 @@ public final class CraftBlockVector { private CraftBlockVector() { } - public static BlockPos toBlockPosition(BlockVector blockVector) { + public static BlockPos toBlockPos(BlockVector blockVector) { return new BlockPos(blockVector.getBlockX(), blockVector.getBlockY(), blockVector.getBlockZ()); } - public static BlockVector toBukkit(Vec3i baseBlockPosition) { - return new BlockVector(baseBlockPosition.getX(), baseBlockPosition.getY(), baseBlockPosition.getZ()); + public static BlockVector toBukkit(BaseBlockPos baseBlockPos) { + return new BlockVector(baseBlockPos.getX(), baseBlockPos.getY(), baseBlockPos.getZ()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java index 594819d6..7b18149e 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java @@ -5,18 +5,19 @@ import com.google.gson.JsonParseException; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.ClickEvent; -import net.minecraft.network.chat.ClickEvent.Action; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.Style; -import net.minecraft.network.chat.TextColor; -import net.minecraft.network.chat.contents.PlainTextContents; +import net.minecraft.EnumChatFormat; +import net.minecraft.network.chat.ChatClickable; +import net.minecraft.network.chat.ChatClickable.EnumClickAction; +import net.minecraft.network.chat.ChatHexColor; +import net.minecraft.network.chat.ChatModifier; +import net.minecraft.network.chat.IChatBaseComponent; +import net.minecraft.network.chat.IChatMutableComponent; +import net.minecraft.network.chat.contents.LiteralContents; import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.server.MinecraftServer; import org.bukkit.ChatColor; @@ -24,21 +25,21 @@ public final class CraftChatMessage { private static final Pattern LINK_PATTERN = Pattern.compile("((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + " \\n]|$))))"); - private static final Map formatMap; + private static final Map formatMap; static { - Builder builder = ImmutableMap.builder(); - for (ChatFormatting format : ChatFormatting.values()) { + Builder builder = ImmutableMap.builder(); + for (EnumChatFormat format : EnumChatFormat.values()) { builder.put(Character.toLowerCase(format.toString().charAt(1)), format); } formatMap = builder.build(); } - public static ChatFormatting getColor(ChatColor color) { - return CraftChatMessage.formatMap.get(color.getChar()); + public static EnumChatFormat getColor(ChatColor color) { + return formatMap.get(color.getChar()); } - public static ChatColor getColor(ChatFormatting format) { + public static ChatColor getColor(EnumChatFormat format) { return ChatColor.getByChar(format.code); } @@ -47,12 +48,12 @@ private static final class StringMessage { // Separate pattern with no group 3, new lines are part of previous string private static final Pattern INCREMENTAL_PATTERN_KEEP_NEWLINES = Pattern.compile("(" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + "[0-9a-fk-orx])|((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + " ]|$))))", Pattern.CASE_INSENSITIVE); // ChatColor.b does not explicitly reset, its more of empty - private static final Style RESET = Style.EMPTY.withBold(false).withItalic(false).withUnderlined(false).withStrikethrough(false).withObfuscated(false); + private static final ChatModifier RESET = ChatModifier.EMPTY.withBold(false).withItalic(false).withUnderlined(false).withStrikethrough(false).withObfuscated(false); - private final List list = new ArrayList(); - private MutableComponent currentChatComponent = Component.empty(); - private Style modifier = Style.EMPTY; - private final Component[] output; + private final List list = new ArrayList(); + private IChatMutableComponent currentChatComponent = IChatBaseComponent.empty(); + private ChatModifier modifier = ChatModifier.EMPTY; + private final IChatBaseComponent[] output; private int currentIndex; private StringBuilder hex; private final String message; @@ -60,12 +61,12 @@ private static final class StringMessage { private StringMessage(String message, boolean keepNewlines, boolean plain) { this.message = message; if (message == null) { - this.output = new Component[]{this.currentChatComponent}; + output = new IChatBaseComponent[]{currentChatComponent}; return; } - this.list.add(this.currentChatComponent); + list.add(currentChatComponent); - Matcher matcher = (keepNewlines ? StringMessage.INCREMENTAL_PATTERN_KEEP_NEWLINES : StringMessage.INCREMENTAL_PATTERN).matcher(message); + Matcher matcher = (keepNewlines ? INCREMENTAL_PATTERN_KEEP_NEWLINES : INCREMENTAL_PATTERN).matcher(message); String match = null; boolean needsAdd = false; while (matcher.find()) { @@ -74,174 +75,173 @@ private StringMessage(String message, boolean keepNewlines, boolean plain) { // NOOP } int index = matcher.start(groupId); - if (index > this.currentIndex) { + if (index > currentIndex) { needsAdd = false; - this.appendNewComponent(index); + appendNewComponent(index); } switch (groupId) { case 1: - char c = match.toLowerCase(java.util.Locale.ENGLISH).charAt(1); - ChatFormatting format = CraftChatMessage.formatMap.get(c); + char c = match.toLowerCase(Locale.ROOT).charAt(1); + EnumChatFormat format = formatMap.get(c); if (c == 'x') { - this.hex = new StringBuilder("#"); - } else if (this.hex != null) { - this.hex.append(c); + hex = new StringBuilder("#"); + } else if (hex != null) { + hex.append(c); - if (this.hex.length() == 7) { - this.modifier = StringMessage.RESET.withColor(TextColor.parseColor(this.hex.toString()).result().get()); - this.hex = null; + if (hex.length() == 7) { + modifier = RESET.withColor(ChatHexColor.parseColor(hex.toString()).result().get()); + hex = null; } - } else if (format.isFormat() && format != ChatFormatting.RESET) { + } else if (format.isFormat() && format != EnumChatFormat.RESET) { switch (format) { case BOLD: - this.modifier = this.modifier.withBold(Boolean.TRUE); + modifier = modifier.withBold(Boolean.TRUE); break; case ITALIC: - this.modifier = this.modifier.withItalic(Boolean.TRUE); + modifier = modifier.withItalic(Boolean.TRUE); break; case STRIKETHROUGH: - this.modifier = this.modifier.withStrikethrough(Boolean.TRUE); + modifier = modifier.withStrikethrough(Boolean.TRUE); break; case UNDERLINE: - this.modifier = this.modifier.withUnderlined(Boolean.TRUE); + modifier = modifier.withUnderlined(Boolean.TRUE); break; case OBFUSCATED: - this.modifier = this.modifier.withObfuscated(Boolean.TRUE); + modifier = modifier.withObfuscated(Boolean.TRUE); break; default: throw new AssertionError("Unexpected message format"); } } else { // Color resets formatting - this.modifier = StringMessage.RESET.withColor(format); + modifier = RESET.withColor(format); } needsAdd = true; break; case 2: if (plain) { - this.appendNewComponent(matcher.end(groupId)); + appendNewComponent(matcher.end(groupId)); } else { if (!(match.startsWith("http://") || match.startsWith("https://"))) { match = "http://" + match; } - this.modifier = this.modifier.withClickEvent(new ClickEvent(Action.OPEN_URL, match)); - this.appendNewComponent(matcher.end(groupId)); - this.modifier = this.modifier.withClickEvent((ClickEvent) null); + modifier = modifier.withClickEvent(new ChatClickable(EnumClickAction.OPEN_URL, match)); + appendNewComponent(matcher.end(groupId)); + modifier = modifier.withClickEvent((ChatClickable) null); } break; case 3: if (needsAdd) { - this.appendNewComponent(index); + appendNewComponent(index); } - this.currentChatComponent = null; + currentChatComponent = null; break; } - this.currentIndex = matcher.end(groupId); + currentIndex = matcher.end(groupId); } - if (this.currentIndex < message.length() || needsAdd) { - this.appendNewComponent(message.length()); + if (currentIndex < message.length() || needsAdd) { + appendNewComponent(message.length()); } - this.output = this.list.toArray(new Component[this.list.size()]); + output = list.toArray(new IChatBaseComponent[list.size()]); } private void appendNewComponent(int index) { - Component addition = Component.literal(this.message.substring(this.currentIndex, index)).setStyle(this.modifier); - this.currentIndex = index; - if (this.currentChatComponent == null) { - this.currentChatComponent = Component.empty(); - this.list.add(this.currentChatComponent); + IChatBaseComponent addition = IChatBaseComponent.literal(message.substring(currentIndex, index)).setStyle(modifier); + currentIndex = index; + if (currentChatComponent == null) { + currentChatComponent = IChatBaseComponent.empty(); + list.add(currentChatComponent); } - this.currentChatComponent.append(addition); + currentChatComponent.append(addition); } - private Component[] getOutput() { - return this.output; + private IChatBaseComponent[] getOutput() { + return output; } } - public static Optional fromStringOrOptional(String message) { - return Optional.ofNullable(CraftChatMessage.fromStringOrNull(message)); + public static Optional fromStringOrOptional(String message) { + return Optional.ofNullable(fromStringOrNull(message)); } - public static Optional fromStringOrOptional(String message, boolean keepNewlines) { - return Optional.ofNullable(CraftChatMessage.fromStringOrNull(message, keepNewlines)); + public static Optional fromStringOrOptional(String message, boolean keepNewlines) { + return Optional.ofNullable(fromStringOrNull(message, keepNewlines)); } - public static Component fromStringOrNull(String message) { - return CraftChatMessage.fromStringOrNull(message, false); + public static IChatBaseComponent fromStringOrNull(String message) { + return fromStringOrNull(message, false); } - public static Component fromStringOrNull(String message, boolean keepNewlines) { - return (message == null || message.isEmpty()) ? null : CraftChatMessage.fromString(message, keepNewlines)[0]; + public static IChatBaseComponent fromStringOrNull(String message, boolean keepNewlines) { + return (message == null || message.isEmpty()) ? null : fromString(message, keepNewlines)[0]; } - public static Component fromStringOrEmpty(String message) { + public static IChatBaseComponent fromStringOrEmpty(String message) { return fromStringOrEmpty(message, false); } - public static Component fromStringOrEmpty(String message, boolean keepNewlines) { + public static IChatBaseComponent fromStringOrEmpty(String message, boolean keepNewlines) { return fromString(message, keepNewlines)[0]; } - public static Component[] fromString(String message) { - return CraftChatMessage.fromString(message, false); + public static IChatBaseComponent[] fromString(String message) { + return fromString(message, false); } - public static Component[] fromString(String message, boolean keepNewlines) { - return CraftChatMessage.fromString(message, keepNewlines, false); + public static IChatBaseComponent[] fromString(String message, boolean keepNewlines) { + return fromString(message, keepNewlines, false); } - public static Component[] fromString(String message, boolean keepNewlines, boolean plain) { + public static IChatBaseComponent[] fromString(String message, boolean keepNewlines, boolean plain) { return new StringMessage(message, keepNewlines, plain).getOutput(); } - public static String toJSON(Component component) { - return Component.Serializer.toJson(component, MinecraftServer.getDefaultRegistryAccess()); + public static String toJSON(IChatBaseComponent component) { + return IChatBaseComponent.ChatSerializer.toJson(component, MinecraftServer.getDefaultRegistryAccess()); } - public static String toJSONOrNull(Component component) { + public static String toJSONOrNull(IChatBaseComponent component) { if (component == null) return null; - return CraftChatMessage.toJSON(component); + return toJSON(component); } - public static Component fromJSON(String jsonMessage) throws JsonParseException { + public static IChatBaseComponent fromJSON(String jsonMessage) throws JsonParseException { // Note: This also parses plain Strings to text components. // Note: An empty message (empty, or only consisting of whitespace) results in null rather than a parse exception. - return Component.Serializer.fromJson(jsonMessage, MinecraftServer.getDefaultRegistryAccess()); + return IChatBaseComponent.ChatSerializer.fromJson(jsonMessage, MinecraftServer.getDefaultRegistryAccess()); } - public static Component fromJSONOrNull(String jsonMessage) { + public static IChatBaseComponent fromJSONOrNull(String jsonMessage) { if (jsonMessage == null) return null; try { - return CraftChatMessage.fromJSON(jsonMessage); // Can return null + return fromJSON(jsonMessage); // Can return null } catch (JsonParseException ex) { return null; } } - public static Component fromJSONOrString(String message) { - return CraftChatMessage.fromJSONOrString(message, false); + public static IChatBaseComponent fromJSONOrString(String message) { + return fromJSONOrString(message, false); } - public static Component fromJSONOrString(String message, boolean keepNewlines) { - return CraftChatMessage.fromJSONOrString(message, false, keepNewlines); + public static IChatBaseComponent fromJSONOrString(String message, boolean keepNewlines) { + return fromJSONOrString(message, false, keepNewlines); } - public static Component fromJSONOrString(String message, boolean nullable, boolean keepNewlines) { + public static IChatBaseComponent fromJSONOrString(String message, boolean nullable, boolean keepNewlines) { return fromJSONOrString(message, nullable, keepNewlines, Integer.MAX_VALUE, false); } - public static Component fromJSONOrString(String message, boolean nullable, boolean keepNewlines, int maxLength, boolean checkJsonContentLength) { + public static IChatBaseComponent fromJSONOrString(String message, boolean nullable, boolean keepNewlines, int maxLength, boolean checkJsonContentLength) { if (message == null) message = ""; if (nullable && message.isEmpty()) return null; - // If the input can be parsed as JSON, we use that: - Component component = CraftChatMessage.fromJSONOrNull(message); + IChatBaseComponent component = fromJSONOrNull(message); if (component != null) { if (checkJsonContentLength) { - String content = CraftChatMessage.fromComponent(component); - String trimmedContent = CraftChatMessage.trimMessage(content, maxLength); + String content = fromComponent(component); + String trimmedContent = trimMessage(content, maxLength); if (content != trimmedContent) { // Identity comparison is fine here // Note: The resulting text has all non-plain text features stripped. return fromString(trimmedContent, keepNewlines)[0]; @@ -249,7 +249,7 @@ public static Component fromJSONOrString(String message, boolean nullable, boole } return component; } else { - message = CraftChatMessage.trimMessage(message, maxLength); + message = trimMessage(message, maxLength); return fromString(message, keepNewlines)[0]; } } @@ -262,15 +262,15 @@ public static String trimMessage(String message, int maxLength) { } } - public static String fromComponent(Component component) { + public static String fromComponent(IChatBaseComponent component) { if (component == null) return ""; StringBuilder out = new StringBuilder(); boolean hadFormat = false; - for (Component c : component) { - Style modi = c.getStyle(); - TextColor color = modi.getColor(); - if (c.getContents() != PlainTextContents.EMPTY || color != null) { + for (IChatBaseComponent c : component) { + ChatModifier modi = c.getStyle(); + ChatHexColor color = modi.getColor(); + if (c.getContents() != LiteralContents.EMPTY || color != null) { if (color != null) { if (color.format != null) { out.append(color.format); @@ -287,23 +287,23 @@ public static String fromComponent(Component component) { } } if (modi.isBold()) { - out.append(ChatFormatting.BOLD); + out.append(EnumChatFormat.BOLD); hadFormat = true; } if (modi.isItalic()) { - out.append(ChatFormatting.ITALIC); + out.append(EnumChatFormat.ITALIC); hadFormat = true; } if (modi.isUnderlined()) { - out.append(ChatFormatting.UNDERLINE); + out.append(EnumChatFormat.UNDERLINE); hadFormat = true; } if (modi.isStrikethrough()) { - out.append(ChatFormatting.STRIKETHROUGH); + out.append(EnumChatFormat.STRIKETHROUGH); hadFormat = true; } if (modi.isObfuscated()) { - out.append(ChatFormatting.OBFUSCATED); + out.append(EnumChatFormat.OBFUSCATED); hadFormat = true; } c.getContents().visit((x) -> { @@ -314,22 +314,22 @@ public static String fromComponent(Component component) { return out.toString(); } - public static Component fixComponent(MutableComponent component) { - Matcher matcher = CraftChatMessage.LINK_PATTERN.matcher(""); - return CraftChatMessage.fixComponent(component, matcher); + public static IChatBaseComponent fixComponent(IChatMutableComponent component) { + Matcher matcher = LINK_PATTERN.matcher(""); + return fixComponent(component, matcher); } - private static Component fixComponent(MutableComponent component, Matcher matcher) { - if (component.getContents() instanceof PlainTextContents) { - PlainTextContents text = ((PlainTextContents) component.getContents()); + private static IChatBaseComponent fixComponent(IChatMutableComponent component, Matcher matcher) { + if (component.getContents() instanceof LiteralContents) { + LiteralContents text = ((LiteralContents) component.getContents()); String msg = text.text(); if (matcher.reset(msg).find()) { matcher.reset(); - Style modifier = component.getStyle(); - List extras = new ArrayList(); - List extrasOld = new ArrayList(component.getSiblings()); - component = Component.empty(); + ChatModifier modifier = component.getStyle(); + List extras = new ArrayList(); + List extrasOld = new ArrayList(component.getSiblings()); + component = IChatBaseComponent.empty(); int pos = 0; while (matcher.find()) { @@ -339,34 +339,34 @@ private static Component fixComponent(MutableComponent component, Matcher matche match = "http://" + match; } - MutableComponent prev = Component.literal(msg.substring(pos, matcher.start())); + IChatMutableComponent prev = IChatBaseComponent.literal(msg.substring(pos, matcher.start())); prev.setStyle(modifier); extras.add(prev); - MutableComponent link = Component.literal(matcher.group()); - Style linkModi = modifier.withClickEvent(new ClickEvent(Action.OPEN_URL, match)); + IChatMutableComponent link = IChatBaseComponent.literal(matcher.group()); + ChatModifier linkModi = modifier.withClickEvent(new ChatClickable(EnumClickAction.OPEN_URL, match)); link.setStyle(linkModi); extras.add(link); pos = matcher.end(); } - MutableComponent prev = Component.literal(msg.substring(pos)); + IChatMutableComponent prev = IChatBaseComponent.literal(msg.substring(pos)); prev.setStyle(modifier); extras.add(prev); extras.addAll(extrasOld); - for (Component c : extras) { + for (IChatBaseComponent c : extras) { component.append(c); } } } - List extras = component.getSiblings(); + List extras = component.getSiblings(); for (int i = 0; i < extras.size(); i++) { - Component comp = extras.get(i); + IChatBaseComponent comp = extras.get(i); if (comp.getStyle() != null && comp.getStyle().getClickEvent() == null) { - extras.set(i, CraftChatMessage.fixComponent(comp.copy(), matcher)); + extras.set(i, fixComponent(comp.copy(), matcher)); } } @@ -374,13 +374,13 @@ private static Component fixComponent(MutableComponent component, Matcher matche Object[] subs = ((TranslatableContents) component.getContents()).getArgs(); for (int i = 0; i < subs.length; i++) { Object comp = subs[i]; - if (comp instanceof Component) { - Component c = (Component) comp; + if (comp instanceof IChatBaseComponent) { + IChatBaseComponent c = (IChatBaseComponent) comp; if (c.getStyle() != null && c.getStyle().getClickEvent() == null) { - subs[i] = CraftChatMessage.fixComponent(c.copy(), matcher); + subs[i] = fixComponent(c.copy(), matcher); } } else if (comp instanceof String && matcher.reset((String) comp).find()) { - subs[i] = CraftChatMessage.fixComponent(Component.literal((String) comp), matcher); + subs[i] = fixComponent(IChatBaseComponent.literal((String) comp), matcher); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftDimensionUtil.java b/src/main/java/org/bukkit/craftbukkit/util/CraftDimensionUtil.java index b52a8543..61538c8b 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftDimensionUtil.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftDimensionUtil.java @@ -1,22 +1,22 @@ package org.bukkit.craftbukkit.util; import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.World; +import net.minecraft.world.level.dimension.WorldDimension; public class CraftDimensionUtil { private CraftDimensionUtil() { } - public static ResourceKey getMainDimensionKey(Level world) { - ResourceKey typeKey = world.getTypeKey(); - if (typeKey == LevelStem.OVERWORLD) { - return Level.OVERWORLD; - } else if (typeKey == LevelStem.NETHER) { - return Level.NETHER; - } else if (typeKey == LevelStem.END) { - return Level.END; + public static ResourceKey getMainDimensionKey(World world) { + ResourceKey typeKey = world.getTypeKey(); + if (typeKey == WorldDimension.OVERWORLD) { + return World.OVERWORLD; + } else if (typeKey == WorldDimension.NETHER) { + return World.NETHER; + } else if (typeKey == WorldDimension.END) { + return World.END; } return world.dimension(); diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftLocation.java b/src/main/java/org/bukkit/craftbukkit/util/CraftLocation.java index 097996d3..1cacea3f 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftLocation.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftLocation.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.util; import net.minecraft.core.BlockPos; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.Vec3D; import org.bukkit.Location; import org.bukkit.World; @@ -10,37 +10,37 @@ public final class CraftLocation { private CraftLocation() { } - public static Location toBukkit(Vec3 vec3D) { - return CraftLocation.toBukkit(vec3D, null); + public static Location toBukkit(Vec3D vec3D) { + return toBukkit(vec3D, null); } - public static Location toBukkit(Vec3 vec3D, World world) { - return CraftLocation.toBukkit(vec3D, world, 0.0F, 0.0F); + public static Location toBukkit(Vec3D vec3D, World world) { + return toBukkit(vec3D, world, 0.0F, 0.0F); } - public static Location toBukkit(Vec3 vec3D, World world, float yaw, float pitch) { + public static Location toBukkit(Vec3D vec3D, World world, float yaw, float pitch) { return new Location(world, vec3D.x(), vec3D.y(), vec3D.z(), yaw, pitch); } public static Location toBukkit(BlockPos blockPosition) { - return CraftLocation.toBukkit(blockPosition, (World) null); + return toBukkit(blockPosition, (World) null); } - public static Location toBukkit(BlockPos blockPosition, net.minecraft.world.level.Level world) { - return CraftLocation.toBukkit(blockPosition, world.getWorld(), 0.0F, 0.0F); + public static Location toBukkit(BlockPos blockPosition, net.minecraft.world.level.World world) { + return toBukkit(blockPosition, world.getWorld(), 0.0F, 0.0F); } public static Location toBukkit(BlockPos blockPosition, World world) { - return CraftLocation.toBukkit(blockPosition, world, 0.0F, 0.0F); + return toBukkit(blockPosition, world, 0.0F, 0.0F); } public static Location toBukkit(BlockPos blockPosition, World world, float yaw, float pitch) { return new Location(world, blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), yaw, pitch); } - public static BlockPos toBlockPosition(Location location) { + public static BlockPos toBlockPos(Location location) { return new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } - public static Vec3 toVec3D(Location location) { - return new Vec3(location.getX(), location.getY(), location.getZ()); + public static Vec3D toVec3D(Location location) { + return new Vec3D(location.getX(), location.getY(), location.getZ()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java index 2ea2c6c6..20cd67e1 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java @@ -2,11 +2,11 @@ import com.google.common.base.Charsets; import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.io.Files; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.serialization.Dynamic; @@ -20,24 +20,23 @@ import java.util.logging.Logger; import net.minecraft.SharedConstants; import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.commands.Commands; -import net.minecraft.commands.arguments.item.ItemParser; +import net.minecraft.commands.CommandDispatcher; +import net.minecraft.commands.arguments.item.ArgumentParserItemStack; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.nbt.DynamicOpsNBT; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagString; +import net.minecraft.resources.MinecraftKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerAdvancementManager; -import net.minecraft.util.datafix.DataFixers; -import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.DataConverterRegistry; +import net.minecraft.util.datafix.fixes.DataConverterTypes; +import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.item.Item; -import net.minecraft.world.item.alchemy.Potion; -import net.minecraft.world.item.component.ItemAttributeModifiers; +import net.minecraft.world.item.alchemy.PotionRegistry; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.LevelResource; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.storage.SavedFile; import org.bukkit.Bukkit; import org.bukkit.FeatureFlag; import org.bukkit.Keyed; @@ -49,11 +48,10 @@ import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.CraftEquipmentSlot; import org.bukkit.craftbukkit.CraftFeatureFlag; import org.bukkit.craftbukkit.CraftRegistry; +import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.attribute.CraftAttribute; -import org.bukkit.craftbukkit.attribute.CraftAttributeInstance; import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.bukkit.craftbukkit.damage.CraftDamageEffect; import org.bukkit.craftbukkit.damage.CraftDamageSourceBuilder; @@ -76,20 +74,22 @@ @SuppressWarnings("deprecation") public final class CraftMagicNumbers implements UnsafeValues { - public static final UnsafeValues INSTANCE = new CraftMagicNumbers(); + public static final CraftMagicNumbers INSTANCE = new CraftMagicNumbers(); + + private final Commodore commodore = new Commodore(); private CraftMagicNumbers() {} - public static BlockState getBlock(MaterialData material) { - return CraftMagicNumbers.getBlock(material.getItemType(), material.getData()); + public static IBlockData getBlock(MaterialData material) { + return getBlock(material.getItemType(), material.getData()); } - public static BlockState getBlock(Material material, byte data) { + public static IBlockData getBlock(Material material, byte data) { return CraftLegacy.fromLegacyData(CraftLegacy.toLegacy(material), data); } - public static MaterialData getMaterial(BlockState data) { - return CraftLegacy.toLegacy(CraftMagicNumbers.getMaterial(data.getBlock())).getNewData(CraftMagicNumbers.toLegacyData(data)); + public static MaterialData getMaterial(IBlockData data) { + return CraftLegacy.toLegacy(getMaterial(data.getBlock())).getNewData(toLegacyData(data)); } public static Item getItem(Material material, short data) { @@ -97,18 +97,18 @@ public static Item getItem(Material material, short data) { return CraftLegacy.fromLegacyData(CraftLegacy.toLegacy(material), data); } - return CraftMagicNumbers.getItem(material); + return getItem(material); } public static MaterialData getMaterialData(Item item) { - return CraftLegacy.toLegacyData(CraftMagicNumbers.getMaterial(item)); + return CraftLegacy.toLegacyData(getMaterial(item)); } // ======================================================================== - public static final Map BLOCK_MATERIAL = new HashMap<>(); - public static final Map ITEM_MATERIAL = new HashMap<>(); - public static final Map MATERIAL_ITEM = new HashMap<>(); - public static final Map MATERIAL_BLOCK = new HashMap<>(); + private static final Map BLOCK_MATERIAL = new HashMap<>(); + private static final Map ITEM_MATERIAL = new HashMap<>(); + private static final Map MATERIAL_ITEM = new HashMap<>(); + private static final Map MATERIAL_BLOCK = new HashMap<>(); static { for (Block block : BuiltInRegistries.BLOCK) { @@ -124,22 +124,22 @@ public static MaterialData getMaterialData(Item item) { continue; } - ResourceLocation key = key(material); + MinecraftKey key = key(material); BuiltInRegistries.ITEM.getOptional(key).ifPresent((item) -> { - CraftMagicNumbers.MATERIAL_ITEM.put(material, item); + MATERIAL_ITEM.put(material, item); }); BuiltInRegistries.BLOCK.getOptional(key).ifPresent((block) -> { - CraftMagicNumbers.MATERIAL_BLOCK.put(material, block); + MATERIAL_BLOCK.put(material, block); }); } } public static Material getMaterial(Block block) { - return CraftMagicNumbers.BLOCK_MATERIAL.get(block); + return BLOCK_MATERIAL.get(block); } public static Material getMaterial(Item item) { - return CraftMagicNumbers.ITEM_MATERIAL.getOrDefault(item, Material.AIR); + return ITEM_MATERIAL.getOrDefault(item, Material.AIR); } public static Item getItem(Material material) { @@ -147,7 +147,7 @@ public static Item getItem(Material material) { material = CraftLegacy.fromLegacy(material); } - return CraftMagicNumbers.MATERIAL_ITEM.get(material); + return MATERIAL_ITEM.get(material); } public static Block getBlock(Material material) { @@ -155,18 +155,22 @@ public static Block getBlock(Material material) { material = CraftLegacy.fromLegacy(material); } - return CraftMagicNumbers.MATERIAL_BLOCK.get(material); + return MATERIAL_BLOCK.get(material); } - public static ResourceLocation key(Material mat) { + public static MinecraftKey key(Material mat) { return CraftNamespacedKey.toMinecraft(mat.getKey()); } // ======================================================================== - public static byte toLegacyData(BlockState data) { + public static byte toLegacyData(IBlockData data) { return CraftLegacy.toLegacyData(data); } + public Commodore getCommodore() { + return this.commodore; + } + @Override public Material toLegacy(Material material) { return CraftLegacy.toLegacy(material); @@ -189,7 +193,7 @@ public Material fromLegacy(MaterialData material, boolean itemPriority) { @Override public BlockData fromLegacy(Material material, byte data) { - return CraftBlockData.fromData(CraftMagicNumbers.getBlock(material, data)); + return CraftBlockData.fromData(getBlock(material, data)); } @Override @@ -202,11 +206,11 @@ public Material getMaterial(String material, int version) { return Material.getMaterial(material); } - Dynamic name = new Dynamic<>(NbtOps.INSTANCE, StringTag.valueOf("minecraft:" + material.toLowerCase(Locale.ROOT))); - Dynamic converted = DataFixers.getDataFixer().update(References.ITEM_NAME, name, version, this.getDataVersion()); + Dynamic name = new Dynamic<>(DynamicOpsNBT.INSTANCE, NBTTagString.valueOf("minecraft:" + material.toLowerCase(Locale.ROOT))); + Dynamic converted = DataConverterRegistry.getDataFixer().update(DataConverterTypes.ITEM_NAME, name, version, this.getDataVersion()); if (name.equals(converted)) { - converted = DataFixers.getDataFixer().update(References.BLOCK_NAME, name, version, this.getDataVersion()); + converted = DataConverterRegistry.getDataFixer().update(DataConverterTypes.BLOCK_NAME, name, version, this.getDataVersion()); } return Material.matchMaterial(converted.asString("")); @@ -228,7 +232,7 @@ public Material getMaterial(String material, int version) { * @return string */ public String getMappingsVersion() { - return "7092ff1ff9352ad7e2260dc150e6a3ec"; + return "ec8b033a89c54252f1dfcb809eab710a"; } @Override @@ -241,7 +245,7 @@ public ItemStack modifyItemStack(ItemStack stack, String arguments) { net.minecraft.world.item.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack); try { - nmsStack.applyComponents(new ItemParser(Commands.createValidationContext(MinecraftServer.getDefaultRegistryAccess())).parse(new StringReader(arguments)).components()); + nmsStack.applyComponents(new ArgumentParserItemStack(CommandDispatcher.createValidationContext(MinecraftServer.getDefaultRegistryAccess())).parse(new StringReader(arguments)).components()); } catch (CommandSyntaxException ex) { Logger.getLogger(CraftMagicNumbers.class.getName()).log(Level.SEVERE, null, ex); } @@ -252,22 +256,22 @@ public ItemStack modifyItemStack(ItemStack stack, String arguments) { } private static File getBukkitDataPackFolder() { - return new File(MinecraftServer.getServer().getWorldPath(LevelResource.DATAPACK_DIR).toFile(), "bukkit"); + return new File(MinecraftServer.getServer().getWorldPath(SavedFile.DATAPACK_DIR).toFile(), "bukkit"); } @Override public Advancement loadAdvancement(NamespacedKey key, String advancement) { Preconditions.checkArgument(Bukkit.getAdvancement(key) == null, "Advancement %s already exists", key); - ResourceLocation minecraftkey = CraftNamespacedKey.toMinecraft(key); + MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(key); - JsonElement jsonelement = ServerAdvancementManager.GSON.fromJson(advancement, JsonElement.class); + JsonElement jsonelement = JsonParser.parseString(advancement); net.minecraft.advancements.Advancement nms = net.minecraft.advancements.Advancement.CODEC.parse(JsonOps.INSTANCE, jsonelement).getOrThrow(JsonParseException::new); if (nms != null) { MinecraftServer.getServer().getAdvancements().advancements.put(minecraftkey, new AdvancementHolder(minecraftkey, nms)); Advancement bukkit = Bukkit.getAdvancement(key); if (bukkit != null) { - File file = new File(CraftMagicNumbers.getBukkitDataPackFolder(), "data" + File.separator + key.getNamespace() + File.separator + "advancements" + File.separator + key.getKey() + ".json"); + File file = new File(getBukkitDataPackFolder(), "data" + File.separator + key.getNamespace() + File.separator + "advancements" + File.separator + key.getKey() + ".json"); file.getParentFile().mkdirs(); try { @@ -287,7 +291,7 @@ public Advancement loadAdvancement(NamespacedKey key, String advancement) { @Override public boolean removeAdvancement(NamespacedKey key) { - File file = new File(CraftMagicNumbers.getBukkitDataPackFolder(), "data" + File.separator + key.getNamespace() + File.separator + "advancements" + File.separator + key.getKey() + ".json"); + File file = new File(getBukkitDataPackFolder(), "data" + File.separator + key.getNamespace() + File.separator + "advancements" + File.separator + key.getKey() + ".json"); return file.delete(); } @@ -316,17 +320,23 @@ public void checkSupported(PluginDescriptionFile pdf) throws InvalidPluginExcept } public static boolean isLegacy(PluginDescriptionFile pdf) { - return false; + return pdf.getAPIVersion() == null; } @Override public byte[] processClass(PluginDescriptionFile pdf, String path, byte[] clazz) { + try { + clazz = commodore.convert(clazz, pdf.getName(), ApiVersion.getOrCreateVersion(pdf.getAPIVersion()), ((CraftServer) Bukkit.getServer()).activeCompatibilities); + } catch (Exception ex) { + Bukkit.getLogger().log(Level.SEVERE, "Fatal error trying to convert " + pdf.getFullName() + ":" + path, ex); + } + return clazz; } @Override public Multimap getDefaultAttributeModifiers(Material material, EquipmentSlot slot) { - return material.getDefaultAttributeModifiers(slot); + return material.getDefaultAttributeModifiers(slot); } @Override @@ -347,13 +357,13 @@ public String getItemTranslationKey(Material material) { @Override public String getTranslationKey(EntityType entityType) { Preconditions.checkArgument(entityType.getName() != null, "Invalid name of EntityType %s for translation key", entityType); - return net.minecraft.world.entity.EntityType.byString(entityType.getName()).map(net.minecraft.world.entity.EntityType::getDescriptionId).orElseThrow(); + return EntityTypes.byString(entityType.getName()).map(EntityTypes::getDescriptionId).orElseThrow(); } @Override public String getTranslationKey(ItemStack itemStack) { net.minecraft.world.item.ItemStack nmsItemStack = CraftItemStack.asNMSCopy(itemStack); - return nmsItemStack.getItem().getDescriptionId(nmsItemStack); + return nmsItemStack.getItem().getDescriptionId(); } @Override @@ -369,7 +379,7 @@ public FeatureFlag getFeatureFlag(NamespacedKey namespacedKey) { @Override public PotionType.InternalPotionData getInternalPotionData(NamespacedKey namespacedKey) { - Potion potionRegistry = CraftRegistry.getMinecraftRegistry(Registries.POTION) + PotionRegistry potionRegistry = CraftRegistry.getMinecraftRegistry(Registries.POTION) .getOptional(CraftNamespacedKey.toMinecraft(namespacedKey)).orElseThrow(); return new CraftPotionType(namespacedKey, potionRegistry); diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java b/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java index be9686a4..44f133cf 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java @@ -5,14 +5,14 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.MojangsonParser; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagDouble; +import net.minecraft.nbt.NBTTagInt; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; import net.minecraft.nbt.SnbtPrinterTagVisitor; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; -import net.minecraft.nbt.TagParser; import org.jetbrains.annotations.NotNull; public class CraftNBTTagConfigSerializer { @@ -20,66 +20,66 @@ public class CraftNBTTagConfigSerializer { private static final Pattern ARRAY = Pattern.compile("^\\[.*]"); private static final Pattern INTEGER = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)?i", Pattern.CASE_INSENSITIVE); private static final Pattern DOUBLE = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?d", Pattern.CASE_INSENSITIVE); - private static final TagParser MOJANGSON_PARSER = new TagParser(new StringReader("")); + private static final MojangsonParser MOJANGSON_PARSER = new MojangsonParser(new StringReader("")); - public static String serialize(@NotNull final Tag base) { + public static String serialize(@NotNull final NBTBase base) { final SnbtPrinterTagVisitor snbtVisitor = new SnbtPrinterTagVisitor(); return snbtVisitor.visit(base); } - public static Tag deserialize(final Object object) { + public static NBTBase deserialize(final Object object) { // The new logic expects the top level object to be a single string, holding the entire nbt tag as SNBT. if (object instanceof final String snbtString) { try { - return TagParser.parseTag(snbtString); + return MojangsonParser.parseTag(snbtString); } catch (final CommandSyntaxException e) { throw new RuntimeException("Failed to deserialise nbt", e); } } else { // Legacy logic is passed to the internal legacy deserialization that attempts to read the old format that *unsuccessfully* attempted to read/write nbt to a full yml tree. - return CraftNBTTagConfigSerializer.internalLegacyDeserialization(object); + return internalLegacyDeserialization(object); } } - private static Tag internalLegacyDeserialization(@NotNull final Object object) { + private static NBTBase internalLegacyDeserialization(@NotNull final Object object) { if (object instanceof Map) { - CompoundTag compound = new CompoundTag(); + NBTTagCompound compound = new NBTTagCompound(); for (Map.Entry entry : ((Map) object).entrySet()) { - compound.put(entry.getKey(), CraftNBTTagConfigSerializer.internalLegacyDeserialization(entry.getValue())); + compound.put(entry.getKey(), internalLegacyDeserialization(entry.getValue())); } return compound; } else if (object instanceof List) { List list = (List) object; if (list.isEmpty()) { - return new ListTag(); // Default + return new NBTTagList(); // Default } - ListTag tagList = new ListTag(); + NBTTagList tagList = new NBTTagList(); for (Object tag : list) { - tagList.add(CraftNBTTagConfigSerializer.internalLegacyDeserialization(tag)); + tagList.add(internalLegacyDeserialization(tag)); } return tagList; } else if (object instanceof String) { String string = (String) object; - if (CraftNBTTagConfigSerializer.ARRAY.matcher(string).matches()) { + if (ARRAY.matcher(string).matches()) { try { - return new TagParser(new StringReader(string)).readArrayTag(); + return new MojangsonParser(new StringReader(string)).readArrayTag(); } catch (CommandSyntaxException e) { throw new RuntimeException("Could not deserialize found list ", e); } - } else if (CraftNBTTagConfigSerializer.INTEGER.matcher(string).matches()) { //Read integers on our own - return IntTag.valueOf(Integer.parseInt(string.substring(0, string.length() - 1))); - } else if (CraftNBTTagConfigSerializer.DOUBLE.matcher(string).matches()) { - return DoubleTag.valueOf(Double.parseDouble(string.substring(0, string.length() - 1))); + } else if (INTEGER.matcher(string).matches()) { //Read integers on our own + return NBTTagInt.valueOf(Integer.parseInt(string.substring(0, string.length() - 1))); + } else if (DOUBLE.matcher(string).matches()) { + return NBTTagDouble.valueOf(Double.parseDouble(string.substring(0, string.length() - 1))); } else { - Tag nbtBase = CraftNBTTagConfigSerializer.MOJANGSON_PARSER.type(string); + NBTBase nbtBase = MOJANGSON_PARSER.type(string); - if (nbtBase instanceof IntTag) { // If this returns an integer, it did not use our method from above - return StringTag.valueOf(nbtBase.getAsString()); // It then is a string that was falsely read as an int - } else if (nbtBase instanceof DoubleTag) { - return StringTag.valueOf(String.valueOf(((DoubleTag) nbtBase).getAsDouble())); // Doubles add "d" at the end + if (nbtBase instanceof NBTTagInt) { // If this returns an integer, it did not use our method from above + return NBTTagString.valueOf(nbtBase.getAsString()); // It then is a string that was falsely read as an int + } else if (nbtBase instanceof NBTTagDouble) { + return NBTTagString.valueOf(String.valueOf(((NBTTagDouble) nbtBase).getAsDouble())); // Doubles add "d" at the end } else { return nbtBase; } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java b/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java index dc88ba24..7ad6f66e 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.util; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.MinecraftKey; import org.bukkit.NamespacedKey; public final class CraftNamespacedKey { @@ -12,19 +12,19 @@ public static NamespacedKey fromStringOrNull(String string) { if (string == null || string.isEmpty()) { return null; } - ResourceLocation minecraft = ResourceLocation.tryParse(string); - return (minecraft == null) ? null : CraftNamespacedKey.fromMinecraft(minecraft); + MinecraftKey minecraft = MinecraftKey.tryParse(string); + return (minecraft == null) ? null : fromMinecraft(minecraft); } public static NamespacedKey fromString(String string) { - return CraftNamespacedKey.fromMinecraft(ResourceLocation.parse(string)); + return fromMinecraft(MinecraftKey.parse(string)); } - public static NamespacedKey fromMinecraft(ResourceLocation minecraft) { + public static NamespacedKey fromMinecraft(MinecraftKey minecraft) { return new NamespacedKey(minecraft.getNamespace(), minecraft.getPath()); } - public static ResourceLocation toMinecraft(NamespacedKey key) { - return ResourceLocation.fromNamespaceAndPath(key.getNamespace(), key.getKey()); + public static MinecraftKey toMinecraft(NamespacedKey key) { + return MinecraftKey.fromNamespaceAndPath(key.getNamespace(), key.getKey()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java b/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java index 5ee538ca..ee910d7b 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.util; import net.minecraft.core.BlockPos; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.EntityHitResult; -import net.minecraft.world.phys.HitResult; -import net.minecraft.world.phys.HitResult.Type; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.MovingObjectPosition; +import net.minecraft.world.phys.MovingObjectPosition.EnumMovingObjectType; +import net.minecraft.world.phys.MovingObjectPositionBlock; +import net.minecraft.world.phys.MovingObjectPositionEntity; +import net.minecraft.world.phys.Vec3D; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -18,22 +18,22 @@ public final class CraftRayTraceResult { private CraftRayTraceResult() {} - public static RayTraceResult fromNMS(World world, HitResult nmsHitResult) { - if (nmsHitResult == null || nmsHitResult.getType() == Type.MISS) return null; + public static RayTraceResult fromNMS(World world, MovingObjectPosition nmsHitResult) { + if (nmsHitResult == null || nmsHitResult.getType() == EnumMovingObjectType.MISS) return null; - Vec3 nmsHitPos = nmsHitResult.getLocation(); + Vec3D nmsHitPos = nmsHitResult.getLocation(); Vector hitPosition = new Vector(nmsHitPos.x, nmsHitPos.y, nmsHitPos.z); BlockFace hitBlockFace = null; - if (nmsHitResult.getType() == Type.ENTITY) { - Entity hitEntity = ((EntityHitResult) nmsHitResult).getEntity().getBukkitEntity(); + if (nmsHitResult.getType() == EnumMovingObjectType.ENTITY) { + Entity hitEntity = ((MovingObjectPositionEntity) nmsHitResult).getEntity().getBukkitEntity(); return new RayTraceResult(hitPosition, hitEntity, null); } Block hitBlock = null; BlockPos nmsBlockPos = null; - if (nmsHitResult.getType() == Type.BLOCK) { - BlockHitResult blockHitResult = (BlockHitResult) nmsHitResult; + if (nmsHitResult.getType() == EnumMovingObjectType.BLOCK) { + MovingObjectPositionBlock blockHitResult = (MovingObjectPositionBlock) nmsHitResult; hitBlockFace = CraftBlock.notchToBlockFace(blockHitResult.getDirection()); nmsBlockPos = blockHitResult.getBlockPos(); } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftSpawnCategory.java b/src/main/java/org/bukkit/craftbukkit/util/CraftSpawnCategory.java index cba660a0..857c7811 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftSpawnCategory.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftSpawnCategory.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.util; -import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.EnumCreatureType; import org.bukkit.entity.SpawnCategory; public class CraftSpawnCategory { @@ -43,7 +43,7 @@ public static long getDefaultTicksPerSpawn(SpawnCategory spawnCategory) { }; } - public static SpawnCategory toBukkit(MobCategory enumCreatureType) { + public static SpawnCategory toBukkit(EnumCreatureType enumCreatureType) { return switch (enumCreatureType) { case MONSTER -> SpawnCategory.MONSTER; case CREATURE -> SpawnCategory.ANIMAL; @@ -57,16 +57,16 @@ public static SpawnCategory toBukkit(MobCategory enumCreatureType) { }; } - public static MobCategory toNMS(SpawnCategory spawnCategory) { + public static EnumCreatureType toNMS(SpawnCategory spawnCategory) { return switch (spawnCategory) { - case MONSTER -> MobCategory.MONSTER; - case ANIMAL -> MobCategory.CREATURE; - case AMBIENT -> MobCategory.AMBIENT; - case AXOLOTL -> MobCategory.AXOLOTLS; - case WATER_ANIMAL -> MobCategory.WATER_CREATURE; - case WATER_AMBIENT -> MobCategory.WATER_AMBIENT; - case WATER_UNDERGROUND_CREATURE -> MobCategory.UNDERGROUND_WATER_CREATURE; - case MISC -> MobCategory.MISC; + case MONSTER -> EnumCreatureType.MONSTER; + case ANIMAL -> EnumCreatureType.CREATURE; + case AMBIENT -> EnumCreatureType.AMBIENT; + case AXOLOTL -> EnumCreatureType.AXOLOTLS; + case WATER_ANIMAL -> EnumCreatureType.WATER_CREATURE; + case WATER_AMBIENT -> EnumCreatureType.WATER_AMBIENT; + case WATER_UNDERGROUND_CREATURE -> EnumCreatureType.UNDERGROUND_WATER_CREATURE; + case MISC -> EnumCreatureType.MISC; default -> throw new UnsupportedOperationException("Unknown SpawnCategory " + spawnCategory + " for EnumCreatureType"); }; } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftStructureSearchResult.java b/src/main/java/org/bukkit/craftbukkit/util/CraftStructureSearchResult.java index 7f5ba5fe..8fb83728 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftStructureSearchResult.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftStructureSearchResult.java @@ -15,10 +15,10 @@ public CraftStructureSearchResult(Structure structure, Location location) { } public Structure getStructure() { - return this.structure; + return structure; } public Location getLocation() { - return this.location; + return location; } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftStructureTransformer.java b/src/main/java/org/bukkit/craftbukkit/util/CraftStructureTransformer.java index b4d569b3..951900a2 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftStructureTransformer.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftStructureTransformer.java @@ -4,11 +4,11 @@ import java.util.Objects; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.ChunkCoordIntPair; +import net.minecraft.world.level.GeneratorAccessSeed; import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.StructureBoundingBox; import org.bukkit.Bukkit; import org.bukkit.block.BlockState; import org.bukkit.craftbukkit.block.CraftBlockState; @@ -38,23 +38,23 @@ private CraftTransformationState(BlockState original, BlockState world) { @Override public BlockState getOriginal() { - if (this.originalCopy != null) { - return this.originalCopy; + if (originalCopy != null) { + return originalCopy; } - return this.originalCopy = this.original.copy(); + return originalCopy = original.copy(); } @Override public BlockState getWorld() { - if (this.worldCopy != null) { - return this.worldCopy; + if (worldCopy != null) { + return worldCopy; } - return this.worldCopy = this.world.copy(); + return worldCopy = world.copy(); } private void destroyCopies() { - this.originalCopy = null; - this.worldCopy = null; + originalCopy = null; + worldCopy = null; } } @@ -63,7 +63,7 @@ private void destroyCopies() { private BlockTransformer[] blockTransformers; private EntityTransformer[] entityTransformers; - public CraftStructureTransformer(Cause cause, WorldGenLevel generatoraccessseed, StructureManager structuremanager, Structure structure, BoundingBox structureboundingbox, ChunkPos chunkcoordintpair) { + public CraftStructureTransformer(Cause cause, GeneratorAccessSeed generatoraccessseed, StructureManager structuremanager, Structure structure, StructureBoundingBox structureboundingbox, ChunkCoordIntPair chunkcoordintpair) { AsyncStructureGenerateEvent event = new AsyncStructureGenerateEvent(structuremanager.level.getMinecraftWorld().getWorld(), !Bukkit.isPrimaryThread(), cause, CraftStructure.minecraftToBukkit(structure), new org.bukkit.util.BoundingBox(structureboundingbox.minX(), structureboundingbox.minY(), structureboundingbox.minZ(), structureboundingbox.maxX(), structureboundingbox.maxY(), structureboundingbox.maxZ()), chunkcoordintpair.x, chunkcoordintpair.z); Bukkit.getPluginManager().callEvent(event); this.blockTransformers = event.getBlockTransformers().values().toArray(BlockTransformer[]::new); @@ -71,18 +71,18 @@ public CraftStructureTransformer(Cause cause, WorldGenLevel generatoraccessseed, this.limitedRegion = new CraftLimitedRegion(generatoraccessseed, chunkcoordintpair); } - public CraftStructureTransformer(WorldGenLevel generatoraccessseed, ChunkPos chunkcoordintpair, Collection blockTransformers, Collection entityTransformers) { + public CraftStructureTransformer(GeneratorAccessSeed generatoraccessseed, ChunkCoordIntPair chunkcoordintpair, Collection blockTransformers, Collection entityTransformers) { this.blockTransformers = blockTransformers.toArray(BlockTransformer[]::new); this.entityTransformers = entityTransformers.toArray(EntityTransformer[]::new); this.limitedRegion = new CraftLimitedRegion(generatoraccessseed, chunkcoordintpair); } public boolean transformEntity(Entity entity) { - EntityTransformer[] transformers = this.entityTransformers; + EntityTransformer[] transformers = entityTransformers; if (transformers == null || transformers.length == 0) { return true; } - CraftLimitedRegion region = this.limitedRegion; + CraftLimitedRegion region = limitedRegion; if (region == null) { return true; } @@ -99,15 +99,15 @@ public boolean transformEntity(Entity entity) { } public boolean canTransformBlocks() { - return this.blockTransformers != null && this.blockTransformers.length != 0 && this.limitedRegion != null; + return blockTransformers != null && blockTransformers.length != 0 && limitedRegion != null; } public CraftBlockState transformCraftState(CraftBlockState originalState) { - BlockTransformer[] transformers = this.blockTransformers; + BlockTransformer[] transformers = blockTransformers; if (transformers == null || transformers.length == 0) { return originalState; } - CraftLimitedRegion region = this.limitedRegion; + CraftLimitedRegion region = limitedRegion; if (region == null) { return originalState; } @@ -123,8 +123,8 @@ public CraftBlockState transformCraftState(CraftBlockState originalState) { } public void discard() { - this.limitedRegion.saveEntities(); - this.limitedRegion.breakLink(); + limitedRegion.saveEntities(); + limitedRegion.breakLink(); this.limitedRegion = null; this.blockTransformers = null; this.entityTransformers = null; diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java b/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java index 3071ac1a..fc63c87f 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java @@ -5,11 +5,11 @@ public final class CraftVector { private CraftVector() { } - public static org.bukkit.util.Vector toBukkit(net.minecraft.world.phys.Vec3 nms) { + public static org.bukkit.util.Vector toBukkit(net.minecraft.world.phys.Vec3D nms) { return new org.bukkit.util.Vector(nms.x, nms.y, nms.z); } - public static net.minecraft.world.phys.Vec3 toNMS(org.bukkit.util.Vector bukkit) { - return new net.minecraft.world.phys.Vec3(bukkit.getX(), bukkit.getY(), bukkit.getZ()); + public static net.minecraft.world.phys.Vec3D toNMS(org.bukkit.util.Vector bukkit) { + return new net.minecraft.world.phys.Vec3D(bukkit.getX(), bukkit.getY(), bukkit.getZ()); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftVoxelShape.java b/src/main/java/org/bukkit/craftbukkit/util/CraftVoxelShape.java index 0e5625ca..641e1a44 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftVoxelShape.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftVoxelShape.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.AxisAlignedBB; import net.minecraft.world.phys.shapes.VoxelShape; import org.bukkit.util.BoundingBox; @@ -18,9 +18,9 @@ public CraftVoxelShape(VoxelShape shape) { @Override public Collection getBoundingBoxes() { - List boxes = this.shape.toAabbs(); + List boxes = shape.toAabbs(); List craftBoxes = new ArrayList<>(boxes.size()); - for (AABB aabb : boxes) { + for (AxisAlignedBB aabb : boxes) { craftBoxes.add(new BoundingBox(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ)); } return craftBoxes; @@ -30,7 +30,7 @@ public Collection getBoundingBoxes() { public boolean overlaps(BoundingBox other) { Preconditions.checkArgument(other != null, "Other cannot be null"); - for (BoundingBox box : this.getBoundingBoxes()) { + for (BoundingBox box : getBoundingBoxes()) { if (box.overlaps(other)) { return true; } diff --git a/src/main/java/org/bukkit/craftbukkit/util/DelegatedGeneratorAccess.java b/src/main/java/org/bukkit/craftbukkit/util/DelegatedGeneratorAccess.java index 5fd6eb75..de520fb3 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/DelegatedGeneratorAccess.java +++ b/src/main/java/org/bukkit/craftbukkit/util/DelegatedGeneratorAccess.java @@ -7,804 +7,785 @@ import java.util.function.Supplier; import java.util.stream.Stream; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.EnumDirection; import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.IRegistry; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.core.particles.ParticleParam; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; +import net.minecraft.server.level.WorldServer; +import net.minecraft.sounds.SoundCategory; +import net.minecraft.sounds.SoundEffect; import net.minecraft.util.RandomSource; -import net.minecraft.world.Difficulty; -import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.DifficultyDamageScaler; +import net.minecraft.world.EnumDifficulty; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.ai.targeting.TargetingConditions; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.ClipBlockStateContext; -import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.ColorResolver; -import net.minecraft.world.level.LightLayer; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.EnumSkyBlock; +import net.minecraft.world.level.GeneratorAccessSeed; +import net.minecraft.world.level.IBlockAccess; +import net.minecraft.world.level.RayTrace; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.BiomeManager; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.entity.TileEntityTypes; +import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.border.WorldBorder; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkSource; +import net.minecraft.world.level.chunk.IChunkAccess; +import net.minecraft.world.level.chunk.IChunkProvider; import net.minecraft.world.level.chunk.status.ChunkStatus; -import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.DimensionManager; import net.minecraft.world.level.entity.EntityTypeTest; import net.minecraft.world.level.gameevent.GameEvent; -import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.HeightMap; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.storage.LevelData; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.level.material.FluidType; +import net.minecraft.world.level.storage.WorldData; +import net.minecraft.world.phys.AxisAlignedBB; +import net.minecraft.world.phys.MovingObjectPositionBlock; +import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.shapes.VoxelShape; +import net.minecraft.world.phys.shapes.VoxelShapeCollision; import net.minecraft.world.ticks.LevelTickAccess; -import net.minecraft.world.ticks.TickPriority; +import net.minecraft.world.ticks.TickListPriority; import org.bukkit.event.entity.CreatureSpawnEvent; -public abstract class DelegatedGeneratorAccess implements WorldGenLevel { +public abstract class DelegatedGeneratorAccess implements GeneratorAccessSeed { - private WorldGenLevel handle; + private GeneratorAccessSeed handle; - public void setHandle(WorldGenLevel worldAccess) { + public void setHandle(GeneratorAccessSeed worldAccess) { this.handle = worldAccess; } - public WorldGenLevel getHandle() { - return this.handle; + public GeneratorAccessSeed getHandle() { + return handle; } @Override public long getSeed() { - return this.handle.getSeed(); + return handle.getSeed(); } @Override - public void setCurrentlyGenerating(Supplier structureName) { - this.handle.setCurrentlyGenerating(structureName); + public boolean ensureCanWrite(BlockPos var0) { + return handle.ensureCanWrite(var0); } @Override - public boolean ensureCanWrite(BlockPos pos) { - return this.handle.ensureCanWrite(pos); + public void setCurrentlyGenerating(Supplier var0) { + handle.setCurrentlyGenerating(var0); } @Override - public ServerLevel getLevel() { - return this.handle.getLevel(); - } - - @Override - public void addFreshEntityWithPassengers(Entity arg0, CreatureSpawnEvent.SpawnReason arg1) { - this.handle.addFreshEntityWithPassengers(arg0, arg1); + public WorldServer getLevel() { + return handle.getLevel(); } @Override public void addFreshEntityWithPassengers(Entity entity) { - this.handle.addFreshEntityWithPassengers(entity); + handle.addFreshEntityWithPassengers(entity); } @Override - public ServerLevel getMinecraftWorld() { - return this.handle.getMinecraftWorld(); + public void addFreshEntityWithPassengers(Entity entity, CreatureSpawnEvent.SpawnReason reason) { + handle.addFreshEntityWithPassengers(entity, reason); } @Override - public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { - return this.handle.getCurrentDifficultyAt(pos); - } - - @Override - public void neighborShapeChanged(Direction direction, BlockState neighborState, BlockPos pos, BlockPos neighborPos, int flags, int maxUpdateDepth) { - this.handle.neighborShapeChanged(direction, neighborState, pos, neighborPos, flags, maxUpdateDepth); + public WorldServer getMinecraftWorld() { + return handle.getMinecraftWorld(); } @Override public long dayTime() { - return this.handle.dayTime(); + return handle.dayTime(); } @Override - public LevelData getLevelData() { - return this.handle.getLevelData(); + public long nextSubTickCount() { + return handle.nextSubTickCount(); } @Override - public boolean hasChunk(int chunkX, int chunkZ) { - return this.handle.hasChunk(chunkX, chunkZ); + public LevelTickAccess getBlockTicks() { + return handle.getBlockTicks(); } @Override - public ChunkSource getChunkSource() { - return this.handle.getChunkSource(); + public void scheduleTick(BlockPos blockposition, Block block, int i, TickListPriority ticklistpriority) { + handle.scheduleTick(blockposition, block, i, ticklistpriority); } @Override - public void scheduleTick(BlockPos pos, Block block, int delay, TickPriority priority) { - this.handle.scheduleTick(pos, block, delay, priority); + public void scheduleTick(BlockPos blockposition, Block block, int i) { + handle.scheduleTick(blockposition, block, i); } @Override - public void scheduleTick(BlockPos pos, Block block, int delay) { - this.handle.scheduleTick(pos, block, delay); + public LevelTickAccess getFluidTicks() { + return handle.getFluidTicks(); } @Override - public void scheduleTick(BlockPos pos, Fluid fluid, int delay, TickPriority priority) { - this.handle.scheduleTick(pos, fluid, delay, priority); + public void scheduleTick(BlockPos blockposition, FluidType fluidtype, int i, TickListPriority ticklistpriority) { + handle.scheduleTick(blockposition, fluidtype, i, ticklistpriority); } @Override - public void scheduleTick(BlockPos pos, Fluid fluid, int delay) { - this.handle.scheduleTick(pos, fluid, delay); + public void scheduleTick(BlockPos blockposition, FluidType fluidtype, int i) { + handle.scheduleTick(blockposition, fluidtype, i); } @Override - public Difficulty getDifficulty() { - return this.handle.getDifficulty(); + public WorldData getLevelData() { + return handle.getLevelData(); } @Override - public void blockUpdated(BlockPos pos, Block block) { - this.handle.blockUpdated(pos, block); + public DifficultyDamageScaler getCurrentDifficultyAt(BlockPos blockposition) { + return handle.getCurrentDifficultyAt(blockposition); } @Override public MinecraftServer getServer() { - return this.handle.getServer(); + return handle.getServer(); } @Override - public RandomSource getRandom() { - return this.handle.getRandom(); + public EnumDifficulty getDifficulty() { + return handle.getDifficulty(); } @Override - public LevelTickAccess getBlockTicks() { - return this.handle.getBlockTicks(); + public IChunkProvider getChunkSource() { + return handle.getChunkSource(); } @Override - public long nextSubTickCount() { - return this.handle.nextSubTickCount(); + public boolean hasChunk(int i, int j) { + return handle.hasChunk(i, j); } @Override - public LevelTickAccess getFluidTicks() { - return this.handle.getFluidTicks(); + public RandomSource getRandom() { + return handle.getRandom(); } @Override - public void playSound(Player except, BlockPos pos, SoundEvent sound, SoundSource category) { - this.handle.playSound(except, pos, sound, category); + public void blockUpdated(BlockPos blockposition, Block block) { + handle.blockUpdated(blockposition, block); } @Override - public void playSound(Player source, BlockPos pos, SoundEvent sound, SoundSource category, float volume, float pitch) { - this.handle.playSound(source, pos, sound, category, volume, pitch); + public void neighborShapeChanged(EnumDirection enumdirection, BlockPos blockposition, BlockPos blockposition1, IBlockData iblockdata, int i, int j) { + handle.neighborShapeChanged(enumdirection, blockposition, blockposition1, iblockdata, i, j); } @Override - public void levelEvent(int eventId, BlockPos pos, int data) { - this.handle.levelEvent(eventId, pos, data); + public void playSound(EntityHuman entityhuman, BlockPos blockposition, SoundEffect soundeffect, SoundCategory soundcategory) { + handle.playSound(entityhuman, blockposition, soundeffect, soundcategory); } @Override - public void levelEvent(Player player, int eventId, BlockPos pos, int data) { - this.handle.levelEvent(player, eventId, pos, data); + public void playSound(EntityHuman entityhuman, BlockPos blockposition, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) { + handle.playSound(entityhuman, blockposition, soundeffect, soundcategory, f, f1); } @Override - public void addParticle(ParticleOptions parameters, double x, double y, double z, double velocityX, double velocityY, double velocityZ) { - this.handle.addParticle(parameters, x, y, z, velocityX, velocityY, velocityZ); + public void addParticle(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) { + handle.addParticle(particleparam, d0, d1, d2, d3, d4, d5); } @Override - public void gameEvent(Holder event, Vec3 emitterPos, GameEvent.Context emitter) { - this.handle.gameEvent(event, emitterPos, emitter); + public void levelEvent(EntityHuman entityhuman, int i, BlockPos blockposition, int j) { + handle.levelEvent(entityhuman, i, blockposition, j); } @Override - public void gameEvent(Holder event, BlockPos pos, GameEvent.Context emitter) { - this.handle.gameEvent(event, pos, emitter); + public void levelEvent(int i, BlockPos blockposition, int j) { + handle.levelEvent(i, blockposition, j); } @Override - public void gameEvent(Entity entity, Holder event, BlockPos pos) { - this.handle.gameEvent(entity, event, pos); + public void gameEvent(Holder holder, Vec3D vec3d, GameEvent.a gameevent_a) { + handle.gameEvent(holder, vec3d, gameevent_a); } @Override - public void gameEvent(Entity entity, Holder event, Vec3 pos) { - this.handle.gameEvent(entity, event, pos); + public void gameEvent(Entity entity, Holder holder, Vec3D vec3d) { + handle.gameEvent(entity, holder, vec3d); } @Override - public List getEntityCollisions(Entity entity, AABB box) { - return this.handle.getEntityCollisions(entity, box); + public void gameEvent(Entity entity, Holder holder, BlockPos blockposition) { + handle.gameEvent(entity, holder, blockposition); } @Override - public Optional getBlockEntity(BlockPos pos, BlockEntityType type) { - return this.handle.getBlockEntity(pos, type); + public void gameEvent(Holder holder, BlockPos blockposition, GameEvent.a gameevent_a) { + handle.gameEvent(holder, blockposition, gameevent_a); } @Override - public BlockPos getHeightmapPos(Heightmap.Types heightmap, BlockPos pos) { - return this.handle.getHeightmapPos(heightmap, pos); + public void gameEvent(ResourceKey resourcekey, BlockPos blockposition, GameEvent.a gameevent_a) { + handle.gameEvent(resourcekey, blockposition, gameevent_a); } @Override - public boolean isUnobstructed(Entity except, VoxelShape shape) { - return this.handle.isUnobstructed(except, shape); + public Optional getBlockEntity(BlockPos var0, TileEntityTypes var1) { + return handle.getBlockEntity(var0, var1); } @Override - public boolean hasNearbyAlivePlayer(double x, double y, double z, double range) { - return this.handle.hasNearbyAlivePlayer(x, y, z, range); + public List getEntityCollisions(Entity var0, AxisAlignedBB var1) { + return handle.getEntityCollisions(var0, var1); } @Override - public List players() { - return this.handle.players(); + public boolean isUnobstructed(Entity var0, VoxelShape var1) { + return handle.isUnobstructed(var0, var1); } @Override - public List getEntities(Entity except, AABB box, Predicate predicate) { - return this.handle.getEntities(except, box, predicate); + public BlockPos getHeightmapPos(HeightMap.Type var0, BlockPos var1) { + return handle.getHeightmapPos(var0, var1); } @Override - public List getEntities(EntityTypeTest filter, AABB box, Predicate predicate) { - return this.handle.getEntities(filter, box, predicate); + public float getMoonBrightness() { + return handle.getMoonBrightness(); } @Override - public List getEntities(Entity except, AABB box) { - return this.handle.getEntities(except, box); + public float getTimeOfDay(float var0) { + return handle.getTimeOfDay(var0); } @Override - public List getEntitiesOfClass(Class entityClass, AABB box) { - return this.handle.getEntitiesOfClass(entityClass, box); + public int getMoonPhase() { + return handle.getMoonPhase(); } @Override - public List getEntitiesOfClass(Class entityClass, AABB box, Predicate predicate) { - return this.handle.getEntitiesOfClass(entityClass, box, predicate); + public IChunkAccess getChunk(int i, int i1, ChunkStatus cs, boolean bln) { + return handle.getChunk(i, i1, cs, bln); } @Override - public Player getNearestPlayer(TargetingConditions targetPredicate, LivingEntity entity, double x, double y, double z) { - return this.handle.getNearestPlayer(targetPredicate, entity, x, y, z); + public int getHeight(HeightMap.Type type, int i, int i1) { + return handle.getHeight(type, i, i1); } @Override - public Player getNearestPlayer(TargetingConditions targetPredicate, double x, double y, double z) { - return this.handle.getNearestPlayer(targetPredicate, x, y, z); + public int getSkyDarken() { + return handle.getSkyDarken(); } @Override - public Player getNearestPlayer(Entity entity, double maxDistance) { - return this.handle.getNearestPlayer(entity, maxDistance); + public BiomeManager getBiomeManager() { + return handle.getBiomeManager(); } @Override - public Player getNearestPlayer(double x, double y, double z, double maxDistance, Predicate targetPredicate) { - return this.handle.getNearestPlayer(x, y, z, maxDistance, targetPredicate); + public Holder getBiome(BlockPos var0) { + return handle.getBiome(var0); } @Override - public Player getNearestPlayer(double x, double y, double z, double maxDistance, boolean ignoreCreative) { - return this.handle.getNearestPlayer(x, y, z, maxDistance, ignoreCreative); + public Stream getBlockStatesIfLoaded(AxisAlignedBB var0) { + return handle.getBlockStatesIfLoaded(var0); } @Override - public Player getNearestPlayer(TargetingConditions targetPredicate, LivingEntity entity) { - return this.handle.getNearestPlayer(targetPredicate, entity); + public int getBlockTint(BlockPos var0, ColorResolver var1) { + return handle.getBlockTint(var0, var1); } @Override - public T getNearestEntity(Class entityClass, TargetingConditions targetPredicate, LivingEntity entity, double x, double y, double z, AABB box) { - return this.handle.getNearestEntity(entityClass, targetPredicate, entity, x, y, z, box); + public Holder getNoiseBiome(int var0, int var1, int var2) { + return handle.getNoiseBiome(var0, var1, var2); } @Override - public T getNearestEntity(List entityList, TargetingConditions targetPredicate, LivingEntity entity, double x, double y, double z) { - return this.handle.getNearestEntity(entityList, targetPredicate, entity, x, y, z); + public Holder getUncachedNoiseBiome(int i, int i1, int i2) { + return handle.getUncachedNoiseBiome(i, i1, i2); } @Override - public Player getPlayerByUUID(UUID uuid) { - return this.handle.getPlayerByUUID(uuid); + public boolean isClientSide() { + return handle.isClientSide(); } @Override - public List getNearbyPlayers(TargetingConditions targetPredicate, LivingEntity entity, AABB box) { - return this.handle.getNearbyPlayers(targetPredicate, entity, box); + public int getSeaLevel() { + return handle.getSeaLevel(); } @Override - public List getNearbyEntities(Class entityClass, TargetingConditions targetPredicate, LivingEntity targetingEntity, AABB box) { - return this.handle.getNearbyEntities(entityClass, targetPredicate, targetingEntity, box); + public DimensionManager dimensionType() { + return handle.dimensionType(); } @Override - @Deprecated - public float getLightLevelDependentMagicValue(BlockPos pos) { - return this.handle.getLightLevelDependentMagicValue(pos); + public int getMinY() { + return handle.getMinY(); } @Override - public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { - return this.handle.getChunkForCollisions(chunkX, chunkZ); + public int getHeight() { + return handle.getHeight(); } @Override - public int getMaxLocalRawBrightness(BlockPos pos) { - return this.handle.getMaxLocalRawBrightness(pos); + public boolean isEmptyBlock(BlockPos var0) { + return handle.isEmptyBlock(var0); } @Override - public int getMaxLocalRawBrightness(BlockPos pos, int ambientDarkness) { - return this.handle.getMaxLocalRawBrightness(pos, ambientDarkness); + public boolean canSeeSkyFromBelowWater(BlockPos var0) { + return handle.canSeeSkyFromBelowWater(var0); } @Override - public boolean canSeeSkyFromBelowWater(BlockPos pos) { - return this.handle.canSeeSkyFromBelowWater(pos); + public float getPathfindingCostFromLightLevels(BlockPos var0) { + return handle.getPathfindingCostFromLightLevels(var0); } @Override - public float getPathfindingCostFromLightLevels(BlockPos pos) { - return this.handle.getPathfindingCostFromLightLevels(pos); + public float getLightLevelDependentMagicValue(BlockPos var0) { + return handle.getLightLevelDependentMagicValue(var0); } @Override - public Stream getBlockStatesIfLoaded(AABB box) { - return this.handle.getBlockStatesIfLoaded(box); + public IChunkAccess getChunk(BlockPos var0) { + return handle.getChunk(var0); } @Override - public Holder getUncachedNoiseBiome(int biomeX, int biomeY, int biomeZ) { - return this.handle.getUncachedNoiseBiome(biomeX, biomeY, biomeZ); + public IChunkAccess getChunk(int var0, int var1) { + return handle.getChunk(var0, var1); } @Override - @Deprecated - public int getSeaLevel() { - return this.handle.getSeaLevel(); + public IChunkAccess getChunk(int var0, int var1, ChunkStatus var2) { + return handle.getChunk(var0, var1, var2); } @Override - public boolean containsAnyLiquid(AABB box) { - return this.handle.containsAnyLiquid(box); + public IBlockAccess getChunkForCollisions(int var0, int var1) { + return handle.getChunkForCollisions(var0, var1); } @Override - public int getMinBuildHeight() { - return this.handle.getMinBuildHeight(); + public boolean isWaterAt(BlockPos var0) { + return handle.isWaterAt(var0); } @Override - public boolean isWaterAt(BlockPos pos) { - return this.handle.isWaterAt(pos); + public boolean containsAnyLiquid(AxisAlignedBB var0) { + return handle.containsAnyLiquid(var0); } @Override - public boolean isEmptyBlock(BlockPos pos) { - return this.handle.isEmptyBlock(pos); + public int getMaxLocalRawBrightness(BlockPos var0) { + return handle.getMaxLocalRawBrightness(var0); } @Override - public boolean isClientSide() { - return this.handle.isClientSide(); + public int getMaxLocalRawBrightness(BlockPos var0, int var1) { + return handle.getMaxLocalRawBrightness(var0, var1); } @Override - public DimensionType dimensionType() { - return this.handle.dimensionType(); + public boolean hasChunkAt(int var0, int var1) { + return handle.hasChunkAt(var0, var1); } @Override - public FeatureFlagSet enabledFeatures() { - return this.handle.enabledFeatures(); + public boolean hasChunkAt(BlockPos var0) { + return handle.hasChunkAt(var0); } @Override - @Deprecated - public boolean hasChunkAt(int x, int z) { - return this.handle.hasChunkAt(x, z); + public boolean hasChunksAt(BlockPos var0, BlockPos var1) { + return handle.hasChunksAt(var0, var1); } @Override - @Deprecated - public boolean hasChunkAt(BlockPos pos) { - return this.handle.hasChunkAt(pos); + public boolean hasChunksAt(int var0, int var1, int var2, int var3, int var4, int var5) { + return handle.hasChunksAt(var0, var1, var2, var3, var4, var5); } @Override - public HolderLookup holderLookup(ResourceKey> registryRef) { - return this.handle.holderLookup(registryRef); + public boolean hasChunksAt(int var0, int var1, int var2, int var3) { + return handle.hasChunksAt(var0, var1, var2, var3); } @Override - public RegistryAccess registryAccess() { - return this.handle.registryAccess(); + public IRegistryCustom registryAccess() { + return handle.registryAccess(); } @Override - public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ) { - return this.handle.getNoiseBiome(biomeX, biomeY, biomeZ); + public FeatureFlagSet enabledFeatures() { + return handle.enabledFeatures(); } @Override - public int getBlockTint(BlockPos pos, ColorResolver colorResolver) { - return this.handle.getBlockTint(pos, colorResolver); + public HolderLookup holderLookup(ResourceKey> var0) { + return handle.holderLookup(var0); } @Override - @Deprecated - public boolean hasChunksAt(BlockPos min, BlockPos max) { - return this.handle.hasChunksAt(min, max); + public float getShade(EnumDirection ed, boolean bln) { + return handle.getShade(ed, bln); } @Override - @Deprecated - public boolean hasChunksAt(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - return this.handle.hasChunksAt(minX, minY, minZ, maxX, maxY, maxZ); + public LevelLightEngine getLightEngine() { + return handle.getLightEngine(); } @Override - @Deprecated - public boolean hasChunksAt(int minX, int minZ, int maxX, int maxZ) { - return this.handle.hasChunksAt(minX, minZ, maxX, maxZ); + public int getBrightness(EnumSkyBlock var0, BlockPos var1) { + return handle.getBrightness(var0, var1); } @Override - public ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create) { - return this.handle.getChunk(chunkX, chunkZ, leastStatus, create); + public int getRawBrightness(BlockPos var0, int var1) { + return handle.getRawBrightness(var0, var1); } @Override - public ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus status) { - return this.handle.getChunk(chunkX, chunkZ, status); + public boolean canSeeSky(BlockPos var0) { + return handle.canSeeSky(var0); } @Override - public ChunkAccess getChunk(BlockPos pos) { - return this.handle.getChunk(pos); + public WorldBorder getWorldBorder() { + return handle.getWorldBorder(); } @Override - public ChunkAccess getChunk(int chunkX, int chunkZ) { - return this.handle.getChunk(chunkX, chunkZ); + public boolean isUnobstructed(IBlockData var0, BlockPos var1, VoxelShapeCollision var2) { + return handle.isUnobstructed(var0, var1, var2); } @Override - public int getHeight(Heightmap.Types heightmap, int x, int z) { - return this.handle.getHeight(heightmap, x, z); + public boolean isUnobstructed(Entity var0) { + return handle.isUnobstructed(var0); } @Override - public int getHeight() { - return this.handle.getHeight(); + public boolean noCollision(AxisAlignedBB var0) { + return handle.noCollision(var0); } @Override - public Holder getBiome(BlockPos pos) { - return this.handle.getBiome(pos); + public boolean noCollision(Entity var0) { + return handle.noCollision(var0); } @Override - public int getSkyDarken() { - return this.handle.getSkyDarken(); + public boolean noCollision(Entity var0, AxisAlignedBB var1) { + return handle.noCollision(var0, var1); } @Override - public BiomeManager getBiomeManager() { - return this.handle.getBiomeManager(); + public boolean noCollision(Entity var0, AxisAlignedBB var1, boolean var2) { + return handle.noCollision(var0, var1, var2); } @Override - public boolean canSeeSky(BlockPos pos) { - return this.handle.canSeeSky(pos); + public boolean noBlockCollision(Entity var0, AxisAlignedBB var1) { + return handle.noBlockCollision(var0, var1); } @Override - public int getRawBrightness(BlockPos pos, int ambientDarkness) { - return this.handle.getRawBrightness(pos, ambientDarkness); + public Iterable getCollisions(Entity var0, AxisAlignedBB var1) { + return handle.getCollisions(var0, var1); } @Override - public LevelLightEngine getLightEngine() { - return this.handle.getLightEngine(); + public Iterable getBlockCollisions(Entity var0, AxisAlignedBB var1) { + return handle.getBlockCollisions(var0, var1); } @Override - public int getBrightness(LightLayer type, BlockPos pos) { - return this.handle.getBrightness(type, pos); + public Iterable getBlockAndLiquidCollisions(Entity var0, AxisAlignedBB var1) { + return handle.getBlockAndLiquidCollisions(var0, var1); } @Override - public float getShade(Direction direction, boolean shaded) { - return this.handle.getShade(direction, shaded); + public MovingObjectPositionBlock clipIncludingBorder(RayTrace var0) { + return handle.clipIncludingBorder(var0); } @Override - public BlockEntity getBlockEntity(BlockPos pos) { - return this.handle.getBlockEntity(pos); + public boolean collidesWithSuffocatingBlock(Entity var0, AxisAlignedBB var1) { + return handle.collidesWithSuffocatingBlock(var0, var1); } @Override - public double getBlockFloorHeight(VoxelShape blockCollisionShape, Supplier belowBlockCollisionShapeGetter) { - return this.handle.getBlockFloorHeight(blockCollisionShape, belowBlockCollisionShapeGetter); + public Optional findSupportingBlock(Entity var0, AxisAlignedBB var1) { + return handle.findSupportingBlock(var0, var1); } @Override - public double getBlockFloorHeight(BlockPos pos) { - return this.handle.getBlockFloorHeight(pos); + public Optional findFreePosition(Entity var0, VoxelShape var1, Vec3D var2, double var3, double var5, double var7) { + return handle.findFreePosition(var0, var1, var2, var3, var5, var7); } @Override - public BlockHitResult clipWithInteractionOverride(Vec3 start, Vec3 end, BlockPos pos, VoxelShape shape, BlockState state) { - return this.handle.clipWithInteractionOverride(start, end, pos, shape, state); + public int getDirectSignal(BlockPos var0, EnumDirection var1) { + return handle.getDirectSignal(var0, var1); } @Override - public BlockState getBlockState(BlockPos pos) { - return this.handle.getBlockState(pos); + public int getDirectSignalTo(BlockPos var0) { + return handle.getDirectSignalTo(var0); } @Override - public FluidState getFluidState(BlockPos pos) { - return this.handle.getFluidState(pos); + public int getControlInputSignal(BlockPos var0, EnumDirection var1, boolean var2) { + return handle.getControlInputSignal(var0, var1, var2); } @Override - public int getLightEmission(BlockPos pos) { - return this.handle.getLightEmission(pos); + public boolean hasSignal(BlockPos var0, EnumDirection var1) { + return handle.hasSignal(var0, var1); } @Override - public BlockHitResult clip(ClipContext context) { - return this.handle.clip(context); + public int getSignal(BlockPos var0, EnumDirection var1) { + return handle.getSignal(var0, var1); } @Override - public BlockHitResult clip(ClipContext arg0, BlockPos arg1) { - return this.handle.clip(arg0, arg1); + public boolean hasNeighborSignal(BlockPos var0) { + return handle.hasNeighborSignal(var0); } @Override - public int getMaxLightLevel() { - return this.handle.getMaxLightLevel(); + public int getBestNeighborSignal(BlockPos var0) { + return handle.getBestNeighborSignal(var0); } @Override - public BlockHitResult isBlockInLine(ClipBlockStateContext context) { - return this.handle.isBlockInLine(context); + public TileEntity getBlockEntity(BlockPos blockposition) { + return handle.getBlockEntity(blockposition); } @Override - public Stream getBlockStates(AABB box) { - return this.handle.getBlockStates(box); + public IBlockData getBlockState(BlockPos blockposition) { + return handle.getBlockState(blockposition); } @Override - public boolean isOutsideBuildHeight(int y) { - return this.handle.isOutsideBuildHeight(y); + public Fluid getFluidState(BlockPos blockposition) { + return handle.getFluidState(blockposition); } @Override - public boolean isOutsideBuildHeight(BlockPos pos) { - return this.handle.isOutsideBuildHeight(pos); + public int getLightEmission(BlockPos blockposition) { + return handle.getLightEmission(blockposition); } @Override - public int getSectionIndexFromSectionY(int coord) { - return this.handle.getSectionIndexFromSectionY(coord); + public Stream getBlockStates(AxisAlignedBB axisalignedbb) { + return handle.getBlockStates(axisalignedbb); } @Override - public int getSectionYFromSectionIndex(int index) { - return this.handle.getSectionYFromSectionIndex(index); + public MovingObjectPositionBlock isBlockInLine(ClipBlockStateContext clipblockstatecontext) { + return handle.isBlockInLine(clipblockstatecontext); } @Override - public int getMaxSection() { - return this.handle.getMaxSection(); + public MovingObjectPositionBlock clip(RayTrace raytrace1, BlockPos blockposition) { + return handle.clip(raytrace1, blockposition); } @Override - public int getMinSection() { - return this.handle.getMinSection(); + public MovingObjectPositionBlock clip(RayTrace raytrace) { + return handle.clip(raytrace); } @Override - public int getSectionIndex(int y) { - return this.handle.getSectionIndex(y); + public MovingObjectPositionBlock clipWithInteractionOverride(Vec3D vec3d, Vec3D vec3d1, BlockPos blockposition, VoxelShape voxelshape, IBlockData iblockdata) { + return handle.clipWithInteractionOverride(vec3d, vec3d1, blockposition, voxelshape, iblockdata); } @Override - public int getSectionsCount() { - return this.handle.getSectionsCount(); + public double getBlockFloorHeight(VoxelShape voxelshape, Supplier supplier) { + return handle.getBlockFloorHeight(voxelshape, supplier); } @Override - public int getMaxBuildHeight() { - return this.handle.getMaxBuildHeight(); + public double getBlockFloorHeight(BlockPos blockposition) { + return handle.getBlockFloorHeight(blockposition); } @Override - public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { - return this.handle.isUnobstructed(state, pos, context); + public List getEntities(Entity entity, AxisAlignedBB aabb, Predicate prdct) { + return handle.getEntities(entity, aabb, prdct); } @Override - public boolean isUnobstructed(Entity entity) { - return this.handle.isUnobstructed(entity); + public List getEntities(EntityTypeTest ett, AxisAlignedBB aabb, Predicate prdct) { + return handle.getEntities(ett, aabb, prdct); } @Override - public WorldBorder getWorldBorder() { - return this.handle.getWorldBorder(); + public List getEntitiesOfClass(Class var0, AxisAlignedBB var1, Predicate var2) { + return handle.getEntitiesOfClass(var0, var1, var2); } @Override - public Optional findFreePosition(Entity entity, VoxelShape shape, Vec3 target, double x, double y, double z) { - return this.handle.findFreePosition(entity, shape, target, x, y, z); + public List players() { + return handle.players(); } @Override - public Iterable getCollisions(Entity entity, AABB box) { - return this.handle.getCollisions(entity, box); + public List getEntities(Entity var0, AxisAlignedBB var1) { + return handle.getEntities(var0, var1); } @Override - public Iterable getBlockCollisions(Entity entity, AABB box) { - return this.handle.getBlockCollisions(entity, box); + public List getEntitiesOfClass(Class var0, AxisAlignedBB var1) { + return handle.getEntitiesOfClass(var0, var1); } @Override - public boolean noCollision(AABB box) { - return this.handle.noCollision(box); + public EntityHuman getNearestPlayer(double var0, double var2, double var4, double var6, Predicate var8) { + return handle.getNearestPlayer(var0, var2, var4, var6, var8); } @Override - public boolean noCollision(Entity entity) { - return this.handle.noCollision(entity); + public EntityHuman getNearestPlayer(Entity var0, double var1) { + return handle.getNearestPlayer(var0, var1); } @Override - public boolean noCollision(Entity entity, AABB box) { - return this.handle.noCollision(entity, box); + public EntityHuman getNearestPlayer(double var0, double var2, double var4, double var6, boolean var8) { + return handle.getNearestPlayer(var0, var2, var4, var6, var8); } @Override - public boolean collidesWithSuffocatingBlock(Entity entity, AABB box) { - return this.handle.collidesWithSuffocatingBlock(entity, box); + public boolean hasNearbyAlivePlayer(double var0, double var2, double var4, double var6) { + return handle.hasNearbyAlivePlayer(var0, var2, var4, var6); } @Override - public Optional findSupportingBlock(Entity entity, AABB box) { - return this.handle.findSupportingBlock(entity, box); + public EntityHuman getPlayerByUUID(UUID var0) { + return handle.getPlayerByUUID(var0); } @Override - public int getBestNeighborSignal(BlockPos pos) { - return this.handle.getBestNeighborSignal(pos); + public boolean setBlock(BlockPos blockposition, IBlockData iblockdata, int i, int j) { + return handle.setBlock(blockposition, iblockdata, i, j); } @Override - public int getControlInputSignal(BlockPos pos, Direction direction, boolean onlyFromGate) { - return this.handle.getControlInputSignal(pos, direction, onlyFromGate); + public boolean setBlock(BlockPos blockposition, IBlockData iblockdata, int i) { + return handle.setBlock(blockposition, iblockdata, i); } @Override - public int getDirectSignal(BlockPos pos, Direction direction) { - return this.handle.getDirectSignal(pos, direction); + public boolean removeBlock(BlockPos blockposition, boolean flag) { + return handle.removeBlock(blockposition, flag); } @Override - public int getDirectSignalTo(BlockPos pos) { - return this.handle.getDirectSignalTo(pos); + public boolean destroyBlock(BlockPos blockposition, boolean flag) { + return handle.destroyBlock(blockposition, flag); } @Override - public boolean hasNeighborSignal(BlockPos pos) { - return this.handle.hasNeighborSignal(pos); + public boolean destroyBlock(BlockPos blockposition, boolean flag, Entity entity) { + return handle.destroyBlock(blockposition, flag, entity); } @Override - public boolean hasSignal(BlockPos pos, Direction direction) { - return this.handle.hasSignal(pos, direction); + public boolean destroyBlock(BlockPos blockposition, boolean flag, Entity entity, int i) { + return handle.destroyBlock(blockposition, flag, entity, i); } @Override - public int getSignal(BlockPos pos, Direction direction) { - return this.handle.getSignal(pos, direction); + public boolean addFreshEntity(Entity entity) { + return handle.addFreshEntity(entity); } @Override - public boolean isStateAtPosition(BlockPos pos, Predicate state) { - return this.handle.isStateAtPosition(pos, state); + public boolean addFreshEntity(Entity entity, CreatureSpawnEvent.SpawnReason reason) { + return handle.addFreshEntity(entity, reason); } @Override - public boolean isFluidAtPosition(BlockPos pos, Predicate state) { - return this.handle.isFluidAtPosition(pos, state); + public int getMaxY() { + return handle.getMaxY(); } @Override - public boolean addFreshEntity(Entity arg0, CreatureSpawnEvent.SpawnReason arg1) { - return this.handle.addFreshEntity(arg0, arg1); + public int getSectionsCount() { + return handle.getSectionsCount(); } @Override - public boolean addFreshEntity(Entity entity) { - return this.handle.addFreshEntity(entity); + public int getMinSectionY() { + return handle.getMinSectionY(); } @Override - public boolean removeBlock(BlockPos pos, boolean move) { - return this.handle.removeBlock(pos, move); + public int getMaxSectionY() { + return handle.getMaxSectionY(); } @Override - public boolean destroyBlock(BlockPos pos, boolean drop, Entity breakingEntity, int maxUpdateDepth) { - return this.handle.destroyBlock(pos, drop, breakingEntity, maxUpdateDepth); + public boolean isInsideBuildHeight(int var0) { + return handle.isInsideBuildHeight(var0); } @Override - public boolean destroyBlock(BlockPos pos, boolean drop, Entity breakingEntity) { - return this.handle.destroyBlock(pos, drop, breakingEntity); + public boolean isOutsideBuildHeight(BlockPos var0) { + return handle.isOutsideBuildHeight(var0); } @Override - public boolean destroyBlock(BlockPos pos, boolean drop) { - return this.handle.destroyBlock(pos, drop); + public boolean isOutsideBuildHeight(int var0) { + return handle.isOutsideBuildHeight(var0); } @Override - public boolean setBlock(BlockPos pos, BlockState state, int flags) { - return this.handle.setBlock(pos, state, flags); + public int getSectionIndex(int var0) { + return handle.getSectionIndex(var0); } @Override - public boolean setBlock(BlockPos pos, BlockState state, int flags, int maxUpdateDepth) { - return this.handle.setBlock(pos, state, flags, maxUpdateDepth); + public int getSectionIndexFromSectionY(int var0) { + return handle.getSectionIndexFromSectionY(var0); } @Override - public float getTimeOfDay(float tickDelta) { - return this.handle.getTimeOfDay(tickDelta); + public int getSectionYFromSectionIndex(int var0) { + return handle.getSectionYFromSectionIndex(var0); } @Override - public float getMoonBrightness() { - return this.handle.getMoonBrightness(); + public boolean isStateAtPosition(BlockPos bp, Predicate prdct) { + return handle.isStateAtPosition(bp, prdct); } @Override - public int getMoonPhase() { - return this.handle.getMoonPhase(); + public boolean isFluidAtPosition(BlockPos bp, Predicate prdct) { + return handle.isFluidAtPosition(bp, prdct); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java b/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java index e837d76e..9b99d441 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java +++ b/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java @@ -3,47 +3,47 @@ import java.util.List; import java.util.function.Predicate; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.EnumDirection; import net.minecraft.core.Holder; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.IRegistryCustom; +import net.minecraft.core.particles.ParticleParam; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundSource; +import net.minecraft.server.level.WorldServer; +import net.minecraft.sounds.SoundCategory; +import net.minecraft.sounds.SoundEffect; import net.minecraft.util.RandomSource; -import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.DifficultyDamageScaler; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.GeneratorAccessSeed; +import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.BiomeManager; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.border.WorldBorder; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkSource; +import net.minecraft.world.level.chunk.IChunkAccess; +import net.minecraft.world.level.chunk.IChunkProvider; import net.minecraft.world.level.chunk.status.ChunkStatus; -import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.DimensionManager; import net.minecraft.world.level.entity.EntityTypeTest; import net.minecraft.world.level.gameevent.GameEvent; -import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.HeightMap; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.level.storage.LevelData; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.ticks.BlackholeTickAccess; +import net.minecraft.world.level.material.FluidType; +import net.minecraft.world.level.material.FluidTypes; +import net.minecraft.world.level.storage.WorldData; +import net.minecraft.world.phys.AxisAlignedBB; +import net.minecraft.world.phys.Vec3D; import net.minecraft.world.ticks.LevelTickAccess; +import net.minecraft.world.ticks.TickListEmpty; -public class DummyGeneratorAccess implements WorldGenLevel { +public class DummyGeneratorAccess implements GeneratorAccessSeed { - public static final WorldGenLevel INSTANCE = new DummyGeneratorAccess(); + public static final GeneratorAccessSeed INSTANCE = new DummyGeneratorAccess(); protected DummyGeneratorAccess() { } @@ -54,7 +54,7 @@ public long getSeed() { } @Override - public ServerLevel getLevel() { + public WorldServer getLevel() { throw new UnsupportedOperationException("Not supported yet."); } @@ -65,26 +65,26 @@ public long nextSubTickCount() { @Override public LevelTickAccess getBlockTicks() { - return BlackholeTickAccess.emptyLevelList(); + return TickListEmpty.emptyLevelList(); } @Override - public void scheduleTick(BlockPos pos, Block block, int delay) { + public void scheduleTick(BlockPos blockposition, Block block, int i) { // Used by BlockComposter } @Override - public LevelTickAccess getFluidTicks() { - return BlackholeTickAccess.emptyLevelList(); + public LevelTickAccess getFluidTicks() { + return TickListEmpty.emptyLevelList(); } @Override - public LevelData getLevelData() { + public WorldData getLevelData() { throw new UnsupportedOperationException("Not supported yet."); } @Override - public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { + public DifficultyDamageScaler getCurrentDifficultyAt(BlockPos blockposition) { throw new UnsupportedOperationException("Not supported yet."); } @@ -94,7 +94,7 @@ public MinecraftServer getServer() { } @Override - public ChunkSource getChunkSource() { + public IChunkProvider getChunkSource() { throw new UnsupportedOperationException("Not supported yet."); } @@ -104,47 +104,47 @@ public RandomSource getRandom() { } @Override - public void playSound(Player source, BlockPos pos, SoundEvent sound, SoundSource category, float volume, float pitch) { + public void playSound(EntityHuman entityhuman, BlockPos blockposition, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void addParticle(ParticleOptions parameters, double x, double y, double z, double velocityX, double velocityY, double velocityZ) { + public void addParticle(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void levelEvent(Player player, int eventId, BlockPos pos, int data) { + public void levelEvent(EntityHuman entityhuman, int i, BlockPos blockposition, int j) { // Used by PowderSnowBlock.removeFluid } @Override - public void gameEvent(Holder event, Vec3 emitterPos, GameEvent.Context emitter) { + public void gameEvent(Holder gameevent, Vec3D vec3d, GameEvent.a gameevent_a) { // Used by BlockComposter } @Override - public List getEntities(Entity except, AABB box, Predicate predicate) { + public List getEntities(Entity entity, AxisAlignedBB aabb, Predicate prdct) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public List getEntities(EntityTypeTest filter, AABB box, Predicate predicate) { + public List getEntities(EntityTypeTest ett, AxisAlignedBB aabb, Predicate prdct) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public List players() { + public List players() { throw new UnsupportedOperationException("Not supported yet."); } @Override - public ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create) { + public IChunkAccess getChunk(int i, int i1, ChunkStatus cs, boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getHeight(Heightmap.Types heightmap, int x, int z) { + public int getHeight(HeightMap.Type type, int i, int i1) { throw new UnsupportedOperationException("Not supported yet."); } @@ -159,7 +159,7 @@ public BiomeManager getBiomeManager() { } @Override - public Holder getUncachedNoiseBiome(int biomeX, int biomeY, int biomeZ) { + public Holder getUncachedNoiseBiome(int i, int i1, int i2) { throw new UnsupportedOperationException("Not supported yet."); } @@ -174,12 +174,12 @@ public int getSeaLevel() { } @Override - public DimensionType dimensionType() { + public DimensionManager dimensionType() { throw new UnsupportedOperationException("Not supported yet."); } @Override - public RegistryAccess registryAccess() { + public IRegistryCustom registryAccess() { throw new UnsupportedOperationException("Not supported yet."); } @@ -189,7 +189,7 @@ public FeatureFlagSet enabledFeatures() { } @Override - public float getShade(Direction direction, boolean shaded) { + public float getShade(EnumDirection ed, boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -199,18 +199,18 @@ public LevelLightEngine getLightEngine() { } @Override - public BlockEntity getBlockEntity(BlockPos pos) { + public TileEntity getBlockEntity(BlockPos blockposition) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BlockState getBlockState(BlockPos pos) { + public IBlockData getBlockState(BlockPos blockposition) { return Blocks.AIR.defaultBlockState(); // SPIGOT-6515 } @Override - public FluidState getFluidState(BlockPos pos) { - return Fluids.EMPTY.defaultFluidState(); // SPIGOT-6634 + public Fluid getFluidState(BlockPos blockposition) { + return FluidTypes.EMPTY.defaultFluidState(); // SPIGOT-6634 } @Override @@ -219,27 +219,27 @@ public WorldBorder getWorldBorder() { } @Override - public boolean isStateAtPosition(BlockPos pos, Predicate state) { + public boolean isStateAtPosition(BlockPos bp, Predicate prdct) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isFluidAtPosition(BlockPos pos, Predicate state) { + public boolean isFluidAtPosition(BlockPos bp, Predicate prdct) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean setBlock(BlockPos pos, BlockState state, int flags, int maxUpdateDepth) { + public boolean setBlock(BlockPos blockposition, IBlockData iblockdata, int i, int j) { return false; } @Override - public boolean removeBlock(BlockPos pos, boolean move) { + public boolean removeBlock(BlockPos blockposition, boolean flag) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean destroyBlock(BlockPos pos, boolean drop, Entity breakingEntity, int maxUpdateDepth) { + public boolean destroyBlock(BlockPos blockposition, boolean flag, Entity entity, int i) { return false; // SPIGOT-6515 } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java b/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java index 6bb01e2a..100b8566 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java +++ b/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java @@ -12,10 +12,10 @@ public class ForwardLogHandler extends ConsoleHandler { private Map cachedLoggers = new ConcurrentHashMap(); private Logger getLogger(String name) { - Logger logger = this.cachedLoggers.get(name); + Logger logger = cachedLoggers.get(name); if (logger == null) { logger = LogManager.getLogger(name); - this.cachedLoggers.put(name, logger); + cachedLoggers.put(name, logger); } return logger; @@ -23,10 +23,10 @@ private Logger getLogger(String name) { @Override public void publish(LogRecord record) { - Logger logger = this.getLogger(String.valueOf(record.getLoggerName())); // See SPIGOT-1230 + Logger logger = getLogger(String.valueOf(record.getLoggerName())); // See SPIGOT-1230 Throwable exception = record.getThrown(); Level level = record.getLevel(); - String message = this.getFormatter().formatMessage(record); + String message = getFormatter().formatMessage(record); if (level == Level.SEVERE) { logger.error(message, exception); diff --git a/src/main/java/org/bukkit/craftbukkit/util/JsonHelper.java b/src/main/java/org/bukkit/craftbukkit/util/JsonHelper.java index 95cfcc10..fea5ea47 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/JsonHelper.java +++ b/src/main/java/org/bukkit/craftbukkit/util/JsonHelper.java @@ -16,7 +16,7 @@ public static JsonObject getObjectOrNull(@Nonnull JsonObject parent, @Nonnull St @Nonnull public static JsonObject getOrCreateObject(@Nonnull JsonObject parent, @Nonnull String key) { - JsonObject jsonObject = JsonHelper.getObjectOrNull(parent, key); + JsonObject jsonObject = getObjectOrNull(parent, key); if (jsonObject == null) { jsonObject = new JsonObject(); parent.add(key, jsonObject); @@ -32,7 +32,7 @@ public static JsonPrimitive getPrimitiveOrNull(@Nonnull JsonObject parent, @Nonn @Nullable public static String getStringOrNull(JsonObject parent, String key) { - JsonPrimitive primitive = JsonHelper.getPrimitiveOrNull(parent, key); + JsonPrimitive primitive = getPrimitiveOrNull(parent, key); return (primitive != null) ? primitive.getAsString() : null; } diff --git a/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java index 62c66e31..f194cf26 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java +++ b/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java @@ -9,67 +9,67 @@ public abstract class LazyHashSet implements Set { @Override public int size() { - return this.getReference().size(); + return getReference().size(); } @Override public boolean isEmpty() { - return this.getReference().isEmpty(); + return getReference().isEmpty(); } @Override public boolean contains(Object o) { - return this.getReference().contains(o); + return getReference().contains(o); } @Override public Iterator iterator() { - return this.getReference().iterator(); + return getReference().iterator(); } @Override public Object[] toArray() { - return this.getReference().toArray(); + return getReference().toArray(); } @Override public T[] toArray(T[] a) { - return this.getReference().toArray(a); + return getReference().toArray(a); } @Override public boolean add(E o) { - return this.getReference().add(o); + return getReference().add(o); } @Override public boolean remove(Object o) { - return this.getReference().remove(o); + return getReference().remove(o); } @Override public boolean containsAll(Collection c) { - return this.getReference().containsAll(c); + return getReference().containsAll(c); } @Override public boolean addAll(Collection c) { - return this.getReference().addAll(c); + return getReference().addAll(c); } @Override public boolean retainAll(Collection c) { - return this.getReference().retainAll(c); + return getReference().retainAll(c); } @Override public boolean removeAll(Collection c) { - return this.getReference().removeAll(c); + return getReference().removeAll(c); } @Override public void clear() { - this.getReference().clear(); + getReference().clear(); } public Set getReference() { @@ -77,18 +77,18 @@ public Set getReference() { if (reference != null) { return reference; } - return this.reference = this.makeReference(); + return this.reference = makeReference(); } abstract Set makeReference(); public boolean isLazy() { - return this.reference == null; + return reference == null; } @Override public int hashCode() { - return 157 * this.getReference().hashCode(); + return 157 * getReference().hashCode(); } @Override @@ -105,6 +105,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return this.getReference().toString(); + return getReference().toString(); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java index 0ab4c7ea..fa471936 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java +++ b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java @@ -4,7 +4,7 @@ import java.util.HashSet; import java.util.List; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.EntityPlayer; import org.bukkit.entity.Player; public class LazyPlayerSet extends LazyHashSet { @@ -17,10 +17,10 @@ public LazyPlayerSet(MinecraftServer server) { @Override HashSet makeReference() { - Preconditions.checkState(this.reference == null, "Reference already created!"); - List players = this.server.getPlayerList().players; + Preconditions.checkState(reference == null, "Reference already created!"); + List players = server.getPlayerList().players; HashSet reference = new HashSet(players.size()); - for (ServerPlayer player : players) { + for (EntityPlayer player : players) { reference.add(player.getBukkitEntity()); } return reference; diff --git a/src/main/java/org/bukkit/craftbukkit/util/LimitedClassRemapper.java b/src/main/java/org/bukkit/craftbukkit/util/LimitedClassRemapper.java index f7536996..6d84b416 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/LimitedClassRemapper.java +++ b/src/main/java/org/bukkit/craftbukkit/util/LimitedClassRemapper.java @@ -40,4 +40,4 @@ public void visitMethodInsn(int opcodeAndSource, String owner, String name, Stri super.visitMethodInsn(opcodeAndSource, owner, name, descriptor, isInterface); } } -} \ No newline at end of file +} diff --git a/src/main/java/org/bukkit/craftbukkit/util/RandomSourceWrapper.java b/src/main/java/org/bukkit/craftbukkit/util/RandomSourceWrapper.java index fc02ab2d..a54aa72e 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/RandomSourceWrapper.java +++ b/src/main/java/org/bukkit/craftbukkit/util/RandomSourceWrapper.java @@ -24,42 +24,42 @@ public PositionalRandomFactory forkPositional() { @Override public synchronized void setSeed(long seed) { - this.random.setSeed(seed); + random.setSeed(seed); } @Override public int nextInt() { - return this.random.nextInt(); + return random.nextInt(); } @Override public int nextInt(int bound) { - return this.random.nextInt(bound); + return random.nextInt(bound); } @Override public long nextLong() { - return this.random.nextLong(); + return random.nextLong(); } @Override public boolean nextBoolean() { - return this.random.nextBoolean(); + return random.nextBoolean(); } @Override public float nextFloat() { - return this.random.nextFloat(); + return random.nextFloat(); } @Override public double nextDouble() { - return this.random.nextDouble(); + return random.nextDouble(); } @Override public synchronized double nextGaussian() { - return this.random.nextGaussian(); + return random.nextGaussian(); } public static final class RandomWrapper extends Random { @@ -72,49 +72,49 @@ public RandomWrapper(RandomSource random) { @Override public void setSeed(long l) { - if (this.random != null) { - this.random.setSeed(l); + if (random != null) { + random.setSeed(l); } } @Override public int nextInt() { - return this.random.nextInt(); + return random.nextInt(); } @Override public int nextInt(int i) { - return this.random.nextInt(i); + return random.nextInt(i); } @Override public long nextLong() { - return this.random.nextLong(); + return random.nextLong(); } @Override public boolean nextBoolean() { - return this.random.nextBoolean(); + return random.nextBoolean(); } @Override public float nextFloat() { - return this.random.nextFloat(); + return random.nextFloat(); } @Override public double nextDouble() { - return this.random.nextDouble(); + return random.nextDouble(); } @Override public double nextGaussian() { - return this.random.nextGaussian(); + return random.nextGaussian(); } @Override public int nextInt(int var0, int var1) { - return this.random.nextInt(var0, var1); + return random.nextInt(var0, var1); } } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java b/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java index fcebd3e7..2e057fd4 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java +++ b/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java @@ -12,11 +12,10 @@ public ServerShutdownThread(MinecraftServer server) { @Override public void run() { try { - org.spigotmc.AsyncCatcher.enabled = false; // Spigot - this.server.close(); + server.close(); } finally { try { - net.minecrell.terminalconsole.TerminalConsoleAppender.close(); + server.reader.getTerminal().restore(); } catch (Exception e) { } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/TerminalCompletionHandler.java b/src/main/java/org/bukkit/craftbukkit/util/TerminalCompletionHandler.java index 7d1c0810..beaa54b5 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/TerminalCompletionHandler.java +++ b/src/main/java/org/bukkit/craftbukkit/util/TerminalCompletionHandler.java @@ -25,23 +25,23 @@ public TerminalCompletionHandler(TerminalConsoleWriterThread writerThread, Compl public boolean complete(ConsoleReader reader, List candidates, int position) throws IOException { // First check normal list, so that we do not unnecessarily create a new HashSet if the not distinct list is already lower if (candidates.size() <= reader.getAutoprintThreshold()) { - return this.delegate.complete(reader, candidates, position); + return delegate.complete(reader, candidates, position); } Set distinct = new HashSet<>(candidates); if (distinct.size() <= reader.getAutoprintThreshold()) { - return this.delegate.complete(reader, candidates, position); + return delegate.complete(reader, candidates, position); } - this.writerThread.setCompletion(distinct.size()); + writerThread.setCompletion(distinct.size()); // FIXME: Potential concurrency issue, when terminal writer prints the display message before the delegate does it // resulting in two display message being present, until a new message gets logged or the user presses y / n // But the probability of this happening are probably lower than the effort needed to fix this // And seeing the display message at all should be a higher priority than seeing it two times in rare cases. - boolean result = this.delegate.complete(reader, candidates, position); + boolean result = delegate.complete(reader, candidates, position); - this.writerThread.setCompletion(-1); + writerThread.setCompletion(-1); // draw line to prevent concurrency issue, // where terminal write would print the display message between delegate#complete finished and the completion set back to -1 // Resulting in the display message being present even after pressing y / n diff --git a/src/main/java/org/bukkit/craftbukkit/util/TerminalConsoleWriterThread.java b/src/main/java/org/bukkit/craftbukkit/util/TerminalConsoleWriterThread.java index 2e5101fc..3a4eb594 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/TerminalConsoleWriterThread.java +++ b/src/main/java/org/bukkit/craftbukkit/util/TerminalConsoleWriterThread.java @@ -40,26 +40,26 @@ public void run() { try { if (Main.useJline) { - this.reader.print(Ansi.ansi().eraseLine(Erase.ALL).toString() + ConsoleReader.RESET_LINE); - this.reader.flush(); - this.output.write(message.getBytes()); - this.output.flush(); + reader.print(Ansi.ansi().eraseLine(Erase.ALL).toString() + ConsoleReader.RESET_LINE); + reader.flush(); + output.write(message.getBytes()); + output.flush(); try { - this.reader.drawLine(); + reader.drawLine(); } catch (Throwable ex) { - this.reader.getCursorBuffer().clear(); + reader.getCursorBuffer().clear(); } - if (this.completion > -1) { + if (completion > -1) { // SPIGOT-6705: Make sure we print the display line again on tab completion, so that the user does not get stuck on it - this.reader.print(String.format(this.bundle.getString("DISPLAY_CANDIDATES"), this.completion)); + reader.print(String.format(bundle.getString("DISPLAY_CANDIDATES"), completion)); } - this.reader.flush(); + reader.flush(); } else { - this.output.write(message.getBytes()); - this.output.flush(); + output.write(message.getBytes()); + output.flush(); } } catch (IOException ex) { Logger.getLogger(TerminalConsoleWriterThread.class.getName()).log(Level.SEVERE, null, ex); diff --git a/src/main/java/org/bukkit/craftbukkit/util/TransformerGeneratorAccess.java b/src/main/java/org/bukkit/craftbukkit/util/TransformerGeneratorAccess.java index 35ecf6f8..e28fe1ac 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/TransformerGeneratorAccess.java +++ b/src/main/java/org/bukkit/craftbukkit/util/TransformerGeneratorAccess.java @@ -2,10 +2,10 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.entity.TileEntity; +import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.levelgen.structure.StructurePiece; -import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Fluid; import org.bukkit.craftbukkit.block.CraftBlockEntityState; import org.bukkit.craftbukkit.block.CraftBlockState; import org.bukkit.craftbukkit.block.CraftBlockStates; @@ -20,57 +20,57 @@ public void setStructureTransformer(CraftStructureTransformer structureTransform } public CraftStructureTransformer getStructureTransformer() { - return this.structureTransformer; + return structureTransformer; } @Override - public boolean addFreshEntity(Entity entity) { - if (this.structureTransformer != null && !this.structureTransformer.transformEntity(entity)) { + public boolean addFreshEntity(Entity arg0) { + if (structureTransformer != null && !structureTransformer.transformEntity(arg0)) { return false; } - return super.addFreshEntity(entity); + return super.addFreshEntity(arg0); } @Override public boolean addFreshEntity(Entity arg0, SpawnReason arg1) { - if (this.structureTransformer != null && !this.structureTransformer.transformEntity(arg0)) { + if (structureTransformer != null && !structureTransformer.transformEntity(arg0)) { return false; } return super.addFreshEntity(arg0, arg1); } @Override - public void addFreshEntityWithPassengers(Entity entity) { - if (this.structureTransformer != null && !this.structureTransformer.transformEntity(entity)) { + public void addFreshEntityWithPassengers(Entity arg0) { + if (structureTransformer != null && !structureTransformer.transformEntity(arg0)) { return; } - super.addFreshEntityWithPassengers(entity); + super.addFreshEntityWithPassengers(arg0); } @Override public void addFreshEntityWithPassengers(Entity arg0, SpawnReason arg1) { - if (this.structureTransformer != null && !this.structureTransformer.transformEntity(arg0)) { + if (structureTransformer != null && !structureTransformer.transformEntity(arg0)) { return; } super.addFreshEntityWithPassengers(arg0, arg1); } public boolean setCraftBlock(BlockPos position, CraftBlockState craftBlockState, int i, int j) { - if (this.structureTransformer != null) { - craftBlockState = this.structureTransformer.transformCraftState(craftBlockState); + if (structureTransformer != null) { + craftBlockState = structureTransformer.transformCraftState(craftBlockState); } // This code is based on the method 'net.minecraft.world.level.levelgen.structure.StructurePiece#placeBlock' // It ensures that any kind of block is updated correctly upon placing it - BlockState iblockdata = craftBlockState.getHandle(); + IBlockData iblockdata = craftBlockState.getHandle(); boolean result = super.setBlock(position, iblockdata, i, j); - FluidState fluid = this.getFluidState(position); + Fluid fluid = getFluidState(position); if (!fluid.isEmpty()) { - this.scheduleTick(position, fluid.getType(), 0); + scheduleTick(position, fluid.getType(), 0); } if (StructurePiece.SHAPE_CHECK_BLOCKS.contains(iblockdata.getBlock())) { - this.getChunk(position).markPosForPostprocessing(position); + getChunk(position).markPosForPostprocessing(position); } - BlockEntity tileEntity = this.getBlockEntity(position); + TileEntity tileEntity = getBlockEntity(position); if (tileEntity != null && craftBlockState instanceof CraftBlockEntityState craftEntityState) { tileEntity.loadWithComponents(craftEntityState.getSnapshotNBT(), this.registryAccess()); } @@ -78,19 +78,19 @@ public boolean setCraftBlock(BlockPos position, CraftBlockState craftBlockState, } public boolean setCraftBlock(BlockPos position, CraftBlockState craftBlockState, int i) { - return this.setCraftBlock(position, craftBlockState, i, 512); + return setCraftBlock(position, craftBlockState, i, 512); } @Override - public boolean setBlock(BlockPos pos, BlockState state, int flags, int maxUpdateDepth) { - if (this.structureTransformer == null || !this.structureTransformer.canTransformBlocks()) { - return super.setBlock(pos, state, flags, maxUpdateDepth); + public boolean setBlock(BlockPos position, IBlockData iblockdata, int i, int j) { + if (structureTransformer == null || !structureTransformer.canTransformBlocks()) { + return super.setBlock(position, iblockdata, i, j); } - return this.setCraftBlock(pos, (CraftBlockState) CraftBlockStates.getBlockState(this, pos, state, null), flags, maxUpdateDepth); + return setCraftBlock(position, (CraftBlockState) CraftBlockStates.getBlockState(this, position, iblockdata, null), i, j); } @Override - public boolean setBlock(BlockPos pos, BlockState state, int flags) { - return this.setBlock(pos, state, flags, 512); + public boolean setBlock(BlockPos position, IBlockData iblockdata, int i) { + return setBlock(position, iblockdata, i, 512); } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java b/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java index 96c4f7ae..3d5cc818 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java +++ b/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java @@ -30,10 +30,10 @@ public UnsafeList(int capacity, int maxIterPool) { super(); if (capacity < 0) capacity = 32; int rounded = Integer.highestOneBit(capacity - 1) << 1; - this.data = new Object[rounded]; - this.initialCapacity = rounded; - this.maxPool = maxIterPool; - this.iterPool[0] = new Itr(); + data = new Object[rounded]; + initialCapacity = rounded; + maxPool = maxIterPool; + iterPool[0] = new Itr(); } public UnsafeList(int capacity) { @@ -46,58 +46,58 @@ public UnsafeList() { @Override public E get(int index) { - this.rangeCheck(index); + rangeCheck(index); - return (E) this.data[index]; + return (E) data[index]; } public E unsafeGet(int index) { - return (E) this.data[index]; + return (E) data[index]; } @Override public E set(int index, E element) { - this.rangeCheck(index); + rangeCheck(index); - E old = (E) this.data[index]; - this.data[index] = element; + E old = (E) data[index]; + data[index] = element; return old; } @Override public boolean add(E element) { - this.growIfNeeded(); - this.data[this.size++] = element; + growIfNeeded(); + data[size++] = element; return true; } @Override public void add(int index, E element) { - this.growIfNeeded(); - System.arraycopy(this.data, index, this.data, index + 1, this.size - index); - this.data[index] = element; - this.size++; + growIfNeeded(); + System.arraycopy(data, index, data, index + 1, size - index); + data[index] = element; + size++; } @Override public E remove(int index) { - this.rangeCheck(index); + rangeCheck(index); - E old = (E) this.data[index]; - int movedCount = this.size - index - 1; + E old = (E) data[index]; + int movedCount = size - index - 1; if (movedCount > 0) { - System.arraycopy(this.data, index + 1, this.data, index, movedCount); + System.arraycopy(data, index + 1, data, index, movedCount); } - this.data[--this.size] = null; + data[--size] = null; return old; } @Override public boolean remove(Object o) { - int index = this.indexOf(o); + int index = indexOf(o); if (index >= 0) { - this.remove(index); + remove(index); return true; } @@ -106,8 +106,8 @@ public boolean remove(Object o) { @Override public int indexOf(Object o) { - for (int i = 0; i < this.size; i++) { - if (o == this.data[i] || o.equals(this.data[i])) { + for (int i = 0; i < size; i++) { + if (o == data[i] || o.equals(data[i])) { return i; } } @@ -117,52 +117,52 @@ public int indexOf(Object o) { @Override public boolean contains(Object o) { - return this.indexOf(o) >= 0; + return indexOf(o) >= 0; } @Override public void clear() { // Create new array to reset memory usage to initial capacity - this.size = 0; + size = 0; // If array has grown too large create new one, otherwise just clear it - if (this.data.length > this.initialCapacity << 3) { - this.data = new Object[this.initialCapacity]; + if (data.length > initialCapacity << 3) { + data = new Object[initialCapacity]; } else { - for (int i = 0; i < this.data.length; i++) { - this.data[i] = null; + for (int i = 0; i < data.length; i++) { + data[i] = null; } } } // actually rounds up to nearest power of two public void trimToSize() { - int old = this.data.length; - int rounded = Integer.highestOneBit(this.size - 1) << 1; + int old = data.length; + int rounded = Integer.highestOneBit(size - 1) << 1; if (rounded < old) { - this.data = Arrays.copyOf(this.data, rounded); + data = Arrays.copyOf(data, rounded); } } @Override public int size() { - return this.size; + return size; } @Override public boolean isEmpty() { - return this.size == 0; + return size == 0; } @Override public Object clone() throws CloneNotSupportedException { UnsafeList copy = (UnsafeList) super.clone(); - copy.data = Arrays.copyOf(this.data, this.size); - copy.size = this.size; - copy.initialCapacity = this.initialCapacity; + copy.data = Arrays.copyOf(data, size); + copy.size = size; + copy.initialCapacity = initialCapacity; copy.iterPool = new Iterator[1]; copy.iterPool[0] = new Itr(); - copy.maxPool = this.maxPool; + copy.maxPool = maxPool; copy.poolCounter = 0; return copy; } @@ -170,7 +170,7 @@ public Object clone() throws CloneNotSupportedException { @Override public Iterator iterator() { // Try to find an iterator that isn't in use - for (Iterator iter : this.iterPool) { + for (Iterator iter : iterPool) { if (!((Itr) iter).valid) { Itr iterator = (Itr) iter; iterator.reset(); @@ -179,112 +179,112 @@ public Iterator iterator() { } // Couldn't find one, see if we can grow our pool size - if (this.iterPool.length < this.maxPool) { - Iterator[] newPool = new Iterator[this.iterPool.length + 1]; - System.arraycopy(this.iterPool, 0, newPool, 0, this.iterPool.length); - this.iterPool = newPool; + if (iterPool.length < maxPool) { + Iterator[] newPool = new Iterator[iterPool.length + 1]; + System.arraycopy(iterPool, 0, newPool, 0, iterPool.length); + iterPool = newPool; - this.iterPool[this.iterPool.length - 1] = new Itr(); - return this.iterPool[this.iterPool.length - 1]; + iterPool[iterPool.length - 1] = new Itr(); + return iterPool[iterPool.length - 1]; } // Still couldn't find a free one, round robin replace one with a new iterator // This is done in the hope that the new one finishes so can be reused - this.poolCounter = ++this.poolCounter % this.iterPool.length; - this.iterPool[this.poolCounter] = new Itr(); - return this.iterPool[this.poolCounter]; + poolCounter = ++poolCounter % iterPool.length; + iterPool[poolCounter] = new Itr(); + return iterPool[poolCounter]; } private void rangeCheck(int index) { - if (index >= this.size || index < 0) { - throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); + if (index >= size || index < 0) { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } } private void growIfNeeded() { - if (this.size == this.data.length) { - Object[] newData = new Object[this.data.length << 1]; - System.arraycopy(this.data, 0, newData, 0, this.size); - this.data = newData; + if (size == data.length) { + Object[] newData = new Object[data.length << 1]; + System.arraycopy(data, 0, newData, 0, size); + data = newData; } } private void writeObject(ObjectOutputStream os) throws IOException { os.defaultWriteObject(); - os.writeInt(this.size); - os.writeInt(this.initialCapacity); - for (int i = 0; i < this.size; i++) { - os.writeObject(this.data[i]); + os.writeInt(size); + os.writeInt(initialCapacity); + for (int i = 0; i < size; i++) { + os.writeObject(data[i]); } - os.writeInt(this.maxPool); + os.writeInt(maxPool); } private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { is.defaultReadObject(); - this.size = is.readInt(); - this.initialCapacity = is.readInt(); - this.data = new Object[Integer.highestOneBit(this.size - 1) << 1]; - for (int i = 0; i < this.size; i++) { - this.data[i] = is.readObject(); + size = is.readInt(); + initialCapacity = is.readInt(); + data = new Object[Integer.highestOneBit(size - 1) << 1]; + for (int i = 0; i < size; i++) { + data[i] = is.readObject(); } - this.maxPool = is.readInt(); - this.iterPool = new Iterator[1]; - this.iterPool[0] = new Itr(); + maxPool = is.readInt(); + iterPool = new Iterator[1]; + iterPool[0] = new Itr(); } public class Itr implements Iterator { int index; int lastRet = -1; - int expectedModCount = UnsafeList.this.modCount; + int expectedModCount = modCount; public boolean valid = true; public void reset() { - this.index = 0; - this.lastRet = -1; - this.expectedModCount = UnsafeList.this.modCount; - this.valid = true; + index = 0; + lastRet = -1; + expectedModCount = modCount; + valid = true; } @Override public boolean hasNext() { - this.valid = this.index != UnsafeList.this.size; - return this.valid; + valid = index != size; + return valid; } @Override public E next() { - if (UnsafeList.this.modCount != this.expectedModCount) { + if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } - int i = this.index; - if (i >= UnsafeList.this.size) { + int i = index; + if (i >= size) { throw new NoSuchElementException(); } - if (i >= UnsafeList.this.data.length) { + if (i >= data.length) { throw new ConcurrentModificationException(); } - this.index = i + 1; - return (E) UnsafeList.this.data[this.lastRet = i]; + index = i + 1; + return (E) data[lastRet = i]; } @Override public void remove() { - Preconditions.checkState(this.lastRet >= 0, ""); + Preconditions.checkState(lastRet >= 0, ""); - if (UnsafeList.this.modCount != this.expectedModCount) { + if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } try { - UnsafeList.this.remove(this.lastRet); - this.index = this.lastRet; - this.lastRet = -1; - this.expectedModCount = UnsafeList.this.modCount; + UnsafeList.this.remove(lastRet); + index = lastRet; + lastRet = -1; + expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } diff --git a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java index fc5044f3..58c3b188 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java +++ b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java @@ -2,6 +2,6 @@ public final class Versioning { public static String getBukkitVersion() { - return "1.21-R0.1-SNAPSHOT"; + return "1.21.2-R0.1-SNAPSHOT"; } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/Waitable.java b/src/main/java/org/bukkit/craftbukkit/util/Waitable.java index 864a213a..73be17fc 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/Waitable.java +++ b/src/main/java/org/bukkit/craftbukkit/util/Waitable.java @@ -16,16 +16,16 @@ private enum Status { @Override public final void run() { synchronized (this) { - Preconditions.checkState(this.status == Status.WAITING, "Invalid state %s", this.status); - this.status = Status.RUNNING; + Preconditions.checkState(status == Status.WAITING, "Invalid state %s", status); + status = Status.RUNNING; } try { - this.value = this.evaluate(); + value = evaluate(); } catch (Throwable t) { this.t = t; } finally { synchronized (this) { - this.status = Status.FINISHED; + status = Status.FINISHED; this.notifyAll(); } } @@ -34,12 +34,12 @@ public final void run() { protected abstract T evaluate(); public synchronized T get() throws InterruptedException, ExecutionException { - while (this.status != Status.FINISHED) { + while (status != Status.FINISHED) { this.wait(); } - if (this.t != null) { - throw new ExecutionException(this.t); + if (t != null) { + throw new ExecutionException(t); } - return this.value; + return value; } } diff --git a/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java b/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java index b25dc23b..489f548b 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java +++ b/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java @@ -12,13 +12,13 @@ public final class WeakCollection implements Collection { private final Collection> collection; public WeakCollection() { - this.collection = new ArrayList<>(); + collection = new ArrayList<>(); } @Override public boolean add(T value) { Preconditions.checkArgument(value != null, "Cannot add null value"); - return this.collection.add(new WeakReference(value)); + return collection.add(new WeakReference(value)); } @Override @@ -34,7 +34,7 @@ public boolean addAll(Collection collection) { @Override public void clear() { - this.collection.clear(); + collection.clear(); } @Override @@ -52,24 +52,24 @@ public boolean contains(Object object) { @Override public boolean containsAll(Collection collection) { - return this.toCollection().containsAll(collection); + return toCollection().containsAll(collection); } @Override public boolean isEmpty() { - return !this.iterator().hasNext(); + return !iterator().hasNext(); } @Override public Iterator iterator() { return new Iterator() { - Iterator> it = WeakCollection.this.collection.iterator(); - Object value = WeakCollection.NO_VALUE; + Iterator> it = collection.iterator(); + Object value = NO_VALUE; @Override public boolean hasNext() { Object value = this.value; - if (value != null && value != WeakCollection.NO_VALUE) { + if (value != null && value != NO_VALUE) { return true; } @@ -91,22 +91,22 @@ public boolean hasNext() { @Override public T next() throws NoSuchElementException { - if (!this.hasNext()) { + if (!hasNext()) { throw new NoSuchElementException("No more elements"); } @SuppressWarnings("unchecked") T value = (T) this.value; - this.value = WeakCollection.NO_VALUE; + this.value = NO_VALUE; return value; } @Override public void remove() throws IllegalStateException { - Preconditions.checkState(this.value == WeakCollection.NO_VALUE, "No last element"); + Preconditions.checkState(value == NO_VALUE, "No last element"); - this.value = null; - this.it.remove(); + value = null; + it.remove(); } }; } @@ -169,7 +169,7 @@ public Object[] toArray() { @Override public T[] toArray(T[] array) { - return this.toCollection().toArray(array); + return toCollection().toArray(array); } private Collection toCollection() { diff --git a/src/main/java/org/bukkit/craftbukkit/util/WorldUUID.java b/src/main/java/org/bukkit/craftbukkit/util/WorldUUID.java index 924abced..0fa55eba 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/WorldUUID.java +++ b/src/main/java/org/bukkit/craftbukkit/util/WorldUUID.java @@ -25,7 +25,7 @@ public static UUID getUUID(File baseDir) { dis = new DataInputStream(new FileInputStream(file1)); return new UUID(dis.readLong(), dis.readLong()); } catch (IOException ex) { - WorldUUID.LOGGER.warn("Failed to read " + file1 + ", generating new random UUID", ex); + LOGGER.warn("Failed to read " + file1 + ", generating new random UUID", ex); } finally { if (dis != null) { try { @@ -44,7 +44,7 @@ public static UUID getUUID(File baseDir) { dos.writeLong(uuid.getMostSignificantBits()); dos.writeLong(uuid.getLeastSignificantBits()); } catch (IOException ex) { - WorldUUID.LOGGER.warn("Failed to write " + file1, ex); + LOGGER.warn("Failed to write " + file1, ex); } finally { if (dos != null) { try { diff --git a/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java b/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java index a9ea2e38..d5f4ece0 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java +++ b/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java @@ -6,31 +6,31 @@ public final class CommandPermissions { private static final String ROOT = "minecraft.command"; - private static final String PREFIX = CommandPermissions.ROOT + "."; + private static final String PREFIX = ROOT + "."; private CommandPermissions() {} public static Permission registerPermissions(Permission parent) { - Permission commands = DefaultPermissions.registerPermission(CommandPermissions.ROOT, "Gives the user the ability to use all vanilla minecraft commands", parent); + Permission commands = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all vanilla minecraft commands", parent); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "kill", "Allows the user to commit suicide", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "me", "Allows the user to perform a chat action", PermissionDefault.TRUE, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "msg", "Allows the user to privately message another player", PermissionDefault.TRUE, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "help", "Allows the user to access Vanilla command help", PermissionDefault.TRUE, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "say", "Allows the user to talk as the console", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "give", "Allows the user to give items to players", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "teleport", "Allows the user to teleport players", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "kick", "Allows the user to kick players", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "stop", "Allows the user to stop the server", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "list", "Allows the user to list all online players", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "gamemode", "Allows the user to change the gamemode of another player", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "xp", "Allows the user to give themselves or others arbitrary values of experience", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "toggledownfall", "Allows the user to toggle rain on/off for a given world", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "defaultgamemode", "Allows the user to change the default gamemode of the server", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "seed", "Allows the user to view the seed of the world", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "effect", "Allows the user to add/remove effects on players", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "selector", "Allows the use of selectors", PermissionDefault.OP, commands); - DefaultPermissions.registerPermission(CommandPermissions.PREFIX + "trigger", "Allows the use of the trigger command", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "kill", "Allows the user to commit suicide", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "me", "Allows the user to perform a chat action", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "msg", "Allows the user to privately message another player", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "help", "Allows the user to access Vanilla command help", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "say", "Allows the user to talk as the console", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "give", "Allows the user to give items to players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "teleport", "Allows the user to teleport players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "kick", "Allows the user to kick players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "stop", "Allows the user to stop the server", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "list", "Allows the user to list all online players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "gamemode", "Allows the user to change the gamemode of another player", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "xp", "Allows the user to give themselves or others arbitrary values of experience", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "toggledownfall", "Allows the user to toggle rain on/off for a given world", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "defaultgamemode", "Allows the user to change the default gamemode of the server", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "seed", "Allows the user to view the seed of the world", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "effect", "Allows the user to add/remove effects on players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "selector", "Allows the use of selectors", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "trigger", "Allows the use of the trigger command", PermissionDefault.TRUE, commands); DefaultPermissions.registerPermission("minecraft.admin.command_feedback", "Receive command broadcasts when sendCommandFeedback is true", PermissionDefault.OP, commands); diff --git a/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java b/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java index 5ac25dab..75f8d47a 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java +++ b/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java @@ -9,14 +9,8 @@ public final class CraftDefaultPermissions { private CraftDefaultPermissions() {} public static void registerCorePermissions() { - Permission parent = DefaultPermissions.registerPermission(CraftDefaultPermissions.ROOT, "Gives the user the ability to use all vanilla utilities and commands"); + Permission parent = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all vanilla utilities and commands"); CommandPermissions.registerPermissions(parent); - // Spigot start - DefaultPermissions.registerPermission(CraftDefaultPermissions.ROOT + ".nbt.place", "Gives the user the ability to place restricted blocks with NBT in creative", org.bukkit.permissions.PermissionDefault.OP, parent); - DefaultPermissions.registerPermission(CraftDefaultPermissions.ROOT + ".nbt.copy", "Gives the user the ability to copy NBT in creative", org.bukkit.permissions.PermissionDefault.TRUE, parent); - DefaultPermissions.registerPermission(CraftDefaultPermissions.ROOT + ".debugstick", "Gives the user the ability to use the debug stick in creative", org.bukkit.permissions.PermissionDefault.OP, parent); - DefaultPermissions.registerPermission(CraftDefaultPermissions.ROOT + ".debugstick.always", "Gives the user the ability to use the debug stick in all game modes", org.bukkit.permissions.PermissionDefault.FALSE, parent); - // Spigot end parent.recalculatePermissibles(); } } diff --git a/src/main/java/org/spigotmc/ActivationRange.java b/src/main/java/org/spigotmc/ActivationRange.java deleted file mode 100644 index 0c7c97f2..00000000 --- a/src/main/java/org/spigotmc/ActivationRange.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.spigotmc; - -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.ExperienceOrb; -import net.minecraft.world.entity.LightningBolt; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.PathfinderMob; -import net.minecraft.world.entity.ambient.AmbientCreature; -import net.minecraft.world.entity.animal.Animal; -import net.minecraft.world.entity.animal.Sheep; -import net.minecraft.world.entity.boss.EnderDragonPart; -import net.minecraft.world.entity.boss.enderdragon.EndCrystal; -import net.minecraft.world.entity.boss.enderdragon.EnderDragon; -import net.minecraft.world.entity.boss.wither.WitherBoss; -import net.minecraft.world.entity.item.PrimedTnt; -import net.minecraft.world.entity.monster.Creeper; -import net.minecraft.world.entity.monster.Monster; -import net.minecraft.world.entity.monster.Slime; -import net.minecraft.world.entity.npc.Villager; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.entity.projectile.AbstractArrow; -import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; -import net.minecraft.world.entity.projectile.ThrowableProjectile; -import net.minecraft.world.entity.projectile.ThrownTrident; -import net.minecraft.world.entity.raid.Raider; -import net.minecraft.world.level.Level; -import net.minecraft.world.phys.AABB; -import org.bukkit.craftbukkit.SpigotTimings; - -public class ActivationRange -{ - - public enum ActivationType - { - MONSTER, - ANIMAL, - RAIDER, - MISC; - - AABB boundingBox = new AABB( 0, 0, 0, 0, 0, 0 ); - } - - static AABB maxBB = new AABB( 0, 0, 0, 0, 0, 0 ); - - /** - * Initializes an entities type on construction to specify what group this - * entity is in for activation ranges. - * - * @param entity - * @return group id - */ - public static ActivationType initializeEntityActivationType(Entity entity) - { - if ( entity instanceof Raider ) - { - return ActivationType.RAIDER; - } else if ( entity instanceof Monster || entity instanceof Slime ) - { - return ActivationType.MONSTER; - } else if ( entity instanceof PathfinderMob || entity instanceof AmbientCreature ) - { - return ActivationType.ANIMAL; - } else - { - return ActivationType.MISC; - } - } - - /** - * These entities are excluded from Activation range checks. - * - * @param entity - * @param config - * @return boolean If it should always tick. - */ - public static boolean initializeEntityActivationState(Entity entity, SpigotWorldConfig config) - { - if ( ( entity.activationType == ActivationType.MISC && config.miscActivationRange == 0 ) - || ( entity.activationType == ActivationType.RAIDER && config.raiderActivationRange == 0 ) - || ( entity.activationType == ActivationType.ANIMAL && config.animalActivationRange == 0 ) - || ( entity.activationType == ActivationType.MONSTER && config.monsterActivationRange == 0 ) - || entity instanceof Player - || entity instanceof ThrowableProjectile - || entity instanceof EnderDragon - || entity instanceof EnderDragonPart - || entity instanceof WitherBoss - || entity instanceof AbstractHurtingProjectile - || entity instanceof LightningBolt - || entity instanceof PrimedTnt - || entity instanceof EndCrystal - || entity instanceof FireworkRocketEntity - || entity instanceof ThrownTrident ) - { - return true; - } - - return false; - } - - /** - * Find what entities are in range of the players in the world and set - * active if in range. - * - * @param world - */ - public static void activateEntities(Level world) - { - SpigotTimings.entityActivationCheckTimer.startTiming(); - final int miscActivationRange = world.spigotConfig.miscActivationRange; - final int raiderActivationRange = world.spigotConfig.raiderActivationRange; - final int animalActivationRange = world.spigotConfig.animalActivationRange; - final int monsterActivationRange = world.spigotConfig.monsterActivationRange; - - int maxRange = Math.max( monsterActivationRange, animalActivationRange ); - maxRange = Math.max( maxRange, raiderActivationRange ); - maxRange = Math.max( maxRange, miscActivationRange ); - maxRange = Math.min( ( world.spigotConfig.simulationDistance << 4 ) - 8, maxRange ); - - for ( Player player : world.players() ) - { - player.activatedTick = MinecraftServer.currentTick; - if ( world.spigotConfig.ignoreSpectatorActivation && player.isSpectator() ) - { - continue; - } - - ActivationRange.maxBB = player.getBoundingBox().inflate( maxRange, 256, maxRange ); - ActivationType.MISC.boundingBox = player.getBoundingBox().inflate( miscActivationRange, 256, miscActivationRange ); - ActivationType.RAIDER.boundingBox = player.getBoundingBox().inflate( raiderActivationRange, 256, raiderActivationRange ); - ActivationType.ANIMAL.boundingBox = player.getBoundingBox().inflate( animalActivationRange, 256, animalActivationRange ); - ActivationType.MONSTER.boundingBox = player.getBoundingBox().inflate( monsterActivationRange, 256, monsterActivationRange ); - - world.getEntities().get(ActivationRange.maxBB, ActivationRange::activateEntity); - } - SpigotTimings.entityActivationCheckTimer.stopTiming(); - } - - /** - * Checks for the activation state of all entities in this chunk. - * - * @param chunk - */ - private static void activateEntity(Entity entity) - { - if ( MinecraftServer.currentTick > entity.activatedTick ) - { - if ( entity.defaultActivationState ) - { - entity.activatedTick = MinecraftServer.currentTick; - return; - } - if ( entity.activationType.boundingBox.intersects( entity.getBoundingBox() ) ) - { - entity.activatedTick = MinecraftServer.currentTick; - } - } - } - - /** - * If an entity is not in range, do some more checks to see if we should - * give it a shot. - * - * @param entity - * @return - */ - public static boolean checkEntityImmunities(Entity entity) - { - // quick checks. - if ( entity.wasTouchingWater || entity.getRemainingFireTicks() > 0 ) - { - return true; - } - if ( !( entity instanceof AbstractArrow ) ) - { - if ( !entity.onGround() || !entity.passengers.isEmpty() || entity.isPassenger() ) - { - return true; - } - } else if ( !( (AbstractArrow) entity ).inGround ) - { - return true; - } - // special cases. - if ( entity instanceof LivingEntity ) - { - LivingEntity living = (LivingEntity) entity; - if ( /*TODO: Missed mapping? living.attackTicks > 0 || */ living.hurtTime > 0 || living.activeEffects.size() > 0 ) - { - return true; - } - if ( entity instanceof PathfinderMob && ( (PathfinderMob) entity ).getTarget() != null ) - { - return true; - } - if ( entity instanceof Villager && ( (Villager) entity ).canBreed() ) - { - return true; - } - if ( entity instanceof Animal ) - { - Animal animal = (Animal) entity; - if ( animal.isBaby() || animal.isInLove() ) - { - return true; - } - if ( entity instanceof Sheep && ( (Sheep) entity ).isSheared() ) - { - return true; - } - } - if (entity instanceof Creeper && ((Creeper) entity).isIgnited()) { // isExplosive - return true; - } - } - // SPIGOT-6644: Otherwise the target refresh tick will be missed - if (entity instanceof ExperienceOrb) { - return true; - } - return false; - } - - /** - * Checks if the entity is active for this tick. - * - * @param entity - * @return - */ - public static boolean checkIfActive(Entity entity) - { - SpigotTimings.checkIfActiveTimer.startTiming(); - // Never safe to skip fireworks or entities not yet added to chunk - if ( entity instanceof FireworkRocketEntity ) { - SpigotTimings.checkIfActiveTimer.stopTiming(); - return true; - } - - boolean isActive = entity.activatedTick >= MinecraftServer.currentTick || entity.defaultActivationState; - - // Should this entity tick? - if ( !isActive ) - { - if ( ( MinecraftServer.currentTick - entity.activatedTick - 1 ) % 20 == 0 ) - { - // Check immunities every 20 ticks. - if ( ActivationRange.checkEntityImmunities( entity ) ) - { - // Triggered some sort of immunity, give 20 full ticks before we check again. - entity.activatedTick = MinecraftServer.currentTick + 20; - } - isActive = true; - } - // Add a little performance juice to active entities. Skip 1/4 if not immune. - } else if ( !entity.defaultActivationState && entity.tickCount % 4 == 0 && !ActivationRange.checkEntityImmunities( entity ) ) - { - isActive = false; - } - SpigotTimings.checkIfActiveTimer.stopTiming(); - return isActive; - } -} diff --git a/src/main/java/org/spigotmc/AsyncCatcher.java b/src/main/java/org/spigotmc/AsyncCatcher.java deleted file mode 100644 index 9cbd6626..00000000 --- a/src/main/java/org/spigotmc/AsyncCatcher.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.spigotmc; - -import net.minecraft.server.MinecraftServer; - -public class AsyncCatcher { - - public static boolean enabled = true; - - public static void catchOp(String reason) { - if (AsyncCatcher.enabled && Thread.currentThread() != MinecraftServer.getServer().serverThread) { - throw new IllegalStateException("Asynchronous " + reason + "!"); - } - } - - public static boolean catchAsync() { - if (enabled && Thread.currentThread() != MinecraftServer.getServer().serverThread) { - return true; - } - return false; - } -} diff --git a/src/main/java/org/spigotmc/CustomTimingsHandler.java b/src/main/java/org/spigotmc/CustomTimingsHandler.java deleted file mode 100644 index 44badfed..00000000 --- a/src/main/java/org/spigotmc/CustomTimingsHandler.java +++ /dev/null @@ -1,137 +0,0 @@ -package org.spigotmc; - -import java.io.PrintStream; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.defaults.TimingsCommand; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Provides custom timing sections for /timings merged. - */ -public class CustomTimingsHandler { - - private static Queue HANDLERS = new ConcurrentLinkedQueue(); - /*========================================================================*/ - private final String name; - private final CustomTimingsHandler parent; - private long count = 0; - private long start = 0; - private long timingDepth = 0; - private long totalTime = 0; - private long curTickTotal = 0; - private long violations = 0; - - public CustomTimingsHandler(@NotNull String name) { - this(name, null); - } - - public CustomTimingsHandler(@NotNull String name, @Nullable CustomTimingsHandler parent) { - this.name = name; - this.parent = parent; - HANDLERS.add(this); - } - - /** - * Prints the timings and extra data to the given stream. - * - * @param printStream output stream - */ - public static void printTimings(@NotNull PrintStream printStream) { - printStream.println("Minecraft"); - for (CustomTimingsHandler timings : HANDLERS) { - long time = timings.totalTime; - long count = timings.count; - if (count == 0) { - continue; - } - long avg = time / count; - - printStream.println(" " + timings.name + " Time: " + time + " Count: " + count + " Avg: " + avg + " Violations: " + timings.violations); - } - printStream.println("# Version " + Bukkit.getVersion()); - int entities = 0; - int livingEntities = 0; - for (World world : Bukkit.getWorlds()) { - entities += world.getEntities().size(); - livingEntities += world.getLivingEntities().size(); - } - printStream.println("# Entities " + entities); - printStream.println("# LivingEntities " + livingEntities); - } - - /** - * Resets all timings. - */ - public static void reload() { - if (Bukkit.getPluginManager().useTimings()) { - for (CustomTimingsHandler timings : HANDLERS) { - timings.reset(); - } - } - TimingsCommand.timingStart = System.nanoTime(); - } - - /** - * Ticked every tick by CraftBukkit to count the number of times a timer - * caused TPS loss. - */ - public static void tick() { - if (Bukkit.getPluginManager().useTimings()) { - for (CustomTimingsHandler timings : HANDLERS) { - if (timings.curTickTotal > 50000000) { - timings.violations += Math.ceil(timings.curTickTotal / 50000000); - } - timings.curTickTotal = 0; - timings.timingDepth = 0; // incase reset messes this up - } - } - } - - /** - * Starts timing to track a section of code. - */ - public void startTiming() { - // If second condtion fails we are already timing - if (Bukkit.getPluginManager().useTimings() && ++timingDepth == 1) { - start = System.nanoTime(); - if (parent != null && ++parent.timingDepth == 1) { - parent.start = start; - } - } - } - - /** - * Stops timing a section of code. - */ - public void stopTiming() { - if (Bukkit.getPluginManager().useTimings()) { - if (--timingDepth != 0 || start == 0) { - return; - } - long diff = System.nanoTime() - start; - totalTime += diff; - curTickTotal += diff; - count++; - start = 0; - if (parent != null) { - parent.stopTiming(); - } - } - } - - /** - * Reset this timer, setting all values to zero. - */ - public void reset() { - count = 0; - violations = 0; - curTickTotal = 0; - totalTime = 0; - start = 0; - timingDepth = 0; - } -} diff --git a/src/main/java/org/spigotmc/LimitStream.java b/src/main/java/org/spigotmc/LimitStream.java deleted file mode 100644 index 8de241a9..00000000 --- a/src/main/java/org/spigotmc/LimitStream.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.spigotmc; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import net.minecraft.nbt.NbtAccounter; - -public class LimitStream extends FilterInputStream -{ - - private final NbtAccounter limit; - - public LimitStream(InputStream is, NbtAccounter limit) - { - super( is ); - this.limit = limit; - } - - @Override - public int read() throws IOException - { - this.limit.accountBytes( 1 ); - return super.read(); - } - - @Override - public int read(byte[] b) throws IOException - { - this.limit.accountBytes( b.length ); - return super.read( b ); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException - { - this.limit.accountBytes( len ); - return super.read( b, off, len ); - } -} diff --git a/src/main/java/org/spigotmc/RestartCommand.java b/src/main/java/org/spigotmc/RestartCommand.java deleted file mode 100644 index de8c7038..00000000 --- a/src/main/java/org/spigotmc/RestartCommand.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.spigotmc; - -import java.io.File; -import java.util.List; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.craftbukkit.util.CraftChatMessage; - -public class RestartCommand extends Command -{ - - public RestartCommand(String name) - { - super( name ); - this.description = "Restarts the server"; - this.usageMessage = "/restart"; - this.setPermission( "bukkit.command.restart" ); - } - - @Override - public boolean execute(CommandSender sender, String currentAlias, String[] args) - { - if ( this.testPermission( sender ) ) - { - MinecraftServer.getServer().processQueue.add( new Runnable() - { - @Override - public void run() - { - RestartCommand.restart(); - } - } ); - } - return true; - } - - public static void restart() - { - RestartCommand.restart( SpigotConfig.restartScript ); - } - - private static void restart(final String restartScript) - { - AsyncCatcher.enabled = false; // Disable async catcher incase it interferes with us - try - { - String[] split = restartScript.split( " " ); - if ( split.length > 0 && new File( split[0] ).isFile() ) - { - System.out.println( "Attempting to restart with " + restartScript ); - - // Disable Watchdog - WatchdogThread.doStop(); - - // Kick all players - for ( ServerPlayer p : (List) MinecraftServer.getServer().getPlayerList().players ) - { - p.connection.disconnect( CraftChatMessage.fromStringOrEmpty( SpigotConfig.restartMessage, true ) ); - } - // Give the socket a chance to send the packets - try - { - Thread.sleep( 100 ); - } catch ( InterruptedException ex ) - { - } - // Close the socket so we can rebind with the new process - MinecraftServer.getServer().getConnection().stop(); - - // Give time for it to kick in - try - { - Thread.sleep( 100 ); - } catch ( InterruptedException ex ) - { - } - - // Actually shutdown - try - { - MinecraftServer.getServer().close(); - } catch ( Throwable t ) - { - } - - // This will be done AFTER the server has completely halted - Thread shutdownHook = new Thread() - { - @Override - public void run() - { - try - { - String os = System.getProperty( "os.name" ).toLowerCase(java.util.Locale.ENGLISH); - if ( os.contains( "win" ) ) - { - Runtime.getRuntime().exec( "cmd /c start " + restartScript ); - } else - { - Runtime.getRuntime().exec( "sh " + restartScript ); - } - } catch ( Exception e ) - { - e.printStackTrace(); - } - } - }; - - shutdownHook.setDaemon( true ); - Runtime.getRuntime().addShutdownHook( shutdownHook ); - } else - { - System.out.println( "Startup script '" + SpigotConfig.restartScript + "' does not exist! Stopping server." ); - - // Actually shutdown - try - { - MinecraftServer.getServer().close(); - } catch ( Throwable t ) - { - } - } - System.exit( 0 ); - } catch ( Exception ex ) - { - ex.printStackTrace(); - } - } -} diff --git a/src/main/java/org/spigotmc/SpigotCommand.java b/src/main/java/org/spigotmc/SpigotCommand.java deleted file mode 100644 index ac0fd418..00000000 --- a/src/main/java/org/spigotmc/SpigotCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.spigotmc; - -import java.io.File; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class SpigotCommand extends Command { - - public SpigotCommand(String name) { - super(name); - this.description = "Spigot related commands"; - this.usageMessage = "/spigot reload"; - this.setPermission("bukkit.command.spigot"); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!this.testPermission(sender)) return true; - - if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Usage: " + this.usageMessage); - return false; - } - - if (args[0].equals("reload")) { - Command.broadcastCommandMessage(sender, ChatColor.RED + "Please note that this command is not supported and may cause issues."); - Command.broadcastCommandMessage(sender, ChatColor.RED + "If you encounter any issues please use the /stop command to restart your server."); - - MinecraftServer console = MinecraftServer.getServer(); - org.spigotmc.SpigotConfig.init((File) console.options.valueOf("spigot-settings")); - for (ServerLevel world : console.getAllLevels()) { - world.spigotConfig.init(); - } - console.server.reloadCount++; - - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Reload complete."); - } - - return true; - } -} diff --git a/src/main/java/org/spigotmc/SpigotConfig.java b/src/main/java/org/spigotmc/SpigotConfig.java deleted file mode 100644 index 59e2a722..00000000 --- a/src/main/java/org/spigotmc/SpigotConfig.java +++ /dev/null @@ -1,396 +0,0 @@ -package org.spigotmc; - -import com.google.common.base.Throwables; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.entity.ai.attributes.Attributes; -import net.minecraft.world.entity.ai.attributes.RangedAttribute; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; - -public class SpigotConfig -{ - - private static File CONFIG_FILE; - private static final String HEADER = "This is the main configuration file for Spigot.\n" - + "As you can see, there's tons to configure. Some options may impact gameplay, so use\n" - + "with caution, and make sure you know what each option does before configuring.\n" - + "For a reference for any variable inside this file, check out the Spigot wiki at\n" - + "http://www.spigotmc.org/wiki/spigot-configuration/\n" - + "\n" - + "If you need help with the configuration or have any questions related to Spigot,\n" - + "join us at the Discord or drop by our forums and leave a post.\n" - + "\n" - + "Discord: https://www.spigotmc.org/go/discord\n" - + "Forums: http://www.spigotmc.org/\n"; - /*========================================================================*/ - public static YamlConfiguration config; - static int version; - static Map commands; - /*========================================================================*/ - - public static void init(File configFile) - { - SpigotConfig.CONFIG_FILE = configFile; - SpigotConfig.config = new YamlConfiguration(); - try - { - SpigotConfig.config.load( SpigotConfig.CONFIG_FILE ); - } catch ( IOException ex ) - { - } catch ( InvalidConfigurationException ex ) - { - Bukkit.getLogger().log( Level.SEVERE, "Could not load spigot.yml, please correct your syntax errors", ex ); - throw Throwables.propagate( ex ); - } - - SpigotConfig.config.options().header( SpigotConfig.HEADER ); - SpigotConfig.config.options().copyDefaults( true ); - - SpigotConfig.commands = new HashMap(); - SpigotConfig.commands.put( "spigot", new SpigotCommand( "spigot" ) ); - - SpigotConfig.version = SpigotConfig.getInt( "config-version", 12 ); - SpigotConfig.set( "config-version", 12 ); - SpigotConfig.readConfig( SpigotConfig.class, null ); - } - - public static void registerCommands() - { - for ( Map.Entry entry : SpigotConfig.commands.entrySet() ) - { - MinecraftServer.getServer().server.getCommandMap().register( entry.getKey(), "Spigot", entry.getValue() ); - } - } - - static void readConfig(Class clazz, Object instance) - { - for ( Method method : clazz.getDeclaredMethods() ) - { - if ( Modifier.isPrivate( method.getModifiers() ) ) - { - if ( method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE ) - { - try - { - method.setAccessible( true ); - method.invoke( instance ); - } catch ( InvocationTargetException ex ) - { - throw Throwables.propagate( ex.getCause() ); - } catch ( Exception ex ) - { - Bukkit.getLogger().log( Level.SEVERE, "Error invoking " + method, ex ); - } - } - } - } - - try - { - SpigotConfig.config.save( SpigotConfig.CONFIG_FILE ); - } catch ( IOException ex ) - { - Bukkit.getLogger().log( Level.SEVERE, "Could not save " + SpigotConfig.CONFIG_FILE, ex ); - } - } - - private static void set(String path, Object val) - { - SpigotConfig.config.set( path, val ); - } - - private static boolean getBoolean(String path, boolean def) - { - SpigotConfig.config.addDefault( path, def ); - return SpigotConfig.config.getBoolean( path, SpigotConfig.config.getBoolean( path ) ); - } - - private static int getInt(String path, int def) - { - SpigotConfig.config.addDefault( path, def ); - return SpigotConfig.config.getInt( path, SpigotConfig.config.getInt( path ) ); - } - - private static List getList(String path, T def) - { - SpigotConfig.config.addDefault( path, def ); - return (List) SpigotConfig.config.getList( path, SpigotConfig.config.getList( path ) ); - } - - private static String getString(String path, String def) - { - SpigotConfig.config.addDefault( path, def ); - return SpigotConfig.config.getString( path, SpigotConfig.config.getString( path ) ); - } - - private static double getDouble(String path, double def) - { - SpigotConfig.config.addDefault( path, def ); - return SpigotConfig.config.getDouble( path, SpigotConfig.config.getDouble( path ) ); - } - - public static boolean logCommands; - private static void logCommands() - { - SpigotConfig.logCommands = SpigotConfig.getBoolean( "commands.log", true ); - } - - public static int tabComplete; - public static boolean sendNamespaced; - private static void tabComplete() - { - if ( SpigotConfig.version < 6 ) - { - boolean oldValue = SpigotConfig.getBoolean( "commands.tab-complete", true ); - if ( oldValue ) - { - SpigotConfig.set( "commands.tab-complete", 0 ); - } else - { - SpigotConfig.set( "commands.tab-complete", -1 ); - } - } - SpigotConfig.tabComplete = SpigotConfig.getInt( "commands.tab-complete", 0 ); - SpigotConfig.sendNamespaced = SpigotConfig.getBoolean( "commands.send-namespaced", true ); - } - - public static String whitelistMessage; - public static String unknownCommandMessage; - public static String serverFullMessage; - public static String outdatedClientMessage = "Outdated client! Please use {0}"; - public static String outdatedServerMessage = "Outdated server! I\'m still on {0}"; - private static String transform(String s) - { - return ChatColor.translateAlternateColorCodes( '&', s ).replaceAll( "\\\\n", "\n" ); - } - private static void messages() - { - if (SpigotConfig.version < 8) - { - SpigotConfig.set( "messages.outdated-client", SpigotConfig.outdatedClientMessage ); - SpigotConfig.set( "messages.outdated-server", SpigotConfig.outdatedServerMessage ); - } - - SpigotConfig.whitelistMessage = SpigotConfig.transform( SpigotConfig.getString( "messages.whitelist", "You are not whitelisted on this server!" ) ); - SpigotConfig.unknownCommandMessage = SpigotConfig.transform( SpigotConfig.getString( "messages.unknown-command", "Unknown command. Type \"/help\" for help." ) ); - SpigotConfig.serverFullMessage = SpigotConfig.transform( SpigotConfig.getString( "messages.server-full", "The server is full!" ) ); - SpigotConfig.outdatedClientMessage = SpigotConfig.transform( SpigotConfig.getString( "messages.outdated-client", SpigotConfig.outdatedClientMessage ) ); - SpigotConfig.outdatedServerMessage = SpigotConfig.transform( SpigotConfig.getString( "messages.outdated-server", SpigotConfig.outdatedServerMessage ) ); - } - - public static int timeoutTime = 60; - public static boolean restartOnCrash = true; - public static String restartScript = "./start.sh"; - public static String restartMessage; - private static void watchdog() - { - SpigotConfig.timeoutTime = SpigotConfig.getInt( "settings.timeout-time", SpigotConfig.timeoutTime ); - SpigotConfig.restartOnCrash = SpigotConfig.getBoolean( "settings.restart-on-crash", SpigotConfig.restartOnCrash ); - SpigotConfig.restartScript = SpigotConfig.getString( "settings.restart-script", SpigotConfig.restartScript ); - SpigotConfig.restartMessage = SpigotConfig.transform( SpigotConfig.getString( "messages.restart", "Server is restarting" ) ); - SpigotConfig.commands.put( "restart", new RestartCommand( "restart" ) ); - WatchdogThread.doStart( SpigotConfig.timeoutTime, SpigotConfig.restartOnCrash ); - } - - public static boolean bungee; - private static void bungee() { - if ( SpigotConfig.version < 4 ) - { - SpigotConfig.set( "settings.bungeecord", false ); - System.out.println( "Outdated config, disabling BungeeCord support!" ); - } - SpigotConfig.bungee = SpigotConfig.getBoolean( "settings.bungeecord", false ); - } - - private static void nettyThreads() - { - int count = SpigotConfig.getInt( "settings.netty-threads", 4 ); - System.setProperty( "io.netty.eventLoopThreads", Integer.toString( count ) ); - Bukkit.getLogger().log( Level.INFO, "Using {0} threads for Netty based IO", count ); - } - - public static boolean disableStatSaving; - public static Map forcedStats = new HashMap<>(); - private static void stats() - { - SpigotConfig.disableStatSaving = SpigotConfig.getBoolean( "stats.disable-saving", false ); - - if ( !SpigotConfig.config.contains( "stats.forced-stats" ) ) { - SpigotConfig.config.createSection( "stats.forced-stats" ); - } - - ConfigurationSection section = SpigotConfig.config.getConfigurationSection( "stats.forced-stats" ); - for ( String name : section.getKeys( true ) ) - { - if ( section.isInt( name ) ) - { - try - { - ResourceLocation key = ResourceLocation.parse( name ); - if ( BuiltInRegistries.CUSTOM_STAT.get( key ) == null ) - { - Bukkit.getLogger().log(Level.WARNING, "Ignoring non existent stats.forced-stats " + name); - continue; - } - SpigotConfig.forcedStats.put( key, section.getInt( name ) ); - } catch (Exception ex) - { - Bukkit.getLogger().log(Level.WARNING, "Ignoring invalid stats.forced-stats " + name); - } - } - } - } - - private static void tpsCommand() - { - SpigotConfig.commands.put( "tps", new TicksPerSecondCommand( "tps" ) ); - } - - public static int playerSample; - private static void playerSample() - { - SpigotConfig.playerSample = SpigotConfig.getInt( "settings.sample-count", 12 ); - System.out.println( "Server Ping Player Sample Count: " + SpigotConfig.playerSample ); - } - - public static int playerShuffle; - private static void playerShuffle() - { - SpigotConfig.playerShuffle = SpigotConfig.getInt( "settings.player-shuffle", 0 ); - } - - public static List spamExclusions; - private static void spamExclusions() - { - SpigotConfig.spamExclusions = SpigotConfig.getList( "commands.spam-exclusions", Arrays.asList( new String[] - { - "/skill" - } ) ); - } - - public static boolean silentCommandBlocks; - private static void silentCommandBlocks() - { - SpigotConfig.silentCommandBlocks = SpigotConfig.getBoolean( "commands.silent-commandblock-console", false ); - } - - public static Set replaceCommands; - private static void replaceCommands() - { - if ( SpigotConfig.config.contains( "replace-commands" ) ) - { - SpigotConfig.set( "commands.replace-commands", SpigotConfig.config.getStringList( "replace-commands" ) ); - SpigotConfig.config.set( "replace-commands", null ); - } - SpigotConfig.replaceCommands = new HashSet( (List) SpigotConfig.getList( "commands.replace-commands", - Arrays.asList( "setblock", "summon", "testforblock", "tellraw" ) ) ); - } - - public static int userCacheCap; - private static void userCacheCap() - { - SpigotConfig.userCacheCap = SpigotConfig.getInt( "settings.user-cache-size", 1000 ); - } - - public static boolean saveUserCacheOnStopOnly; - private static void saveUserCacheOnStopOnly() - { - SpigotConfig.saveUserCacheOnStopOnly = SpigotConfig.getBoolean( "settings.save-user-cache-on-stop-only", false ); - } - - public static double movedWronglyThreshold; - private static void movedWronglyThreshold() - { - SpigotConfig.movedWronglyThreshold = SpigotConfig.getDouble( "settings.moved-wrongly-threshold", 0.0625D ); - } - - public static double movedTooQuicklyMultiplier; - private static void movedTooQuicklyMultiplier() - { - SpigotConfig.movedTooQuicklyMultiplier = SpigotConfig.getDouble( "settings.moved-too-quickly-multiplier", 10.0D ); - } - - public static double maxAbsorption = 2048; - public static double maxHealth = 2048; - public static double movementSpeed = 2048; - public static double attackDamage = 2048; - private static void attributeMaxes() - { - SpigotConfig.maxAbsorption = SpigotConfig.getDouble( "settings.attribute.maxAbsorption.max", SpigotConfig.maxAbsorption ); - ( (RangedAttribute) Attributes.MAX_ABSORPTION.value() ).maxValue = SpigotConfig.maxAbsorption; - SpigotConfig.maxHealth = SpigotConfig.getDouble( "settings.attribute.maxHealth.max", SpigotConfig.maxHealth ); - ( (RangedAttribute) Attributes.MAX_HEALTH.value() ).maxValue = SpigotConfig.maxHealth; - SpigotConfig.movementSpeed = SpigotConfig.getDouble( "settings.attribute.movementSpeed.max", SpigotConfig.movementSpeed ); - ( (RangedAttribute) Attributes.MOVEMENT_SPEED.value() ).maxValue = SpigotConfig.movementSpeed; - SpigotConfig.attackDamage = SpigotConfig.getDouble( "settings.attribute.attackDamage.max", SpigotConfig.attackDamage ); - ( (RangedAttribute) Attributes.ATTACK_DAMAGE.value() ).maxValue = SpigotConfig.attackDamage; - } - - public static boolean debug; - private static void debug() - { - SpigotConfig.debug = SpigotConfig.getBoolean( "settings.debug", false ); - - if ( SpigotConfig.debug && !LogManager.getRootLogger().isTraceEnabled() ) - { - // Enable debug logging - LoggerContext ctx = (LoggerContext) LogManager.getContext( false ); - Configuration conf = ctx.getConfiguration(); - conf.getLoggerConfig( LogManager.ROOT_LOGGER_NAME ).setLevel( org.apache.logging.log4j.Level.ALL ); - ctx.updateLoggers( conf ); - } - - if ( LogManager.getRootLogger().isTraceEnabled() ) - { - Bukkit.getLogger().info( "Debug logging is enabled" ); - } else - { - Bukkit.getLogger().info( "Debug logging is disabled" ); - } - } - - public static boolean disableAdvancementSaving; - public static List disabledAdvancements; - private static void disabledAdvancements() { - SpigotConfig.disableAdvancementSaving = SpigotConfig.getBoolean("advancements.disable-saving", false); - SpigotConfig.disabledAdvancements = SpigotConfig.getList("advancements.disabled", Arrays.asList(new String[]{"minecraft:story/disabled"})); - } - - public static boolean logVillagerDeaths; - public static boolean logNamedDeaths; - private static void logDeaths() { - SpigotConfig.logVillagerDeaths = SpigotConfig.getBoolean("settings.log-villager-deaths", true); - SpigotConfig.logNamedDeaths = SpigotConfig.getBoolean("settings.log-named-deaths", true); - } - - public static boolean disablePlayerDataSaving; - private static void disablePlayerDataSaving() { - SpigotConfig.disablePlayerDataSaving = SpigotConfig.getBoolean("players.disable-saving", false); - } - - public static boolean belowZeroGenerationInExistingChunks; - private static void belowZeroGenerationInExistingChunks() { - SpigotConfig.belowZeroGenerationInExistingChunks = SpigotConfig.getBoolean("world-settings.default.below-zero-generation-in-existing-chunks", true); - } -} diff --git a/src/main/java/org/spigotmc/SpigotWorldConfig.java b/src/main/java/org/spigotmc/SpigotWorldConfig.java deleted file mode 100644 index 557a6e8a..00000000 --- a/src/main/java/org/spigotmc/SpigotWorldConfig.java +++ /dev/null @@ -1,401 +0,0 @@ -package org.spigotmc; - -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; - -public class SpigotWorldConfig -{ - - private final String worldName; - private final YamlConfiguration config; - private boolean verbose; - - public SpigotWorldConfig(String worldName) - { - this.worldName = worldName; - this.config = SpigotConfig.config; - this.init(); - } - - public void init() - { - this.verbose = this.getBoolean( "verbose", false ); - - this.log( "-------- World Settings For [" + this.worldName + "] --------" ); - SpigotConfig.readConfig( SpigotWorldConfig.class, this ); - } - - private void log(String s) - { - if ( this.verbose ) - { - Bukkit.getLogger().info( s ); - } - } - - private void set(String path, Object val) - { - this.config.set( "world-settings.default." + path, val ); - } - - private boolean getBoolean(String path, boolean def) - { - this.config.addDefault( "world-settings.default." + path, def ); - return this.config.getBoolean( "world-settings." + this.worldName + "." + path, this.config.getBoolean( "world-settings.default." + path ) ); - } - - private double getDouble(String path, double def) - { - this.config.addDefault( "world-settings.default." + path, def ); - return this.config.getDouble( "world-settings." + this.worldName + "." + path, this.config.getDouble( "world-settings.default." + path ) ); - } - - private int getInt(String path) - { - return this.config.getInt( "world-settings." + this.worldName + "." + path ); - } - - private int getInt(String path, int def) - { - this.config.addDefault( "world-settings.default." + path, def ); - return this.config.getInt( "world-settings." + this.worldName + "." + path, this.config.getInt( "world-settings.default." + path ) ); - } - - private List getList(String path, T def) - { - this.config.addDefault( "world-settings.default." + path, def ); - return (List) this.config.getList( "world-settings." + this.worldName + "." + path, this.config.getList( "world-settings.default." + path ) ); - } - - private String getString(String path, String def) - { - this.config.addDefault( "world-settings.default." + path, def ); - return this.config.getString( "world-settings." + this.worldName + "." + path, this.config.getString( "world-settings.default." + path ) ); - } - - private Object get(String path, Object def) - { - this.config.addDefault( "world-settings.default." + path, def ); - return this.config.get( "world-settings." + this.worldName + "." + path, this.config.get( "world-settings.default." + path ) ); - } - - // Crop growth rates - public int cactusModifier; - public int caneModifier; - public int melonModifier; - public int mushroomModifier; - public int pumpkinModifier; - public int saplingModifier; - public int beetrootModifier; - public int carrotModifier; - public int potatoModifier; - public int wheatModifier; - public int wartModifier; - public int vineModifier; - public int cocoaModifier; - public int bambooModifier; - public int sweetBerryModifier; - public int kelpModifier; - public int twistingVinesModifier; - public int weepingVinesModifier; - public int caveVinesModifier; - private int getAndValidateGrowth(String crop) - { - int modifier = this.getInt( "growth." + crop.toLowerCase(java.util.Locale.ENGLISH) + "-modifier", 100 ); - if ( modifier == 0 ) - { - this.log( "Cannot set " + crop + " growth to zero, defaulting to 100" ); - modifier = 100; - } - this.log( crop + " Growth Modifier: " + modifier + "%" ); - - return modifier; - } - private void growthModifiers() - { - this.cactusModifier = this.getAndValidateGrowth( "Cactus" ); - this.caneModifier = this.getAndValidateGrowth( "Cane" ); - this.melonModifier = this.getAndValidateGrowth( "Melon" ); - this.mushroomModifier = this.getAndValidateGrowth( "Mushroom" ); - this.pumpkinModifier = this.getAndValidateGrowth( "Pumpkin" ); - this.saplingModifier = this.getAndValidateGrowth( "Sapling" ); - this.beetrootModifier = this.getAndValidateGrowth( "Beetroot" ); - this.carrotModifier = this.getAndValidateGrowth( "Carrot" ); - this.potatoModifier = this.getAndValidateGrowth( "Potato" ); - this.wheatModifier = this.getAndValidateGrowth( "Wheat" ); - this.wartModifier = this.getAndValidateGrowth( "NetherWart" ); - this.vineModifier = this.getAndValidateGrowth( "Vine" ); - this.cocoaModifier = this.getAndValidateGrowth( "Cocoa" ); - this.bambooModifier = this.getAndValidateGrowth( "Bamboo" ); - this.sweetBerryModifier = this.getAndValidateGrowth( "SweetBerry" ); - this.kelpModifier = this.getAndValidateGrowth( "Kelp" ); - this.twistingVinesModifier = this.getAndValidateGrowth( "TwistingVines" ); - this.weepingVinesModifier = this.getAndValidateGrowth( "WeepingVines" ); - this.caveVinesModifier = this.getAndValidateGrowth( "CaveVines" ); - } - - public double itemMerge; - private void itemMerge() - { - this.itemMerge = this.getDouble("merge-radius.item", 2.5 ); - this.log( "Item Merge Radius: " + this.itemMerge ); - } - - public double expMerge; - private void expMerge() - { - this.expMerge = this.getDouble("merge-radius.exp", 3.0 ); - this.log( "Experience Merge Radius: " + this.expMerge ); - } - - public int viewDistance; - private void viewDistance() - { - if ( SpigotConfig.version < 12 ) - { - this.set( "view-distance", null ); - } - - Object viewDistanceObject = this.get( "view-distance", "default" ); - this.viewDistance = ( viewDistanceObject ) instanceof Number ? ( (Number) viewDistanceObject ).intValue() : -1; - if ( this.viewDistance <= 0 ) - { - this.viewDistance = Bukkit.getViewDistance(); - } - - this.viewDistance = Math.max( Math.min( this.viewDistance, 32 ), 3 ); - this.log( "View Distance: " + this.viewDistance ); - } - - public int simulationDistance; - private void simulationDistance() - { - Object simulationDistanceObject = this.get( "simulation-distance", "default" ); - this.simulationDistance = ( simulationDistanceObject ) instanceof Number ? ( (Number) simulationDistanceObject ).intValue() : -1; - if ( this.simulationDistance <= 0 ) - { - this.simulationDistance = Bukkit.getSimulationDistance(); - } - - this.log( "Simulation Distance: " + this.simulationDistance ); - } - - public byte mobSpawnRange; - private void mobSpawnRange() - { - this.mobSpawnRange = (byte) this.getInt( "mob-spawn-range", 6 ); - this.log( "Mob Spawn Range: " + this.mobSpawnRange ); - } - - public int itemDespawnRate; - private void itemDespawnRate() - { - this.itemDespawnRate = this.getInt( "item-despawn-rate", 6000 ); - this.log( "Item Despawn Rate: " + this.itemDespawnRate ); - } - - public int animalActivationRange = 32; - public int monsterActivationRange = 32; - public int raiderActivationRange = 48; - public int miscActivationRange = 16; - public boolean tickInactiveVillagers = true; - public boolean ignoreSpectatorActivation = false; - private void activationRange() - { - this.animalActivationRange = this.getInt( "entity-activation-range.animals", this.animalActivationRange ); - this.monsterActivationRange = this.getInt( "entity-activation-range.monsters", this.monsterActivationRange ); - this.raiderActivationRange = this.getInt( "entity-activation-range.raiders", this.raiderActivationRange ); - this.miscActivationRange = this.getInt( "entity-activation-range.misc", this.miscActivationRange ); - this.tickInactiveVillagers = this.getBoolean( "entity-activation-range.tick-inactive-villagers", this.tickInactiveVillagers ); - this.ignoreSpectatorActivation = this.getBoolean( "entity-activation-range.ignore-spectators", this.ignoreSpectatorActivation ); - this.log( "Entity Activation Range: An " + this.animalActivationRange + " / Mo " + this.monsterActivationRange + " / Ra " + this.raiderActivationRange + " / Mi " + this.miscActivationRange + " / Tiv " + this.tickInactiveVillagers + " / Isa " + this.ignoreSpectatorActivation ); - } - - public int playerTrackingRange = 48; - public int animalTrackingRange = 48; - public int monsterTrackingRange = 48; - public int miscTrackingRange = 32; - public int displayTrackingRange = 128; - public int otherTrackingRange = 64; - private void trackingRange() - { - this.playerTrackingRange = this.getInt( "entity-tracking-range.players", this.playerTrackingRange ); - this.animalTrackingRange = this.getInt( "entity-tracking-range.animals", this.animalTrackingRange ); - this.monsterTrackingRange = this.getInt( "entity-tracking-range.monsters", this.monsterTrackingRange ); - this.miscTrackingRange = this.getInt( "entity-tracking-range.misc", this.miscTrackingRange ); - this.displayTrackingRange = this.getInt( "entity-tracking-range.display", this.displayTrackingRange ); - this.otherTrackingRange = this.getInt( "entity-tracking-range.other", this.otherTrackingRange ); - this.log( "Entity Tracking Range: Pl " + this.playerTrackingRange + " / An " + this.animalTrackingRange + " / Mo " + this.monsterTrackingRange + " / Mi " + this.miscTrackingRange + " / Di " + this.displayTrackingRange + " / Other " + this.otherTrackingRange ); - } - - public int hopperTransfer; - public int hopperCheck; - public int hopperAmount; - public boolean hopperCanLoadChunks; - private void hoppers() - { - // Set the tick delay between hopper item movements - this.hopperTransfer = this.getInt( "ticks-per.hopper-transfer", 8 ); - if ( SpigotConfig.version < 11 ) - { - this.set( "ticks-per.hopper-check", 1 ); - } - this.hopperCheck = this.getInt( "ticks-per.hopper-check", 1 ); - this.hopperAmount = this.getInt( "hopper-amount", 1 ); - this.hopperCanLoadChunks = this.getBoolean( "hopper-can-load-chunks", false ); - this.log( "Hopper Transfer: " + this.hopperTransfer + " Hopper Check: " + this.hopperCheck + " Hopper Amount: " + this.hopperAmount + " Hopper Can Load Chunks: " + this.hopperCanLoadChunks ); - } - - public int arrowDespawnRate; - public int tridentDespawnRate; - private void arrowDespawnRate() - { - this.arrowDespawnRate = this.getInt( "arrow-despawn-rate", 1200 ); - this.tridentDespawnRate = this.getInt( "trident-despawn-rate", this.arrowDespawnRate ); - this.log( "Arrow Despawn Rate: " + this.arrowDespawnRate + " Trident Respawn Rate:" + this.tridentDespawnRate ); - } - - public boolean zombieAggressiveTowardsVillager; - private void zombieAggressiveTowardsVillager() - { - this.zombieAggressiveTowardsVillager = this.getBoolean( "zombie-aggressive-towards-villager", true ); - this.log( "Zombie Aggressive Towards Villager: " + this.zombieAggressiveTowardsVillager ); - } - - public boolean nerfSpawnerMobs; - private void nerfSpawnerMobs() - { - this.nerfSpawnerMobs = this.getBoolean( "nerf-spawner-mobs", false ); - this.log( "Nerfing mobs spawned from spawners: " + this.nerfSpawnerMobs ); - } - - public boolean enableZombiePigmenPortalSpawns; - private void enableZombiePigmenPortalSpawns() - { - this.enableZombiePigmenPortalSpawns = this.getBoolean( "enable-zombie-pigmen-portal-spawns", true ); - this.log( "Allow Zombie Pigmen to spawn from portal blocks: " + this.enableZombiePigmenPortalSpawns ); - } - - public int dragonDeathSoundRadius; - private void keepDragonDeathPerWorld() - { - this.dragonDeathSoundRadius = this.getInt( "dragon-death-sound-radius", 0 ); - } - - public int witherSpawnSoundRadius; - private void witherSpawnSoundRadius() - { - this.witherSpawnSoundRadius = this.getInt( "wither-spawn-sound-radius", 0 ); - } - - public int endPortalSoundRadius; - private void endPortalSoundRadius() - { - this.endPortalSoundRadius = this.getInt( "end-portal-sound-radius", 0 ); - } - - public int villageSeed; - public int desertSeed; - public int iglooSeed; - public int jungleSeed; - public int swampSeed; - public int monumentSeed; - public int oceanSeed; - public int outpostSeed; - public int shipwreckSeed; - public int slimeSeed; - public int endCitySeed; - public int netherSeed; - public int mansionSeed; - public int fossilSeed; - public int portalSeed; - private void initWorldGenSeeds() - { - this.villageSeed = this.getInt( "seed-village", 10387312 ); - this.desertSeed = this.getInt( "seed-desert", 14357617 ); - this.iglooSeed = this.getInt( "seed-igloo", 14357618 ); - this.jungleSeed = this.getInt( "seed-jungle", 14357619 ); - this.swampSeed = this.getInt( "seed-swamp", 14357620 ); - this.monumentSeed = this.getInt( "seed-monument", 10387313 ); - this.shipwreckSeed = this.getInt( "seed-shipwreck", 165745295 ); - this.oceanSeed = this.getInt( "seed-ocean", 14357621 ); - this.outpostSeed = this.getInt( "seed-outpost", 165745296 ); - this.endCitySeed = this.getInt( "seed-endcity", 10387313 ); - this.slimeSeed = this.getInt( "seed-slime", 987234911 ); - this.netherSeed = this.getInt( "seed-nether", 30084232 ); - this.mansionSeed = this.getInt( "seed-mansion", 10387319 ); - this.fossilSeed = this.getInt( "seed-fossil", 14357921 ); - this.portalSeed = this.getInt( "seed-portal", 34222645 ); - this.log( "Custom Map Seeds: Village: " + this.villageSeed + " Desert: " + this.desertSeed + " Igloo: " + this.iglooSeed + " Jungle: " + this.jungleSeed + " Swamp: " + this.swampSeed + " Monument: " + this.monumentSeed - + " Ocean: " + this.oceanSeed + " Shipwreck: " + this.shipwreckSeed + " End City: " + this.endCitySeed + " Slime: " + this.slimeSeed + " Nether: " + this.netherSeed + " Mansion: " + this.mansionSeed + " Fossil: " + this.fossilSeed + " Portal: " + this.portalSeed ); - } - - public float jumpWalkExhaustion; - public float jumpSprintExhaustion; - public float combatExhaustion; - public float regenExhaustion; - public float swimMultiplier; - public float sprintMultiplier; - public float otherMultiplier; - private void initHunger() - { - if ( SpigotConfig.version < 10 ) - { - this.set( "hunger.walk-exhaustion", null ); - this.set( "hunger.sprint-exhaustion", null ); - this.set( "hunger.combat-exhaustion", 0.1 ); - this.set( "hunger.regen-exhaustion", 6.0 ); - } - - this.jumpWalkExhaustion = (float) this.getDouble( "hunger.jump-walk-exhaustion", 0.05 ); - this.jumpSprintExhaustion = (float) this.getDouble( "hunger.jump-sprint-exhaustion", 0.2 ); - this.combatExhaustion = (float) this.getDouble( "hunger.combat-exhaustion", 0.1 ); - this.regenExhaustion = (float) this.getDouble( "hunger.regen-exhaustion", 6.0 ); - this.swimMultiplier = (float) this.getDouble( "hunger.swim-multiplier", 0.01 ); - this.sprintMultiplier = (float) this.getDouble( "hunger.sprint-multiplier", 0.1 ); - this.otherMultiplier = (float) this.getDouble( "hunger.other-multiplier", 0.0 ); - } - - public int currentPrimedTnt = 0; - public int maxTntTicksPerTick; - private void maxTntPerTick() { - if ( SpigotConfig.version < 7 ) - { - this.set( "max-tnt-per-tick", 100 ); - } - this.maxTntTicksPerTick = this.getInt( "max-tnt-per-tick", 100 ); - this.log( "Max TNT Explosions: " + this.maxTntTicksPerTick ); - } - - public int hangingTickFrequency; - private void hangingTickFrequency() - { - this.hangingTickFrequency = this.getInt( "hanging-tick-frequency", 100 ); - } - - public int tileMaxTickTime; - public int entityMaxTickTime; - private void maxTickTimes() - { - this.tileMaxTickTime = this.getInt("max-tick-time.tile", 50); - this.entityMaxTickTime = this.getInt("max-tick-time.entity", 50); - this.log("Tile Max Tick Time: " + this.tileMaxTickTime + "ms Entity max Tick Time: " + this.entityMaxTickTime + "ms"); - } - - public int thunderChance; - private void thunderChance() - { - this.thunderChance = this.getInt("thunder-chance", 100000); - } - - public boolean belowZeroGenerationInExistingChunks; - private void belowZeroGenerationInExistingChunks() { - this.belowZeroGenerationInExistingChunks = this.getBoolean("below-zero-generation-in-existing-chunks", true); - } - - public boolean unloadFrozenChunks; - private void unloadFrozenChunks() { - this.unloadFrozenChunks = this.getBoolean("unload-frozen-chunks", false); - } -} diff --git a/src/main/java/org/spigotmc/TickLimiter.java b/src/main/java/org/spigotmc/TickLimiter.java deleted file mode 100644 index 4074538e..00000000 --- a/src/main/java/org/spigotmc/TickLimiter.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.spigotmc; - -public class TickLimiter { - - private final int maxTime; - private long startTime; - - public TickLimiter(int maxtime) { - this.maxTime = maxtime; - } - - public void initTick() { - this.startTime = System.currentTimeMillis(); - } - - public boolean shouldContinue() { - long remaining = System.currentTimeMillis() - this.startTime; - return remaining < this.maxTime; - } -} diff --git a/src/main/java/org/spigotmc/TicksPerSecondCommand.java b/src/main/java/org/spigotmc/TicksPerSecondCommand.java deleted file mode 100644 index d9ec48be..00000000 --- a/src/main/java/org/spigotmc/TicksPerSecondCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.spigotmc; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class TicksPerSecondCommand extends Command -{ - - public TicksPerSecondCommand(String name) - { - super( name ); - this.description = "Gets the current ticks per second for the server"; - this.usageMessage = "/tps"; - this.setPermission( "bukkit.command.tps" ); - } - - @Override - public boolean execute(CommandSender sender, String currentAlias, String[] args) - { - if ( !this.testPermission( sender ) ) - { - return true; - } - - StringBuilder sb = new StringBuilder( ChatColor.GOLD + "TPS from last 1m, 5m, 15m: " ); - for ( double tps : MinecraftServer.getServer().recentTps ) - { - sb.append( this.format( tps ) ); - sb.append( ", " ); - } - sender.sendMessage( sb.substring( 0, sb.length() - 2 ) ); - sender.sendMessage(ChatColor.GOLD + "Current Memory Usage: " + ChatColor.GREEN + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024)) + "/" + (Runtime.getRuntime().totalMemory() / (1024 * 1024)) + " mb (Max: " - + (Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " mb)"); - - return true; - } - - private String format(double tps) - { - return ( ( tps > 18.0 ) ? ChatColor.GREEN : ( tps > 16.0 ) ? ChatColor.YELLOW : ChatColor.RED ).toString() - + ( ( tps > 20.0 ) ? "*" : "" ) + Math.min( Math.round( tps * 100.0 ) / 100.0, 20.0 ); - } -} diff --git a/src/main/java/org/spigotmc/TrackingRange.java b/src/main/java/org/spigotmc/TrackingRange.java deleted file mode 100644 index 73f95635..00000000 --- a/src/main/java/org/spigotmc/TrackingRange.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.spigotmc; - -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.Display; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.ExperienceOrb; -import net.minecraft.world.entity.decoration.ItemFrame; -import net.minecraft.world.entity.decoration.Painting; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.monster.Ghast; - -public class TrackingRange -{ - - /** - * Gets the range an entity should be 'tracked' by players and visible in - * the client. - * - * @param entity - * @param defaultRange Default range defined by Mojang - * @return - */ - public static int getEntityTrackingRange(Entity entity, int defaultRange) - { - if ( defaultRange == 0 ) - { - return defaultRange; - } - SpigotWorldConfig config = entity.level().spigotConfig; - if ( entity instanceof ServerPlayer ) - { - return config.playerTrackingRange; - } else if ( entity.activationType == ActivationRange.ActivationType.MONSTER || entity.activationType == ActivationRange.ActivationType.RAIDER ) - { - return config.monsterTrackingRange; - } else if ( entity instanceof Ghast ) - { - if ( config.monsterTrackingRange > config.monsterActivationRange ) - { - return config.monsterTrackingRange; - } else - { - return config.monsterActivationRange; - } - } else if ( entity.activationType == ActivationRange.ActivationType.ANIMAL ) - { - return config.animalTrackingRange; - } else if ( entity instanceof ItemFrame || entity instanceof Painting || entity instanceof ItemEntity || entity instanceof ExperienceOrb ) - { - return config.miscTrackingRange; - } else if ( entity instanceof Display ) - { - return config.displayTrackingRange; - } else - { - return config.otherTrackingRange; - } - } -} diff --git a/src/main/java/org/spigotmc/ValidateUtils.java b/src/main/java/org/spigotmc/ValidateUtils.java deleted file mode 100644 index c7c1ac3a..00000000 --- a/src/main/java/org/spigotmc/ValidateUtils.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.spigotmc; - -public class ValidateUtils -{ - public static String limit(String str, int limit) - { - if ( str.length() > limit ) - { - return str.substring( 0, limit ); - } - return str; - } -} diff --git a/src/main/java/org/spigotmc/WatchdogThread.java b/src/main/java/org/spigotmc/WatchdogThread.java deleted file mode 100644 index c4bf7053..00000000 --- a/src/main/java/org/spigotmc/WatchdogThread.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.spigotmc; - -import java.lang.management.ManagementFactory; -import java.lang.management.MonitorInfo; -import java.lang.management.ThreadInfo; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.minecraft.server.MinecraftServer; -import org.bukkit.Bukkit; - -public class WatchdogThread extends Thread -{ - - private static WatchdogThread instance; - private long timeoutTime; - private boolean restart; - private volatile long lastTick; - private volatile boolean stopping; - - private WatchdogThread(long timeoutTime, boolean restart) - { - super( "Spigot Watchdog Thread" ); - this.timeoutTime = timeoutTime; - this.restart = restart; - } - - private static long monotonicMillis() - { - return System.nanoTime() / 1000000L; - } - - public static void doStart(int timeoutTime, boolean restart) - { - if ( WatchdogThread.instance == null ) - { - WatchdogThread.instance = new WatchdogThread( timeoutTime * 1000L, restart ); - WatchdogThread.instance.start(); - } else - { - WatchdogThread.instance.timeoutTime = timeoutTime * 1000L; - WatchdogThread.instance.restart = restart; - } - } - - public static void tick() - { - WatchdogThread.instance.lastTick = WatchdogThread.monotonicMillis(); - } - - public static void doStop() - { - if ( WatchdogThread.instance != null ) - { - WatchdogThread.instance.stopping = true; - } - } - - @Override - public void run() - { - while ( !this.stopping ) - { - // - if ( this.lastTick != 0 && this.timeoutTime > 0 && WatchdogThread.monotonicMillis() > this.lastTick + this.timeoutTime ) - { - Logger log = Bukkit.getServer().getLogger(); - log.log( Level.SEVERE, "------------------------------" ); - log.log( Level.SEVERE, "The server has stopped responding! This is (probably) not a Spigot bug." ); - log.log( Level.SEVERE, "If you see a plugin in the Server thread dump below, then please report it to that author" ); - log.log( Level.SEVERE, "\t *Especially* if it looks like HTTP or MySQL operations are occurring" ); - log.log( Level.SEVERE, "If you see a world save or edit, then it means you did far more than your server can handle at once" ); - log.log( Level.SEVERE, "\t If this is the case, consider increasing timeout-time in spigot.yml but note that this will replace the crash with LARGE lag spikes" ); - log.log( Level.SEVERE, "If you are unsure or still think this is a Spigot bug, please report to https://www.spigotmc.org/" ); - log.log( Level.SEVERE, "Be sure to include ALL relevant console errors and Minecraft crash reports" ); - log.log( Level.SEVERE, "Spigot version: " + Bukkit.getServer().getVersion() ); - // - if ( net.minecraft.world.level.Level.lastPhysicsProblem != null ) - { - log.log( Level.SEVERE, "------------------------------" ); - log.log( Level.SEVERE, "During the run of the server, a physics stackoverflow was supressed" ); - log.log( Level.SEVERE, "near " + net.minecraft.world.level.Level.lastPhysicsProblem ); - } - // - log.log( Level.SEVERE, "------------------------------" ); - log.log( Level.SEVERE, "Server thread dump (Look for plugins here before reporting to Spigot!):" ); - WatchdogThread.dumpThread( ManagementFactory.getThreadMXBean().getThreadInfo( MinecraftServer.getServer().serverThread.getId(), Integer.MAX_VALUE ), log ); - log.log( Level.SEVERE, "------------------------------" ); - // - log.log( Level.SEVERE, "Entire Thread Dump:" ); - ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads( true, true ); - for ( ThreadInfo thread : threads ) - { - WatchdogThread.dumpThread( thread, log ); - } - log.log( Level.SEVERE, "------------------------------" ); - - if ( this.restart && !MinecraftServer.getServer().hasStopped() ) - { - RestartCommand.restart(); - } - break; - } - - try - { - sleep( 10000 ); - } catch ( InterruptedException ex ) - { - this.interrupt(); - } - } - } - - private static void dumpThread(ThreadInfo thread, Logger log) - { - log.log( Level.SEVERE, "------------------------------" ); - // - log.log( Level.SEVERE, "Current Thread: " + thread.getThreadName() ); - log.log( Level.SEVERE, "\tPID: " + thread.getThreadId() - + " | Suspended: " + thread.isSuspended() - + " | Native: " + thread.isInNative() - + " | State: " + thread.getThreadState() ); - if ( thread.getLockedMonitors().length != 0 ) - { - log.log( Level.SEVERE, "\tThread is waiting on monitor(s):" ); - for ( MonitorInfo monitor : thread.getLockedMonitors() ) - { - log.log( Level.SEVERE, "\t\tLocked on:" + monitor.getLockedStackFrame() ); - } - } - log.log( Level.SEVERE, "\tStack:" ); - // - for ( StackTraceElement stack : thread.getStackTrace() ) - { - log.log( Level.SEVERE, "\t\t" + stack ); - } - } -} diff --git a/src/main/java/org/spigotmc/event/entity/package-info.java b/src/main/java/org/spigotmc/event/entity/package-info.java deleted file mode 100644 index 264664eb..00000000 --- a/src/main/java/org/spigotmc/event/entity/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Spigot-specific entity events. - */ -package org.spigotmc.event.entity; diff --git a/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java b/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java deleted file mode 100644 index 2515887c..00000000 --- a/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.spigotmc.event.player; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Called when player is about to spawn in a world after joining the server. - */ -public class PlayerSpawnLocationEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); - private Location spawnLocation; - - public PlayerSpawnLocationEvent(@NotNull final Player who, @NotNull Location spawnLocation) { - super(who); - this.spawnLocation = spawnLocation; - } - - - /** - * Gets player's spawn location. - * If the player {@link Player#hasPlayedBefore()}, it's going to default to the location inside player.dat file. - * For new players, the default spawn location is spawn of the main Bukkit world. - * - * @return the spawn location - */ - @NotNull - public Location getSpawnLocation() { - return spawnLocation; - } - - /** - * Sets player's spawn location. - * - * @param location the spawn location - */ - public void setSpawnLocation(@NotNull Location location) { - this.spawnLocation = location; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/org/spigotmc/event/player/package-info.java b/src/main/java/org/spigotmc/event/player/package-info.java deleted file mode 100644 index 6a2d5d84..00000000 --- a/src/main/java/org/spigotmc/event/player/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Spigot-specific player events. - */ -package org.spigotmc.event.player; diff --git a/src/main/java/org/spigotmc/package-info.java b/src/main/java/org/spigotmc/package-info.java deleted file mode 100644 index a287faff..00000000 --- a/src/main/java/org/spigotmc/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Spigot-specific classes. - */ -package org.spigotmc;